Как мне упростить формулу добавления букв
favorite_fruits = ['papaya', 'apple', 'banana', 'coconut', 'orange', 'pineapple']
x = 1
if 'banana' in favorite_fruits:
print(f"You "
f"{'r'+ 'e'*x + 'a'*x + 'l'*x + 'ly'}"
" like bananas!")
x += 1
if 'apple' in favorite_fruits:
print(f"You "
f"{'r'+ 'e'*x + 'a'*x + 'l'*x + 'ly'}"
" like apples!")
x += 1
if 'coconut' in favorite_fruits:
print(f"You "
f"{'r'+ 'e'*x + 'a'*x + 'l'*x + 'ly'}"
" like coconuts!")
x += 1
Мне нужно упростить формулу:
'r'+ 'e'*x + 'a'*x + 'l'*x + 'ly'
Или найти другие способы это сделать, что бы при каждом пройденном условии добавлялась еще одна буква E, A, L.
Ответы (1 шт):
Автор решения: ΝNL993
→ Ссылка
Можно попытаться сделать так, возможно это то что вам подходит:
favorite_fruits = ['papaya', 'apple', 'banana', 'coconut', 'orange', 'pineapple', 'berry']
fruits = ['banana', 'apple', 'coconut', 'berry']
x = 1
def what_i_like(fruit):
letters_e = 'e' * x
letters_a = 'a' * x
letters_l = 'l' * x
ends_with_y = fruit.endswith('y')
end = 'ies' if ends_with_y else 's'
fruit_name = (fruit[0:-1] if ends_with_y else fruit) + end
print('You r' + letters_e + letters_a + letters_l + 'ly like ' + fruit_name + '!')
for fruit in fruits:
if fruit in favorite_fruits:
what_i_like(fruit)
x += 1
Я также добавил небольшую проверку, чтобы проверить, оканчивается ли название фрукта на y, если так, тогда окончание будет ies, в противоположном случае будет s.