I';m a bit confused right now as to what I'm supposed to be doing.
CodePudding user response:
That happens because you're trying to slice an integer, not a list.
You can solve this problem by changing the integer to a list, and then try using slicing.
This can be done by the code below.
listNum = list(map(int, str(num)))
use this listNum
instead of n
in your code.
CodePudding user response:
You need to repeat the process until the result is a single digit.
Then, the number is divisible by 11 if and only if that single digit is 0.
For example:
def div_11(n):
while n > 9:
s = str(n)
x = sum([int(s[i]) for i in range(0,len(s),2)]) # sum of digits in even places
y = sum([int(s[i]) for i in range(1,len(s),2)]) # sum of digits in odd places
n = abs(x - y) # just in case the intermediate result is negative
return n == 0
CodePudding user response:
You are passing an integer to the function, which can't be sliced. The passed number should be a string in order to pick the alternative digits using slicing.
Furthermore, you're still using the modulus operator to determine the divisibility by 11, which can be replaced by a look-up inside a list.
Try the following:
def div_11(n):
n = str(n)
alternative = sum(int(digit) for digit in n[::2])
second_alternative = sum(int(digit) for digit in n[1::2])
if (alternative - second_alternative) in [-11, 0, 11]:
return True
else:
return False