![](/img/trans.png)
[英]How to use the 'for loop' function and find numbers divisible by 7, python?
[英]How to create a function to find numbers divisible by 7 but not by 5
我正在尝试编写一个名为find_numbers的函数,该函数将找到所有可以被7而不是5整除的数字。
我的问题是到目前为止的实际功能:
def find_numbers(lower_bound, upper_bound):
for i in range(lower_bound,upper_bound):
if (i % 7 == 0 and i % 5 !=0):
print(i)
return ()
我有正确的参数吗? 我到底要返回什么? 我觉得我已经接近正确的解决方案了,但是我真的很困惑:(它正在打印出我想要的内容,但不是正确的。非常感谢您的帮助!谢谢大家!
lower_bound = int( input("Lower bound to search for numbers: ") )
upper_bound = int( input("Upper bound to search for numbers: ") )
found_numbers = find_numbers(lower_bound, upper_bound)
print("The numbers that are divisible by 7 but not by 5
are:\n{}".format(found_numbers))
def find_numbers(lower_bound, upper_bound):
results=[]
for i in range(lower_bound,upper_bound):
if (i % 7 == 0 and i % 5 !=0):
results.append(i)
return results
lower_bound = int( input("Lower bound to search for numbers: ") )
upper_bound = int( input("Upper bound to search for numbers: ") )
found_numbers = find_numbers(lower_bound, upper_bound)
print("The numbers that are divisible by 7 but not by 5
are:\n{}".format(found_numbers))
为此,您可以使用简单的列表理解。
result = [x for x in range(lower_bound, upper_bound) if x % 7 == 0 and x % 5 != 0]
如果您想使它更加优雅和可重复使用,则可以将其包装在一个函数中。
def find_numbers(lower_bound, upper_bound):
return [x for x in range(lower_bound, upper_bound) if x % 7 == 0 and x % 5 != 0]
lower_bound = int( input("Lower bound to search for numbers: ") )
upper_bound = int( input("Upper bound to search for numbers: ") )
found_numbers = find_numbers(lower_bound, upper_bound)
print("The numbers that are divisible by 7 but not by 5 are:\n{}".format(found_numbers))
可以看出,这种列表理解方法的运行速度将比常规循环解决方案快一些。
逻辑中有几处错误:
我会这样修改它:
In [1]: def find_numbers(L, U):
...: r = []
...: for i in range(L, U):
...: if i % 7 == 0 and i % 5 != 0:
...: r.append(i)
...: if not r:
...: return None
...: else:
...: return r
...:
您可以将其视为模式,偏移量,而不是上下限。
7 * 5 = 35 =>您将得到一个长度为35的谐波图案,其中7、14、21、28是您感兴趣的数字,而35是您跳过的数字。 加上n * 35作为偏移量,您将在手触及的范围内达到无穷大😏
抱歉使用java。 随身携带自己的手机,这使我在脑海中轻松自如。
List<Integer> pattern = Arrays.asList(7, 14, 21, 28);
Stream.iterate(0, offset -> offset + 1)
.forEach(offset -> pattern.stream()
.forEach(p -> print(35 * offset + p))
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.