[英]Am trying to write a code that will print the numbers within the range of 'a' that are not divisible by y
sample.py示例.py
y = [2,3,4,5,6,7,8,9] # array
Function is created below Function 在下面创建
def _div(a): # Needed to create a function
z = 0 # constant
for x in range(1 , a +1): # To check for all the numbers within the range of a
while z < 8:
if x % y[z] != 0 : # To check if the value of x is divisible by any of the value in the array
j = [x]
Print (j[0])
z += 1
Calling function调用 function
div(15) # not showing any result on Python
end Python结束 Python
def not_dividable_by(factor, quotient_list, unique_output=True):
"""
Args:
factor(int): All numbers from 0-factor are calculated
quotient_list(list): List of to test if factor is divisable with
unique_output(bool): Numbers may occur multiple times if False
Returns:
list: with integers of numbers not divisable by any of 0-factor
"""
result = []
for i in range(0, factor + 1):
for x in quotient_list:
if i % x:
if x not in result or not unique_output:
result.append(x)
return sorted(result) if unique_output else result
print(not_dividable_by(15, [2,3,4,5,6,7,8,9]))
But most of the times the output will be all numbers in the list.但大多数时候 output 将是列表中的所有数字。
Loop over all values in the range from 1 to the given number.循环从 1 到给定数字范围内的所有值。 For each value check if the modulo operation gives a value other than 0
for all divisors.对于每个值,检查模运算是否为所有除数提供了除0
以外的值。 If yes, add the value to the list.如果是,请将值添加到列表中。
Now we can write that down in Python code.现在我们可以在 Python 代码中写下来。
def _div(number, divisors):
result = []
for value in range(1, number + 1):
if all(value % divisor != 0 for divisor in divisors):
result.append(value)
return result
y = [2, 3, 4, 5, 6, 7, 8, 9]
print(_div(15, y))
This will give you [1, 11, 13]
.这会给你[1, 11, 13]
。
There is a possible optimization.有一个可能的优化。 Instead of checking if the current value is not divisible by all divisors we can check if the value is divisible by any divisor.我们可以检查该值是否可以被任何除数整除,而不是检查当前值是否不能被所有除数整除。 This will end the check (shortcut) when a matching divisor is found.当找到匹配的除数时,这将结束检查(快捷方式)。
So replace所以更换
if all(value % divisor != 0 for divisor in divisors):
result.append(value)
with和
if not any(value % divisor == 0 for divisor in divisors):
result.append(value)
I replaced the variable names in the function by more meaningful ones.我将 function 中的变量名替换为更有意义的变量名。 The function itself would deserve a better name too. function 本身也应该有一个更好的名字。 At least I added the list of divisors as a parameter because it's a bad idea to work with global states in a function.至少我添加了除数列表作为参数,因为在 function 中使用全局状态是个坏主意。
With a list comprehension you could even make a one-liner out of this but I prefer the more readable multiline version.通过列表理解,您甚至可以从中制作单行,但我更喜欢更具可读性的多行版本。
def _div(number, divisors):
return [value for value in range(1, number + 1) if not any(value % divisor == 0 for divisor in divisors)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.