尽管以前的实现工作,但多可分计算器失败了



首先,定义:

多整形数是一个整数,其中数字的前 n 位数字(从左到右(完全可以被n整除。例如,整数 141 是可多除的,因为:

  • 1 % 1 == 0
  • 14 % 2 == 0
  • 141 % 3 == 0

我正在研究一个递归多除检查器,给定一个数字,它将检查该数字是否是可多除的,如果不是,则递归检查所有其他数字,直到它到达一个可多分的数字。 不幸的是,我的代码没有按照我想要的方式工作。有趣的是,当我输入一个已经是多整治的数字时,它会完成它的工作并输出该多除数。当我输入不可多除数(例如 13(时,会出现此问题。 下一个可分数应该是 14,但程序无法输出它。相反,它会陷入无限循环,直到内存耗尽。 这是我的代码:

def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
else:
return num
else:
print("Number must be non-negative")
return None

我假设问题发生在 while 循环内的 else 语句中,如果数字无法多整,程序会将i重置为 0,并将 1 加到原始数字,以便它可以开始检查新数字。但是,就像我解释的那样,它并没有按照我想要的方式工作。 知道代码可能有什么问题,以及如何确保它在达到 1 时停止并输出正确的多整形数(如 14(?

(另请注意,此检查器只应接受非负数,因此如果条件为初始值(

错误是您在增加数字后没有更新数字。

这是工作代码:

def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
number = str(num) # added line
else:
return num
else:
print("Number must be non-negative")
return None

我对@PranavaGande有类似的答案,原因是我没有找到任何迭代 Int 的方法。嘟嘟!!

def is_polydivisible(n):
str_n = str(n)

list_2 = []
for i in range(len(str_n)):
list_2.append(len(str_n[:i+1]))
print(list_2)
list_1 = []
new_n = 0
for i in range(len(str_n)):
new_n = int(str_n[:i+1])
list_1.append(new_n)
print(list_1)
products_of_lists = []
for n1, n2 in zip(list_1, list_2):
products_of_lists.append(n1 % n2)
print(products_of_lists)
for val in products_of_lists:
if val != 0:
return False
return True

现在,我为这么多行代码道歉,因为它必须更小。但是,每个整数都必须单独拆分,然后除以其索引 [从 1 开始而不是 0]。因此,我发现列出它们并按索引划分它们更容易。

有比我的短得多的代码,但是我希望这有助于查找数字是否是多整形的。 当然,您可以调整代码以查找值,其中商进入小数,返回非零的余数。

最新更新