#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    8
    Rep Power
    0

    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!
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,711
    Rep Power
    480

    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!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    8
    Rep Power
    0
    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!!
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    16
    Rep Power
    0
    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!

IMN logo majestic logo threadwatch logo seochat tools logo