pythonpython-3.xoctal

How can you convert a list of octal digits to an integer in Python using reduce()?


Recently, the reduce() function was introduced as part of my lecture. We were given the task to write a function that takes a list of octal digits as its argument, and using the reduce() function, returns the int value of the number represented by those digits, e.g. the assert

assert function([6, 4, 4]) == 420

should return True.

I know that to convert an oct to an int, you have to do oct * 8**n, where n is the position of the value. e.g. in the given list, it'd be 6 * 8**2 + 4 * 8**1 + 4 * 8**0.

However, I'm not quite sure how to implement this, especially since reduce() only takes a function that needs two variables, and applies them on each value in an iterable.

I tried a few things, involving index() and len() of the list you give to the function, but all came out wrong. They'd give far too high values, or ended up not using the second variable required by reduce() at all.

How would you do this?


Solution

  • You can use lambda x, y: 8*x+y as function in reduce:

    from functools import reduce
    
    def function(l):
        return reduce(lambda x, y: 8*x+y, l)
    
    assert function([6, 4, 4]) == 420
    

    Breaking down the steps:

     x=6, y=4:  8*6 + 4 =  52
    x=52, y=4: 8*52 + 4 = 420