11个状态的整除性检验如果一个数的奇数位数和偶数位数之和的差可以被11整除,那么整个数就可以被11整除。
例如7689,其中奇数位数的和=9+6= 15,而偶数位数的和=8+7= 15。
如(15 - 15) % 11 == 0,该数字可被11整除。
我写了一个迭代函数来计算它,如果这个数字确实能被11整除,我会给出一个True的结果。我怎么写这个代码的递归版本呢?我很难分解这个问题。
def divisible_by_11_iter(num):
num_lst = [i for i in str(num)]
even_sum = 0
odd_sum = 0
for even in num_lst[::2]: # naming does not really matter as negatives taken into acc
even_sum += int(even)
for odd in num_lst[1::2]:
odd_sum += int(odd)
if (odd_sum - even_sum) % 11 == 0:
return True
else:
return False发布于 2020-05-20 15:17:53
您当前的代码不是迭代的,它只是通过对最后的差值做一个实际的模数来“作弊”。如果你能做something % 11 == 0,你应该对顶部的num做同样的事情,而不是把数字加起来。
无论如何,要以递归方式实现这一点,您需要找出您可以轻松解决的基本情况。我建议您可以很容易地解决小于11的正值。0是可整除的,0到11之间的所有数字都是不可除的。
对于较大的数字,您需要进行数字求和和递归。
def divisible_by_11(num):
if num == 0:
return True
if num < 11:
return False
num_lst = [int(i) for i in str(num)]
even_sum = sum(num_lst[::2])
odd_sum = sum(num_lst[1::2])
return divisible_by_11(abs(even_sum - odd_sum))发布于 2020-05-20 15:21:36
def rec(num, oddsum=0, evensum=0, odd=True):
m = num % 10 # First we extract the mod 10 and thus, effectively remove the first digit
num = num // 10
if odd:
oddsum += m
else:
evensum += m
if num == 0:
return abs(oddsum - evensum) % 11 == 0 # Finally to end the recursion
return rec(num, oddsum, evensum, not odd) # Notice how we flip the odd variable. So it becomes even in the next call.
print(rec(7689))
print(rec(11))
print(rec(22))
print(rec(420))
#Output
True
True
True
Falsehttps://stackoverflow.com/questions/61907020
复制相似问题