Reputation: 1
I'm writing a program to efficiantly divide by three, but I can extract the individual numbers from the int.
I have already tried map() and list() and set() and they have not worked
num = 1
while True:
num = num + 1
threetest = 0
digits = list(num) #(This is line 17)
for a in range ( 0, len(str(num))):
threetest = threetest + digits[a]
if (treetest % 3) != 0:
...
Traceback (most recent call last): File "C:\test.py", line 17, in digits = list(num) TypeError: 'int' object is not iterable
I would expect to be able to add up the induvidual digits of a number like 936 and then divide the sum by 3 to efficiantly find if it is a multipule of 3
Upvotes: 0
Views: 555
Reputation: 5785
Check this,
>>> digits = [ast.literal_eval(i) for i in str(a)]
>>> digits
[3, 4, 6]
You can replace,
digits = list(num)
with,
digits = [int(i) for i in str(a)]
Upvotes: 0
Reputation: 4860
To get a list
of the digits of type int
, try
digits = list(map(int, str(num)))
num
is an int
, which isn't an iterable. First get a str
of num
, then iterate over it and make each digit an int
, and pack it all in a list
.
Also, the code below is more pythonic:
num = 1
while True:
num += 1
three_test = 0
digits = list(map(int, str(num)))
for digit in range(digits):
three_test += digit
if (tree_test % 3) != 0:
Upvotes: 0
Reputation: 236004
You can get the desired effect by replacing this:
threetest = 0
digits = list(num)
for a in range (0, len(str(num))):
threetest = threetest + digits[a]
With this:
threetest = 0
for digit in str(num):
threetest += int(digit)
Or even simpler (and way more idiomatic):
threetest = sum(int(digit) for digit in str(num))
Upvotes: 1