你如何在python中正确测试divisibility [关闭](How do you correctly test for divisibility in python [closed])

编程入门 行业动态 更新时间:2024-10-26 04:30:42
你如何在python中正确测试divisibility [关闭](How do you correctly test for divisibility in python [closed])

我编写了一些代码来评估x和y之间的整数,并通过整数3和5检查可分性。这是代码。

def div_3_5(start, end): result = 0 result2 = 0 result3 = 0 while start < end: result2 = start + result result = result2 - start + 1 if result2 % 3==0 or 5==0: result3 = result3 + 1 else: result3 = result3 + 0 return result3

我只是一个初学者,但在代码中一切似乎都很好,除非我错误地使用了“或”语句或错误地检查了可分性。 这让我想到了主要问题。 任何帮助,将不胜感激。

I wrote some code to evaluate the integers between x and y and check for divisibility by the integers 3 and 5. This is the code.

def div_3_5(start, end): result = 0 result2 = 0 result3 = 0 while start < end: result2 = start + result result = result2 - start + 1 if result2 % 3==0 or 5==0: result3 = result3 + 1 else: result3 = result3 + 0 return result3

I'm just a beginner but everything seems fine in the code of course unless I have used the "or" statement incorrectly or checked for divisibility incorrectly. Which brings me to the main question. Any help would be appreciated.

最满意答案

你需要这样做:

if result2 % 3 == 0 or result2 % 5 == 0:

否则,它被解析为if (result2 % 3==0) or (5==0):这显然是错误的,因为5 != 0 。

另一个建议可能非常有用,因为您有更多数字要检查可分性:

if any(result2 % i == 0 for i in (3, 5)):

这是你似乎想要做的更简单的版本(Project Euler问题1):

def div_3_5(start, end): return sum(1 for i in range(start, end+1) if i % 3 == 0 or i % 5 == 0)

或者,使用De Morgan的定律以及0是False - 值的事实:

def div_3_5(start, end): return sum(1 for i in range(start, end+1) if not (i % 3 and i % 5))

You need to do this:

if result2 % 3 == 0 or result2 % 5 == 0:

Otherwise it is parsed as if (result2 % 3==0) or (5==0):, which is clearly wrong as 5 != 0.

Another suggestion which can be quite useful as you have more numbers you want to check for divisibility:

if any(result2 % i == 0 for i in (3, 5)):

This is a much simpler version of what you seem to be trying to do (Project Euler problem 1):

def div_3_5(start, end): return sum(1 for i in range(start, end+1) if i % 3 == 0 or i % 5 == 0)

Or, using De Morgan's laws and the fact that 0 is a False-ish value:

def div_3_5(start, end): return sum(1 for i in range(start, end+1) if not (i % 3 and i % 5))

更多推荐

本文发布于:2023-08-06 02:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1442007.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   测试   如何在   python   closed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!