我编写了一些代码来评估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 result3I'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))更多推荐
发布评论