dimanche 26 avril 2020

Python 3.x | How to use random.choice() or .sample() to make sure it doesn't pick the same value in a dictionary

I am a beginner in python and making an english/norwegian dictionary.
I am trying not to have the same english word come more than once when I run the program.
I know that this has been answered many times already, but I just can't get the right code for that implemented in the program.
I would appreciate very much if someone could implement the right code for that problem.
Here is the code so far:

import random
eng_nor = {'one':'en', 'two': 'to', 'three': 'tre', 'four': 'fire', 'five': 'fem', 'six': 'seks', 'seven': 'syv',
           'eight': 'åtte', 'nine': 'ni', 'ten': 'ti'}
print()
print('Number of words in the dictionary: ',len(eng_nor))
print()

eng = list(eng_nor.keys())
print('If you want to exit, type 0')
antall_gloser=int(input('How many words do you want to practice?\n '))
if antall_gloser>len(eng_nor):
    x=len(eng_nor)
    antall_gloser=x
    print('We have just ', x, ' words in the dictionary.')
point = 0

for i in range(antall_gloser):
    eng_ord = random.choice(eng)
    norsk_ord = eng_nor[eng_ord]
    user_guess = input('What is the norwegian word of %s?\n' % eng_ord)
    if user_guess == 0:
        break
    elif user_guess == norsk_ord:
        point += 1
        print('Correct! Your score is %d' % point)
    else:
        print('Wrong. The norwegian word of {} is {}.'.format(eng_ord, norsk_ord))
print('We are done. Your final score is %d, Thank you.' % point)

An example of an output I get could be like this:

D:\Users\heva\PycharmProjects\test\virtual\Scripts\python.exe D:/Users/heva/PycharmProjects/test/test10.py

Number of words in the dictionary:  10

If you want to exit, type 0
How many words do you want to practice?
 3
What is the norwegian word of two?
to
Correct! Your score is 1
What is the norwegian word of two?
to
Correct! Your score is 2
What is the norwegian word of seven?
syv
Correct! Your score is 3
We are done. Your final score is 3, Thank you.

Process finished with exit code 0

As you see in this example, two of the english words are the same....
Any help would be highly appreciated..
Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire