Python: count string and output letters that match a number - python

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())

Related

Counting how many times each letter appears in the string

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.

function error and getting the code to work

def PatternCount(Text,Pattern):
count = 0
for i in range(0,1+len(Text)-len(Pattern)):
if Text[i:i+len(Pattern)] == Pattern:
count = count + 1
return count
def Frequentwords(Text,K):
FrequentPattern = {}
for i in range(0,len(Text)-K):
Pattern = Text(i,K)
Count(i)=PatternCount(Text,Pattern)
maxCount = max(Count)
for i in range(0,len(Text)-K):
if Count(i) == maxCount:
FrequentPattern.add(Text(i,K))
list(set(FrequentPattern))
return FrequentPattern
Text = input("enter DNA sequence: ")
K = int(input("enter the length of the pattern: "))
print(Frequentwords(Text,K))
this code is to find the most frequent K-mers (the length of a short DNA sequence) in a string Text(DNA sequences) checks all k-mers appearing in this string (there are |Text| − k + 1 such k-mers) and then computes how many times each k-mer appears in Text.
there is an error in this line:
Count(i)=PatternCount(Text,Pattern)
it is SyntaxError: can't assign to function call
l want this code to
Input: A string Text DNA Seguence and an integer k.
Output: All most frequent k-mers in Text
This line Count(i)=PatternCount(Text,Pattern) doesn't make sense because you are assigning a function to another function. If Count is an array, then it should be like this:
Count[i]=PatternCount(Text,Pattern)
you should change all Count(i) in your code to Count[i]. Here's the code fixed:
def pattern_count(sequence,pattern):
count = 0
for i in range(0,1+len(sequence)-len(pattern)):
if sequence[i:i+len(pattern)] == pattern:
count = count + 1
return count
def frequent_words(sequence,t):
counters = [0]*len(sequence)
for i in range(0,len(sequence)-k):
pattern = sequence[i:i+k]
counters[i] = pattern_count(sequence,pattern)
maxCounter = max(counters)
print(counters)
for i in range(0,len(sequence)-k):
if counters[i] == maxCounter:
frequent_pattern = sequence[i:i+k]
return frequent_pattern
sequence = input("enter DNA sequence: ")
k = int(input("enter the length of the pattern: "))
print(frequent_words(sequence,k))
The base idea was fine, but there were some syntax errors. I also changed some variables names to fit standards.
You could optimize this by doing like this:
def frequent_words(sequence,t):
counters = [0]*len(sequence)
for i in range(0,len(sequence)-k):
pattern = sequence[i:i+k]
counters[i] = pattern_count(sequence,pattern)
max_index = counters.index(max(counters))
return sequence[max_index:max_index+k]
I hope this works for you.

finding duplicates in a string at python 3

def find_duplicate():
x =input("Enter a word = ")
for char in x :
counts=x.count(char)
while counts > 1:
return print(char,counts)
I've got small problem in there i want to find all duplicates in string but this program give me only one duplicate ex: aassdd is my input function gave me only a : 2 but it need to be in that form a : 2 s : 2 d : 2 thanks for your answers.
return is a keyword that works more or less as immediately exit this function (and optionally carry some output with you). You thus need to remove the return statement:
def find_duplicate():
x =input("Enter a word = ")
for char in x :
counts=x.count(char)
print(char,counts)
Furthermore you also have to remove the while loop (or update the counter if you want to print multiple times), otherwise you will get stuck in an infinite loop since count is not updated and the test will thus always succeed.
Mind however that in this case a will be printed multiple times (in this case two) if it is found multiple times in the string. You can solve this issue by first constructing a set of the characters in the string and iterate over this set:
def find_duplicate():
x =input("Enter a word = ")
for char in set(x):
counts=x.count(char)
print(char,counts)
Finally it is better to make a separation between functions that calculate and functions that do I/O (for instance print). So you better make a function that returns a dictionary with the counts, and one that prints that dictionary. You can generate a dictionary like:
def find_duplicate(x):
result = {}
for char in set(x):
result[char]=x.count(char)
return result
And a calling function:
def do_find_duplicates(x):
x =input("Enter a word = ")
for key,val in find_duplicate(x).items():
print(key,val)
And now the best part is: you actually do not need to write the find_duplicate function: there is a utility class for that: Counter:
from collections import Counter
def do_find_duplicates(x):
x =input("Enter a word = ")
for key,val in Counter(x).items():
print(key,val)
This will help you.
def find_duplicate():
x = input("Enter a word = ")
for char in set(x):
counts = x.count(char)
while counts > 1:
print(char, ":", counts, end=' ')
break
find_duplicate()
Just because this is fun, a solution that leverages the built-ins to avoid writing any more custom code than absolutely needed:
from collections import Counter, OrderedDict
# To let you count characters while preserving order of first appearance
class OrderedCounter(Counter, OrderedDict): pass
def find_duplicate(word):
return [(ch, cnt) for ch, cnt in OrderedCounter(word).items() if cnt > 1]
It's likely more efficient (it doesn't recount each character over and over), only reports each character once, and uses arguments and return values instead of input and print, so it's more versatile (your main method can prompt for input and print output if it chooses).
Usage is simple (and thanks to OrderedCounter, it preserves order of first appearance in the original string too):
>>> find_duplicate('aaacfdedbfrf')
[('a', 3), ('f', 3), ('d', 2)]
def find_duplicate():
x = input("Enter a word = ")
dup_letters = []
dup_num = []
for char in x:
if char not in dup_letters and x.count(char) > 1:
dup_letters.append(char)
dup_num.append(x.count(char))
return zip(dup_letters, dup_num)
dup = find_duplicate()
for i in dup:
print(i)
This version should be fast as I am not using any library or more than one cycle, do you have any faster options?
import datetime
start_time = datetime.datetime.now()
some_string = 'Laptop' * 99999
ans_dict = {}
for i in some_string:
if i in ans_dict:
ans_dict[i] += 1
else:
ans_dict[i] = 1
print(ans_dict)
end_time = datetime.datetime.now()
print(end_time - start_time)
def find_duplicate():
x = input("Enter a word = ")
y = ""
check = ""
for char in x:
if x.count(char) > 1 and char not in y and char != check:
y += (char + ":" + str(x.count(char)) + " ")
check = char
return y.strip()

Write a program that lets the user enter a string and displays the character that appears most frequently in the 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()

Write a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n

Whenever I run this code it just gives me a blank list, I am wondering what I am doing wrong. I am trying to print a list of words that are longer than n. When i try to run the updated code it only prints the first word from the list of words that i enter.
def filterlongword(string,number):
for i in range(len(string)):
listwords = []
if len(string[i]) > number:
listwords.append(string[i])
return listwords
def main():
words = input("Please input the list of words: ")
integer = eval(input("Please input an integer: "))
words1 = filterlongword(words,integer)
print("The list of words greater than the integer is",words1)
main()
Initialize listwords before the loop
Return listwords after the loop
Split the input string into a list of words
def filterlongword(string,number):
listwords = []
for i in range(len(string)):
if len(string[i]) > number:
listwords.append(string[i])
return listwords
And a nicer version using list comprehension:
def filterlongword(string,number):
return [word for word in string if len(word) > number]
To split the input string into a list of words, use
words = input("Please input the list of words: ").split()
even better would be just
def filterlongword(string,number):
return filter(lambda word:len(word)>number, string)
# or: return [w for w in string if len(w) > number]
def listing(guess, number):
new_list = []
for i in range(len(guess)):
if len(guess[i]) > number:
new_list.append(guess[i])
print (new_list)
list1 = input("take input: ")
list = list1.split(",")
def main():
global list, integer1
integer = input()
integer1 = int(integer)
listing(list, integer1)
main()
**try this code..this will work, use a delimiter to form a list of your input **
Your main problem is passing words as a single string rather than an iterable of strings. The secondary problem is not specifying the separator between words for the missing .split. Here is my version.
I made longwords a generator function because in actually use, one does not necessary need the sequence of long words to be a list, and I gave an example of this in the output formatting.
def longwords(wordlist, length):
return (word for word in wordlist if len(word) >= length)
def main():
words = input("Enter words, separated by spaces: ").split()
length = int(input("Minimum length of words to keep: "))
print("Words longer than {} are {}.".format(length,
', '.join(longwords(words, length))))
main()
This results in, for instance
Enter words, separated by spaces: a bb ccc dd eeee f ggggg
Minimum length of words to keep: 3
Words longer than 3 are ccc, eeee, ggggg.
Maybe you can shorten the code to the following:
def filter_long_words():
n = raw_input("Give words and a number: ").split()
return sorted(n)[1:] # sorted the List , number it is the shorter .
# called the item from the second position to ende .
print filter_long_words()
def filter_long_words(**words**,**number**):
l=[]
split = **words**.split(",")
for i in split:
if len(i) > **number**:
l.append(i)
return l
**w** = input("enter word:")
**n** = int(input("Enter number"))
filter_long_words(**w**,**n**)
TRY THIS
***
def filter_long_words(n, words):
list_of_words=[]
a= words.split(" ")
for x in a:
if len(x)>n:
list_of_words.append(x)
return list_of_words
for i in range(len(listOfWords)):
listOfInt = []
for i in range(len(listOfWords)):
listOfInt.append(len(listOfWords[i]))
print('List of word length: ',listOfInt)
def filter_long_words(lst,n):
a=[]
for i in lst:
if n<len(i):
a.append(i)
return a
To filter list of words
def filter_long_words(lst,n):
return [word for word in lst if len(word)>n]

Categories