October 25th, 2013, 07:30 AM

Can anyone please help with this ?
Hi,
I've been given this short piece of code i need to get it to working firstly, as it currently does not work (something small i think is the issue) and explain what the code is doing.
I think its doing something to with the length?
Here it is, any help would be awesome!!
The code is not indented, because this is how i received it.
"Consider the following implementation of a function f, where x is a positive integer".
def f(x):
xs = str(x)
if len(xs) == 1:
return int(xs)
n = int(xs[0]) + int(xs[1])
if len(xs) == 2:
return n
else:
return n + f(xs[2:])
What does f(2112) return?
Like i say any help would be great as I'm really struggling with this. Like i say i need to get the code working, and explain what it is doing, I know it is something to do with length, but i really am not sure what.
Thanks!
October 25th, 2013, 08:42 AM

recursively sum digits.
Code:
def f(x):
xs = str(x)
if len(xs) == 1:
return int(xs)
n = int(xs[0]) + int(xs[1])
if len(xs) == 2:
return n
else:
return n + f(xs[2:])
print(f(2112))
[code]
Code tags[/code] are essential for python code and Makefiles!
October 25th, 2013, 08:52 AM

Many Thanks for your help!!
May i ask please what is the code doing is it finding the length of something?
I'm really new to programming and find arrays particularly hard to understand.
Once again thanks!!
October 25th, 2013, 03:40 PM

The function is taking in a number, then converting it to a string. Then it looks at the length of the string to figure out what to do next.
If the string is only 1 long, then the sum of the digits is just that digit itself. e.g.
sum of 5 = 5
If the string is 2 long, then the sum is just the sum of the two digits.
sum of 12 = 1 + 2 = 3
If the string is longer than 2, then add the first two digits and then add that to the sum of the rest.
e.g 123 = 1 + 2 + sum_of_digits(3) = 3 + 3 = 6
Tada!