Python Forum
Stranger in our midst
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Stranger in our midst
#1
Exercise is as following:
Find the outsider that is hidden in a list where one word is repeated over and over.
Input
A list of n words (n>0) — each on a separate line — ending with a line that only contains the word stop. Of all n words, at least one is different from the others.
Output
If all words are equal, the text there is no outsider should appear. Otherwise, the text the outsider is "word" should appear. The word in italics is the word that is different from the rest. If the list consists of 2 different words, it is impossible to determine which of both is wrong. In this case, the text outsider can't be determined should appear.
Example
Input:
Paraguay
Egypt
Paraguay
Paraguay
Paraguay
Paraguay
Paraguay
stop
Output:

the outsider is "Egypt"
So I'm already stuck at the first half of the problem namely adding words to the list line per line. This is what I've tried:

words=[]
new_word=str(input("Enter a word\n"))
if new_word != "stop":
    words.append(new_word)
#So this code immediately stops after the new word is added, what is normal because it isn't a loop. So i tried to replace if with while so it would keep adding words till the word is stop but than the program won't even run. 
print(words)
Reply
#2
Using a while loop is the right idea. There are many ways to approach this. I personally prefer using a break to exit the loop when the stop condition is satisfied.

words = []

while True:
    new_word = input('Enter a word\n')  # str() is not needed because input() returns a string by default
    if new_word.lower() == 'stop':  # using lower() makes this comparison work for 'STOP', 'Stop', etc.
        break
    words.append(new_word)

print(words)
Reply
#3
While I prefer to do it this way:
words = []
new_word = input('Enter a word\n')
while new_word.lower() != 'stop':
    words.append(new_word)
    new_word = input('Enter a word\n')
 
print(words)
Reply
#4
This is ugly. Duplicate code that never seems to be an exact duplicate.
words = []
new_word = input('Enter a word\n')
while new_word.lower() != 'stop':
    words.append(new_word)
    new_word = input('Enter word\n')
  
print(words)
I like this a little better.
while True:
    new_word = input('Enter a word\n')
    if new_word == 'stop':
        break
    words.append(new_word)
No duplicate code, but it is slightly longer and "while True" as the "forever is only a short time" loop looks odd.

But you can combine the benefits of the two with the new "walrus" operator :=
words = []
print('Enter list of words, one per line.  End list with "stop"')
while (word := input()).lower() != 'stop':
    words.append(word)
Short. No duplicate code.

Pascal RULES!!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020