I'm writing a Hangman Program, and I'm basically done, I'm just stuck on one part. So you have to detect repetition in your input, i got that part done, but then i messes up with words that have the same letter in it.
For Example:
The Word is apple:
when I input a, it says well done, the letter is in the word and prints a----
but when I input p, it says well done as well but only prints the first p, so the output looks like this ap---
but i want it to detect all p in the word, for example : app--
here are my codes for that part:
def getGuessedWord():
position = word.index(letter.lower())
global words
words = words[:position] + letter.lower() + words[position+1:]
print(words)
return words
You need to find all the positions of the letter in your word!
Iterate through your word(enumerate function returns the list of index and value) and check if the value is the letter your are searching for!
Then
modify your words string!
That is
def getGuessedWord(letter,words,word):
for position, ltr in enumerate(word):
if ltr == letter:
words = words[:position] + letter.lower() + words[position+1:]
print(words)
return words
word='apple'
words='-'*len(word)
while '-' in words:
words = getGuessedWord(raw_input('Enter a letter : '),words,word)
Output:
Enter a letter : l
---l-
Enter a letter : e
---le
Enter a letter : a
a--le
Enter a letter : p
apple
Hope it helps!
Given, for example:
letter = 'p'
word = 'apple'
With this list comprehension:
[x==letter for x in word]
You can detect where is a certain letter is, if it is at all, in this example it would return:
[False, True, True, False, False]
Which corresponds with the fact that only the second and third letters in apple are "p".
Because True is 1 in Python, the same happens with 0 and False. So, if you want a numeric value you can just sum the values in the list, by doing:
sum([x==letter for x in word])
You could try this to verify the previous statement:
>>> True == 1
True
>>> False == 0
True
For a more detailed/specific answer, I'll need more information about how it is implemented.
Related
For an assignment, I needed to make a program that counts the vowels and consonants in a string using for i in range(0, len(str)):
I put this program together using what I learned, but I can't really wrap my head around why it works.
vowelCount = 0
consonantCount = 0
sentence = input("Enter your sentence: ")
for char in range(0, len(sentence)):
if sentence[char] in "aeiouAEIOU":
vowelCount += 1
if sentence[char] in "bcdfghjklmnpqrstvwxyBCDFGHJKLMNPQRSTVWXYZ":
consonantCount += 1
print("There are", vowelCount, "vowels")
print("There are", consonantCount, "consonants")
Why am I getting the range of the length of the sentence?
Here's an alternative program I wrote without the range.
vowelCount = 0
consonantCount = 0
sentence = input("Enter your sentence: ")
for i in sentence:
if i in "aeiouAEIOU":
vowelCount += 1
if i in "bcdfghjklmnpqrstvwxyBCDFGHJKLMNPQRSTVWXYZ":
consonantCount += 1
print("There are", vowelCount, "vowels")
print("There are", consonantCount, "consonants")
Why do I need to use sentence[char] in the range version? Why the brackets?
Your program is going through sentence one letter at a time. For each letter (retreived by sentence[char]) it checks whether it is in the list of vowels (if yes, increment vowelCount) or in the list of consonants (if yes, increment consonantCount).
The form a in b for strings a and b checks whether a is contained somewhere as exact substring in b. So if a is just a single letter, it checks whether b contains the letter a anywhere.
I suspect part of your confusion might arise because of the word "char." In the following code snippet, range(0, len(sentence)) generates numerical values. Thus, char is an index.
for char in range(0, len(sentence))
In other words, on the first iteration through the loop sentence[char] really looks something like sentence[0], or the first character in the sentence. If this character is in the string "aeiouAEIOU", the the boolean conditional in the loop returns TRUE
Note that if sentence[char] in "aeiouAEIOU" could be re-written like
if sentence[char] in set(['a','e','i','o','u','A','E','I','O','U'])
First: "aeiouAEIOU" is a string, which can also be seen as a List of characters in this context.
So ['a', 'e', 'i', 'o'....'U'] is equivalent to this string representation above.
Second: The in operator in python checks if the element on the left side is "in" the list on the right side. So for example
1 in [1,2,3] would return TRUE while 10 in [1,2,3] would return FALSE. Or for characters, 'o' in "Foobar" would return TRUE while 'c' in "Foobar" would return FALSE
The rest is just (pseudocode) IF ... THEN increase a number, so you basically loop through every character of a sentence and increase two variables if the character is in the list of vovels or in the list of consonants. After the loop is finished, you present the final counts.
I am looking for a way to store the position integer of a character into a variable, but now I'm using a way I used in Delphi 2010, which is not right, according to Jupyter Notebook
This is my code I have this far:
def animal_crackers(text):
for index in text:
if index==' ':
if text[0] == text[pos(index)+1]:
return True
else:
return False
else:
pass
The aim, is to get two words (word + space + word) and if the beginning letters, of both words, match, then it has to show True, otherwise it shows False
For getting the index of a letter in a string (as the title asks), just use str.index(), or str.find() if you don't want an error to be raised if the letter/substring could not be found:
>>> text = 'seal sheep'
>>> text.index(' ')
4
However for your program, you do not need to use str.index if you want to identify the first and second word. Instead, use str.split() to break up a given text into a list of substrings:
>>> words = text.split() # With no arguments, splits words by whitespace
>>> words
['seal', 'sheep']
Then, you can take the letter of the first word and check if the second word begins with the same letter:
# For readability, you can assign the two words into their own variables
>>> first_word, second_word = words[0], words[1]
>>> first_word[0] == second_word[0]
True
Combined into a function, it may look like this:
def animal_crackers(text):
words = text.split()
first_word, second_word = words[0], words[1]
return first_word[0] == second_word[0]
Assuming that text is a single line containing two words:
def animal_crackers(text):
words = text.split()
if len(words)== 1:
break # we only have one word!
# here, the .lower() is only necessary is the program is NOT case-sensitive
# if you do care about the case of the letter, remove them
if word[0].lower() == words[1][0].lower():
return True
else:
return false
I am currently programming the Caesar Cipher.
I created a list of the alphabets
It simply asks for a sentence
Gets the index position of each letter in the sentence in corresponding to the alphabet list,
Adds the offset onto each offset using a while loop, creating a new index
Prints out the corresponding alphabet list index with new index which makes a coded word.
Therefore creating a coded sentence
The problem is that the alphabet list does not contain spaces, so I get an error when I try to make a sentence (because it is separated by spaces), only single words/letters work...
CODE HERE:
#Creating Lists
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
#Unpickling Dictionary
unpickle_codedwords = open("CWs.txt", "rb")
codedwords = pickle.load(unpickle_codedwords)
unpickle_codedwords.close()
###############################################################
""" #
IMPROVMENTS: #
Spaces/Sentences dont work <-- bob is a boy (ERROR) #
""" #
###############################################################
loop = 0#Using this to make my program loop continously
while loop == 0:
choice=int(input("What would you like to do?\n1)Code a word\n2)Decode a word\n3)Print the coded words list\n4)Quit the program\n5)Clear Coded Words List\n>>>"))#Asking for choice from user
if choice ==1:#If the choice selected was 1:
word=input("Enter the word you want to code\n>>>")
offset=int(input("Enter the offset below\n>>>"))
if word.isalpha() ==True:#checking alphabet only
for letter in word.lower(): # getting index of everysingle letter and converting it to lowercase
index=alphabet.index(letter)
index=index+offset#adding the index to the offset to create new index
while index>25:#if index is more than 25 i have to while loop it
index=index-26#creatingn the new index
codedwords.append([alphabet[index]])#appending each letter to word
#print(alphabet[index])<-- REMOVE LATER
answer = [''.join([x[0] for x in codedwords])] #instead of print(codedwords) because that prints[i],[i],[i] not iii
print(answer)
while word.isalpha()==False:#if word is not alphabeticals
print("Invalid Entry!, Please Try again\n")#loop it around again untill it's correct
word=input("Enter the word you want to code\n>>>")
if word.isalpha()==True:#looping round untill correct
for letter in word.lower():
index=alphabet.index(letter)
index=index+offset#Repeated again as above
while index>25:
index=index-26
codedwords.append([alphabet[index]])
answer = [''.join([x[0] for x in codedwords])]
print(answer)
You can use all to check if all letters in user input (word) are alpahanumeric or spaces:
while all(True if letter in alphabet + [' '] else False for letter in word):
>>> all([True, True])
True
>>> all([True, False])
False
>>>
After that:
for letter in word:
if letter == ' ':
codedwords.append([letter])
else:
# Code the letter
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.
I would like to compare the input letters(dictionary) with the list(textfile with words) and print the words matching the inputed letters. What have I done wrong?(I know i only have a print YES or NO-function if it finds a matching word at the moment. What's the best way to create this function by the way?).
def ordlista(list):
fil = open("ord.txt", "r")
words = fil.readlines()
list = []
for w in words:
w = w.strip()
list.append(w)
return list
chars = {}
word = raw_input("Write 9 letters: ")
for w in word:
w = w.lower()
if w not in chars:
chars[w] = 1
else:
chars[w] += 1
if chars.keys() in ordlista(list):
print "YES"
else:
print "NO"
chars.keys() is a list, so
chars.keys() in ordlista(list):
will never be True. What you want is match the letter counts against each word in your list. So I'd suggest
charsum = sum(chars.values())
for word in wordlist:
if len(word) == charsum and all([(word.count(c) == chars[c]) for c in chars]):
print "YES for word '%s'" % word
EDIT: If you want those words to match which have at least the letter counts (i.e. a word with 3 a's will match an input of two a's), then you'll have to change the == to a >=.
EDIT2: Since you want exact matches, the easiest solution would be to count the number of chars and make sure the word has that length.
You are checking for the presence of the entire list of keys in your character list, rather than checking for each key individually. You must iterate over your keys individually, and then check for their presence.
for k in chars:
if k in ordlista(list):
print "YES"
else:
print "NO"
If you want to print the words which consist solely of the letters in your character list, you may use the following approach.
for word in ordlista(list):
if not filter(lambda char: char not in chars, word):
print word
Use sets:
chars = set(raw_input("Write 9 letters: "))
for word in ordlista(None):
if(set(word) == chars):
print "YES for '%s'" % word
BTW, the argument list to ordlista is unnecessary, as it is not used. I would also advise against using the name list in general, because it hides the built-in <type 'list'>
Update: I have read your comment on jellybean's post. If every letter can only be used once, you can obviously not use sets!