5运算python计算器

时间:2019-12-21 01:56:14

标签: python jupyter-notebook calculator

在这里,我实现了一个仅需5次操作的简单计算器。

2 个答案:

答案 0 :(得分:2)

您犯了一个错误-您必须确保平方根是整数且大于或等于x,但不能完全等于x(请参见下面的评论):

if x > 1 and y > x:
    num_of_programs = [None] * (y + 1)

    for i in range(x):
        num_of_programs[i] = 0

    num_of_programs[x] = 1

    for i in range(x + 1, y + 1):
        num_of_programs[i] = 0
        if i % 2 == 0 and i // 2 >= x:
            num_of_programs[i] += num_of_programs[i // 2]
        if i % 3 == 0 and i // 3 >= x:
            num_of_programs[i] += num_of_programs[i // 3]
        if i - 5 >= x:
            num_of_programs[i] += num_of_programs[i - 5]
        if i - 7 >= x:
            num_of_programs[i] += num_of_programs[i - 7]
        # fix here!
        if i ** (1/2) - int(i ** (1/2)) == 0 and i ** (1/2) >= x:
            num_of_programs[i] += num_of_programs[int(i ** (1/2))]

    print(num_of_programs[y])

答案 1 :(得分:0)

这是使用递归函数的另一种“蛮力”解决方案:

def calc(number, target, program="", programs=None):
    if programs is None:
        programs = []
    if number == target:
        programs.append(program)
        return
    if number > target:
        return
    calc(number * 2, target, program + "A", programs)
    calc(number * 3, target, program + "B", programs)
    calc(number + 5, target, program + "C", programs)
    calc(number + 7, target, program + "D", programs)
    calc(number ** 2, target, program + "E", programs)
    return programs

示例调用:

>>> len(calc(2, 10))
0
>>> len(calc(3, 20))
5
>>> len(calc(5, 100))
34660

您还可以检查导致目标的实际程序:

>>> calc(3, 20)
['ADD', 'CCD', 'CDC', 'DA', 'DCC']
  • A:将屏幕上的当前数字乘以2
  • B:将屏幕上的当前数字乘以3
  • C:在屏幕上的当前号码前加5
  • D:将7添加到屏幕上的当前数字
  • E:以屏幕上当前数字的平方为单位