<jupyter_start><jupyter_text>学习记录2021-06-05 [X] 第1-20个实例 2021-06-10 [X] 第21-26个实例2021-06-18 [x] 第27-37个实例2021-06-21 [x] 第38-60个实例2021-06-22 [x] 第61-80个实例2021-06-23 [x] 第81-100个实例  实例001：数字组合题目 有四个数字：1、2、3、4，能组成多少个互不相同且无重复数字的三位数？各是多少？<jupyter_code># **程序分析** 遍历全部可能，把有重复的剃掉。

total = 0
for i in range(1, 5):
    for j in range(1, 5):
        for k in range(1, 5):
            if ((i != j) and (j != k) and (k != i)):
                print(i, j, k)
                total += 1
print("所组成的互不相同且无重复的数字有: {}".format(total))
# print("所组成的互不相同且无重复的数字有: %d",total)
# 简便方法，用itertools中的排列permutations

import itertools
sum2 = 0
a = [1, 2, 3, 4]
for i in itertools.permutations(a, 3):
    print(i)
    sum2 += 1
print(sum2)<jupyter_output><empty_output><jupyter_text>实例002：“个税计算”题目 企业发放的奖金根据利润提成。利润(I)低于或等于10万元时，奖金可提10%；利润高于10万元，低于20万元时，低于10万元的部分按10%提成，高于10万元的部分，可提成7.5%；20万到40万之间时，高于20万元的部分，可提成5%；40万到60万之间时高于40万元的部分，可提成3%；60万到100万之间时，高于60万元的部分，可提成1.5%，高于100万元时，超过100万元的部分按1%提成，从键盘输入当月利润I，求应发放奖金总数？<jupyter_code># 程序分析：分区间计算即可

profit = int(input("Show me the money: "))
bonus = 0
thresholds = [100000, 100000, 200000, 200000, 400000]
rates = [0.1, 0.075, 0.05, 0.03, 0.015, 0.01]
for i in range(len(thresholds)):
    if profit <= thresholds[i]:
        bonus += profit * rates[i]
        profit = 0
        break
    else:
        bonus += thresholds[i]*rates[i]
        profit -= thresholds[i]
bonus += profit * rates[-1]
print(bonus)<jupyter_output><empty_output><jupyter_text>实例003：完全平方数题目 一个整数，它加上100后是一个完全平方数，再加上168又是一个完全平方数，请问该数是多少？<jupyter_code>## 程序分析：因为168对于指数爆炸来说实在太小了，所以可以直接省略数学分析，用最朴素的方法来获取上限：

n  = 0
while (n+1)**2 - n*n <=168:
    n += 1

print(n+1)
# 思路：最坏的结果是n的平方与(n+1)的平方刚好差168，由于是平方的关系，不可能存在比这跟大的间隙。
# 至于判断是否是完全平方数，最简单的方法是：平方根的值小数为0即可。

# 先找到n的上限
n = 0
while (n+1)**2 - n*n <= 168:
    n += 1

for i in range((n+1)**2):
    if i**0.5 == int(i**0.5) and (i+168)**0.5 == int((i+168)**0.5):
        print(i-100)

import math
math.sqrt(1681+168)<jupyter_output><empty_output><jupyter_text>实例004：这天第几天题目 输入某年某月某日，判断这一天是这一年的第几天？<jupyter_code># 程序分析：特殊情况，闰年时需考虑二月多加一天

# 四年一闰，百年不闰，四百年再闰
def isLeapYear(y):
    return (y%400 == 0 or (y%4 == 0 and y%100 != 0))
DofM = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30]

res = 0
year = int(input("Year: "))
month = int(input("Month: "))
day = int(input("Day: "))

if isLeapYear(year):
    DofM[2] += 1
for i in range(month):
    res += DofM[i]
print(res+day)<jupyter_output><empty_output><jupyter_text>实例005：三数排序题目 输入三个整数x,y,z，请把这三个数由小到大输出。<jupyter_code># 程序分析：练练手就随便找个排序算法实现一下，偷懒就直接调用函数。

raw = []

for i in range(3):
    x = int(input("int%d: "%(i)))
    raw.append(x)

for i in range(len(raw)):
    for j in range(i, len(raw)):
        if raw[i] > raw[j]:
            raw[i], raw[j] = raw[j], raw[i]

print(raw)

raw2 =[]
for i in range(3):
    y = int(input("int%d:"%(i)))
    raw2.append(y)
print(sorted(raw2))<jupyter_output><empty_output><jupyter_text>实例006：斐波那契数列题目 斐波那契数列。<jupyter_code># 程序分析：斐波那契数列(Fibonacci sequence),从1，1开始，后面的每一项等于前面两项之和。图啥啊？图方便就递归实现，图性能就用循环。

# 递归实现
def Fib(n):
    return 1 if n<= 2 else Fib(n-1) + Fib(n-2)
print(Fib(int(input("请输入斐波那契数列的项数："))))

# 朴素循环实现

target = int(input("请输入斐波那契数列的项数："))
res = 0
a, b = 1, 1
for i in range(target-1):
    a,b = b, a+b
print(a)<jupyter_output><empty_output><jupyter_text>实例007：copy题目 将一个列表的数据复制到另一个列表中。<jupyter_code># 程序分析：使用列表[:]，拿不准可以调用copy模块。

import copy
a = [1, 2, 3, 4, ['a', 'b']]

b = a # 赋值
c = a[:] # 浅拷贝
d = copy.copy(a) # 浅拷贝
e = copy.deepcopy(a) # 深拷贝

a.append(5)
a[4].append('c')

print("a=", a)
print("b=", b)
print("c=", c)
print("d=", d)
print("e=", e)<jupyter_output><empty_output><jupyter_text>实例008：九九乘法表题目 输出 9*9 乘法口诀表。<jupyter_code># 程序分析：分行与分列考虑，共9行9列，i控制行，j控制列

for i in range(1, 10):
    for j in range(1, i+1):
        print("%d*%d=%2ld"%(i,j,i*j), end=' ') # end=' '意思是末尾不换行，加空格。
    print() # 控制每一行换行<jupyter_output><empty_output><jupyter_text>实例009：暂停一秒输出题目 暂停一秒输出。<jupyter_code># 程序分析：使用time模块的sleep()函数

import time

for i in range(4):
    # print(str(int(time.time()))[-2:])
    print(time.time())
    time.sleep(1)<jupyter_output><empty_output><jupyter_text>实例010：给人看的时间题目 暂停一秒输出，并格式化当前时间。<jupyter_code>import time

for i in range(4):
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
    print(time.time())
    time.sleep(1)<jupyter_output><empty_output><jupyter_text>实例011：养兔子题目 有一对兔子，从出生后第3个月起每个月都生一对兔子，小兔子长到第三个月后每个月又生一对兔子，假如兔子都不死，问每个月的兔子总数为多少？<jupyter_code>"""
程序分析：我认为原文的解法有点扯，没有考虑3个月成熟的问题，人家还是婴儿怎么生孩子？考虑到三个月成熟，可以构建四个数据，其中：一月兔每个月长大成为二月兔，二月兔变三月兔，三月兔变成年兔，成年兔（包括新成熟的三月兔）生等量的一月兔。
"""

month = int(input("繁殖几个月？："))
month_1 = 1
month_2 = 0
month_3 = 0
month_elder = 0
for i in range(month):
    month_1,month_2,month_3,month_elder = month_elder+month_3, month_1, month_2, month_elder+month_3
    total = month_1 + month_2 + month_3 + month_elder
    print("第%d个月共"%(i+1), total, "对兔子")
    print("其中1月兔: ", month_1)
    print("其中2月兔: ", month_2)
    print("其中3月兔: ", month_3)
    print("其中成年兔: ", month_elder)<jupyter_output><empty_output><jupyter_text>实例012：100到200的素数题目 判断101-200之间有多少个素数，并输出所有素数。<jupyter_code>"""程序分析 判断素数的方法：用一个数分别去除2到sqrt(这个数)，如果能被整除，则表明此数不是素数，反之是素数。用else可以进一步简化代码.
"""

import math
for i in range(100, 200):
    flag = 0
    for j in range(2, round(math.sqrt(i))+1): # round() 方法返回浮点数x的四舍五入值。
        if i%j ==0:
            flag = 1
            break
    if flag:
        continue
    print(i)

print("\n Simplify the code with 'else'\n")

for i in range(100, 200):
    for j in range(2, round(math.sqrt(i))+1):
        if i % j == 0:
            break
    else: # else的这种用法倒是第一次见。
        print(i)<jupyter_output><empty_output><jupyter_text>实例013：所有水仙花数题目 打印出所有的"水仙花数"，所谓"水仙花数"是指一个三位数，其各位数字立方和等于该数本身。例如：153是一个"水仙花数"，因为153=1的三次方＋5的三次方＋3的三次方。<jupyter_code>"""
程序分析：利用for循环控制100-999个数，每个数分解出个位，十位，百位。
"""

for i in range(100, 1000):
    s = str(i)
    one = int(s[-1])
    ten = int(s[-2])
    hun = int(s[-3])
    if i == one**3 + ten**3 + hun**3:
        print(i)<jupyter_output><empty_output><jupyter_text>实例014：分解质因数题目 将一个整数分解质因数。例如：输入90,打印出`90 =2*3*3*5`。<jupyter_code>"""
程序分析: 根本不需要判断是否是质数，从2开始向数本身遍历，能整除的肯定是最小的质数。
"""

target = int(input("请输入一个整数: "))
print(target, "=", end=" ")

if target < 0:
    target=abs(target)
    print('-1*', end='')

flag = 0
if target <= 1:
    print(target)
    flag=1

while True:
    if flag:
        break
    for i in range(2, int(target+1)):
        if target % i == 0:
            print("%d"%i, end='')
            if target == i:
                flag=1
                break
            print("*", end="")
            target /= i
            break<jupyter_output><empty_output><jupyter_text>实例015：分数归档题目 利用条件运算符的嵌套来完成此题：学习成绩>=90分的同学用A表示，60-89分之间的用B表示，60分以下的用C表示。<jupyter_code># 程序分析：用条件判断即可。

points = int(input("请输入分数："))

if points >= 90:
    grade = "A"
elif points < 60:
    grade = "C"
else:
    grade = "B"
print(grade)<jupyter_output><empty_output><jupyter_text>实例016：输出日期题目 输出指定格式的日期。<jupyter_code># 程序分析：使用datetime模块。

import datetime
print(datetime.date.today())
print(datetime.date(233,2,3))
print(datetime.date.today().strftime("%d/%m/%Y"))

day = datetime.date(111,2,3)
day = day.replace(year=day.year + 22)
print(day)<jupyter_output><empty_output><jupyter_text>实例017：字符串构成题目 输入一行字符，分别统计出其中英文字母、空格、数字和其它字符的个数。<jupyter_code>"""
程序分析：利用while或for语句，条件为输入的字符不为'\n'
"""
string = input("请输入字符串：")
alp = 0
num = 0
spa = 0
oth = 0
for i in range(len(string)):
    if string[i].isspace():
        spa += 1
    elif string[i].isdigit():
        num += 1
    elif string[i].isalpha():
        alp += 1
    else:
        oth += 1
print("space:", spa)
print("digit:", num)
print("alpha:", alp)
print("other:", oth)<jupyter_output><empty_output><jupyter_text>实例018：复读机相加题目 求s=a+aa+aaa+aaaa+aa…a的值，其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加)，几个数相加由键盘控制。<jupyter_code># 程序分析：用字符串解决。

a = input("被加数字: ") # a代表字符串

n = int(input("加几次？: "))

res = 0

for i in range(n):
    res += int(a)
    a += a[0] # a[0]代表字符串，2+2='22'
    # print(a)
print("结果是: ", res)<jupyter_output><empty_output><jupyter_text>实例019：完数题目 一个数如果恰好等于它的因子之和，这个数就称为"完数"。例如6=1＋2＋3.编程找出1000以内的所有完数。<jupyter_code>"""
程序分析：将每一对因子加进集合，在这个过程中已经自动去重.最后的结果要求不计算其本身。
"""
def factor(num):
    target = int(num)
    res = set()
    for i in range(1, num):
        if num%i == 0:
            res.add(i)
            res.add(num/i)
    return res

for i in range(2, 1001):
    if i == sum(factor(i))-i:
        print(i)

a = set()
a.add(1)
print(a)
print(sum(a))<jupyter_output><empty_output><jupyter_text>实例020：高空抛物题目 一球从100米高度自由落下，每次落地后反跳回原高度的一半；再落下，求它在第10次落地时，共经过多少米？第10次反弹多高？<jupyter_code>high = 200
total = 100
for i in range(10):
    high /= 2
    total += high
    print(high/2)
print("总长: ",total)<jupyter_output><empty_output><jupyter_text>实例021：猴子偷桃题目 猴子吃桃问题：猴子第一天摘下若干个桃子，当即吃了一半，还不瘾，又多吃了一个.第二天早上又将剩下的桃子吃掉一半，又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时，见只剩下一个桃子了。求第一天共摘了多少。<jupyter_code>"""
程序分析 按规则反向推断：猴子有一个桃子，他偷来一个桃子，觉得不够又偷来了与手上等量的桃子，一共偷了9天。
"""

# 逆向思维，喵喵喵

peach = 1
for i in range(9):
    peach = (peach+1)*2
print(peach)<jupyter_output><empty_output><jupyter_text>实例022：比赛对手题目 两个乒乓球队进行比赛，各出三人。甲队为a,b,c三人，乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比，c说他不和x,z比，请编程序找出三队赛手的名单。<jupyter_code># 程序分析 找到条件下不重复的三个对手即可。

a = set(['x', 'y', 'z'])
b = set(['x', 'y', 'z'])
c = set(['x', 'y', 'z'])
c -= set(('x', 'z'))
a -= set('x')
for i in a:
    for j in b:
        for k in c:
            if len(set((i, j, k))) == 3:
                print("a: %s, b: %s, c: %s"%(i, j, k))
print(a)
print(b)
print(c)<jupyter_output><empty_output><jupyter_text>实例023：画菱形题目 打印出如下图案（菱形）:<jupyter_code># 程序分析：递归调用即可

def draw(num):
    a = "*" * (2*(4 - num) + 1)
    print(a.center(9,' '))
    if num != 1:
        draw(num-1)
        print(a.center(9, ' '))
draw(4)<jupyter_output><empty_output><jupyter_text>实例024：斐波那契数列II题目 有一分数序列：2/1，3/2，5/3，8/5，13/8，21/13…求出这个数列的前20项之和。<jupyter_code># 程序分析：就是斐波那契数列的最后一项除以前一项

a = 2.0
b = 1.0
s = 0
for n in range(1, 21):
    s += a / b
    a, b = a + b, a
    print(s)<jupyter_output><empty_output><jupyter_text>实例025：阶乘求和题目 求1+2!+3!+…+20!的和。<jupyter_code>%%time
# 程序分析：1+2!+3!+...+20!=1+2(1+3(1+4(...20(1))))
import time

T1 = time.time()
res = 1
for i in range(20, 1, -1):
    res = i*res + 1
print(res)

T2 = time.time()

print("该单元运行了多长时间: {}s".format(T2-T1)) # Wall time: 999 µs
%%time
# 另解：自定义求阶乘的函数，然后递归
# %%time 将会给出cell的代码运行一次所花费的时间 
"""单元命令需要放在第一行"""
# %time 将会给出当前行的代码运行一次所花费的时间。
# %timeit 使用Python的timeit模块，它将会执行一个语句100，000次(默认情况下)，然后给出运行最快3次的平均值。
import time

T1 = time.time()

def Factorial(num):
    return num*Factorial(num-1) if num>2 else num*1

max = 20
res = 0
for i in range(1,max+1):
    res += Factorial(i)
print(res)

T2 = time.time()

print("该单元运行了多长时间: {}s".format(T2-T1)) # Wall time: 1 ms<jupyter_output>2561327494111820313
该单元运行了多长时间: 0.0010027885437011719s
Wall time: 1 ms<jupyter_text>实例026：递归求阶乘题目 利用递归方法求5!。<jupyter_code># 程序分析：利用递归方法求5！

def factorial(n):
    return n*factorial(n-1) if n > 1 else 1

print(factorial(5))<jupyter_output>120<jupyter_text>实例027：递归输出题目 利用递归函数调用方式，将所输入的5个字符，以相反顺序打印出来。<jupyter_code># 程序分析：递归真是蠢方法

def rec(string):
    if len(string) != 1:
        rec(string[1:])
    print(string[0], end='')

print("<NAME>", end="")
print("Hello world!")
rec(input('string here:'))<jupyter_output>Ch<NAME>Hello world!
nauygnefnehc<jupyter_text>实例028：递归求等差数列题目 有5个人坐在一起，问第五个人多少岁？他说比第4个人大2岁。问第4个人岁数，他说比第3个人大2岁。问第三个人，又说比第2人大两岁。问第2个人，说比第一个人大两岁。最后问第一个人，他说是10岁。请问第五个人多大？<jupyter_code># 程序分析：就一等差数列

def age(n):
    if n == 1:
        return 10
    return 2 + age(n-1)

print(age(5))
print(10+12+14+16+18)<jupyter_output>18
70<jupyter_text>实例029：反向输出题目 给一个不多于5位的正整数，要求：一、求它是几位数，二、逆序打印出各位数字。<jupyter_code>"""学会分解每一位数，用字符串的方法总是比较省事。
"""

n = int(input("输入一个正整数："))
n = str(n)
print("%d位数"%len(n))
print(n[::-1])<jupyter_output>5位数
54321<jupyter_text>实例030：回文数题目 一个5位数，判断它是不是回文数。即12321是回文数，个位与万位相同，十位与千位相同。<jupyter_code># 程序分析：用字符串比较方便，就算输入的不是数字都ok

n = input("随便你输入啥啦：") # input默认输入字符串
a = 0
b = len(n) -1
flag = True
while a < b:
    if n[a] != n[b]:
        print("不是回文串")
        flag = False
        break
    a, b = a+1, b-1
if flag:
    print("是回文串")<jupyter_output>是回文串<jupyter_text>实例031：字母识词题目 请输入星期几的第一个字母来判断一下是星期几，如果第一个字母一样，则继续判断第二个字母。<jupyter_code># 程序分析：这里用字典的形式直接将对照关系存好

weekT = {'h':'thursday', 'u':'tuesday'}

weekS = {'a':'saturday', 'u':'sunday'}

week = {'t':weekT, 's':weekS, 
'm':'monday', 'w':'wensday', 'f':'friday'}

a = week[str(input("请输入第一位字母：")).lower()]

if a == weekT or a == weekS:
    print(a[str(input("请输入第二位字母：")).lower()])
else:
    print(a)<jupyter_output>sunday<jupyter_text>实例032：反向输出II题目 按相反的顺序输出列表的值。<jupyter_code># 程序分析：无

a = ['one', 'two', 'three']

print(a[::-1])<jupyter_output>['three', 'two', 'one']<jupyter_text>实例033：列表转字符串题目 按逗号分隔列表。<jupyter_code># 程序分析：无

L = [1, 2, 3, 4, 5]
print(','.join(str(n) for n in L))<jupyter_output>1,2,3,4,5<jupyter_text>实例034：调用函数题目 练习函数调用。<jupyter_code># 程序分析：无

def hello():
    print("Hello World!")

def helloAgain():
    for i in range(2):
        hello()

if __name__ == "__main__":
    helloAgain()<jupyter_output>Hello World!
Hello World!<jupyter_text>实例035：设置输出颜色题目 文本颜色设置<jupyter_code># 程序分析：无

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
print(bcolors.WARNING + "警告的颜色字体？" + bcolors.ENDC)
print(bcolors.HEADER + "标题的颜色字体？" + bcolors.ENDC)
print(bcolors.OKBLUE + "OKBLUE的颜色字体？" + bcolors.ENDC)
print(bcolors.OKGREEN + "OKGREEN的颜色字体？" + bcolors.ENDC)
print(bcolors.FAIL + "FAIL的颜色字体？" + bcolors.ENDC)<jupyter_output>[93m警告的颜色字体？[0m
[95m标题的颜色字体？[0m
[94mOKBLUE的颜色字体？[0m
[92mOKGREEN的颜色字体？[0m
[91mFAIL的颜色字体？[0m<jupyter_text>实例036：算素数题目 求100之内的素数。<jupyter_code># 程序分析：用else执行for循环的奖励代码（如果for是正常完结，非break）。

low = int(input("下限："))
high = int(input("上限："))
for i in range(low, high+1):
    if i > 1:
        for j in range(2, i):
            if (i % j) == 0: # 判断素数的方式：该数除以从2到它本身的遍历，判断是否能整除
                break
        else:
            print(i, end=" ")<jupyter_output>2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97<jupyter_text>实例037：排序题目 对10个数进行排序。<jupyter_code># 程序分析：同实例005 练练手就随便找个排序算法实现一下，偷懒就直接调函数。

# 排序

raw = []
for i in range(10):
    x = int(input("int%d: "%(i)))
    raw.append(x)

for i in range(len(raw)):
    for j in range(i, len(raw)):
        if raw[i] > raw[j]:
            raw[i], raw[j] = raw[j], raw[i]
print(raw)<jupyter_output>[0, 2, 3, 3, 4, 6, 6, 7, 8, 9]<jupyter_text>实例038：矩阵对角线之和题目 求一个3*3矩阵主对角线元素之和。<jupyter_code>mat = [[1, 2, 3],
[3, 4, 5],
[4, 5, 6]]

res = 0
for i in range(len(mat)):
    res+=mat[i][i]
print(res)<jupyter_output>11<jupyter_text>实例039：有序列表插入元素题目 有一个已经排好序的数组。现输入一个数，要求按原来的规律将它插入数组中。<jupyter_code># 程序分析：首先判断此数是否大于最后一个数，然后再考虑插入中间的数的情况，插入后此元素之后的数，依次后移一个位置。

list = [1, 10, 100, 1000, 10000, 100000]
n = int(input("insert a number: "))
list.append(n)
for i in range(len(list)-1):
    if list[i] >=n:
        for j in range(i, len(list)):
            list[j], list[-1] = list[-1], list[j]
            break
print(list)<jupyter_output>[1, 10, 99, 100, 1000, 10000, 100000]<jupyter_text>实例040：逆序列表题目 将一个数组逆序输出。<jupyter_code># 程序分析: 依次交换位置，或者直接调用reverse方法

# 方法1：依次交换位置

list = [1, 10, 100, 1000, 10000, 100000]
for i in range(int(len(list)/2)):
    list[i], list[len(list)-1-i] = list[len(list)-1-i], list[i]

print("第一种实现: ")
print(list)

# 方法二：调用reverse方法
list = [1, 10, 100, 1000, 10000, 100000]
print("第二种实现：")
list.reverse()
print(list)<jupyter_output>第一种实现: 
[100000, 10000, 1000, 100, 10, 1]
第二种实现：
[100000, 10000, 1000, 100, 10, 1]<jupyter_text>实例041：类的方法与变量题目 模仿静态变量的用法。<jupyter_code># 程序分析：构造类，了解类的方法与变量

def dummy():
    i = 0
    print(i)
    i += 1

class cls:
    i = 0
    def dummy(self):
        print(self.i)
        self.i += 1

a = cls()
for i in range(50):
    print("*",i,"*")
    dummy()
    a.dummy()

"""
结果分析：自定义的函数中的变量是局部变量
自定义类中的变量是全局变量
"""<jupyter_output>* 0 *
0
0
* 1 *
0
1
* 2 *
0
2
* 3 *
0
3
* 4 *
0
4
* 5 *
0
5
* 6 *
0
6
* 7 *
0
7
* 8 *
0
8
* 9 *
0
9
* 10 *
0
10
* 11 *
0
11
* 12 *
0
12
* 13 *
0
13
* 14 *
0
14
* 15 *
0
15
* 16 *
0
16
* 17 *
0
17
* 18 *
0
18
* 19 *
0
19
* 20 *
0
20
* 21 *
0
21
* 22 *
0
22
* 23 *
0
23
* 24 *
0
24
* 25 *
0
25
* 26 *
0
26
* 27 *
0
27
* 28 *
0
28
* 29 *
0
29
* 30 *
0
30
* 31 *
0
31
* 32 *
0
32
* 33 *
0
33
* 34 *
0
34
* 35 *
0
35
* 36 *
0
36
* 37 *
0
37
* 38 *
0
38
* 39 *
0
39
* 40 *
0
40
* 41 *
0
41
* 42 *
0
42
* 43 *
0
43
* 44 *
0
44
* 45 *
0
45
* 46 *
0
46
* 47 *
0
47
* 48 *
0
48
* 49 *
0
49<jupyter_text>实例042：变量作用域题目 学习使用auto定义变量的用法。<jupyter_code># 程序分析：Python中变量作用域

i = 0
n = 0
def dummy():
    i = 0
    print(i)
    i += 1
def dummy2():
    global n
    print(n)
    n += 1
print("函数内部的同名变量: ")
for j in range(20):
    print('*',i,"*")
    dummy()
    i += 1
print("global声明同名变量：")
for k in range(20):
    print('*',n,"*")
    dummy2()
    n += 10<jupyter_output>函数内部的同名变量: 
* 0 *
0
* 1 *
0
* 2 *
0
* 3 *
0
* 4 *
0
* 5 *
0
* 6 *
0
* 7 *
0
* 8 *
0
* 9 *
0
* 10 *
0
* 11 *
0
* 12 *
0
* 13 *
0
* 14 *
0
* 15 *
0
* 16 *
0
* 17 *
0
* 18 *
0
* 19 *
0
global声明同名变量：
* 0 *
0
* 11 *
11
* 22 *
22
* 33 *
33
* 44 *
44
* 55 *
55
* 66 *
66
* 77 *
77
* 88 *
88
* 99 *
99
* 110 *
110
* 121 *
121
* 132 *
132
* 143 *
143
* 154 *
154
* 165 *
165
* 176 *
176
* 187 *
187
* 198 *
198
* 209 *
209<jupyter_text>实例043：作用域、类的方法与变量题目 模仿静态变量(static)另一案例。<jupyter_code># 程序分析 综合实例041和实例042。

class dummy:
    num = 1
    def Num(self):
        print("class dummy num: ", self.num)
        print("global num: ", num)
        self.num += 1

n = dummy()
num = 1
for i in range(5):
    num *= 10
    n.Num()<jupyter_output>class dummy num:  1
global num:  10
class dummy num:  2
global num:  100
class dummy num:  3
global num:  1000
class dummy num:  4
global num:  10000
class dummy num:  5
global num:  100000<jupyter_text>实例044：矩阵相加题目 计算两个矩阵相加。<jupyter_code># 程序分析：创建一个新的矩阵，使用for迭代并取出X和Y矩阵中对应位置的值，相加后放到新矩阵的对应位置中

X = [[12, 7, 3],
    [4, 5, 6],
    [7, 8, 9]]

Y = [[5, 8, 1],
    [6, 7, 3],
    [4, 5, 9]]

res = [[0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]]

print("res[0]=", res[0]) # 输出第一行的元素
# print("res[0]=", res[0])

for i in range(len(res)): # res代表行的数量
    for j in range(len(res[0])): # res[0]代表列的数量
        res[i][j] = X[i][j] + Y[i][j]
print(res)
print("res[0]=", res[0])<jupyter_output>res[0]= [0, 0, 0]
[[17, 15, 4], [10, 12, 9], [11, 13, 18]]
res[0]= [17, 15, 4]<jupyter_text>实例045：求和题目 统计 1 到 100 之和。<jupyter_code>res = 0
for i in range(1, 101):
    res += i
print(res)<jupyter_output>5050<jupyter_text>实例046：打破循环题目 求输入数字的平方，如果平方运算后小于 50 则退出。<jupyter_code>while True:
    try:
        n = float(input("输入一个数字： "))
    except:
        print("输入错误")
        continue
    dn = n ** 2
    print("其平方和为：", dn)
    if dn < 50:
        print("平方和小于50，退出")
        break<jupyter_output>输入错误
其平方和为： 16.0
平方和小于50，退出<jupyter_text>实例047：函数交换变量题目 两个变量值用函数互换。<jupyter_code>def exc(a, b):
    return (b, a)

a = 0
b = 10
a, b = exc(a, b)
print(a, b)<jupyter_output>10 0<jupyter_text>实例048：数字比大小题目 数字比较。<jupyter_code>a = int(input("a="))
b = int(input("b="))
if a < b:
    print("a<b")
elif a > b:
    print("a>b")
else:
    print("a=b")<jupyter_output>a<b<jupyter_text>实例049：lambda题目 使用lambda来创建匿名函数。<jupyter_code>Max = lambda x, y : x*(x>=y) + y*(y>x)
Min = lambda x, y : x*(x<=y) + y*(y<x)

a = int(input("1: "))
b = int(input("2: "))

print(Max(a, b))
print(Min(a, b))<jupyter_output>2222
10<jupyter_text>实例050：随机数题目 输出一个随机数。<jupyter_code># 程序分析：使用random模块

import random 
for i in range(20):
    print(random.uniform(10, 20))<jupyter_output>10.492790771605694
11.760329126434282
15.814332801234947
10.395333678274968
15.557895440483698
12.204704365652816
16.421288161623902
15.281680292071304
16.352176056257292
19.026751680141086
15.000148168432032
16.331487538763163
17.215621670851977
19.206565427413857
18.822152199842947
14.687490465623867
12.158905246235477
10.873428952999618
16.816366343978977
16.01155424750104<jupyter_text>实例051：按位与题目 学习使用按位与 & 。<jupyter_code>""" 按位与：一假即假
0&0=0
0&1=0
1&0=0
1&1=1
"""

a = 0o77 # 八进制 7*8+7=63
print(a)
b = a&3
print(b)
c = b&7
print(c)

"""
63 = 0011 1111
3  = 0000 0011
7  = 0000 0111
"""<jupyter_output>63
3
3<jupyter_text>实例052：按位或题目 学习使用按位或 | 。<jupyter_code>""" 按位或：一真即真
0|0=0
0|1=1
1|0=1
1|1=1
"""

a = 0o77
print(a|3)
print(a|3|7)<jupyter_output>63
63<jupyter_text>实例053：按位异或题目 学习使用按位异或 ^ 。<jupyter_code>""" 按位异或：对应的位不相同为真，对应的位相同为假
0^0=0
0^1=1
1^0=1
1^1=0
"""

"""
63 = 0011 1111
3  = 0000 0011
7  = 0000 0111
"""
a = 0o77
print(a^3) # 60
print(a^3^7) # 63-(4)<jupyter_output>60
59<jupyter_text>实例054：位取反、位移动题目 取一个整数a从右端开始的4～7位。<jupyter_code>"""
程序分析：可以这样考虑
1. 先使a右移4位。
2. 设置一个低4位全为1，其余全为0的数。可用（0<<4）
3. 将上面二者进行&运算。
"""

"""
左移：数字向左移动，右侧补0
右移：数字向右移动，左侧补0

"""

a = int(input("输入一个数字："))
b = 0 # 0
b = ~b # 1
b = b << 4 # 10000
b = ~b # 1111

c = a>>4
d = c&b
print("a:", bin(a))
print("b:", bin(b))
print("c:", bin(c))
print("d:", bin(d))
print(c)
print(d)<jupyter_output>a: 0b111111
b: 0b1111
c: 0b11
d: 0b11
3
3<jupyter_text>实例055：按位取反题目 学习使用按位取反~。<jupyter_code>"""
按位取反：~n = -(n+1)
~0=1；
~1=0
"""

"""
计算机普遍使用补码表示负数,欲求其源码，需先对其取反，然后再加1.
"""
print(~234)
print(~~234)<jupyter_output>-235
234<jupyter_text>实例056：画圈题目 画图，学用circle画圆形。<jupyter_code>from tkinter import *
canvas = Canvas(width=800, height=600, bg="yellow")
canvas.pack(expand=YES, fill=BOTH)
k = 1
j = 1
for i in range(26):
    canvas.create_oval(310-k, 250-k, 310+k, 250+k, width=1)
    k += j
    j += 0.3
mainloop()<jupyter_output><empty_output><jupyter_text>实例057：画线题目 画图，学用line画直线。<jupyter_code>if __name__ == "__main__":
    from tkinter import *

    canvas = Canvas(width=300, height=300, bg="green")
    canvas.pack(expand=YES, fill=BOTH)
    x0 = 263
    y0 = 263
    y1 = 275
    x1 = 275
    for i in range(19):
        canvas.create_line(x0, y0, x0, y1, width=1, fill="red")
        x0 = x0 - 5
        y0 = y0 - 5
        x1 = x1 + 5
        y1 = y1 + 5

    x0 = 263
    y1 = 275
    y0 = 263
    for i in range(21):
        canvas.create_line(x0, y0, x0, y1, fill="red")
        x0 += 5
        y0 += 5
        y1 += 5

    mainloop()<jupyter_output><empty_output><jupyter_text>实例058：画矩形题目 画图，学用rectangle画方形。<jupyter_code>if __name__ == "__main__":
    from tkinter import *
    root = Tk()
    root.title("Canvas")
    canvas = Canvas(root, width=400, height=400, bg="yellow")
    x0 = 263
    y0 = 263
    y1 = 275
    x1 = 275
    for i in range(19):
        canvas.create_rectangle(x0, y0, x1, y1)
        x0 -= 5
        y0 -= 5
        x1 += 5
        y1 += 5
    
    canvas.pack()
    root.mainloop()<jupyter_output><empty_output><jupyter_text>实例059：画图（丑）题目 画图，综合例子。<jupyter_code>if __name__ == "__main__":
    from tkinter import *
    canvas = Canvas(width=300, height=300, bg="green")
    canvas.pack(expand=YES, fill=BOTH)
    x0 = 150
    y0 = 100
    canvas.create_oval(x0-10, y0-10, x0+10, y0+10)
    canvas.create_oval(x0-20, y0-20, x0+20, y0+20)
    canvas.create_oval(x0-50, y0-50, x0+50, y0+50)
    import math
    B = 0.809
    for i in range(16):
        a = 2 * math.pi / 16 * i
        x = math.ceil(x0 + 48 * math.cos(a)) # 向上取整
        y = math.ceil(y0 + 48 * math.sin(a) * B)
        canvas.create_line(x0, y0, x, y, fill="red")
    canvas.create_oval(x0-60, y0-60, x0+60, y0+60)

    for k in range(51):
        a = (a * math.pi / 16) * i + (2 * math.pi / 180) * k - 1
        x = math.ceil(x0 + 48 * math.cos(a)) 
        y = math.ceil(y0 + 48 * math.sin(a) * B)
        canvas.create_line(x0, y0, x, y, fill="red")
    mainloop()<jupyter_output><empty_output><jupyter_text>实例060：字符串长度题目 计算字符串长度。<jupyter_code>s = input("请输入一段字符串：")
print(len(s))<jupyter_output>12<jupyter_text>实例061：杨辉三角题目 打印出杨辉三角形前十行。<jupyter_code>def generate(numRows):
    r = [[1]]
    for i in range(1, numRows):
        r.append(list(map(lambda x,y:x+y, [0]+r[-1], r[-1]+[0]))) # 杨辉三角的匿名函数
    return r[:numRows]

a=generate(10)
for i in a:
    print(i)
print(a)
r = [[1]]

print([0]+r[-1])

print(r[-1]+[0])<jupyter_output>[0, 1]
[1, 0]<jupyter_text>实例062：查找字符串题目 查找字符串。<jupyter_code>s1 = "aabbxuebixuebi"
s2 = "ab"
s3 = "xue"
print(s1.find(s2))
print(s1.find(s3))<jupyter_output>1
4<jupyter_text>实例063：画椭圆题目 画椭圆。<jupyter_code>if __name__ == "__main__":
    from tkinter import *
    x = 360
    y = 160
    top = y - 30
    bottom = y - 30

    canvas = Canvas(width=400, height=600, bg="white")
    for i in range(20):
        canvas.create_oval(250-top, 250-bottom, 250+top, 250+bottom)
        top -= 5
        bottom += 5
    canvas.pack()
    mainloop()<jupyter_output><empty_output><jupyter_text>实例064：画椭圆、矩形题目 利用ellipse 和 rectangle 画图。。<jupyter_code>if __name__ == "__main__":
    from tkinter import *
    canvas = Canvas(width=400, height=600, bg="white")
    left = 20
    right = 50
    top = 50
    num = 15
    for i in range(num):
        canvas.create_oval(250-right, 250-left, 250+right, 250+left)
        canvas.create_oval(250-20, 250-top, 250+20, 250+top)
        canvas.create_rectangle(20-2*i, 20-2*i, 10*(i+2),10*(i+2))
        right += 5
        left += 5
        top += 10

    canvas.pack()
    mainloop()<jupyter_output><empty_output><jupyter_text>实例065：画组合图形题目 一个最优美的图案。<jupyter_code>import math
from tkinter import *


class PTS:
    def __init__(self):
        self.x = 0
        self.y = 0
points = []


def LineToDemo():
    screenx = 400
    screeny = 400
    canvas = Canvas(width=screenx, height=screeny, bg="white")

    AspectRatio = 0.85
    MAXPTS = 15
    h = screeny
    w = screenx
    xcenter = w / 2
    ycenter = h / 2
    radius = (h - 30) / (AspectRatio*2) - 20
    step = 360 / MAXPTS
    angle = 0.0
    for i in range(MAXPTS):
        rads = angle*math.pi / 180.0
        p = PTS()
        p.x = xcenter + int(math.cos(rads)* radius)
        p.y = ycenter - int(math.sin(rads)*radius*AspectRatio)
        angle += step
        points.append(p)
    canvas.create_oval(xcenter - radius, ycenter - radius, xcenter + radius, ycenter+radius)
    for i in range(MAXPTS):
        for j in range(i, MAXPTS):
            canvas.create_line(points[i].x, points[i].y, points[j].x, points[j].y)
    canvas.pack()
    mainloop()

if __name__ == "__main__":
    LineToDemo()<jupyter_output><empty_output><jupyter_text>实例066：三数排序题目 输入3个数a,b,c，按大小顺序输出。<jupyter_code>raw = []

for i in range(3):
    x = int(input("int%d: "%(i)))
    raw.append(x)

for i in range(len(raw)):
    for j in range(i, len(raw)):
        if raw[i]>raw[j]:
            raw[i], raw[j] = raw[j], raw[i]
print(raw)

raw2 = []
for i in range(3):
    x = int(input("int%d: "%(i)))
    raw2.append(x)
print(sorted(raw2))<jupyter_output>[2, 3, 123]
[2, 3, 4]<jupyter_text>实例067：交换位置题目 输入数组，最大的与第一个元素交换，最小的与最后一个元素交换，输出数组<jupyter_code>li = [3, 2, 5, 7, 8, 1, 5]

li[-1], li[li.index(min(li))] = li[li.index(min(li))], li[-1]

m = li[0]

ind = li.index(max(li))
li[0] = li[ind]
li[ind] = m

print(li)<jupyter_output>[8, 2, 5, 7, 3, 5, 1]<jupyter_text>实例068：旋转数列题目 有n个整数，使其前面各数顺序向后移m个位置，最后m个数变成最前面的m个数<jupyter_code>from collections import *
li = [1, 2, 3, 4, 5, 6, 7, 8, 9]
deq = deque(li, maxlen=len(li))
print(li)
deq.rotate(int(input("rotate: ")))
print(list(deq))<jupyter_output>[1, 2, 3, 4, 5, 6, 7, 8, 9]
[8, 9, 1, 2, 3, 4, 5, 6, 7]<jupyter_text>实例069：报数题目 有n个人围成一圈，顺序排号。从第一个人开始报数（从1到3报数），凡报到3的人退出圈子，问最后留下的是原来第几号的那位。<jupyter_code>"""
这个实例没太弄懂其目的是什么，以及整个逻辑过程。
"""

if __name__ == "__main__":
    nmax = 50
    n = int(input("请输入总人数："))
    num = []
    for i in range(n):
        num.append(i + 1)
    
    # 测试1
    print(num)

    i = 0
    k = 0
    m = 0

    while m < n-1:
        if num[i] != 0:
            k += 1
        if k == 3:
            num[i] = 0
            k = 0
            m += 1
        i += 1
        if i == n:
            i = 0
    i = 0
    while num[i] ==0:
        i += 1
    print(num[i])<jupyter_output>[1, 2, 3]
2<jupyter_text>实例070：字符串长度II题目 写一个函数，求一个字符串的长度，在main函数中输入字符串，并输出其长度。<jupyter_code>def lenofstr(s):
    return len(s)

print(lenofstr(input("请输入字符串：")))<jupyter_output>16<jupyter_text>实例071：输入和输出题目 编写input()和output()函数输入，输出5个学生的数据记录。<jupyter_code>N = 3
# stu
# num: string
# name: string
# score[4]: list
student = []
for i in range(5):
    student.append(['','',[]])

def input_stu(stu):
    for i in range(N):
        stu[i][0] = input("input student num:\n")
        stu[i][1] = input("input student name:\n")
        for j in range(3):
            stu[i][2].append(int(input("score:\n")))

def output_stu(stu):
    for i in range(N):
        print("%-6s%-10s" % (stu[i][0], stu[i][1]))
        for j in range(3):
            print("%-8d" % (stu[i][2][j]))

if __name__ == "__main__":
    input_stu(student)
    print(student)
    output_stu(student)<jupyter_output>[['1', 'alan', [90, 91, 92]], ['2', 'brown', [80, 81, 82]], ['3', 'cathy', [70, 71, 72]], ['', '', []], ['', '', []]]
1     alan      
90      
91      
92      
2     brown     
80      
81      
82      
3     cathy     
70      
71      
72<jupyter_text>实例072：创建链表题目 创建一个链表。<jupyter_code>class Node:

    def __init__(self, data):
        self.data = data
        self.next = None


    def get_data(self):
        return self.data

class List:

    def __init__(self, head):
        self.head = head


    def is_empty(self):
        return self.get_len() == 0

    def get_len(self):
        length = 0
        temp = self.head
        while temp is not None:
            length += 1
            temp = temp.next
        return length

    def append(self, node):
        temp = self.head
        while temp.next is not None:
            temp = temp.next
        temp.next = node

    def delete(self, index):
        if index < 1 or index > self.get_len():
            print("给定位置不合理")
            return
        if index == 1:
            self.head == self.head.next
            return
        temp = self.head
        cur_pos += 1
        if cur_pos == index-1:
            temp.next = temp.next.next
        temp = temp.next

    def insert(self, pos, node):
        if pos < 1 or pos > self.get_len():
            print("插入结点位置不合理")
            return
        temp = self.head
        cur_pos = 0
        while temp is not Node:
            cur_pos += 1
            if cur_pos == pos-1:
                node.next = temp.next
                temp.next = node
                break
            temp = temp.next

    def reverse(self, head):
        if head is None and head.next is None:
            return head
        pre = head
        cur = head.next
        while cur is not None:
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp
        head.next = None
        return pre

    def print_list(self, head):
        init_data = []
        while head is not None:
            init_data.append(head.get_data())
            head = head.next
        return init_data

if __name__ == "__main__":
    head = Node("head")
    link = List(head)
    for i in range(10):
        node = Node(i)
        link.append(node)
    print(link.print_list(head))<jupyter_output>['head', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]<jupyter_text>实例073：反向输出链表题目 反向输出一个链表。<jupyter_code>class Node:

    def __init__(self, data):
        self.data = data
        self.next = None

    def get_data(self):
        return self.data


class List:

    def __init__(self, head):
        self.head = head

    def is_empty(self):
        return self.get_len() == 0

    def get_len(self):
        length = 0
        temp = self.head
        while temp is not None:
            length += 1
            temp = temp.next
        return length

    def append(self, node):
        temp = self.head
        while temp.next is not None:
            temp = temp.next
        temp.next = node

    def delete(self, index):
        if index < 1 or index > self.get_len():
            print("给定位置不合理")
            return 
        if index == 1:
            self.head = self.head.next
            return 
        temp = self.head
        cur_pos = 0
        while temp is not None:
            cur_pos += 1
            if cur_pos == index-1:
                temp.next = temp.next.next
            temp = temp.next

    def insert(self, pos, node):
        if pos < 1 or pos > self.get_len():
            print("插入结点位置不合理")
            return
        temp = self.head
        cur_pos = 0
        while temp is not Node:
            cur_pos += 1
            if cur_pos == pos-1:
                node.next = temp.next
                temp.next = node
                break
            temp = temp.next

    def reverse(self, head):
        if head is None and head.next is None:
            return head
        pre = head
        cur = head.next
        while cur is not None:
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp
        head.next = None
        return pre

    def print_list(self, head):
        init_data = []
        while head is not None:
            init_data.append(head.get_data())
            head = head.next
        return init_data

if __name__ == "__main__":
    head = Node('head')
    link = List(head)
    for i in range(10):
        node = Node(i)
        link.append(node)
    print(link.print_list(head))
    print(link.print_list(link.reverse(head)))<jupyter_output>['head', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 'head']<jupyter_text>实例074：列表排序、连接题目 列表排序及连接。<jupyter_code>a = [2, 6, 8]
b = [7, 0, 4]
a.extend(b)
a.sort()
print(a)
"""
程序分析：排序可使用sort()方法，连接可以使用+号或extend()方法
"""<jupyter_output><empty_output><jupyter_text>实例075：不知所云题目 放松一下，算一道简单的题目。<jupyter_code>if __name__ == "__main__":
    for i in range(5):
        n = 0
        if i != 1:
            n += 1
        if i == 3:
            n += 1
        if i == 4:
            n += 1
        if i != 4:
            n += 1
        if n == 3: 
            print(64 + i)

# 只有当i=3时，才满足n=3，执行最后一行程序的操作<jupyter_output>67<jupyter_text>实例076：做函数题目 编写一个函数，输入n为偶数时，调用函数求1/2+1/4+…+1/n,当输入n为奇数时，调用函数1/1+1/3+…+1/n<jupyter_code>def peven(n):
    i = 0
    s = 0.0
    for i in range(2, n+1, 2):
        s += 1.0/i
    return s

def podd(n):
    s = 0.0
    for i in range(1, n+1, 2):
        s += 1.0/i
    return s

def dcall(fp, n):
    s = fp(n)
    return s

if __name__ == "__main__":
    n = int(input("input a number: "))
    if n % 2 == 0:
        sum = dcall(peven, n)
    else:
        sum = dcall(podd, n)
    print(sum)<jupyter_output>0.75<jupyter_text>实例077：遍历列表题目 循环输出列表<jupyter_code>I = ["moyu", "niupi", "xuecaibichi", "shengfaji", "42"]
for i in range(len(I)):
    print(I[i])<jupyter_output>moyu
niupi
xuecaibichi
shengfaji
42<jupyter_text>实例078：字典题目 找到年龄最大的人，并输出。请找出程序中有什么问题。<jupyter_code>if __name__ == "__main__":
    person = {"li":18, "wang":50, "zhang":20, "sun":22}
    m = "li"
    print(person)
    for key in person.keys():
        if person[m] < person[key]:
            m = key
    print("%s, %d" % (m, person[m]))<jupyter_output>{'li': 18, 'wang': 50, 'zhang': 20, 'sun': 22}
wang, 50<jupyter_text>实例079：字符串排序题目 字符串排序。<jupyter_code>l = ['baaa', 'aaab', 'aaba', 'aaaa', 'abaa']
l.sort()
print(l)<jupyter_output>['aaaa', 'aaab', 'aaba', 'abaa', 'baaa']<jupyter_text>实例080：猴子分桃**剑指offer的一道题**题目 海滩上有一堆桃子，五只猴子来分。第一只猴子把这堆桃子平均分为五份，多了一个，这只猴子把多的一个扔入海中，拿走了一份。第二只猴子把剩下的桃子又平均分成五份，又多了一个，它同样把多的一个扔入海中，拿走了一份，第三、第四、第五只猴子都是这样做的，问海滩上原来最少有多少个桃子？<jupyter_code>if __name__ == "__main__":
    i = 0 #执行次数
    j = 1 #最后猴子拿到的桃子数
    x = 0 #每次均分后，第一只猴子拿了之后剩下的总数
    while(i<5):
        x = 4*j
        for i in range(0,5):
            if (x%4 != 0):
                break
            else:
                i += 1
            x = (x/4) * 5 + 1
        j += 1
    print(x)

    for p in range(5):
        x = (x-1)/5*4
        print("第{}只猴子拿了桃子后还剩下的桃子数量：".format(p+1))
        print(x)

# 方法二：强行for循环

for x in range(1,10000):
    for n in range(1,1000):
        n = (((((((((int(x) - 1) * 4 / 5) - 1) * 4 / 5) - 1) * 4 / 5) - 1) * 4 / 5) - 1) * 4 / 5
        if n%4 == 0:
            print(x)
        else:
            break<jupyter_output>3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
3121
[...]<jupyter_text>实例081：求未知数题目 809*??=800*??+9*?? 其中??代表的两位数, 809*??为四位数，8*??的结果为两位数，9*??的结果为3位数。求??代表的两位数，及809*??后的结果。<jupyter_code>a = 809
for i in range(10, 100):
    b = i * a
    if b >= 1000 and b <= 10000 and 8*i < 100 and 9*i >=100:
        print(b, "=800 *", i, "+ 9 *", i)

for i in range(10, 100):
    if 8*i>99 or 9*i<100:
        continue
    if 809*i == 800*i + 9*i:
        print(i)
        break<jupyter_output>9708 =800 * 12 + 9 * 12
12<jupyter_text>实例082：八进制转十进制题目 八进制转换为十进制<jupyter_code>n = eval('0o'+str(int(input("八进制输入："))))
print(n)<jupyter_output>8<jupyter_text>实例083：制作奇数题目 求0—7所能组成的奇数个数。程序分析组成1位数是4个。1,3,5,7结尾组成2位数是7*4个。第一位不能为0组成3位数是7*8*4个。中间随意组成4位数是7*8*8*4个。<jupyter_code>if __name__ == "__main__":
    sum = 4
    s = 4
    for j in range(2, 9):
        print(sum)
        if j <= 2:
            s *= 7
        else:
            s *= 8
        sum += s
    print("sum = %d" % sum)
28*8+32<jupyter_output><empty_output><jupyter_text>实例084：连接字符串题目 连接字符串。<jupyter_code>delimiter = ','
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))<jupyter_output>Brazil,Russia,India,China<jupyter_text>实例085：整除题目 输入一个奇数，然后判断最少几个 9 除于该数的结果为整数。<jupyter_code>if __name__ == "__main__":
    zi = int(input("请输入一个整数："))
    n1 = 1
    c9 = 1
    m9 = 9
    sum = 9
    while n1 != 0:
        if sum % zi == 0:
            n1 = 0
        else:
            m9 *= 10
            sum += m9
            c9 += 1
    print("%d 个9可以被%d整除：%d"%(c9, zi, sum))
    r = sum / zi
    print("%d / %d = %d"%(sum, zi, r))<jupyter_output>6 个9可以被13整除：999999
999999 / 13 = 76923<jupyter_text>实例086：连接字符串II题目 两个字符串连接程序<jupyter_code>a = 'guangtou'
b = 'feipang'
print(a+b)<jupyter_output>guangtoufeipang<jupyter_text>实例087：访问类成员题目 回答结果（结构体变量传递）。<jupyter_code>if __name__ == "__main__":
    class student:
        x = 0
        c = 0
    def f(stu):
        stu.x = 20
        stu.c = 'c'
    a = student()
    a.x = 3
    a.c = 'a'
    print(a.x, a.c)
    f(a)
    print(a.x, a.c)<jupyter_output>3 a
20 c<jupyter_text>实例088：打印星号题目 读取7个数（1—50）的整数值，每读取一个值，程序打印出该值个数的＊。<jupyter_code>for i in range(3):
    print('*' * int(input("input a number: ")))<jupyter_output>***
******
**************************************************************************************************<jupyter_text>实例089：解码题目 某个公司采用公用电话传递数据，数据是四位的整数，在传递过程中是加密的，加密规则如下：每位数字都加上5,然后用和除以10的余数代替该数字，再将第一位和第四位交换，第二位和第三位交换。<jupyter_code>n = input()
n = str(n)
a =[]
for i in range(4):
    a.append(int(n[i])+5)
a[0], a[3] = a[3], a[0]
a[1], a[2] = a[2], a[1]
print("".join("%s" %s for s in a))
print(a)<jupyter_output>9876
[9, 8, 7, 6]<jupyter_text>实例090：列表详解题目 列表使用实例。<jupyter_code># list
# 新建列表
testList = [10086, '中国移动', [1, 2, 4, 5]]

# 访问列表长度
print(len(testList))
# 到列表结尾
print(testList[1:])
# 向列表添加元素
testList.append('i\'m new here!')
testList

print(len(testList))
print(testList[-1])

# 弹出列表的最后一个元素
print(testList.pop(1))
print(len(testList))
print(testList)

matrix = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]
print(matrix)
print(matrix[1]) # 输出第2行
col2 = [row[1] for row in matrix] # 获取矩阵的第2列
print(col2)
col2even = [row[1] for row in matrix if row[1]%2 == 0] # 过滤奇数项
print(col2even)<jupyter_output>3
['中国移动', [1, 2, 4, 5]]
4
i'm new here!
中国移动
3
[10086, [1, 2, 4, 5], "i'm new here!"]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[4, 5, 6]
[2, 5, 8]
[2, 8]<jupyter_text>实例091：time模块题目 时间函数举例1。<jupyter_code>if __name__ == "__main__":
    import time
    print(time.ctime(time.time()))
    print(time.asctime(time.localtime(time.time())))
    print(time.asctime(time.gmtime(time.time())))<jupyter_output>Wed Jun 23 10:41:34 2021
Wed Jun 23 10:41:34 2021
Wed Jun 23 02:41:34 2021<jupyter_text>实例092：time模块II题目 时间函数举例2。<jupyter_code>if __name__ == "__main__":
    import time
    start = time.time()
    for i in range(3000):
        print(i)

    end = time.time()

    print(start - end)<jupyter_output>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
27[...]<jupyter_text>实例093：time模块III题目 时间函数举例3。<jupyter_code>if __name__ == "__main__":
    import time
    start = time.process_time()
    for i in range(100):
        print(i)
    end = time.process_time()
    print("different is %6.3f" %(end - start))

"""
* 处理器时间：这是此特定进程在 CPU 上主动执行所花费的时间。睡眠、等待 Web 请求或仅执行其他进程的时间不会对此产生影响。

    用 time.process_time()
* 挂钟时间：这是指“挂在墙上的时钟”已经过去了多少时间，即在实时之外。

    用 time.perf_counter()

time.time() 也测量挂钟时间，但可以重置，所以你可以回到过去
time.monotonic() 无法重置（单调 = 只前进）但精度低于 time.perf_counter()
"""<jupyter_output>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
different is  0.000<jupyter_text>实例094：time模块IV题目 时间函数举例4<jupyter_code>if __name__ == "__main__":
    import time
    import random

    play_it = input("do you want to play it.(\'y\' or \'n\')")
    while play_it == 'y':
        c = input("input a character:\n")
        i = random.randint(0, 2**32) % 100
        print("please input number you guess:\n")
        start = time.process_time()
        a = time.time()
        guess = int(input("input your guess:\n"))
        while guess != i:
            if guess > i:
                print("please input a little smaller")
                guess = int(input("input your guess:\n"))
            else:
                print("please input a little bigger")
                guess = int(input("input your guess:\n"))
        end = time.process_time()
        b =time.time()
        var = (end - start) / 18.2
        print(var)
        if var < 15:
            print("You are very clever!")
        elif var < 25:
            print("You are normal!")
        else:
            print("You are stupid!")
        print("Congratulations!")
        print("The number you guess is %d" % i)
        play_it = input("do you want to play it.")<jupyter_output>please input number you guess:

please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little bigger
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please input a little smaller
please in[...]<jupyter_text>实例095：转换时间格式题目 字符串日期转换为易读的日期格式。程序分析 看看就得了，dateutil是个第三方库。<jupyter_code>from dateutil import parser
dt = parser.parse("Aug 28 2015 12:00AM")
print(dt)<jupyter_output>2015-08-28 00:00:00<jupyter_text>实例096：计算复读次数题目 计算字符串中子串出现的次数。<jupyter_code>s1 = "xuebixuebixuebixuebixuebixuebixuebixue"
s2 = "xuebi"
print(s1.count(s2))<jupyter_output>7<jupyter_text>实例097：磁盘写入题目 从键盘输入一些字符，逐个把它们写到磁盘文件上，直到输入一个  为止。<jupyter_code>if __name__ == "__main__":
    from sys import stdout
    filename = input("请输入文件名:\n")
    fp = open(filename, 'w')
    ch = input("请输入字符串:\n")
    while ch != "#":
        fp.write(ch)
        stdout.write(ch)
        ch = input("")
    fp.close<jupyter_output><EMAIL><jupyter_text>实例098：磁盘写入II题目 从键盘输入一个字符串，将小写字母全部转换成大写字母，然后输出到一个磁盘文件"test"中保存。<jupyter_code>if __name__ == "__main__":
    fp = open("test.txt",'w')
    string = input("please input a string:\n")
    string = string.upper()
    fp.write(string)
    fp = open("test.txt", 'r')
    print(fp.read())
    fp.close()<jupyter_output><EMAIL><jupyter_text>实例099：磁盘读写题目 有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列), 输出到一个新文件C中。<jupyter_code>if __name__ == "__main__":
    import string
    fp = open("test1.txt","a")
    fp.write(input("请输入string：\n"))
    fp = open("test1.txt","r")
    a = fp.read()
    fp.close()

    fp = open("test2.txt", "a")
    fp.write(input("请输入string：\n"))
    fp = open("test2.txt", "r")
    b = fp.read()
    fp.close()

    fp = open("test3.txt", 'w')
    l = list(a+b)
    l.sort()
    s = ""
    print(s)
    s = s.join(l)
    fp.write(s)
    fp.close



if __name__ == '__main__':
    import string
    fp = open('test1.txt')
    a = fp.read()
    fp.close()
    print(a)

    fp = open('test2.txt')
    b = fp.read()
    fp.close()
    print(b)

    fp = open('test3.txt','w')
    l = list(a + b)
    l.sort()
    s = ''
    s = s.join(l)
    print(s)
    fp.write(s)
    fp.close()<jupyter_output>my heart will go onmy heart will go onapple
<NAME>
         CDaaaaaeeeeegghhiiiillllllmmmnnnnnoooooopprrttwwyyz<jupyter_text>实例100：列表转字典题目 列表转换为字典。<jupyter_code>i = ['a', 'b']
i =[1, 2]
print(dict(zip(i,l)))<jupyter_output>{1: ' ', 2: ' '}
{'fraction_non_alphanumeric': 0.1599031147749968, 'fraction_numerical': 0.10916585220753836, 'mean_word_length': 3.170388091440723, 'pattern_counts': {'":': 30, '<': 370, '<?xml version=': 0, '>': 362, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '100', 'dir': 'jupyter-structured-clean-dedup', 'id': '611876', 'license': 'MIT', 'n_tokens_mistral': 27192, 'n_tokens_neox': 25189, 'n_words': 4548, 'path': '2021-06-05Python-100problem.ipynb', 'repo_name': 'yuancf1024/Python-cf', 'size': '47121'}