Мне нужно иметь возможность подсчитать вхождения строки и распечатать ее только один раз? - PullRequest
0 голосов
/ 29 января 2020

Поэтому я хочу, чтобы мой код выводил каждую букву в строке только один раз и в алфавитном порядке, например, banana будет выводить abn ...

Суть в том, что мне все еще нужно это посчитайте вхождения каждой буквы в строке, поэтому выходные данные должны быть следующими:

a occurs in the word banana a total of 3 times(s)
b occurs in the word banana a total of 1 time(s)
n occurs in the word banana a total of 2 time(s)
...

Это мой код:

def letter_counter(string):
    stg = string.lower()
    stg = ''.join(sorted(stg))
    for i in stg:
        a = stg.count(i)
        print(f'the letter {i} appears in the word {string} {a} times')

letter_counter('banana')

А текущий вывод выглядит следующим образом:

the letter a appears in the word banana 3 times
the letter a appears in the word banana 3 times
the letter a appears in the word banana 3 times
the letter b appears in the word banana 1 times
the letter n appears in the word banana 2 times
the letter n appears in the word banana 2 times

Ответы [ 3 ]

1 голос
/ 29 января 2020

Хитрость для удаления дубликатов состоит в том, чтобы сделать ее set:

def letter_counter(string):
    stg = string.lower()
    stg = ''.join(stg)
    for i in sorted(set(stg)):
        a = stg.count(i)
        print(f'the letter {i} appears in the word {string} {a} time{"" if a == 1 else "s"}')

letter_counter('banana')

распечатывает:

the letter a appears in the word banana 3 times
the letter b appears in the word banana 1 time
the letter n appears in the word banana 2 times

Обратите внимание на движение от sorted одна строка позже. A set является неупорядоченным , поэтому исходный отсортированный порядок теряется. Сортировка снова, непосредственно перед циклом, сортирует это.

1 голос
/ 29 января 2020

Вы можете использовать Counter для простого подсчета букв:

from collections import Counter

def letter_counter(string):
    for letter, count in sorted(Counter(string.lower()).items()):
        print(f'the letter {letter} appears in the word {string} {count} times')

letter_counter("banana")

Дает:

the letter a appears in the word banana 3 times
the letter b appears in the word banana 1 times
the letter n appears in the word banana 2 times
0 голосов
/ 29 января 2020

Для уникальных букв вы можете попробовать использовать set (). Так что-то вроде for i in sorted(set(stg)):

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...