Задача: вывести информацию о транзакции яблок в «человеческом» виде.
Первое решение: алгоритм согласования повторялся (копировался) для каждого словосочетания.
Второе решение: алгоритм был вынесен в функцию, что сильно сократило как размер программы, так и усилия на потенциальные добавляение ноавых согласований.
Функция принимает число и три формы существительного и возвращает согласующуюся форму.
from random import randint
amount_init = randint(10, 200)
amount_given = randint(0, amount_init)
amount_left = amount_init - amount_given
last = amount_init % 10
penult = amount_init // 10 % 10
word = "яблок"
if last == 1 and penulte != 1:
word = "яблоко"
elif 2 <= last <= 4 and penult != 1:
word = "яблока"
sentence1 = "У Геннадия было %s %s." % (amount_init, word)
last = amount_given % 10
penult = amount_given // 10 % 10
word = "яблоками"
if last == 1 and penulte != 1:
word = "яблоком"
sentence2 = "Он поделился %s %s с Чебурашкой." % (amount_given, word)
last = amount_left % 10
penult = amount_left // 10 % 10
word = "яблок"
if last == 1 and penulte != 1:
word = "яблоко"
elif 2 <= last <= 4 and penult != 1:
word = "яблока"
sentence3 = "Теперь у Гены осталось всего %s %s." % (amount_left, word)
print(sentence1)
print(sentence2)
print(sentence3)
from random import randint
amount_init = randint(10, 200)
amount_given = randint(0, amount_init)
amount_left = amount_init - amount_given
def agree(number, form1, form2, form3):
last = number % 10
penult = number // 10 % 10
word = form3
if last == 1 and penulte != 1:
word = form1
elif 2 <= last <= 4 and penult != 1:
word = form2
return word
word = agree(amount_init, "яблоко", "яблока", "яблок")
sentence1 = "У Геннадия было %s %s." % (amount_init, word)
word = agree(amount_given, "яблоком", "яблоками", "яблоками")
sentence2 = "Он поделился %s %s с Чебурашкой." % (amount_given, word)
word = agree(amount_left, "яблоко", "яблока", "яблок")
sentence3 = "Теперь у Гены осталось всего %s %s." % (amount_left, word)
print(sentence1)
print(sentence2)
print(sentence3)