def function producing incorrect output

Viewed 152

My task is to:

Write a function, starts_with(word, chs) that returns whether or not the string word begins with one of the characters in the list chs.

If word is an empty string, return False.

If chs is an empty list, return False.

I'm passing 6/7 test cases except for one which shows an Assertion error, however, I don't know what input is being used in each test case so I can't figure out the issue. What could the issue be?

def starts_with(word, chs):
    x = 0
    if (len(chs)== 0) or (word == ""):
        return (False)
    while x < len(chs):
        s = word[0]
        if s == chs[x]: {
        }
        x += 1
        return (True)

word = ()
chs = ()
2 Answers

Try this:

def starts_with(word, chs):
        if (len(chs)== 0) or (word == ""):
            return False
        elif word[0] in chs:
            return True

an update:

def starts_with(word, chs):
    if not word: return False
    elif word[0] in chs:
        return True

Try approaching this task using the proper Python builtin functions rather than apply C/Java-style programming. It is way more readable.

Using string.startswith():

def starts_with(word, chs):
    for c in chs:
        if word.startswith(c):
            return True
    return False #you can avoid this line, it will return None by default

Another way would be to check if the first letter of word is in chs:

def f(word, chs):
    if word and chs and word[0] in chs:
        return True
    return False
Related