0

A simple question, that I've actually had a hard time finding a solution to, as most suggest using the much easier to work with, for loop.

I have an assignment that tells me explicitly to use the while loop to return either true or false, based on if a string occurs in a list.

My current solution (which works) is as follows:

def word_in_list(word, words):
x=0
length = int(len(words)) -1

while words[x] != word and x < length:
    x = x+1

    if words[x] == word:
        print (True)

    elif x == length and words[x] != word:
        print (False)

My biggest issue has been limiting the function to the length of the list, otherwise I get an error stating "list index out of range".

However, as this is a rather clunky way of doing something so simple, I'm looking for suggestions on how to streamline it a little - if there's a way that is. And as stated, the for-loop, that you'd normally use, is not an option.

2 Answers 2

2

here is something that runs a bit more efficiently. Each iteration checks two indices, rather than one.

def word_in_list(word, words):
    l, r = 0, len(words) - 1
    while l <= r:
        if words[l] == word or words[r] == word:
            return True
        l += 1
        r -= 1
    return False

Hope that helps!

Sign up to request clarification or add additional context in comments.

Comments

1

Fixed a small error and cleaned up a little, but as a simple exercise requiring the use of while the algorithm fundamentally looks fine.

def word_in_list(word, words):

    x = 0
    length = len(words) - 1

    while x < length:

        if words[x] == word:
            return True

        elif x == length:
            return False

        x += 1

word_in_list('hello', ['now', 'this', 'hello', 'world'])   # True
word_in_list('hello2', ['now', 'this', 'hello', 'world'])  # False

2 Comments

Using words[x] != word in elif after if words[x] == word: seems redundant.
Thank you! This do indeed look much better, however it's a small mistake in your example, as you add -1 in two places, which equals -2, missed it as well initially, but now it works great! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.