0

Мне нужно множество, которое будет составляться из 3 элементов: 1) Первые буквы каждого слова из текста заданого с клавиатуры; 2) Буквы, которые повторяются 2 и больше раз; 3) Буквы которые повторяются только 1 раз. В моём коде 3 элемент не прибавляется к множеству отдельным элементом, а смешивается с вторым элементом.

text = str(input("text - "))
s = text.split(" ")
b = [i[0] for i in s]
x = "".join(b)
M = set()
twoandmore = []
oneletter = []
M.update([x])
for j in text:
    count = text.count(j)
    if count > 1:
        twoandmore.append(j)
        l = ''.join(set(twoandmore))
        M.update(l)
        M.discard(" ")
    if count == 1:
        oneletter.append(j)
        k = ''.join(set(oneletter))
        M.update(k)
input_set = M
g = list(input_set)
tmp = [i for i in g if len(i) > 1]
res = ''.join([i for i in g if len(i) == 1])
tmp.append(res)
input_set = set(tmp)
print(input_set)

Ввод:

text - I love spaghetti and birds

Вывод:

{'Ilsab', 'thsdelgipInbroav'}

а нужно

{'Ilsab', 'iesatd', 'lovbrnpgh'}

1 ответ 1

2
text = 'I love spaghetti and birds'

block1 = ''.join(word[0] for word in text.split())
block2 = ''.join({letter for letter in text.lower() if text.lower().count(letter) > 1 and letter != ' '})
block3 = ''.join({letter for letter in text.lower() if text.lower().count(letter) == 1 and letter != ' '})

res = {block1, block2, block3}
2
  • Спасибо большое) 9 дек 2020 в 16:24
  • 1
    если есть стандартные средства - лучше всего долбить ими, в моем коде я бы еще сделал text_l = text.lower().replace(' ', '') - тогда для 2 и 3 блока меньше кода писать бы пришлось
    – Zhihar
    9 дек 2020 в 16:31

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.