Problem description
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
For example
persistence(39) # returns 3, because 39=27, 27=14, 1*4=4
# and 4 has only one digit
persistence(999) # returns 4, because 999=729, 729=126,
# 126=12, and finally 1*2=2
persistence(4) # returns 0, because 4 is already a one-digit number
Code
'''
1. 分析问题:
输入一个整数,将整数的各部分拆分然后相乘,
直到得到的数为一个个位数结束,返回‘相乘’的次数。
2. 算法总结:
1)输入一个整数N;
2)转为字符串类型'N';
3)对字符串进行split操作得到类似{1,2,3,4...}等的字符串;
4)将上一步的字符串转为整数型并相乘得到一个整数N1,并执行了一次乘法计数加一;
5)判断N1是否为个位数,如果不是则转到1)如果是个位数就输出执行乘法的次数。
3. 编程分析
定义一个函数输入为一个形参N,输出乘法过程的次数。
用到int()函数和str()函数;需要用到乘法multiply()因为这个函数是operator类中的一个方法,所以需要导入operator模块;
while循环:停机条件,不断累加乘法运算的次数以最终输出这个值。
reduce()对拆分的序列值进行相乘返回结果。(有两个参数,一个是函数,二是可迭代对象,也就是函数中输入的值,最终输出是函数的值。与map()不同的是这个调用不仅仅调用一次,而是得出结果继续调用,符合我们的要求,因为当有至少三个数字相乘时,是先进行前两个相乘再将结果和第三个相乘不断调用此过程)
reduce()是functools模块的一个函数,需要先导入
'''
import operator
from functools import reduce
def persistance(N):
i = 0
while N >= 10:
reduce(operator.mul, [int(item) for item in str(N).split()])
i += 1
return i
# 这里[obj for obj in itreables]是列表生成式,生成可迭代对象,这里生成的是一个列表。
Concluding
运算操作的模块:operator 中的mul,函数工具箱模块:functools 中的reduce(map是调用一次函数,是python内置函数)
调用方式可以 from 模块 import 具体方法(函数),使用时直接写函数。或则import 模块,使用时用模块.函数()。比如:from functools import reduce 可以写成 import functools 使用时直接functools.reduce()。
operator模块:
functools模块:
functools模块特点是有个参数是函数,可以理解为对函数的加工的功能。reduce()最常用,同python自带库reduce()功能相同,只是functools模块的reduce()用c编写速度更快,传入可迭代序列递归调用函数并返回相应值。
还有一个partial(),它的作用是‘冻结’所调用函数的一个参数或多个参数,它的参数组成是:函数,需要冻结该函数的参数(设定一个值即冻结),当调用functools.partial()传入的参数是被调用的参数,被调用函数的部分参数被partial()所冻结。
题目参见:https://www.codewars.com
Thanks for reading