问:
【基础题】:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数
【提高题】:一球从 100 米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第 10 次落地时,共经过多少米?第 10 次反弹多高?
答:
import re def split_func(): tmp_str = input('请输入字符串:') char_num = 0 dig_num = 0 space_num = 0 other_num = 0 for i in range(len(tmp_str)): if re.match('[a-zA-Z]', tmp_str[i]): char_num += 1 elif re.match('d', tmp_str[i]): dig_num += 1 elif re.match('s', tmp_str[i]): space_num += 1 else: other_num += 1 print('字符:', char_num) print('数字:', dig_num) print('空格:', space_num) print('其他:', other_num) split_func()
方法2:
s = input('请输入字符串:') dic = {'letter': 0, 'integer': 0, 'space': 0, 'other': 0} for i in s: if i > 'a' and i < 'z' or i > 'A' and i < 'Z': dic['letter'] += 1 elif i in '0123456789': dic['integer'] += 1 elif i == ' ': dic['space'] += 1 else: dic['other'] += 1 print('统计字符串:', s) print(dic) print('------------显示结果2---------------') for i in dic: print('%s=' % i, dic[i]) print('------------显示结果3---------------') for key, value in dic.items(): print('%s=' % key, value)
【提高题】:一球从 100 米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第 10 次落地时,共经过多少米?第 10 次反弹多高?
方法1:
# 数学方法求总位移 s = 100 + (100 * (1 - 0.5 ** 9)) * 2 print("小球工经过", s, "米") # 第10次小球弹起高度 def get_height_of_bounce(initial_height): bounce_off_height = initial_height / 2 while True: yield bounce_off_height bounce_off_height = bounce_off_height / 2 number_of_bounce = 10 initial_height = 100 bounce_off_heights = [] bounce_height = get_height_of_bounce(initial_height) for i in range(number_of_bounce): bounce_off_heights.append(bounce_height.__next__()) print("每次小球弹起的高度为", bounce_off_heights) print("第10次弹起高度为", bounce_off_heights[9], "米")
方法2:
def cal_distance(n: int) -> None: distance = 100 height = distance / 2 for i in range(2, n+1): distance += 2 * height height /= 2 print(f"经过{n}次落地后总长{distance}") print(f"经过{n}次落地后反弹高度{height}") cal_distance(2) cal_distance(3) cal_distance(10)
方法3:
def reboud(n): height = 100 sum_distance = 100 for i in range(1, n+1): reboud_height = (0.5 ** i) * height sum_distance += (reboud_height * 2) if i == n-1: print("第{}次落地经过的总距离为{}米".format(n, sum_distance)) print("第{}次反弹的高度为{}米".format(n, reboud_height)) reboud(10)