Reputation: 31
I don't understand why this code gives me 'Error' and not 2. I am trying to do this without recursion. An example with recursion would also be appreciated.
def addDigits(num):
num = str(num)
if(len(num) > 1):
for i in range(0, len(num)-1):
for j in range(1, len(num)):
if(len(str(int(num[i]) + int(num[j]))) > 1):
x = len(str(int(num[i]) + int(num[j])))
for i2 in range(0, x-1):
for j2 in range(1, x):
if(x == 1):
return(int(num[i]) + int(num[j]))
else:
return('Error')
else:
return('Error2')
else:
return(num)
print(addDigits(38))
Upvotes: 0
Views: 1688
Reputation: 115
Here is one way to do it with loops,i am from java so bear with me with semicolons.
def addDigits(num):
while(num >= 10):
int temp = 0;
while(num > 0):
temp = temp + num % 10;
num = num/10;
num = temp;
return num;
addDigits(38)
this should give you the correct answer which is 2
Upvotes: 0
Reputation: 390
Like you mentioned, recursive is the best way to do it. If you ever write a code with more than 2 loops, just think again whether it is absolutely necessary.
def add_digits(x):
if x/10>1:
x=add_digits(sum([int(i) for i in str(x)]))
else:
return x
if x/10<1:
return x
add_digits(123456)
output:
3
The above code will help you sum the digits until its a single digit number.
Unlike C or C++, python is not a super fast language. Avoiding loops will make a significant difference.
Upvotes: 1
Reputation: 31
I think if you output x
and you will find x=2
rather than x=1
, so the program run execute the else: return('Error')
.
Upvotes: 0