I'm trying to make a word guessing program and I'm having trouble printing parallel tuples. I need to print the "secret word" with the corresponding hint, but the code that I wrote doesn't work. I can't figure out where I'm going wrong.
Any help would be appreciated :)
This is my code so far:
import random
Words = ("wallet","canine")
Hints = ("Portable money holder","Man's best friend")
vowels = "aeiouy"
secret_word = random.choice(Words)
new_word = ""
for letter in secret_word:
if letter in vowels:
new_word += '_'
else:
new_word += letter
maxIndex = len(Words)
for i in range(1):
random_int = random.randrange(maxIndex)
print(new_word,"\t\t\t",Hints[random_int])
The issue here is that random_int is, as defined, random. As a result you'll randomly get the right result sometimes.
A quick fix is by using the tuple.index method, get the index of the element inside the tuple Words and then use that index on Hints to get the corresponding word, your print statement looking like:
print(new_word,"\t\t\t",Hints[Words.index(secret_word)])
This does the trick but is clunky. Python has a data structure called a dictionary with which you can map one value to another. This could make your life easier in the long run. To create a dictionary from the two tuples we can zip them together:
mapping = dict(zip(Words, Hints))
and create a structure that looks like:
{'canine': "Man's best friend", 'wallet': 'Portable money holder'}
This helps.
Another detail you could fix is in how you create the new_word; instead of looping you can use a comprehension to create the respective letters and then join these on the empty string "" to create the resulting string:
new_word = "".join("_" if letter in vowels else letter for letter in secret_word)
with exactly the same effect. Now, since you also have the dictionary mapping, getting the respective hint is easy, just supply the key new_word to mapping and it'll return the key.
A revised version of your code looks like this:
import random
Words = ("wallet", "canine")
Hints = ("Portable money holder", "Man's best friend")
mapping = dict(zip(Words, Hints))
vowels = "aeiouy"
secret_word = random.choice(Words)
new_word = "".join("_" if letter in vowels else letter for letter in secret_word)
print(new_word,"\t\t\t", d[secret_word])
Related
I am struggling with this project that I am working on.
Edit: I want the program to find 2 words from the dictionary that are the anagram of the input word(s). The way I wanted to approach this program is by using counter(input()) and then looping through the dictionary content twice (finding first word anagram then the next). The loop would take every word from the dictionary, counter(that word) and see if it is <= counter(input word). Once the program finds first anagram, it adds that word to candidate and proceeds to second loop to find the second word.
To put to simple words, if I input a word (or a phrase), I would like the program to run through a dictionary text file (which I have saved) and find two words from the dictionary that becomes anagram to my input. For instance, if I input "dormitory" the program output should be "dirty room" and if input "a gentleman", output "elegant man". Here is what I have done so far:
from pathlib import Path
from collections import Counter
my_dictionary = open(Path.home() / 'dictionary.txt')
my_words = my_dictionary.read().strip().split('\n')
my_dictionary.close()
letter_number = 0
my_word = []
print('Please type in your phrase:')
word = input()
word = word.replace(" ","")
word_map = Counter(word.lower())
for a_word in my_words:
test = ''
candidate = ''
test_word = Counter(a_word.lower())
for letter in test_word:
if test_word[letter] <= word_map[letter]:
test += letter
if Counter(test) == test_word:
candidate += a_word.lower()
for a_word in my_words:
test = ''
test_word = Counter(a_word.lower())
for letter in test_word:
if test_word[letter] <= word_map[letter]:
test += letter
if Counter(test) == test_word:
candidate += a_word.lower()
if Counter(candidate) == word_map:
my_word.append(candidate)
print(my_word)
For some reason I am getting nothing from the output.
I cannot get any result after I put my input.
I also have tried to use del. command for getting rid of the word counter of first word from dictionary then proceed to find a second word from the dictionary but that didn't work either.
In summary, there must be some wrong place in the codes that flaws the program to not give any output.
Please help me figure out my mistake and error.
Thanks in advance.
Code can be optimized as follows:
# script.py
from pathlib import Path
from collections import Counter
filename = 'dictionary.txt'
my_words = Path.home().joinpath(filename).read_text().strip().splitlines()
word = input('Please type in your phrase:\n').replace(" ","")
word_counter = Counter(word.lower())
def parse(my_words=my_words):
matches = []
for a_word in my_words:
a_word_counter = Counter(a_word.lower())
if all(c <= word_counter[w] for c in a_word_counter.values()):
matches.append(a_word)
return matches
def exactly_parse(my_words=my_words):
return [w for w in my_words if Counter(w) == word_counter]
my_word = parse()
print(my_word)
Let's say content of dictionary.txt:
$ cat dictionary.txt
how
are
you
fine
thanks
input word is how
What's the expected output? how
$ python script.py
Please type in your phrase:
how
['how']
$ python script.py
Please type in your phrase:
thanksyou
['you', 'thanks']
I wish to write a hangman program and in order to do so, I have to replace the hash ('-') letter(s) with the user's guessed letter (guess). But when I run the code, it replaces all the hashes with the user's guess letter.
The code seems okay but I don't get the desired result.
words is a list of words I have written before the function.
def word_guess():
random.shuffle(words)
word = words[0]
words.pop(0)
print(word)
l_count = 0
for letter in word:
l_count += 1
# the hidden words are shown a '-'
blank = '-' * l_count
print(blank)
guess = input("please guess a letter ")
if guess in word:
# a list of the position of all the specified letters in the word
a = [i for i, letter in enumerate(word) if letter == guess]
for num in a:
blank_reformed = blank.replace(blank[num], guess)
print(blank_reformed)
word_guess()
e.g: when the word is 'funny', and guess is 'n', the output is 'nnnnn'.
How should I replace the desired hash string with guess letter?
it replaces all the hashes
This is exactly what blank.replace is supposed to do, though.
What you should do is replace that single character of the string. Since strings are immutable, you can't really do this. However, lists of strings are mutable, so you could do blank = ['-'] * l_count, which would be a list of dashes, and then modify blank[num]:
for num in a:
blank[num] = guess
print(blank)
A couple things to note:
inefficient/un-pythonic pop operation (see this)
l_count is just len(word)
un-pythonic, unreadable replacement
Instead, here's a better implementation:
def word_guess() -> str:
random.shuffle(words)
word = words.pop()
guess = input()
out = ''
for char in word:
if char == guess:
out.append(char)
else:
out.append('-')
return out
If you don't plan to use the locations of the correct guess later on, then you can simplify the last section of code:
word = 'hangman'
blank = '-------'
guess = 'a'
if guess in word:
blank_reformed = ''.join(guess if word[i] == guess else blank[i] for i in range(len(word)))
blank_reformed
'-a---a-'
(You still have some work to do make the overall game work...)
Hello I'm new to programming and have been teaching myself Python through various means for the past year.I have been lurking here for a while and have gotten a lot of help but now i have a specific problem:
Im working on a word scramble game and i ran into a snag.
Python 3.x code
def scrambler(word):
word_to_scramble = list(word)
random.shuffle(word_to_scramble)
new_word = ''.join(word_to_scramble)
return new_word
Now the code above works as desired, but occasionally it will return the original word i fed into the scrambler function.
My question is: Is there a way to ensure that the string returned is always different than the one given.
I attempted to use the scrambler function inside itself with a while loop, which would crash the script and give me an error stating the recursion limit had been reached.
Any help would be greatly appreciated.
If you're hitting the recursion limit, then it's likely that you're trying to scramble a 1-character word. However, it's quite easy to remove the recursion in this problem ...:
def _scrambler(word):
word_to_scramble = list(word)
random.shuffle(word_to_scramble)
new_word = ''.join(word_to_scramble)
return new_word
def scrambler(word):
new_word = _scrambler(word)
while new_word == word and len(word) > 1:
new_word = _scrambler(word)
return new_word
I've added a len(word) > 1 check so this should eventually give you a different word than what you put in if it is possible to do so.
hope you enjoy with programming Chris.
well if u test like this...
from random import shuffle
word='test'
def scrambler(word):
word_to_scramble = list(word)
shuffle(word_to_scramble)
new_word = ''.join(word_to_scramble)
return new_word
print(scrambler(word))
u will get the word test in ~ <25th try as i did ...(cant be sure because its not realy random)
so u can just put some if statement in your function. and if new_world is same as word u can just recall the function again... and it doesn't need any loop. its like some recursive base function.
something like this...
enter code here
from random import shuffle
word = 'test'
def scrambler(word):
word_to_scramble = list(word)
shuffle(word_to_scramble)
new_word = ''.join(word_to_scramble)
#print (new_word) if u want to check what is going on ...
if new_word == word:
scrambler(word)
elif new_word != word:
return new_word
print(new_word)
scrambler(word)
the question asks to have to user enter a one word string, then randomize the place of the letters in the word, for example, "hello" can turn into "elhlo"
import random
def word_jumble():
word = raw_input("Enter a word: ")
new_word = ""
for ch in range(len(word)):
r = random.randint(0,len(word)-1)
new_word += word[r]
word = word.replace(word[r],"",1)
print new_word
def main():
word_jumble()
main()
I got the program from someone else, but have no idea how it works. can someone explain to me please? I understand everything before
new_word += word[r]
The code is unnecessarily complex, maybe this will be easier to understand:
import random
word = raw_input("Enter a word: ")
charlst = list(word) # convert the string into a list of characters
random.shuffle(charlst) # shuffle the list of characters randomly
new_word = ''.join(charlst) # convert the list of characters back into a string
r is a randomly selected index in the word, so word[r] is a randomly selected character in the word. What the code does is it selects a random character from word and appends it to new_word (new_word += word[r]). The next line removes the character from the original word.
If you use a bytearray, you can use random.shuffle directly
import random
word = bytearray(raw_input("Enter a word: "))
random.shuffle(word)
Below is some code from a game I am creating which scrambles the letters of a random word for a player to guess. I was wondering why when I put my letter variable (which assigns a random letter from one of the words in my word bank to the variable letter) above my while word: statement there is a string index error but if I put the same variable in the while word: statement there is no error.
I know that in the string koala, for example, k is 0 and a is 4. Why would that change within the while statement? Or is there something else going on?
This works:
while word:
letter = random.randrange(len(word))
scrambled_word += word[letter]
word = word[:letter] + word[(letter+1):]
This does not work:
scrambled_word = ''
letter = random.randrange(len(word))
while word:
scrambled_word += word[letter]
word = word[:letter] + word[(letter+1):]
Why?
With each iteration of
while word:
scrambled_word += word[letter]
word = word[:letter] + word[(letter+1):]
word is shortened by one letter:
>>> "koala"[:3]
'koa'
>>> "koala"[4:]
'a'
so eventually word[letter] will try to access a letter that's no longer there.
If you want to scramble a word, there's a built-in function for that, though:
>>> word = "koala"
>>> l = list(word)
>>> random.shuffle(l)
>>> word = "".join(l)
>>> word
'oklaa'
(taking a detour via a list object because strings themselves are immutable and can't be shuffled directly).
I'm not a python programmer, but this is probably wrong:
word = word[:letter] + word[(letter+1):]
You need to check if the letter is the last one, otherwise word[(letter+1):] is out of bound.