Skip to main content

Command Palette

Search for a command to run...

Python "reduce()" function

Updated
1 min read
Python "reduce()" function

I was solving a question on Codewars and it was something like this -

You will be given a number and you have to reduce it to a single digit by multiplying its digit and return the number of steps in doing that. Check the question here..

Here is my solution which is a pretty simple one -

def check(n):
    st = str(n)
    num=1
    for s in st:
        num=num*(int(s))
    return num

def persistence(n):
    if n<10:
        return 0
    count=0
    while True:
        n = check(n)
        count=count+1
        if n<10:
            break
    return count

But I found a very neat solution also. Check it here and I am also pasting the code snippet here.

import operator
def persistence(n):
    i = 0
    while n>=10:
        n=reduce(operator.mul,[int(x) for x in str(n)],1)
        i+=1
    return i

Here, reduce function is used. "reduce(fun,seq)" takes 2 arguments and applies the function to the list which is the second argument.

  1. First it will take 2 or more numbers(whatever is required by the function) and compute the result.
  2. Then it will take the result and also the next set of numbers(again, depending on the arguments required by the function) and apply the same process until the list is exhausted.

More from this blog

Untitled Publication

13 posts