Raphael Eid
Raphael Eid

Reputation: 29

checking if string contains letters from list

I am trying to make a function called valide(seq), and to be valid, the string should only contains letters a t g c.

ex: attgcattgggacf -> true

ex2: atgjglkdatfklja -> false

If valid it should return true and if not it should return false

Everytime im running the full code, im entering a string that contains only these letters and its not accepting it

def valide(seq) :
    sub = ["a", "t", "g", "c"]
    if any(seq in s for s in sub):
      return True
    else:
      return False

Upvotes: 0

Views: 2496

Answers (3)

Hacked
Hacked

Reputation: 102

Let's take your example input: attgcattgggac (I guess the final f was a typo). What your code does is looking at each letter individually, so a, then t, etc. and checks if the array ["a", "t", "g", "c"] is contained in it, which is obviously false. It also only checks if at least one does. You should use all() to check if they all do. What you wanna do is check if the letter exists in your array. this would give:

def valide(seq) :
    sub = ["a", "t", "g", "c"]
    if all(s in sub for s in seq):
      return True
    else:
      return False

As any yields a boolean and strings are iterable, you can also compact it this way:

def valide(seq) :
    sub = "atgc"
    return all(s in sub for s in seq):

Upvotes: 0

user15072974
user15072974

Reputation:

You should be using all():

def valide(seq):
    sub = ["a", "t", "g", "c"]
    if all(letter in sub for letter in seq):
        return True
    else:
        return False

all() returns True if every entry it checks holds true. This works because, as Hacked says, strings are iterable. Thus, if there were any errors, you would get False.

You could condense it though:

def valide(seq):
    sub = ["a", "t", "g", "c"]
    return all(letter in sub for letter in seq)

Since you return a True/False value anyway.

Other possible changes

  • You could replace ["a", "t", "g", "c"] with "atgc", since strings are iterable.
  • Since this is a short string, you could directly use this in the all() function, saving a line.
  • You could save another line using Lambda Notation.

These changes are shown below:

valide = lambda seq : all(letter in "atgc" for letter in seq)

This result is concise and readable.

Upvotes: 3

Sivaram Rasathurai
Sivaram Rasathurai

Reputation: 6333

def isValid(seq):
       sub = ["a", "t", "g", "c"]
       for e in seq:
          if e not in sub:
            return false
       return true

Check each letter is not in the list if the letter is not in the list it will return false otherwise all letters in the list then full for loop will run and finally function will return true

Upvotes: 0

Related Questions