往期练习:
Python3算法基础练习:编程100例(1~5)
Python3算法基础练习:编程100例(6 ~ 10)
Python3算法基础练习:编程100例(11 ~ 15)
题目:输出指定格式的日期; 并且计算当前日期前后3天的日期
代码:
# 输出指定格式的日期
# 计算当前日期前后3天的日期
from datetime import date, datetime, timedelta
if __name__ == '__main__':
# 输出今日日期,格式为 dd/mm/yyyy。更多选项可以查看 strftime() 方法
print("当前日期:"+date.today().strftime('%d/%m/%Y'))
day = date.today()
print(("当前日期:{}").format(day))
# 当前日期的前3天,后3天的日期是?
now = datetime.now()
delta = timedelta(days=3)
n_days_after = now + delta
n_days_forward = now - delta
print("向后推迟3天的日期:{}".format((now + delta).strftime('%Y-%m-%d')))
print("向后推迟3天的日期:{}".format((now + delta).strftime('%d/%m/%Y')))
print("向前推3天的日期:{}".format(n_days_forward.strftime('%Y-%m-%d')))
print("向前推3天的日期:{}".format(n_days_forward.strftime('%d/%m/%Y')))
结果:
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数
分析: 判断字母:isalpha(); 判断空格isspace(); 判断数字 isdigit();
一个 for 循环就可以搞定
代码:
# 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数
# 判断字母:isalpha();
# 判断空格isspace();
# 判断数字 isdigit();
# 一个 for 循环就可以搞定
import string
s = input('请输入一个字符串:\n')
letters = 0
space = 0
digit = 0
others = 0
for c in s:
if c.isalpha():
letters += 1
elif c.isspace():
space += 1
elif c.isdigit():
digit += 1
else:
others += 1
print ('英文字母 = %d,空格 = %d,数字 = %d,其它字符 = %d' % (letters,space,digit,others))
题目:求s=a+aa+aaa+aaaa+aa…a的值,其中a是一个数字。
例如 2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘控制
代码:
from functools import reduce
Temp = 0
Sn = []
print("计算几位数相加,请输入 n:")
n = int(input('n = '))
print("请输入 a 的值:")
a = int(input('a = '))
for count in range(n):
Temp = Temp + a
a = a * 10
Sn.append(Temp)
print(Temp)
Sum = reduce(lambda x, y: x + y, Sn) # 使用 lambda 匿名函数
print("计算结果为:", Sum)
题目:一个数如果恰好等于它的因子之和,这个数就称为"完数"。
例如 6=1+2+3.
编程找出1000以内的所有完数
代码:
# 一个数如果恰好等于它的因子之和,这个数就称为"完数"。
#
# 例如 6=1+2+3.
#
# 编程找出1000以内的所有完数
# 标准输出
from sys import stdout
for j in range(2, 1001):
k = [] # 存放因子
n = -1 # 因子的索引 输出时使用
s = j # 暂存 j 的原始值
for i in range(1, j): # 找因子
if j % i == 0:
n += 1 # 记录对应因子的索引
s -= i # 判断 j 是否等于因子之和
k.append(i)
if s == 0: # 是元数
stdout.write(str(j)) # 不会默认换行
stdout.write(' = ')
for i in range(n): # 到 n 不是 n+1;为了最后一个输出
stdout.write(str(k[i]))
stdout.write(' + ')
print(k[n]) # 注意此处对于 + 与 最后一个因子的输出处理 ,n 为索引
结果:
题目:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
代码:
简单的数学问题 核心在于 每次落地后反跳回原高度的一半!!
# 一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,
# 求它在第10次落地时,共经过多少米?
# 第10次反弹多高?
# 核心在于 每次落地后反跳回原高度的一半!!
height = [] # 每一次的反弹高度
hei = 100 # 起始高度
num = 10 # 次数
for i in range(1, num + 1):
# 每次落地后反跳回原高度的一半
hei /= 2
height.append(hei)
print('它在第10次落地时,共经过 {0} 米'.format(sum(height) * 2 - height[9] * 2 + 100))
print('第10次反弹 {0} 米'.format(height[-1]))
结果: