【问题标题】:Integer Divisions整数除法
【发布时间】:2022-01-18 04:44:03
【问题描述】:
n = int(input('Give a Number: '))
tambolenler = []

def tambolenleribul(n):
    for i in range(-100,n):
        if n % i == 0:
            tambolenler.append(i)
    return tambolenler
print(tambolenleribul(n))

        else:
            (n == 0)
        

print('n equal is zero') 

大家好。我想解决这个问题,但我猜错了。 我想找到输入的数字 n 的整数除数。 有两个条件。 首先,n 必须在 -100 到 100 之间。 其次,如果 n 数等于零,我想打印零作为输出。

【问题讨论】:

    标签: python python-3.x list integer


    【解决方案1】:

    这是一个具有非最优算法的版本,但它应该可以完成这项工作:

    LOWER_BOUND = -100
    UPPER_BOUND = 100
    
    
    def find_divisors(n: int) -> list:
        """
        >>> find_divisors(8)
        [-8, -4, -2, -1, 1, 2, 4, 8]
        >>> find_divisors(-8)
        [-8, -4, -2, -1, 1, 2, 4, 8]
        >>> find_divisors(0)
        []
        """
        return [i for i in range(-abs(n), abs(n) + 1) if i != 0 and n % i == 0]
    
    
    def main():
        n = int(input(f"Give a non-zero value between {LOWER_BOUND} and {UPPER_BOUND}: "))
        if n != 0 and LOWER_BOUND <= n <= UPPER_BOUND:
            print(f"The divisors of {n} are {find_divisors(n)}")
        else:
            print(f"{n} is not a valid input")
    
    
    if __name__ == "__main__":
        main()
    
    

    【讨论】:

    • 代码有效,但我真正想要的是我们将给出的数字在 -100 和 100 之间。另外,当我们给出的数字是 0 时,我想要一个类似 n = 0 的输出屏幕。
    • @BerkAkyıldız 我编辑了答案以更好地满足要求
    • 感谢这段代码。代码对我来说很好用。
    猜你喜欢
    • 1970-01-01
    • 2011-07-03
    • 2013-05-25
    • 2012-12-21
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多