下面是两种方式实现,返回所有约数的函数:
#/use/bin/env python
#-*-coding:utf-8-*-
"this is a custom module"
import math
def getfactors(num):
"""接受一个整型作为参数,
返回它所有约数的列表,
包括1和本身
"""
if num <= 0 :
return None
factors = []
for n in range(1, num+1):
if num % n == 0:
factors.append(n)
return factors
def getfactorsex(num):
"""接受一个整型作为参数,
返回它所有约数的列表,
包括1和本身
"""
if num <= 0:
return None
factors = [n for n in range(1, num+1) if (num % n == 0)]
return factors
if __name__ == '__main__':
print "打印约数"
print getfactors(4)
print getfactors(6)
print getfactors(12)
print getfactorsex(4)
print getfactorsex(6)
print getfactorsex(12)