简体   繁体   中英

Python: count string and output letters that match a number

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM