2

May I kindly ask you for help.

I must write a program in python for homewrok which it asks two competitors alternately for one single letter. The program is over when there is no such word in dictionary (I imported dictionary which it is in text format that I get from teacher).

Here is how it should look like:

Competitor 1, letter a: m

Competitor 2, letter b: o

Competitor 1, letter a: u

Competitor 2, letter b: s

Competitor 1, letter a: e

Competitor 2, letter b: i

There is no such word mousei in dictionary!

And here is how I started:

dictionary=open("dictionary.txt", encoding="latin2").read().lower().split()
a=input("Competitor 1, letter a:")
b=input("Competitor 2, letter b:")
word=a+b

while word in dictonary:
      a=input("Competitor 1, letter a:")
      word=word+a
      b=input("Competitor 2, letter b:")
      word=word+b

print("There is no such word" ,word, "in dictionary!")

But something is wrong. Because when I start program and I write first two letters. It says there is no such word in dictionary.

Please help me!

One more thing: The game must stop immediately after the first wrong character. Could you please show how to make this.

2
  • 1
    In your game, competitor 2 will always lose Commented Oct 21, 2012 at 9:16
  • The game must stop immediately after the first wrong character. Could you please show how to make this. Commented Oct 21, 2012 at 11:29

4 Answers 4

1

That's because your condition is wrong! You shouldn't check if the word is in dictionary, but if there is a word in the dictionary that starts with the word!

Here is one possible solution (maybe not the prettiest one):

word_ok = True
dictionary=open("dictionary.txt", encoding="latin2").read().lower().split()
a=raw_input("Competitor 1, letter a:")
b=raw_input("Competitor 2, letter b:")
word=a+b

while word_ok:
        word_ok = False
        for dict_word in dictionary:
            if dict_word.startswith(word):
                word_ok = True
                break
        if word_ok:                                
            a=raw_input("Competitor 1, letter a:")
            word=word+a
            b=raw_input("Competitor 2, letter b:")
            word=word+b
        else:
            break

print("There is no such word" ,word, "in dictionary!")

EDIT:

OK, here is a kind of compilation from the other answers. Note that encoding is not a valid keyword parameter to the builtin open() function. If you want to specify the encoding, use codecs.open(). Note as well that the word check is done twice within the while loop, after each competitor's input.

import codecs

dictionary = codecs.open('dictionary.txt','r',encoding='latin2').read().lower().split()

# Word we will build
word = ''

while True:
    letter = raw_input("C1: ")
    word = word + letter
    if not any(known_word.startswith(word) for known_word in dictionary):
        break

    letter = raw_input("C2: ")
    word = word + letter
    if not any(known_word.startswith(word) for known_word in dictionary):
        break

print "There is no such word", word, "in dictionary!"
Sign up to request clarification or add additional context in comments.

6 Comments

Yes. but how can I do that? Could you write me the right condition?
Look at halex's answer. It's more readable. Basically it says: If any of the word in the dictionary starts with the input word, game should continue, otherwise end the game
Also you should make clear if the game must stop immediately after the first wrong character, or it should let the second competitor play its turn. In the first case, the condition is to be checked after each competitor's input!! (This means two checks in one loop iteration!)
Could you please show how to make this. Because the game must stop immediately after the first wrong character.
"Note that encoding is not a valid keyword parameter to the builtin open() function." It is in Python 3, which is what the OP must be using if the code ran.
|
1

You have to change the condition of your while. The way you do it you check whether word is inside dictionary as a single word and not part of a word as you want it. You can do it the following way:

while any(x.startswith(word) for x in dictionary): 

This way you make a list of boolean values where every element is True if the word in the dictionary at the same position starts with your word. If any of the dictionary's words start with word the condition will be true and the players should input another characters.

2 Comments

That's much more readable as a generator: while any(x.startswith(word) for x in dictionary):
@Eric Thank you for pointing that out :) I edited the answer. I sometimes have a barricade in my brain beacause my first idea is to use map although listcomprehension is way better.
1

Since this is for a class, I'm assuming it has to be somewhat simple. Here is a super basic example of how it could work using a function (not sure if these have been covered in your class or not, so disregard if not):

def CheckWord(word, dictionary):
    # Check if any words in your dictionary start with the current word
    for term in dictionary:
        if term.startswith(word):
            return True
    return False

# Basic dictionary
dictionary = ['mouse', 'louse']

# Word we will build
word = ''

# Keep the loop going until we get a False from our function, at which point it stops
while True:
    a = raw_input("C1: ")
    word += a
    b = raw_input("C2: ")
    word += b

    # Check the current word with our function
    match = CheckWord(word, dictionary)

    # If the function returns False, quit
    if not match:
        print ("There is no such word", word, "in dictionary!")
        break

3 Comments

Pro-tip: python comments are #
@Eric Haha, man, that was a bit embarrassing. I was like 'Why is this looking funny?'. Must be time for bed :)
The game must stop immediately after the first wrong character. Could you please show how to make this.
1

Your rules are inconsistent. Consider this game:

 s      # Not a word
 su     # Not a word
 sun    # Word
 sund   # Not a word
 sunda  # Not a word
 sunday # Word

When should the game end?

The program is over when there is no such word in dictionary

Your rules say it should end on the first move, since the result is not a word. A better rule would be:

The program is over when there are no words in dictionary starting with the input


The implementation of "asking two competitors alternately" is also wrong. Your program asks both competitors for a letter, then checks the word. You want to check the word in between players.

dictionary = open("dictionary.txt", encoding="latin2").read().lower().split()
word = ""
c1turn = True

while any(knownword.startswith(word) for knownword in dictonary):
    if c1turn:
        letter = input("Competitor 1:")
    else:
        letter = input("Competitor 2:")

    word = word + letter
    c1turn = not c1turn

print("There is no such word", word, "in the dictionary!")

1 Comment

Thank you very much. Your solution is the most simple

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.