def words_to_numbers(word):
"""Преобразует числа, записанные словами, в их числовое представление."""
numbers = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"ten": 10
}
return numbers.get(word.lower(), None)
def numbers_to_words(number):
"""Преобразует числовое представление в числа, записанные словами."""
numbers = {
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
10: "ten",
0: "zero"
}
return numbers.get(number, None)
def calculate_expression(expression):
"""Вычисляет выражение в текстовом формате и возвращает результат словами."""
parts = expression.split()
if len(parts) != 3:
raise ValueError("Input should contain two numbers and an operator separated by spaces.")
# Разбираем числа и оператор
first_number = words_to_numbers(parts[0])
operator = parts[1]
second_number = words_to_numbers(parts[2])
if first_number is None or second_number is None:
raise ValueError("Invalid number word in the input.")
if operator not in ["+", "-"]:
raise ValueError("Operator should be '+' or '-'.")
# Вычисляем результат
if operator == "+":
result = first_number + second_number
elif operator == "-":
result = first_number - second_number
# Преобразуем результат в слова
result_word = numbers_to_words(result)
if result_word is None:
raise ValueError("Result is out of bounds (valid range: 0 to 10).")
return result_word
# Пример использования
input_expression = "three + five"
result = calculate_expression(input_expression)
print(result) # Вывод: eight
def words_to_number(word):
num_dict = {
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'seven': 7,
'eight': 8,
'nine': 9,
'ten': 10
}
return num_dict[word]
def number_to_words(number):
words_dict = {
-10: 'minus ten',
-9: 'minus nine',
-8: 'minus eight',
-7: 'minus seven',
-6: 'minus six',
-5: 'minus five',
-4: 'minus four',
-3: 'minus three',
-2: 'minus two',
-1: 'minus one',
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten'
}
return words_dict[number]
def calculate(input_string):
parts = input_string.split()
num1_word = parts[0]
operator = parts[1]
num2_word = parts[2]
num1 = words_to_number(num1_word)
num2 = words_to_number(num2_word)
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
else:
raise ValueError("Unsupported operator. Use '+' or '-'")
# Ensure the result is within the range -10 to 10, as per problem statement
if not (-10 <= result <= 10):
raise ValueError("Result out of range. Valid results are from minus ten to ten.")
return number_to_words(result)
# Пример использования с пользовательским вводом:
try:
input_string = input("Enter two numbers (one to ten) in words and an operator (+ or -): ")
output = calculate(input_string)
print(output)
except ValueError as e:
print(e)
Нужно найти сумму чисел и вывести результат словами, при этом всё на английском