13、打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。
#python3.7
importmathfor n in range(100,1000):
i= math.floor(n / 100)#百位数
j = math.floor((n - i * 100) / 10)#十位数
k = n - math.floor(n/10) * 10#个位数
if n == i**3 + j**3 + k**3:print(n)
结果:
153
370
371
407
14、将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:
(1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。
(2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数你n,重复执行第一步。
(3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步
#python3.7
defreduceNum(n):print('{} ='.format(n))if not isinstance(n, int) or n <=0:print('请输入一个正确的数字!')
exit(0)elif n in [1]:print('{}'.format(n))while n not in [1]:#循环保证递归
for index in range(2, int(n + 1)):if n % index ==0:
n/= index #n等于n/index
if n == 1:print(index)else:#index一定是素数
print('{} *'.format(index))breakreduceNum(99)
reduceNum(100)
reduceNum(210)
15、利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。
程序分析:程序分析:(a>b)?a:b这是条件运算符的基本例子。
#python3.7
score= int(input('输入分数: '))if score >= 90:
grade= 'A'
elif score >= 60:
grade= 'B'
else:
grade= 'C'
print('%d属于%s' % (score, grade))
16、输出指定格式的日期。
程序分析:使用 datetime 模块。
#python3.7
importdatetimeif __name__ == '__main__':#输出今天的日期,格式为dd/mm/yy
print(datetime.date.today().strftime('%d/%m/%y'))#创建日期对象
AliceBirthDate = datetime.date(2008, 9, 27)print(AliceBirthDate.strftime('%d/%m/%y'))
JackBirthDate= AliceBirthDate - datetime.timedelta(days=99)print(JackBirthDate.strftime('%d/%m/%y'))#日期替换
AliceAge = AliceBirthDate.replace(year = AliceBirthDate.year + 11)print(AliceAge.strftime('%d/%m/%y'))
17、输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
程序分析:利用 while 或 for 语句,条件为输入的字符不为 ' '。
importstring
s= input('请输入一个字符串: ')
letters=0
space=0
digit=0
others=0for c ins:if c.isalpha():#字母
letters +=1
elifc.isspace():
space+= 1
elifc.isdigit():
digit+= 1
else:
others+= 1
print('char = %d, space = %d, digit = %d, others = %d' % (letters, space, digit, others))
18、求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘控制。
程序分析:关键是计算出每一项的值。
#python3.7
from functools importreduce
Tn=0
Sn=[]
n= int(input('n ='))
a= int(input('a ='))for count inrange(n):
Tn= Tn +a
a= a * 10Sn.append(Tn)print(Tn)
Sn= reduce(lambda x,y: x +y, Sn)print('计算和为:', Sn)
结果:
n= 6a= 6
6
66
666
6666
66666
666666计算和为:740736
参考资料:
1、Python 100例
2、Python练习题009:水仙花数:https://www.cnblogs.com/iderek/p/5958568.html