我目前正在制作一个简单的计算器,用于持续执行计算。它是菜单驱动的,所以我不能在不同的操作之间真正交换,直到最后我可以追加答案并选择不同的操作(希望我能想出来,也许是另一次)。我需要的菜单选项之一是减法。
到目前为止,我设法通过添加和乘法使其工作。下面是一个函数,将输入存储为我的数组中的元素:
有没有办法通过下一个元素输入减去运行总计来创建反向运行总计?此外,是否可以在反向运行总计和元素输入中使数字变为负值?
TL; DR我想在每个列表元素之间减去运行总计。如果可能的话,我需要一种方法来使负数对输入和反向运行总数起作用,这些都是浮点数,而不是整数。
def number_list(operator_item, previous_total):
number_list = []
counter = 1
print("Enter values, enter '=' to create final answer and copy answer")
while number_list != "=":
try:
list_value = float(input())
except ValueError:
sentinel_value = input("Type '=' again to finalize calculation, copy answer, and return to menu to select another operation\n")
if sentinel_value == "=":
copy(running_total)
return running_total
else:
print("Invalid option")
menu_selection() #This is irrelevant
number_list.append(list_value)
counter += 1
if operator_item == "+":
running_total = addition(number_list)
print("Current sum:", running_total + ans)
#Using function as an example. Subtraction will be a separate function as well
def addition(number_array):
total = sum(number_array)
return total
如果我理解你的问题,我认为itertools.accumulate
满足您对任何操作的需求:
import itertools
import operator
nums = [5, 3, 4, 2, 1]
# Addition
print(list(itertools.accumulate(nums, operator.add)))
# [5, 8, 12, 14, 15]
# Subtraction
print(list(itertools.accumulate(nums, operator.sub)))
# [5, 2, -2, -4, -5]
# Multiplication
print(list(itertools.accumulate(nums, operator.mul)))
# [5, 15, 60, 120, 120]
operator
中定义了许多其他操作。如果您不需要中间结果,请改用functools.reduce
。例如,减法:
import functools
import operator
nums = [5, 3, 4, 2, 1]
print(functools.reduce(operator.sub, nums))
# -5