我是一个编程新手,我正在做这个项目,给我一个学习的理由。你知道吗
下面是我非常简单的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)
当我运行它,它要求我的最大值,然后停止做任何事情。你知道吗
谢谢!你知道吗
只有当thirdvide.is\整数()或fifthDivide.is\是整数()是真的。所以如果两者都不是真的,你就在相同的x值上无限循环
假设您在Python 3中使用字符串而不是float,或float而不是字符串,infite循环的修复方法如下:
注意,我不检查你的算法的正确性,也不检查它是否计算出它应该做什么。但现在它产生了一些结果并进行了编译。你知道吗
您可以使用
filter
和reduce
用functional approach来求解它:工作原理:
range(1000)
的每个元素的函数g
。g
接受一个参数x
,检查if
是3
或5
的倍数(检查modulo操作%
的其余部分)。你知道吗0
到1000
的range。你知道吗f
,它接受两个参数:一个累加器acc
和一个表示列表中当前元素的变量v
。你知道吗filter
返回的经过筛选的range。你知道吗输出:
range(10)
=23
range(1000)
=233168
使用lambda函数(相同的逻辑只是不同的语法):
相关问题 更多 >
编程相关推荐