题目16
import re
def str_parse(s: str):
content = {'alpha': [], 'space': [], 'digit': [], 'other': []}
for i in s:
if i.isalpha():
content['alpha'].append(i)
elif i.isspace():
content['space'].append(i)
elif i.isdigit():
content['digit'].append(i)
else:
content['other'].append(i)
return content
def str_parse1(s: str):
content = {'alpha': [], 'space': [], 'digit': [], 'other': []}
regex = re.compile(r'[a-zA-Z]')
x = regex.findall(s)
content['alpha'] = x
regex = re.compile(r'[0-9]')
x = regex.findall(s)
content['space'] = x
regex = re.compile(r' ')
x = regex.findall(s)
content['digit'] = x
regex = re.compile(r'[^0-9\w ]')
x = regex.findall(s)
content['other'] = x
return content
str1 = r'das154qwe4r1asdqw4&%$#@ fasd fs 165a4s6fa )(!#@$%^&^'
content = str_parse1(str1)
print(f"字母的个数为{len(content['alpha'])},它们是{content['alpha']}\n \
空格的个数为{len(content['space'])},它们是{content['space']}\n \
数字的个数是{len(content['digit'])},它们是{content['digit']}\n \
其它字符的个数是{len(content['other'])},它们是{content['other']}")
题目17
def get_sum(cnt: int, num: int):
str1 = ""
num_list = []
for i in range(cnt):
str1 = str1 + str(num) * (i + 1)
if i != cnt - 1:
str1 += "+"
num_list.append(int(str(num) * (i + 1)))
return {'key': sum(num_list), 'value': str1}
while True:
try:
num = int(input('请输入需要重复的数字:\n'))
cnt = int(input(f'请输入数字{num}重复的次数\n'))
dict1 = get_sum(cnt, num)
print(f'{dict1["key"]} = {dict1["value"]}')
except ValueError as e:
print('请输入数字!!!', e)
break
题目18
def get_sum_factor(num:int):
temp = []
for i in range(1, num):
if num % i == 0:
temp.append(i)
if sum(temp) == num:
print_str = f"{num} = "
for j, i in enumerate(temp):
if temp[0] == i and not j:
print_str += f"{i}"
else:
print_str += f"+{i}"
print(print_str)
for i in range(2, 1001):
get_sum_factor(i)
题目19
def get_height(start, times):
print(f"初始高度为:{start}米,", end='')
height_sum = 100
for i in range(times):
start /= 2
height_sum += start * 2
print(f'第{times}次高度为:{start:.3f}米,共经过{height_sum:.3f}米')
get_height(100, 10)
题目20
def calc_peaches_number(left, day):
""" 返回第一天的桃子数量
left: 剩下的桃子数量
day: 天数
"""
before = 0
cur = left
for i in range(day,1,-1):
before = (cur + 1) * 2
cur = before
print(cur)
calc_peaches_number(1,10)