I am comfused with how to tackle this, I have done the first few parts by opening the file, converting it to a list and completing the first prompt but now I dont really understand how to do this. The prompt for this part is:
All Words that Have a User Chosen Letter in a Specified Location
This task builds on the first task, but instead of the letter appearing anywhere in the word, you need to output every word that has the letter in a very specific location. The user provides a single letter, and what location in the word it appears in. Make sure you give clear instructions to the user on how to denote the letter location (is the first letter 0? 1? something else? They won't know what your program expects unless you tell them).
All Words that Have a User Specified Number of Vowels
Supposedly the best way to play Wordle is to use a word with lots of vowels as your first guess. For this task you will let the user choose how many vowels they want in their word, and then output all words that have that number of vowels. This task is the hardest of the required tasks, so think about it after you've reasoned through the others. Recall that vowels in English are the letters a, e, i, o, and u.
import os.path
def name_file():
# asking user name of file
file_name = input("What is the name of the file to read the names from?")
while not os.path.exists(file_name):
print("This file does not exist")
file_name = input("What is the name of the file to read the names from?")
return file_name
name_file()
file_opener = open("5letterwords.txt","r")
read_line_by_line = file_opener.readlines()
word_list = []
for line in read_line_by_line:
word_list.append(line.strip())
print(word_list)
letter = input("Pick a letter of your choosing and every word with that letter will be outputted:")
for word in word_list:
if letter in word:
print(word)
letter2 = input("Pick another letter and every word with that letter will be outputted")
location = input("Pick what location you want the letter to be in from 1-5")
for word in word_list:
if letter2 in word and :
I currently have that done and starting from the variable letter 2 is where I start wrking on the prompt but I am clueless as to what to do. I would like some hints and tips on how to do this, i've been working on it for almost 3 weeks now and not much progress
I think there are three steps to your second task:
Get the input letter and index.
Iterate over the list of words.
Check each word to see if the letter is in the desired index and print the word if so.
You have part of number 1 and all of number 2 handled already.
To finish the first step, you need to convert your location value, which is a numeric string, into an integer and make sure it matches the zero-indexing of Python strings.
For the third step, you need to index your each word string with the converted index value you got from the user. You might want some error handling here, to correctly report invalid indexes, but since that isn't specifically called out in your requirements something minimal might serve (e.g. print an error message and quit). The comparison of the indexed letter to the input letter should be trivial after that.
Related
displayed_word = ["-"*length]
#how do you write the guess in the designated spot in hangman?? and to replace the "-" ]
designated_spot = s.find(guess)
how_many = s.count(guess)
print(f"the word had {how_many} of your guess in it")
print(designated_spot)
newletter = s.replace(guess, designated_spot)
print(newletter)
I know a did a lot wrong here but i dont know what to do and how to write it.
I tried to do replace but i realised you couldnt use an integer and the integer is designated_spot and fhsdjkfsh
also s is the random.choice of my list
So I am trying to replace a user input aka "guess" in the designated spot where the guess fits in the random choice that python has generated from a list. As in change the "-" in its designated spot with the letter that the user guessed when the letter that is guessed is in the random word that the computer has generated.
I think what you're looking for is something like this:
word = "apple" # example output from your list
displayed_word = "-"*len(word) # make a string the same length of the word that shows guessed letters
def make_guess(s: str, guess: str, displayed_word: str) -> str:
# convert the displayed word to a list so that it is mutable (allows us to change characters)
displayed_word = list(displayed_word)
# loop through the string you are guessing, s, one character at a time.
for i, letter in enumerate(s):
if letter == guess: # if the current letter in s matches the guess, reveal that letter.
displayed_word[i] = letter
return "".join(displayed_word) # finally convert the displayed word back into a string.
displayed_word = make_guess(word, "p", displayed_word)
print(displayed_word) # outputs: "-pp--"
displayed_word = make_guess(word, "e", displayed_word)
print(displayed_word) # outputs: "-pp-e"
Check the documentation for replace for information about how to use str.replace, as it doesn't replace characters at a specific index as you might have misunderstood, I hope this helps.
I have a python program that I am trying to create where the user can input a letter and the program filters out all the words that do not begin with this letter. Unfortunately me and my beginner brain cannot figure out how to write this in code, so any help?
The code I have already:
#Open list of words file and add to "content" variable
content = open('Word List').read().splitlines()
#Take the first character of every word and make a new variable to add that to.
firstchar = [x[0] for x in content]
#Ask the user which letter they'd like to use
print("Which letter would you like to use?")
u_selected = input("> ")
Not very much as you can see, but I'm proud of it. I figure I need something that uses firstchar[i] and u_selected to match the two letters together.
As you've done, you can use [0] to access the first character of a string. The below will add each word to a new list for you if it matches the condition specified.
chosen_words = [word for word in content if word.lower()[0] == u_selected.lower()]
The .lower() is to just to convert everything to lower case, to make sure case is ignored
Strings have there own methods to make things easier with strings.
dir(str)
You can test the beginning of a string with .startswith(). For example,
words = open('Word List').read().splitlines()
new_words = [word for word in words if word.startswith('A')]
To filter that you need to do:
#Open list of words file and add to "content" variable
content = open('Word List').read().splitlines()
#Ask the user which letter they'd like to use
print("Which letter would you like to use?")
u_selected = input("> ")
filtered_words = [word for word in content if word.startswith(u_selected)
I trying to convert my code using function. As this coding is not done yet but i manage to get the code running well. The only thing is every time i guess a letter, it reset my previous record. How to i store my previous guess result and continue add if the letter is guessed correctly?
import random
def chooseAword(wordList):
correct_word = random.choice(wordList)
return correct_word
#def spelltheword(word)
def guessAletter(guessedletter):
word = guessedletter
guess = input('Guess a letter: ')
letter = ''.join(x if x in guess else '-' for x in word)
if guess in word:
print("So far you have: ", letter)
else:
print("So far you have: ", letter)
return letter
def playAgame(wordList):
word = chooseAword(wordList)
for n in range(5):
guessletter = guessAletter(word)
def main():
wordList = ('python', 'csharp','java','oracle')
playAgame(wordList)
main()
No, it doesn't reset your previous record: you have no previous record. Every call to guessAletter very specifically puts a hyphen in any position that is not the currently guessed letter.
Yes, you return the word (which you named letter, for some reason) of hyphens and correct letters, but the calling program playAgame puts this into a local variable guessletter (another misleading name), and then never uses it again.
I have several suggestions:
Practice incremental programming. Write a few lines of code to perform a trivial part of your program. Debug them. Do not continue until you know they do what you want, through testing several possibilities. Then write a few more lines; repeat this process until your program works.
Use meaningful variable names. word doesn't tell us much; we don't know whether this is the word we're supposed to guess, the current game progress you show the user, or something else. At the worst, you use guessedLetter for something that is not a single letter, and is not a guess.
With the incremental programming, follow the status of your game state: this should be one value passed back and forth with your guess-and-check function. You update it in that function, and print it in the guess-a-letter loop.
I decided to write a little application in python to help me learn to type using the dvorak keyboard layout. In my algorithms class, we discussed trees, and tries, and implemented an autocomplete function.
I grabbed a word list from this site. Then I loaded all the words in it into a trie, (which surprisingly only took about a third of a second) and now I am trying to figure out how to make words that are relevant.
I currently am maintaining a priority queue to keep track of which letters the user is typing wrongly the most, and so I remove say 3 letters from this queue to start. If I wanted all the words that started with each of these letters, I could do this, and then probably just filter out all words that don't have any of the other letters that the user types wrongly the most.
is it possible to efficiently (or maybe even not efficiently) get a list of all words with the letters from the priority queue in them, and then filter out so that I get the word that will be the biggest challenge to the typer?
I was able to do this with characters, but the words present an interesting challenge, because the nature of the trie only gets words that have prefixes that start with the letters we have in the queue.
Do you need a trie here at all? I think you either don't need any advanced structure, or you need something else.
How much words do you want to process? If it takes only a third of a second to load them to a trie, then it will take not much longer to just go through all of them and chose whatever you want. You will have to do this every time, but if it's just 1/3 of a second, it will not be a problem.
You could re-calculate the TRIE to hold all the sub strings (on top of the real words themselves) as well, where the end of the sub string points to the real word in the TRIE.
This way you can use the code you already have and apply it to sub strings.
Okay. The solution I came up with combined #shapiro-yaacov's answer with code I wrote.
I scrapped the trie, and used a thing with bins for each letter. Each word is put into a bin for each letter, and then the algorithm adds up letters to find which words have the most wanted letters. I also take a 10th of a point away from words for each letter that I don't want, to encourage my program to give reasonable words, because if I simply were to add up all words with the most letters, I would get huge words.
Here is my Words.py:
import string
import random
import operator
class Bin:
"""
A bin is a container that stores words given in a dictionary file.
It is designed to retrieve all words in this file with the given letters.
The words are stored in this container in an array and when new words get added,
the container automatically adds the word to the words list,
and places them into as many bins as need be.
For example,
>>> bin=Bin("words.txt") #get all words from bin.txt
>>>bin.addWord("about")
now, the bins for a, b, o, u, t will have a pointer to "about".
Now immagine the bin has the words "king", "fish", and "dish" in it.
>>> d=bin.getWordWithLetters("sh")
>>> print d
["fish", "dish"]
"""
def __init__(self, wordsFile):
"""initialize the container from the given file,
if None, just initialize an empty container.
"""
self.bins={}
for i in string.ascii_lowercase+".'&": #these are the letters I need.
self.bins[i]=[] #initialize an empty list for each bin.
if wordsFile == None:
return
with open(wordsFile) as words:
for i in words:
self.addWord(i.strip("\n"))
def addWord(self, word):
for i in word:
self.bins[i].append(word) #add the word to the bin for each letter in that word.
def getWordsWithLetters(self, lrs):
"""Gets best word that has the letters lrs in it.
For example, if abcdef is given, and the words [has, babe, shame] are there,
[babe] would be returned because it is the word with the maximum return,
since it contains b,a,e."""
words=[]
for i in lrs:
words+=self.bins[i]
#Now we go through the words, and calculate the score of each word.
#a score is calculated by adding up the number of times a letter from lrs appears in each word.
# Then we will subtract out the number of
for index, item in enumerate(words):
score=random.randint(0,10) #give some randomness for the typing thing.
#print(score)
#score = 0 #to make it deterministic.
base=score
itCounts={}
for i in lrs:
itCounts[i]=False
for letter in item:
if letter in lrs and (not itCounts[letter]):
score+=1
itCounts[letter]= True
else:
score-=.1
words[index] = (item, score)
words = sorted(words, key=operator.itemgetter(1), reverse=True)
w=[]
for i in words:
if i[1] > base:
w.append(i[0])
return w[:50]
I've just started to learn Python and I'm creating the game Hangman. I've got the basic functionality down. I have a list containing the words and they're randomly selected. I have an input for the user to guess letters and check it against the list that the word is split into, I have another list that the correctly guessed letters are put into at the position they are in the randomly selected word.
The problem I am having is that if the word has a letter within it more than once, it will only find the first letter and add that. How would I go about looking for all instances of a letter and adding them?
This is the code I'm using to map guessed letters against the randomly selected word.
if user_input in choose_word:
print "Good guess!"
print trys_remaining, "trys remaining!"
word_index = letter_list.index(user_input)
correct_letters[word_index] = user_input
If anyone could point me in the right direction, it would be great.
You need to loop over all matching indices:
for word_index, letter in enumerate(letter_list):
if letter == user_input:
correct_letters[word_index] = user_input
Note: If the loop would be for letter in letter_list: you would only iterate over letters but won't get the corresponding index. The enumerate() function allows to get the index at the same time.
See also the enumerate documentation.
You can use a list comprehension:
correct_letters = [letter if user_input == letter else correct
for (correct, letter) in zip(correct_letters, letter_list)]
Note that this will create a new correct_letters list, instead
of modifying the original one.