项目Euler/Python:求3和5的倍数之和。程序未通过inpu

2024-09-27 00:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个编程新手,我正在做这个项目,给我一个学习的理由。你知道吗

下面是我非常简单的python代码

x = 1                       
thirdDivide = 0             
fifthDivide=0     
total = 0                   

print('Enter the max value')

maxValue = input()

while (x != maxValue):
    thirdDivide = x / 3
    fifthDivide = x / 5
    if (thirdDivide).is_integer():
        total = total + x
        x = x + 1
    elif (fifthDivide).is_integer():
        total = total + x
        x = x + 1

print ("The sum of the multiples of 3 and 5 between 0 and " + maxValue + " is " + total)

当我运行它,它要求我的最大值,然后停止做任何事情。你知道吗

谢谢!你知道吗


Tags: andofthe项目代码is编程integer
3条回答

只有当thirdvide.is\整数()或fifthDivide.is\是整数()是真的。所以如果两者都不是真的,你就在相同的x值上无限循环

假设您在Python 3中使用字符串而不是float,或float而不是字符串,infite循环的修复方法如下:

x = 1
thirdDivide = 0
fifthDivide=0
total = 0

maxValue = float(input('Enter the max value: '))

while (x != maxValue):
    thirdDivide = x / 3
    fifthDivide = x / 5
    if (thirdDivide).is_integer():
        total = total + x
    elif (fifthDivide).is_integer():
        total = total + x
    x = x + 1

print("The sum of the multiples of 3 and 5 between 0 and " + str(maxValue) + " is " + str(total))

注意,我不检查你的算法的正确性,也不检查它是否计算出它应该做什么。但现在它产生了一些结果并进行了编译。你知道吗

您可以使用filterreducefunctional approach来求解它:

def f(acc, v): return acc + v


def g(x): return x % 3 == 0 or x % 5 == 0


print reduce(f, filter(g, range(1000)))

工作原理:

  • filter:接受两个参数:
    1. 第一个是应用于range(1000)的每个元素的函数gg接受一个参数x,检查if35的倍数(检查modulo操作%的其余部分)。你知道吗
    2. 第二个是从01000range。你知道吗
  • reduce:接受两个参数:
    1. 第一个是一个函数f,它接受两个参数:一个累加器acc和一个表示列表中当前元素的变量v。你知道吗
    2. 第二个参数是前面由filter返回的经过筛选的range。你知道吗

输出:

  • range(10)=23
  • range(1000)=233168

使用lambda函数(相同的逻辑只是不同的语法):

print reduce(lambda acc, v: acc + v, filter(lambda x: x % 3 == 0 or x % 5 == 0, range(1000)))

相关问题 更多 >

    热门问题