I'm trying to count how many times each letter appears in the string and then display it in a list eg.
The word "hello" would be:
{h:1, e:1, l:2, o:2}
This is my code.
text = input()
dict = {}
for k in range(len(text)):
if text[k] in dict:
count +=1
dict.update({text[k]:count})
else:
count=1
dict.update({text[k]:count})
print(dict)
The code works on smaller words but not for words that are >10
Can someone please point out what is wrong or what I am missing.
You can use the following code to count letter frequencies:
d = {}
for letter in text:
d[letter] = d.get(letter, 0) + 1
print(d)
I've changed your code around a bit that seems to work:
trans = {}
def letterCounter(num):
for ch in num.lower():
if ch in trans.keys():
trans[ch] += 1;
else:
trans[ch] = 1;
print('Counts letters shown in the input:')
for x in sorted(trans):
print(f"Letter \"{x}\": {trans[x]}")
try:
usr = input('Please insert your input & press ENTER to count its letters: ')
letterCounter(usr)
except ValueError:
print('Input must contain a word or sentence')
I know this is a little bit different than what you asked for, but this seems to work very well, and I used www.cologic.dev to do it. It uses code completion to help you learn and code more efficiently.
Related
I want to take any string and have the user input a number. the output should then be the letters that appear as many times as that number. For example, if the user inputs "apple" and the number is 2 then the output should be "p". any advice? as far as I've gotten is being able to count the letters
You could make use of the set() function to get all the unique characters, iterate through the resultant set, and match the character count for each of the values retrieved. You can use the following code to achieve the desired output.
userInput = input('Enter a string: ')
matchNumValue = int(input('Enter a number: '))
matchingCharacters = [charValue for charValue in list(set(userInput)) if userInput.count(charValue) == matchNumValue]
print(matchingCharacters)
Hope this helps! 😊
You can use the count method.
Here an example:
word = input('Enter a string: ')
number = int(input('Enter a number: '))
usedLetters = []
for letter in word:
if letter not in usedLetters:
n = word.count(letter)
usedLetters.append(letter)
if n == number:
print(n)
The output will be:
2
Most intuitive without any extra libraries is just to use a dict to keep track of the number of occurrences of each letter. Then iterate through to see which ones have the correct number of occurrences.
def countString(string, num):
counter = {}
res = []
for char in string:
if char in counter.keys():
counter[char] += 1
else:
counter[char] = 1
for k,v in counter.items():
if v == num:
res.append(k)
return res
print(countString('apple', 2))
You could use a collections.Counter to count the characters in the string and then reverse it to a dictionary mapping counts to a list of characters with that count. collection.defaultdict creates new key/value pairs for you, to keep the line count down.
import collections
def count_finder(string, count):
counts = collections.defaultdict(list)
for char,cnt in collections.Counter(string).items():
counts[cnt].append(char)
return counts.get(count, [])
#If you don't want to import anything just use this code.
a = int(input('Enter the number'))
b='banana'
l=[]
for i in b:
if a==b.count(i):
l.append(i)
else:
pass
print(l.pop())
I am working on a project where I have to generate a puzzle based on the users input. I would ask the user how many words they will want to include in the puzzle and will also ask for the word. However, the puzzle must work with 4-9 words and each word must be at least 9 letters long. I already wrote some code to start off with since I'm doing it in pieces (I'm new to python) but my code does not stop asking the user for more words, it just keeps asking. If the user says they want only 4 words, and once they enter the 4 words, it should stop there but my code still keeps asking for more words. Any guidance is appreciated! I have 2 python files. one named "main.py" and the other one named "puzzler.py" in my main.py I have this code:
import puzzler
changeable_grid = list()
ways = 0
word_list = []
# TODO:
# 1A. ask user to input how many words they wanna work with
def ask_num_words() -> int:
global num_of_words
while True:
try:
num_of_words = int(input('How many words would you want to work with: '))
except ValueError as e:
print(e)
if puzzler.MIN_WORD <= num_of_words <= puzzler.MAX_WORD:
break
else:
print('Sorry words can only be between {} and {}'.format(puzzler.MIN_WORD, puzzler.MAX_WORD))
print('')
continue
return num_of_words
# 1B. ask user to input the words for the puzzle
def ask_for_words(amt_of_words: int) -> list:
global word
while True:
try:
for i in range(amt_of_words):
word = input('Please enter the word: ')
word_length = len(word)
if puzzler.MIN_WORD_LENGTH >= word_length or word_length >= puzzler.MAX_WORD_LENGTH:
print('The word must be be between {} and {} in length'.format(puzzler.MIN_WORD_LENGTH,
puzzler.MAX_WORD_LENGTH))
print('')
word = input('Re-enter the word again:')
word_length = len(word)
word_list.append(word)
except ValueError as e:
print(e)
print(word_list)
return word_list
if __name__ == "__main__":
amt_of_words = ask_num_words()
ask_for_words(amt_of_words
)
In my puzzler.py file so far I only have this code:
MAX_WORD = 9
MIN_WORD = 4
MAX_WORD_LENGTH = 9
MIN_WORD_LENGTH = 1
You use "while True:" when you want something to happen forever.I think you should just take it out from ask_for_words.
This is what I've come up with so far. it gives me an error saying that "each" is not defined and I don't know what to do to make it work. I am very new to coding so any advice is much appreciated.
my_string = input("Enter a sentence: ")
def main(my_string):
count = {}
for ch in my_string:
if ch in count:
count[each] += 1
else:
count[each] = 1
return count
main(my_string)
Maybe you meant to say ch instead of each both times.
This error is coming up because you never defined the each variable before calling it.
Just change that each variable into ch
my_string = input("Enter a sentence: ")
def main(my_string):
count = {}
for ch in my_string:
if ch in count:
count[ch] += 1
else:
count[ch] = 1
return count
main(my_string)
I am currently working on python, and I do not understand this much. I am looking for help with this question, before the dictionaries. This question is to be completed without any dictionaries. The problem is I do not know much about the max function.
So Far I have:
AlphaCount = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for ch in text:
ch = ch.upper()
index=Alpha.find(ch)
if index >-1:
AlphaCount[index] = AlphaCount[index]+1
You can use Counter
from collections import Counter
foo = 'wubalubadubdub'
Counter(list(foo))
To get the most frequent letter
Counter(list(foo)).most_common(1)
You can use set which will get only unique characters from the input. Then iterate over them and count how many times it occurs in the input with count. If it occurs more often then the max and isalpha (not a space) then set max to the count.
text='This is a test of tons of tall tales'
un=set(text.upper())
max=0
fav=''
for u in un:
c=text.upper().count(u)
if c>max and u.isalpha():
max=c
fav=u
print(fav) # T
print(max) # 6
EDIT
To do this from your code: fix capitalization(for, if) and then find and print/return the most common letter. Also AlphaCount has an extra 0, you only need 26.
text='This is a test of tons of tall talez'
AlphaCount=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Alpha='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for ch in text:
ch= ch.upper()
index=Alpha.find(ch)
if index >-1:
AlphaCount[index]+=1
print(AlphaCount) # the count of characters
print(max(AlphaCount)) # max value in list
print(AlphaCount.index(max(AlphaCount))) # index of max value
print(Alpha[AlphaCount.index(max(AlphaCount))]) # letter that occurs most frequently
def main():
string = input('Enter a sentence: ')
strings=string.lower()
counter = 0
total_counter = 0
most_frequent_character = ""
for ch in strings:
for str in strings:
if str == ch:
counter += 1
if counter > total_counter:
total_counter = counter
most_frequent_character = ch
counter = 0
print("The most frequent character is", most_frequent_character, "and it appears", total_counter, "times.")
main()
Im working on a word game. The purpose for the user is to guess a 5 letter word in 5 attempts. The user can know the first letter. And if he doesn't get the word correct, but if he has a letter in the correct place he gets to know this.
This is my code:
import random
list_of_words = ["apple","table", "words", "beers", "plural", "hands"]
word = random.choice(list_of_words)
attempts = 5
for attempt in range(attempts):
if attempt == 0:
tempList = list(word[0] + ("." * 4))
print("The first letter of the word we are looking for: %s" % "".join(tempList))
answer = raw_input("What is the word we are looking for?:")
if len(answer) != 5:
print ('Please enter a 5 letter word')
Else:
if answer != word:
wordlist = list(word)
answerlist = list(answer)
for i in range(min(len(wordlist), len(answerlist))):
if wordlist[i] == answerlist[i]:
tempList[i] = wordlist[i]
print(tempList)
else:
print("correct, you have guessed the word in:", attempt, "attempts")
if answer != word:
print("Sorry maximum number of tries, the word is: %s" % word)
I have two questions about this code:
The first one is a small problem: If the user gives a 6 or 4 letter word it will still print the word. While I'd rather have it that the word is just ignored and the attempt isnt used..
If a letter is given correct (and also the first letter) it doesnt become a standard part of the feedback. Trying to get this with temp but of yet its not working great.
Any suggestions to clean up my code are also appreciated!
Thanks for your attention
I made some changes in your code, now it's working according to your specification. I also wrote a couple of explaining comments in it:
import random
list_of_words = ["apple", "table", "words", "beers", "plural", "hands"]
word = random.choice(list_of_words)
# changed the loop to a 'while', because i don't want to count the invalid length answers
# and wanted to exit the loop, when the user guessed correctly
attempts = 5
attempt = 0
correct = False
while attempt < attempts and not correct:
if attempt == 0:
# i stored a working copy of the initial hint (ex: "w....")
# i'll use this to store the previously correctrly guessed letters
tempList = list(word[0] + ("." * 4))
print("The first letter of the word we are looking for: %s" % "".join(tempList))
answer = raw_input("What is the word we are looking for?:")
if len(answer) != 5:
print("Please enter a 5 letter word")
else:
if answer != word:
# i simplified this loop to comparing the wordlist and answerlist and update templist accordingly
wordlist = list(word)
answerlist = list(answer)
for i in range(min(len(wordlist), len(answerlist))):
if wordlist[i] == answerlist[i]:
tempList[i] = wordlist[i]
print(tempList)
else:
correct = True
print("Correct, you have guessed the word in %s attempts" % (attempt + 1))
attempt += 1
if answer != word:
# also i used string formatting on your prints, so is prints as a string, and not as a tuple.
print("Sorry maximum number of tries, the word is: %s" % word)
There are several problems with the code.
Just 1 for now. I notice in the sample output you are entering five letter words (beeds and bread) and it still prints out Please enter a 5 letter word.
These two lines:
if len(answer) != 4:
print ('Please enter a 5 letter word')
Surely this should be:
if len(answer) != 5:
print ('Please enter a 5 letter word')
continue
This would catch an invalid input and go round the loop again.
Answering your specific questions:
You will need to have a for loop around your input, keeping the user in that loop until they enter a word of appropriate length
If you move guessed letters to the correct places, it is trivial to win by guessing "abcde" then "fghij", etc. You need to think carefully about what your rules will be; you could have a separate list of "letters in the guess that are in the answer but in the wrong place" and show the user this.
To keep the display version with all previously-guessed characters, keep a list of the display characters: display = ["." for letter in answer], and update this as you go.
Other problems you have:
Too much hard-coding of word length (especially as len("plural") != 5); you should rewrite your code to use the length of the word (this makes it more flexible).
You only tell the user they've won if they guess the whole answer. What if they get to it with overlapping letters? You could test as if all(letter != "." for letter in display): to see if they have got to the answer that way.
Your list comprehension [i for i in answer if answer in word] is never assigned to anything.