My task is to check the word list on doublings and output the result in a dictionary.
Firstly i was trying to execute this code:
for word in wordsList:
for letter in word:
if word[letter] == word[letter+1]:
But as long as i got a mistake, i've changed it a bit:
wordsList = ["creativity", "anna", "civic", "apology", "refer", "mistress", "rotor", "mindset"]
dictionary = {}
for word in wordsList:
for letter in range(len(word)-1):
if word[letter] == word[letter+1]:
dictionary[word] = ("This word has a doubling")
else:
dictionary[word] = ("This word has no doubling")
print(dictionary)
Now it works, but not properly. I really need suggestions! Thanks in advance
I expect the output
{creativity: 'This word has no doubling'}, {anna: 'This ward has a doubling'} etc.
wordsList = ["creativity", "anna", "civic", "apology", "refer", "mistress", "rotor", "mindset"]
dictionary = {}
for word in wordsList:
for index, char in enumerate(word[:-1]): # Take one less to prevent out of bounds
if word[index + 1] == char: # Check char with next char
dictionary[word] = True
break # The one you forgot, with the break you wouldnt override the state
else:
dictionary[word] = False
print(dictionary)
You forgot the break statement; The loop would continue and override your found conclusion.
I made my own implementation of your casus.
wordsList = ["creativity", "anna", "civic", "apology", "refer", "mistress", "rotor", "mindset"]
dictionaries = []
for word in wordsList: #for example:creativity
alphabets=[]
for x in word:
alphabets+=x #now alphabets==['c','r','e','a','t','i','v','i','t','y']
num=0
while True:
x=alphabets[0] #for example 'c'
alphabets.remove(x) #now alphabets==['r','e','a','t','i','v','i','t','y']
if x in alphabets: # if alphabets contain 'c'
doubling=True # it is doubling
break
else:
doubling=False #continue checking
if len(alphabets)==1: #if there is only one left
break #there is no doubling
if doubling:
dictionaries.append({word:"This word has a doubling"})
else:
dictionaries.append({word:"This word has no doubling"})
print(dictionaries)
Related
This may sound like a stupid question but I had to ask. The following code checks whether a word entered by the user is a palindrome or not. When I use the below code, it says "This word is a Palindrome" for all the words.
word = input("Enter a word for a Palindrome : ")
word = word.replace(" ","")
k = -1
b = False
for i in range(0,len(word)):
if word[i] == word[k]:
k-=1
b=True
else:
b=False
if b:
print("The word is a Palindrome.")
else:
print("The word is not a Palindrome.")
But when I do this small change in the next block of code, it correctly detects whether the word is palindrome or not. I got this in a trial and error basis.
word = input("Enter a word for a Palindrome : ")
word = word.replace(" ","")
k = -1
b = False
for i in range(0,len(word)):
if word[i] == word[k]:
b=True
else:
b=False
k-=1
if b:
print("The word is a Palindrome.")
else:
print("The word is not a Palindrome.")
Please help. Thanks in advance.
At the moment, some of the issue is that your "final" answer is based on the "last" test. What you really want to do is say "Not a Palindrome" as soon as you determine that and then stop.
Try:
is_a_palindrome = True
for index in range(len(word)):
if word[index] != word[- (index+1)]:
is_a_palindrome = False
break
Note as well, that this can be technically simplified to:
is_a_palindrome = word == "".join(reversed(word))
The qustion is:
given the List of strings called "string_list" which contains:
string_list = ["darpa","da","arprpa"]
you need to make a new list, called my_list, that contains all the 3 length possible strings in each word of the string_list:
my_list = ['dar', 'arp', 'rpa', 'arp', 'rpr', 'prp', 'rpa']
string_list = ["darpa","da","arprpa"]
new_list = []
for word in string_list:
if len(word) >=3:
i=0
for char in word:
if len(word[i:i+3]) == 3:
new_list.append(word[i:i+3])
i = i+1
print(new_list)
My question is:
1. did i solve it in the best efficient way? (i know its o(n^2))
2. Which code will be the most efficient and maybe the shortest for this given task.
thank you!
You can shorten it and omit if's if you only use words that are lenght 3 to begin with:
string_list = ["darpa","da","arprpa"]
# as list comp
k1 = [word[start:start+3] for word in string_list for start in range(len(word)-2)]
# written out
k2 = []
for word in string_list:
lw = len(word)
for start in range(lw-2): # eliminates words shorter then 3 automatically,
# range(0) or less is valid but does not enter the loop
k2.append(word[start:start+3]) # this also removes the manual counter
print(k1)
print(k2)
Output (identical):
['dar', 'arp', 'rpa', 'arp', 'rpr', 'prp', 'rpa']
I'm trying to get a function to put correct guesses in their blanks in a hangman program, but all it does is, whatever the guess and no matter whether it's right or wrong, it just gradually reveals the word. Where am I going wrong?
code:
while lettersrevealed!=word:
guess=getGuess(lettersrevealed)
for i in range(len(word)):
if guess in word:
blanks = blanks[:i] + word[i] + blanks[i+1:]
print(blanks)
ex:
(secret word is badger)
Guess a letter:
a
b*****
ba****
bad***
badg**
badge*
badger
Guess a letter:
OR:
Guess a letter:
h
b*****
ba****
bad***
badg**
badge*
badger
Guess a letter:
The issue is with the for loop
for i in range(len(word)): # This will run 6 times for "badger" | 0, 1, .., 5
if guess in word:
# blanks == ****** then gradually gets the next letter added replacing a *
blanks = blanks[:i] + word[i] + blanks[i+1:]
print(blanks)
You probably want something like this.
def convert_to_blanks(word, letters):
return ''.join(c if c in letters else '*' for c in word)
>>> word = 'badger'
>>> letters = set()
>>> convert_to_blanks(word, letters)
'******'
>>> letters.add('g')
>>> letters
{'g'}
>>> convert_to_blanks(word, letters)
'***g**'
And so you have a while loop prompting for letter something like this.
guessed = set()
word = 'badger'
while True:
guess = input("Guess a letter")
guessed.add(guess)
blanks = convert_to_blanks(word, guessed)
print(blanks)
if blanks == word:
break
I'm trying to create a word guessing game, after each guess the computer should return the frequency of letters in the right place, however it is this part that I have been unable to manage to get working. Can anyone help me?
import random
def guess(secret,testWord):
return (len([(x, y) for x, y in zip(secret, testWord) if x==y]))
words = ('\nSCORPION\nFLOGGING\nCROPPERS\nMIGRAINE\nFOOTNOTE\nREFINERY\nVAULTING\nVICARAGE\nPROTRACT\nDESCENTS')
Guesses = 0
print('Welcome to the Word Guessing Game \n\nYou have 4 chances to guess the word \n\nGood Luck!')
print(words)
words = words.split('\n')
WordToGuess = random.choice(words)
GameOn = True
frequencies = []
while GameOn:
currentguess = input('\nPlease Enter Your Word to Guess from the list given').upper()
Guesses += 1
print(Guesses)
correctLength = guess(WordToGuess,currentguess)
if correctLength == len(WordToGuess):
print('Congragulations, You Won!')
GameOn = False
else:
print(correctLength, '/', len(WordToGuess), 'correct')
if Guesses >= 4:
GameOn = False
print('Sorry you have lost the game. \nThe word was ' + WordToGuess)
In your guess function, you are printing the value, not returning it. Later, however, you try to assign something to correctLength. Just replace print by return, and your code should work.
Update to answer question in comments:
I think a very easy possibility (without a lot of changes to your code posted in the comment) would be to add an else clause, such that in case that the input is empty, you return directly to the start of the loop.
while GameOn:
currentguess = input('\nPlease Enter Your Word to Guess from the list given').upper()
if len(currentguess) <=0:
print('Sorry you must enter a guess')
else:
correctLength = guess(WordToGuess,currentguess)
if correctLength == len(WordToGuess):
print('statement')
GameOn = False
elif Guesses <= 0:
GameOn = False
print('statement')
else:
Guesses = Guesses -1
print('statement')
print('statment')
Here is my function:
def evilSetup():
words = setUp()
result = {}
char = input('Please enter your one letter guess: ')
for word in words:
key = ' '.join(char if c == char else '-' for c in word)
if key not in result:
result[key] = []
result[key].append(word)
return max(result.items(), key=lambda keyValue: len(keyValue[1]))
from collections import defaultdict
import random
words= evilSetup()#list of words from which to choose
won, lost = 0,0 #accumulators for games won, and lost
while True:
wrongs=0 # accumulator for wrong guesses
secretWord = words
print(secretWord) #for testing purposes
guess= len(secretWord)*'_'
print('Secret Word:' + ' '.join(guess))
while wrongs < 8 and guess != secretWord:
wrongs, guess = playRound(wrongs, guess)
won, lost = endRound(wrongs,won,lost)
if askIfMore()== 'N':
break
printStats(won, lost)
The function will take a list of words, and sort them into a dictionary based on the position of the guessed letter. As of now, it returns the key,value pair that is the largest. What I would like it to ultimately return is a random word from the biggest dictionary entry. The values as of now are in the form of a list.
For example {- - -, ['aah', 'aal', 'aas']}
Ideally I would grab a random word from this list to return. Any help is appreciated. Thanks in advance.
If you have a list lst, then you can simply do:
random_word = random.choice(lst)
to get a random entry of the list. So here, you will want something like:
return random.choice(max(result.items(), key=lambda kv: len(kv[1]))[1])
# ^^^^^^^^^^^^^^ ^^^^