繁体   English   中英

我正在尝试编写一个代码来打印 'a' 范围内不能被 y 整除的数字

[英]Am trying to write a code that will print the numbers within the range of 'a' that are not divisible by y

示例.py

y = [2,3,4,5,6,7,8,9] # array

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

调用 function

div(15)  # not showing any result on 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]))

但大多数时候 output 将是列表中的所有数字。

循环从 1 到给定数字范围内的所有值。 对于每个值,检查模运算是否为所有除数提供了除0以外的值。 如果是,请将值添加到列表中。

现在我们可以在 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))

这会给你[1, 11, 13]

有一个可能的优化。 我们可以检查该值是否可以被任何除数整除,而不是检查当前值是否不能被所有除数整除。 当找到匹配的除数时,这将结束检查(快捷方式)。

所以更换

if all(value % divisor != 0 for divisor in divisors):
    result.append(value)

if not any(value % divisor == 0 for divisor in divisors):
    result.append(value)

我将 function 中的变量名替换为更有意义的变量名。 function 本身也应该有一个更好的名字。 至少我添加了除数列表作为参数,因为在 function 中使用全局状态是个坏主意。

通过列表理解,您甚至可以从中制作单行,但我更喜欢更具可读性的多行版本。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM