练习题

一个字符串里面aAd123sdacD12dad2,然后遇到数字取第一个,后面的数字用来分隔,结果是这样
【aAd1,sdacD1,dad2】

import string
ss = 'aaa123bbb321cc456'
flag = 1
str_temp = ''
a = []
for i in ss:
if i.isalpha():
str_temp += i
flag = 1
elif i.isdigit():
if flag == 1:
str_temp += i
a.append(str_temp)
flag = 0
str_temp = ''
print(a)
f.close()


['aaa1', 'bbb3', 'cc4']
s = 'aaa123bb234cc345'
res = []
t = ''

for i in s:
    t += i
    if i.isdigit():
        if not t.isdigit():
            res.append(t)
        t = ''
print(res)
import re

ss = '22aaa123bbb321cc456'

temp = re.findall(pattern='D+d', string=ss)
print(temp)

查找文件中以print开头的行的内容及行号
import re
count = 1
d = {}
f = open("C:/Users/asus/Desktop/1.py",'r')
tmp = f.readline()
if tmp == '':
    d[count] = tmp
# pattern = re.compile(r"^print")

while tmp:
    str = re.findall(pattern='^print', string=tmp, flags=re.I)
    if len(str) != 0:
        # sb = "%d:%s" % (count, tmp)
        d[count] = tmp
    count += 1
    tmp = f.readline()
print(d)


斐波那契数列

0, 1, 1, 2, 3, 5, 8, 13

方法1:
def func(): n1 = 0 n2 = 1 while True: yield n1 n1, n2 = n2, n1+n2 f = func() for i in range(6): print(next(f), end=' ') #0 1 1 2 3 5
方法2:
def func(num):
    n1 = 0
    n2 = 1
    if num <= 0:
        print("不满足条件")
    else:
        for i in range(num):
            print(n1, end=' ')
            n1, n2 = n2, n1+n2
func(10)

约瑟夫生者死者小游戏
30 个人在一条船上,超载,需要 15 人下船。
于是人们排成一队,排队的位置即为他们的编号。
报数,从 1 开始,数到 9 的人下船。
如此循环,直到船上仅剩 15 人为止,问都有哪些编号的人下船了呢?

a = [i for i in range(1, 31)]
b = []
j = 0
step = 0
while True:
    if j == 15:
        break
    for i in range(len(a)):
        # print(i,a[i])
        if (i+1+step) % 9 == 0:
            print('%d 下车了' % a[i])
            j = j+1
        else:
            b.append(a[i])
    step += len(a)
    a = b
    b = []

原文地址:https://www.cnblogs.com/xinjing-jingxin/p/9801347.html