I was creating a wordle clone but when I enter word it doesn't do anything, help so how it works is that there is only 29 possible words and the game is suppose to tell you how many of the letters in the code are in the actual wordle.
import random
words=['about','block','chair','dream','eagle','faint','great','homes','ideas','joker','karen','latin','mouth','noise','orion','paint','queen','raven','speed','smart','tooth','truck','unite','venom','venus','where','xerox','youth','zebra']
wordlenum=random.randint(0,28)
wordle=words.pop(wordlenum)
letters1=''
for char1 in wordle:
letters1 = char1
letters2=''
correct=0
while True:
guess=input('guess:')
for char2 in guess:
letters2 =char2
for l1 in letters1:
for l2 in letters2:
if l1==l2:
correct =1
if correct == 5:
print('you win')
break
else:
print(correct)
CodePudding user response:
You have extra for loops in your code,
for l1 in letters1:
for l2 in letters2:
this part of code will execute 25 times, and will match if any of the letters in both words are same. Hence give false results, For this you can use zip method.
Also, After the failed attempt, you need to reset the correct counter and the word also needs to be reset, otherwise it is keep adding on top of the that.
Also, you would not require to explicitly add the words again to a new variable.
This
letters1=''
for char1 in wordle:
letters1 = char1
and
for char2 in guess:
letters2 =char2
are unnecessary.
After modification, here you can use.
import random
words=['about','block','chair','dream','eagle','faint','great','homes','ideas','joker','karen','latin','mouth','noise','orion','paint','queen','raven','speed','smart','tooth','truck','unite','venom','venus','where','xerox','youth','zebra']
wordlenum=random.randint(0,28)
wordle=words.pop(wordlenum)
while True:
correct = 0
guess=input('guess:')
# you can put some validations here on guess, like len(guess) == 5 and only chars
for l1, l2 in zip(wordle, guess):
if l1==l2:
correct =1
if correct == 5:
print('you win')
break
else:
print(correct)
Hope this helps.
CodePudding user response:
If you want to find out how many letters from one string occur in another string then convert the strings to sets and find the length of their intersection. For example:
s1 = 'chair'
s2 = 'train'
print(len(set.intersection(set(s1), set(s2))))
Output:
3