python3.0 100例

原文链接:
https://blog.csdn.net/weixin_41084236/article/details/81564963#001_18

python3.0 100例

Python3 100例

原题地址:
http://www.runoob.com/python/python-100-examples.html
git地址:
https://github.com/RichardFu123/Python100Cases
转载请标注:
https://blog.csdn.net/weixin_41084236/article/details/81564963
原例为Python2.7版本
重写过程中有不少是随意发挥的
重写运行版本:Python3.7
作者:Shawn

  • 总的来说,并没有什么难度,全部搂了一遍也只花了不到2天时间,其中还有一半以上的时间是用来写文档的。
  • 用来练练手还是凑合的。

文章目录

实例001:数字组合

题目 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?

程序分析 遍历全部可能,把有重复的剃掉。

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(total)

    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

简便方法 用itertools中的permutations即可。

import itertools
sum2=0
a=[1,2,3,4]
for i in itertools.permutations(a,3):
    print(i)
    sum2+=1
print(sum2)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

实例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,求应发放奖金总数?

程序分析 分区间计算即可。

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)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

实例003:完全平方数

题目 一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?

程序分析 因为168对于指数爆炸来说实在太小了,所以可以直接省略数学分析,用最朴素的方法来获取上限:

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

print(n+1)

85

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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

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

for i in range((n+1)2):
if i0.5int(i0.5) and (i+168)0.5int((i+168)**0.5):
print(i100)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

实例004:这天第几天

题目 输入某年某月某日,判断这一天是这一年的第几天?

程序分析 特殊情况,闰年时需考虑二月多加一天:

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

实例005:三数排序

题目 输入三个整数x,y,z,请把这三个数由小到大输出。

程序分析 练练手就随便找个排序算法实现一下,偷懒就直接调函数。

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))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

实例006:斐波那契数列

题目 斐波那契数列。

程序分析 斐波那契数列(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(target1):
a,b=b,a+b
print(a)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

实例007:copy

题目 将一个列表的数据复制到另一个列表中。

程序分析 使用列表[:],拿不准可以调用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)

RESTART: F:\PyWorkspace\Python100\100examples<span class=“token number”>007.py
a= [1, 2, 3, 4, [‘a’, ‘b’, ‘c’], 5]
b= [1, 2, 3, 4, [‘a’, ‘b’, ‘c’], 5]
c= [1, 2, 3, 4, [‘a’, ‘b’, ‘c’]]
d= [1, 2, 3, 4, [‘a’, ‘b’, ‘c’]]
e= [1, 2, 3, 4, [‘a’, ‘b’]]

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

实例008:九九乘法表

题目 输出 9*9 乘法口诀表。

程序分析 分行与列考虑,共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='')
    print()

  
  • 1
  • 2
  • 3
  • 4

实例009:暂停一秒输出

题目 暂停一秒输出。

程序分析 使用 time 模块的 sleep() 函数。

import time
for i in range(4):
    print(str(int(time.time()))[-2:])
    time.sleep(1)

  
  • 1
  • 2
  • 3
  • 4

实例010:给人看的时间

题目 暂停一秒输出,并格式化当前时间。

程序分析 同009.

import time

for i in range(4):
print(time.strftime(’%Y-%m-%d %H:%M:%S’,time.localtime(time.time())))
time.sleep(1)

  • 1
  • 2
  • 3
  • 4
  • 5

实例011:养兔子

题目 有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

程序分析 我认为原文的解法有点扯,没有考虑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
    print('第%d个月共'%(i+1),month_1+month_2+month_3+month_elder,'对兔子')
    print('其中1月兔:',month_1)
    print('其中2月兔:',month_2)
    print('其中3月兔:',month_3)
    print('其中成年兔:',month_elder)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

实例012:100到200的素数

题目 判断101-200之间有多少个素数,并输出所有素数。

程序分析 判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数。 用else可以进一步简化代码.

import math
for i in range(100,200):
    flag=0
    for j in range(2,round(math.sqrt(i))+1):
        if i%j==0:
            flag=1
            break
    if flag:
        continue
    print(i)

print(’\nSimplify 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:
print(i)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

实例013:所有水仙花数

题目 打印出所有的”水仙花数”,所谓”水仙花数”是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个”水仙花数”,因为153=1的三次方+5的三次方+3的三次方。

程序分析 利用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)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

实例014:分解质因数

题目 将一个整数分解质因数。例如:输入90,打印出90=233*5。

程序分析 根本不需要判断是否是质数,从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%i0:
print(“%d”%i,end=’’)
if targeti:
flag=1
break
print(’*’,end=’’)
target/=i
break

  • 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

实例015:分数归档

题目 利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。

程序分析 用条件判断即可。

points=int(input('输入分数:'))
if points>=90:
    grade='A'
elif points<60:
    grade='C'
else:
    grade='B'
print(grade)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

实例016:输出日期

题目 输出指定格式的日期。

程序分析 使用 datetime 模块。

import datetime
print(datetime.date.today())
print(datetime.date(2333,2,3))
print(datetime.date.today().strftime('%d/%m/%Y'))
day=datetime.date(1111,2,3)
day=day.replace(year=day.year+22)
print(day)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

实例017:字符串构成

题目 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

程序分析 利用 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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

实例018:复读机相加

题目 求s=a+aa+aaa+aaaa+aa…a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘控制。

程序分析 用字符串解决。

a=input('被加数字:')
n=int(input('加几次?:'))
res=0
for i in range(n):
    res+=int(a)
    a+=a[0]
print('结果是:',res)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

实例019:完数

题目 一个数如果恰好等于它的因子之和,这个数就称为”完数”。例如6=1+2+3.编程找出1000以内的所有完数。

程序分析 将每一对因子加进集合,在这个过程中已经自动去重。最后的结果要求不计算其本身。

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)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

实例020:高空抛物

题目 一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?

程序分析

high=200.
total=100
for i in range(10):
    high/=2
    total+=high
    print(high/2)
print('总长:',total)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

实例021:猴子偷桃

题目 猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。

程序分析 按规则反向推断:猴子有一个桃子,他偷来一个桃子,觉得不够又偷来了与手上等量的桃子,一共偷了9天。

peach=1
for i in range(9):
    peach=(peach+1)*2
print(peach)

  
  • 1
  • 2
  • 3
  • 4

实例022:比赛对手

题目 两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。

程序分析 找到条件下不重复的三个对手即可。

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))

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

实例023:画菱形

题目 打印出如下图案(菱形):

    *
   ***
  *****
 *******
  *****
   ***
    *

程序分析 递归调用即可。

def draw(num):
    a="*"*(2*(4-num)+1)
    print(a.center(9,' '))
    if num!=1:
        draw(num-1)
        print(a.center(9,' '))
draw(4)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

实例024:斐波那契数列II

题目 有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13…求出这个数列的前20项之和。

程序分析 就是斐波那契数列的后一项除以前一项。

a = 2.0
b = 1.0
s = 0
for n in range(1,21):
    s += a / b
    a,b = a + b,a
print (s)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

实例025: 阶乘求和

题目 求1+2!+3!+…+20!的和。

程序分析 1+2!+3!+…+20!=1+2(1+3(1+4(…20(1))))

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

  
  • 1
  • 2
  • 3
  • 4

实例026:递归求阶乘

题目 利用递归方法求5!。

程序分析 递归调用即可。

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

  
  • 1
  • 2
  • 3

实例027:递归输出

题目 利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。

程序分析 递归真是蠢方法。

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

rec(input(‘string here:’))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

实例028:递归求等差数列

题目 有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?

程序分析 就一等差数列。

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

  
  • 1
  • 2
  • 3
  • 4
  • 5

实例029:反向输出

题目 给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。

程序分析 学会分解出每一位数,用字符串的方法总是比较省事。

n=int(input('输入一个正整数:'))
n=str(n)
print('%d位数'%len(n))
print(n[::-1])

  
  • 1
  • 2
  • 3
  • 4

实例030:回文数

题目 一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。

程序分析 用字符串比较方便,就算输入的不是数字都ok。

n=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('是回文串')

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

实例031:字母识词

题目 请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。

程序分析 这里用字典的形式直接将对照关系存好。

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

实例032:反向输出II

题目 按相反的顺序输出列表的值。

程序分析 无。

a = ['one', 'two', 'three']
print(a[::-1])

  
  • 1
  • 2

实例033:列表转字符串

题目 按逗号分隔列表。

程序分析 无。

L = [1,2,3,4,5]
print(','.join(str(n) for n in L))

  
  • 1
  • 2

实例034:调用函数

题目 练习函数调用。

程序分析 无。

def hello():
    print('Hello World!')
def helloAgain():
    for i in range(2):
        hello()

if name==main:
helloAgain()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

实例035:设置输出颜色

题目 文本颜色设置。

程序分析 无。

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)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

实例036:算素数

题目 求100之内的素数。

程序分析 用else执行for循环的奖励代码(如果for是正常完结,非break)。

lo=int(input('下限:'))
hi=int(input('上限:'))
for i in range(lo,hi+1):
    if i > 1:
        for j in range(2,i):
            if (i % j) == 0:
                break
        else:
            print(i)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

实例037:排序

题目 对10个数进行排序。

程序分析 同实例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)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

实例038:矩阵对角线之和

题目 求一个3*3矩阵主对角线元素之和。

程序分析 无。

mat=[[1,2,3],
     [3,4,5],
     [4,5,6]
    ]
res=0
for i in range(len(mat)):
    res+=mat[i][i]
print(res)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

实例039:有序列表插入元素

题目 有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。

程序分析 首先判断此数是否大于最后一个数,然后再考虑插入中间的数的情况,插入后此元素之后的数,依次后移一个位置。

lis=[1,10,100,1000,10000,100000]
n=int(input('insert a number: '))
lis.append(n)
for i in range(len(lis)-1):
    if lis[i]>=n:
        for j in range(i,len(lis)):
            lis[j],lis[-1]=lis[-1],lis[j]
        break
print(lis)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

实例040:逆序列表

题目 将一个数组逆序输出。

程序分析 依次交换位置,或者直接调用reverse方法。

lis=[1,10,100,1000,10000,100000]
for i in range(int(len(lis)/2)):
    lis[i],lis[len(lis)-1-i]=lis[len(lis)-1-i],lis[i]
print('第一种实现:')
print(lis)

lis=[1,10,100,1000,10000,100000]
print(‘第二种实现:’)
lis.reverse()
print(lis)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

实例041:类的方法与变量

题目 模仿静态变量的用法。

程序分析 构造类,了解类的方法与变量。

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):
dummy()
a.dummy()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

实例042:变量作用域

题目 学习使用auto定义变量的用法。

程序分析 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

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

实例043:作用域、类的方法与变量

题目 模仿静态变量(static)另一案例。

程序分析 综合实例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()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

实例044:矩阵相加

题目 计算两个矩阵相加。

程序分析 创建一个新的矩阵,使用 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]]
for i in range(len(res)):
for j in range(len(res[0])):
res[i][j]=X[i][j]+Y[i][j]
print(res)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

实例045:求和

题目 统计 1 到 100 之和。

程序分析

res=0
for i in range(1,101):
    res+=i
print(res)

  
  • 1
  • 2
  • 3
  • 4

实例046:打破循环

题目 求输入数字的平方,如果平方运算后小于 50 则退出。

程序分析

while True:
    try:
        n=float(input('输入一个数字:'))
    except:
        print('输入错误')
        continue
    dn=n**2
    print('其平方为:',dn)
    if dn<50:
        print('平方小于50,退出')
        break

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

实例047:函数交换变量

题目 两个变量值用函数互换。

程序分析

def exc(a,b):
    return (b,a)
a=0
b=10
a,b=exc(a,b)
print(a,b)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

实例048:数字比大小

题目 数字比较。

程序分析

a=int(input('a='))
b=int(input('b='))
if a<b:
    print('a<b')
elif a>b:
    print('a>b')
else:
    print('a=b')

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

实例049:lambda

题目 使用lambda来创建匿名函数。

程序分析

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))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

实例050:随机数

题目 输出一个随机数。

程序分析 使用 random 模块。

import random
print(random.uniform(10,20))

  
  • 1
  • 2

实例051:按位与

题目 学习使用按位与 & 。

程序分析 0&0=0; 0&1=0; 1&0=0; 1&1=1。

a=0o77
print(a)
b=a&3
print(b)
b=b&7
print(b)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

实例052:按位或

题目 学习使用按位或 | 。

程序分析 0|0=0; 0|1=1; 1|0=1; 1|1=1

a=0o77
print(a|3)
print(a|3|7)

  
  • 1
  • 2
  • 3

实例053:按位异或

题目 学习使用按位异或 ^ 。

程序分析 0^0=0; 0^1=1; 1^0=1; 1^1=0

a=0o77
print(a^3)
print(a^3^7)

  
  • 1
  • 2
  • 3

实例054:位取反、位移动

题目 取一个整数a从右端开始的4〜7位。

程序分析 可以这样考虑:
(1)先使a右移4位。
(2)设置一个低4位全为1,其余全为0的数。可用(0<<4)
(3)将上面二者进行&运算。

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))

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

实例055:按位取反

题目 学习使用按位取反~。

程序分析 ~0=1; ~1=0;

print(~234)
print(~~234)

  
  • 1
  • 2

实例056:画圈

题目 画图,学用circle画圆形。

程序分析 无。

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()

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

实例057:画线

题目 画图,学用line画直线。

程序分析 无。

if __name__ == '__main__':
    from tkinter import *
canvas <span class="token operator">=</span> Canvas<span class="token punctuation">(</span>width<span class="token operator">=</span><span class="token number">300</span><span class="token punctuation">,</span> height<span class="token operator">=</span><span class="token number">300</span><span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'green'</span><span class="token punctuation">)</span>   
canvas<span class="token punctuation">.</span>pack<span class="token punctuation">(</span>expand<span class="token operator">=</span>YES<span class="token punctuation">,</span> fill<span class="token operator">=</span>BOTH<span class="token punctuation">)</span>                  
x0 <span class="token operator">=</span> <span class="token number">263</span>
y0 <span class="token operator">=</span> <span class="token number">263</span>
y1 <span class="token operator">=</span> <span class="token number">275</span>
x1 <span class="token operator">=</span> <span class="token number">275</span>
<span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token number">19</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    canvas<span class="token punctuation">.</span>create_line<span class="token punctuation">(</span>x0<span class="token punctuation">,</span>y0<span class="token punctuation">,</span>x0<span class="token punctuation">,</span>y1<span class="token punctuation">,</span> width<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span> fill<span class="token operator">=</span><span class="token string">'red'</span><span class="token punctuation">)</span>
    x0 <span class="token operator">=</span> x0 <span class="token operator">-</span> <span class="token number">5</span>
    y0 <span class="token operator">=</span> y0 <span class="token operator">-</span> <span class="token number">5</span>
    x1 <span class="token operator">=</span> x1 <span class="token operator">+</span> <span class="token number">5</span>
    y1 <span class="token operator">=</span> y1 <span class="token operator">+</span> <span class="token number">5</span>

x0 <span class="token operator">=</span> <span class="token number">263</span>
y1 <span class="token operator">=</span> <span class="token number">275</span>
y0 <span class="token operator">=</span> <span class="token number">263</span>
<span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token number">21</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    canvas<span class="token punctuation">.</span>create_line<span class="token punctuation">(</span>x0<span class="token punctuation">,</span>y0<span class="token punctuation">,</span>x0<span class="token punctuation">,</span>y1<span class="token punctuation">,</span>fill <span class="token operator">=</span> <span class="token string">'red'</span><span class="token punctuation">)</span>
    x0 <span class="token operator">+=</span> <span class="token number">5</span>
    y0 <span class="token operator">+=</span> <span class="token number">5</span>
    y1 <span class="token operator">+=</span> <span class="token number">5</span>

mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span>
  • 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

实例058:画矩形

题目 画图,学用rectangle画方形。

程序分析 无。

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<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>
root<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

实例059:画图(丑)

题目 画图,综合例子。

程序分析 丑。

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)
<span class="token keyword">for</span> k <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token number">501</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token number">17</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        a <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token number">2</span> <span class="token operator">*</span> math<span class="token punctuation">.</span>pi <span class="token operator">/</span> <span class="token number">16</span><span class="token punctuation">)</span> <span class="token operator">*</span> i <span class="token operator">+</span> <span class="token punctuation">(</span><span class="token number">2</span> <span class="token operator">*</span> math<span class="token punctuation">.</span>pi <span class="token operator">/</span> <span class="token number">180</span><span class="token punctuation">)</span> <span class="token operator">*</span> k
        x <span class="token operator">=</span> math<span class="token punctuation">.</span>ceil<span class="token punctuation">(</span>x0 <span class="token operator">+</span> <span class="token number">48</span> <span class="token operator">*</span> math<span class="token punctuation">.</span>cos<span class="token punctuation">(</span>a<span class="token punctuation">)</span><span class="token punctuation">)</span>
        y <span class="token operator">=</span> math<span class="token punctuation">.</span>ceil<span class="token punctuation">(</span>y0 <span class="token operator">+</span> <span class="token number">48</span> <span class="token operator">+</span> math<span class="token punctuation">.</span>sin<span class="token punctuation">(</span>a<span class="token punctuation">)</span> <span class="token operator">*</span> B<span class="token punctuation">)</span>
        canvas<span class="token punctuation">.</span>create_line<span class="token punctuation">(</span>x0<span class="token punctuation">,</span>y0<span class="token punctuation">,</span>x<span class="token punctuation">,</span>y<span class="token punctuation">,</span>fill <span class="token operator">=</span> <span class="token string">'red'</span><span class="token punctuation">)</span>
    <span class="token keyword">for</span> j <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token number">51</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        a <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token number">2</span> <span class="token operator">*</span> math<span class="token punctuation">.</span>pi <span class="token operator">/</span> <span class="token number">16</span><span class="token punctuation">)</span> <span class="token operator">*</span> i <span class="token operator">+</span> <span class="token punctuation">(</span><span class="token number">2</span><span class="token operator">*</span> math<span class="token punctuation">.</span>pi <span class="token operator">/</span> <span class="token number">180</span><span class="token punctuation">)</span> <span class="token operator">*</span> k <span class="token operator">-</span> <span class="token number">1</span>
        x <span class="token operator">=</span> math<span class="token punctuation">.</span>ceil<span class="token punctuation">(</span>x0 <span class="token operator">+</span> <span class="token number">48</span> <span class="token operator">*</span> math<span class="token punctuation">.</span>cos<span class="token punctuation">(</span>a<span class="token punctuation">)</span><span class="token punctuation">)</span>
        y <span class="token operator">=</span> math<span class="token punctuation">.</span>ceil<span class="token punctuation">(</span>y0 <span class="token operator">+</span> <span class="token number">48</span> <span class="token operator">*</span> math<span class="token punctuation">.</span>sin<span class="token punctuation">(</span>a<span class="token punctuation">)</span> <span class="token operator">*</span> B<span class="token punctuation">)</span>
        canvas<span class="token punctuation">.</span>create_line<span class="token punctuation">(</span>x0<span class="token punctuation">,</span>y0<span class="token punctuation">,</span>x<span class="token punctuation">,</span>y<span class="token punctuation">,</span>fill <span class="token operator">=</span> <span class="token string">'red'</span><span class="token punctuation">)</span>
mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span>
  • 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

实例060:字符串长度

题目 计算字符串长度。

程序分析 无。

s='zhangguang101'
print(len(s))

  
  • 1
  • 2

实例061:杨辉三角

题目 打印出杨辉三角形前十行。

程序分析 无。

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)

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

实例062:查找字符串

题目 查找字符串。

程序分析 无。

s1='aabbxuebixuebi'
s2='ab'
s3='xue'
print(s1.find(s2))
print(s1.find(s3))

  
  • 1
  • 2
  • 3
  • 4
  • 5

实例063:画椭圆

题目 画椭圆。

程序分析 使用 tkinter。

if __name__ == '__main__':
    from tkinter import *
    x = 360
    y = 160
    top = y - 30
    bottom = y - 30
canvas <span class="token operator">=</span> Canvas<span class="token punctuation">(</span>width <span class="token operator">=</span> <span class="token number">400</span><span class="token punctuation">,</span>height <span class="token operator">=</span> <span class="token number">600</span><span class="token punctuation">,</span>bg <span class="token operator">=</span> <span class="token string">'white'</span><span class="token punctuation">)</span>
<span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    canvas<span class="token punctuation">.</span>create_oval<span class="token punctuation">(</span><span class="token number">250</span> <span class="token operator">-</span> top<span class="token punctuation">,</span><span class="token number">250</span> <span class="token operator">-</span> bottom<span class="token punctuation">,</span><span class="token number">250</span> <span class="token operator">+</span> top<span class="token punctuation">,</span><span class="token number">250</span> <span class="token operator">+</span> bottom<span class="token punctuation">)</span>
    top <span class="token operator">-=</span> <span class="token number">5</span>
    bottom <span class="token operator">+=</span> <span class="token number">5</span>
canvas<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>
mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

实例064:画椭圆、矩形

题目 利用ellipse 和 rectangle 画图。。

程序分析 无。

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<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>
mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

实例065:画组合图形

题目 一个最优美的图案。

程序分析 无。

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 <span class="token operator">=</span> <span class="token number">0.85</span>
MAXPTS <span class="token operator">=</span> <span class="token number">15</span>
h <span class="token operator">=</span> screeny
w <span class="token operator">=</span> screenx
xcenter <span class="token operator">=</span> w <span class="token operator">/</span> <span class="token number">2</span>
ycenter <span class="token operator">=</span> h <span class="token operator">/</span> <span class="token number">2</span>
radius <span class="token operator">=</span> <span class="token punctuation">(</span>h <span class="token operator">-</span> <span class="token number">30</span><span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token punctuation">(</span>AspectRatio <span class="token operator">*</span> <span class="token number">2</span><span class="token punctuation">)</span> <span class="token operator">-</span> <span class="token number">20</span>
step <span class="token operator">=</span> <span class="token number">360</span> <span class="token operator">/</span> MAXPTS
angle <span class="token operator">=</span> <span class="token number">0.0</span>
<span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span>MAXPTS<span class="token punctuation">)</span><span class="token punctuation">:</span>
    rads <span class="token operator">=</span> angle <span class="token operator">*</span> math<span class="token punctuation">.</span>pi <span class="token operator">/</span> <span class="token number">180.0</span>
    p <span class="token operator">=</span> PTS<span class="token punctuation">(</span><span class="token punctuation">)</span>
    p<span class="token punctuation">.</span>x <span class="token operator">=</span> xcenter <span class="token operator">+</span> <span class="token builtin">int</span><span class="token punctuation">(</span>math<span class="token punctuation">.</span>cos<span class="token punctuation">(</span>rads<span class="token punctuation">)</span> <span class="token operator">*</span> radius<span class="token punctuation">)</span>
    p<span class="token punctuation">.</span>y <span class="token operator">=</span> ycenter <span class="token operator">-</span> <span class="token builtin">int</span><span class="token punctuation">(</span>math<span class="token punctuation">.</span>sin<span class="token punctuation">(</span>rads<span class="token punctuation">)</span> <span class="token operator">*</span> radius <span class="token operator">*</span> AspectRatio<span class="token punctuation">)</span>
    angle <span class="token operator">+=</span> step
    points<span class="token punctuation">.</span>append<span class="token punctuation">(</span>p<span class="token punctuation">)</span>
canvas<span class="token punctuation">.</span>create_oval<span class="token punctuation">(</span>xcenter <span class="token operator">-</span> radius<span class="token punctuation">,</span>ycenter <span class="token operator">-</span> radius<span class="token punctuation">,</span>
                   xcenter <span class="token operator">+</span> radius<span class="token punctuation">,</span>ycenter <span class="token operator">+</span> radius<span class="token punctuation">)</span>
<span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span>MAXPTS<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">for</span> j <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span>i<span class="token punctuation">,</span>MAXPTS<span class="token punctuation">)</span><span class="token punctuation">:</span>
        canvas<span class="token punctuation">.</span>create_line<span class="token punctuation">(</span>points<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">.</span>x<span class="token punctuation">,</span>points<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">.</span>y<span class="token punctuation">,</span>points<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">.</span>x<span class="token punctuation">,</span>points<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">.</span>y<span class="token punctuation">)</span>

canvas<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>
mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span>

if name == main:
LineToDemo()

  • 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

实例066:三数排序

题目 输入3个数a,b,c,按大小顺序输出。

程序分析 同实例005。

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))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

实例067:交换位置

题目 输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。

程序分析 无。

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)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

实例068:旋转数列

题目 有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数

程序分析 无。

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))

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

实例069:报数

题目 有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。

程序分析 无。

if __name__ == '__main__':
    nmax = 50
    n = int(input('请输入总人数:'))
    num = []
    for i in range(n):
        num.append(i + 1)
i <span class="token operator">=</span> <span class="token number">0</span>
k <span class="token operator">=</span> <span class="token number">0</span>
m <span class="token operator">=</span> <span class="token number">0</span>

<span class="token keyword">while</span> m <span class="token operator">&lt;</span> n <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">:</span>
    <span class="token keyword">if</span> num<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">!=</span> <span class="token number">0</span> <span class="token punctuation">:</span> k <span class="token operator">+=</span> <span class="token number">1</span>
    <span class="token keyword">if</span> k <span class="token operator">==</span> <span class="token number">3</span><span class="token punctuation">:</span>
        num<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">0</span>
        k <span class="token operator">=</span> <span class="token number">0</span>
        m <span class="token operator">+=</span> <span class="token number">1</span>
    i <span class="token operator">+=</span> <span class="token number">1</span>
    <span class="token keyword">if</span> i <span class="token operator">==</span> n <span class="token punctuation">:</span> i <span class="token operator">=</span> <span class="token number">0</span>

i <span class="token operator">=</span> <span class="token number">0</span>
<span class="token keyword">while</span> num<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">:</span> i <span class="token operator">+=</span> <span class="token number">1</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>num<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

实例070:字符串长度II

题目 写一个函数,求一个字符串的长度,在main函数中输入字符串,并输出其长度。

程序分析 无。

def lenofstr(s):
    return len(s)

print(lenofstr(‘tanxiaofengsheng’))

  • 1
  • 2
  • 3
  • 4

实例071:输入和输出

题目 编写input()和output()函数输入,输出5个学生的数据记录。

程序分析 无。

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)

  • 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

实例072:创建链表

题目 创建一个链表。

程序分析 原文不太靠谱。

class Node:
<span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> data<span class="token punctuation">)</span><span class="token punctuation">:</span>
    self<span class="token punctuation">.</span>data <span class="token operator">=</span> data
    self<span class="token punctuation">.</span><span class="token builtin">next</span> <span class="token operator">=</span> <span class="token boolean">None</span>

<span class="token keyword">def</span> <span class="token function">get_data</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> self<span class="token punctuation">.</span>data

class List:

<span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> head<span class="token punctuation">)</span><span class="token punctuation">:</span>
    self<span class="token punctuation">.</span>head <span class="token operator">=</span> head

<span class="token keyword">def</span> <span class="token function">is_empty</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span> 
    <span class="token keyword">return</span> self<span class="token punctuation">.</span>get_len<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span>

<span class="token keyword">def</span> <span class="token function">get_len</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>  
    length <span class="token operator">=</span> <span class="token number">0</span>
    temp <span class="token operator">=</span> self<span class="token punctuation">.</span>head
    <span class="token keyword">while</span> temp <span class="token keyword">is</span> <span class="token operator">not</span> <span class="token boolean">None</span><span class="token punctuation">:</span>
        length <span class="token operator">+=</span> <span class="token number">1</span>
        temp <span class="token operator">=</span> temp<span class="token punctuation">.</span><span class="token builtin">next</span>
    <span class="token keyword">return</span> length

<span class="token keyword">def</span> <span class="token function">append</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> node<span class="token punctuation">)</span><span class="token punctuation">:</span>
    temp <span class="token operator">=</span> self<span class="token punctuation">.</span>head
    <span class="token keyword">while</span> temp<span class="token punctuation">.</span><span class="token builtin">next</span> <span class="token keyword">is</span> <span class="token operator">not</span> <span class="token boolean">None</span><span class="token punctuation">:</span>
        temp <span class="token operator">=</span> temp<span class="token punctuation">.</span><span class="token builtin">next</span>
    temp<span class="token punctuation">.</span><span class="token builtin">next</span> <span class="token operator">=</span> node

<span class="token keyword">def</span> <span class="token function">delete</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> index<span class="token punctuation">)</span><span class="token punctuation">:</span> 
    <span class="token keyword">if</span> index <span class="token operator">&lt;</span> <span class="token number">1</span> <span class="token operator">or</span> index <span class="token operator">&gt;</span> self<span class="token punctuation">.</span>get_len<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"给定位置不合理"</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span>
    <span class="token keyword">if</span> index <span class="token operator">==</span> <span class="token number">1</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>head <span class="token operator">=</span> self<span class="token punctuation">.</span>head<span class="token punctuation">.</span><span class="token builtin">next</span>
        <span class="token keyword">return</span>
    temp <span class="token operator">=</span> self<span class="token punctuation">.</span>head
    cur_pos <span class="token operator">=</span> <span class="token number">0</span>
    <span class="token keyword">while</span> temp <span class="token keyword">is</span> <span class="token operator">not</span> <span class="token boolean">None</span><span class="token punctuation">:</span>
        cur_pos <span class="token operator">+=</span> <span class="token number">1</span>
        <span class="token keyword">if</span> cur_pos <span class="token operator">==</span> index<span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">:</span>
            temp<span class="token punctuation">.</span><span class="token builtin">next</span> <span class="token operator">=</span> temp<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token punctuation">.</span><span class="token builtin">next</span>
        temp <span class="token operator">=</span> temp<span class="token punctuation">.</span><span class="token builtin">next</span>

<span class="token keyword">def</span> <span class="token function">insert</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> pos<span class="token punctuation">,</span> node<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">if</span> pos <span class="token operator">&lt;</span> <span class="token number">1</span> <span class="token operator">or</span> pos <span class="token operator">&gt;</span> self<span class="token punctuation">.</span>get_len<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"插入结点位置不合理"</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span>
    temp <span class="token operator">=</span> self<span class="token punctuation">.</span>head
    cur_pos <span class="token operator">=</span> <span class="token number">0</span>
    <span class="token keyword">while</span> temp <span class="token keyword">is</span> <span class="token operator">not</span> Node<span class="token punctuation">:</span>
        cur_pos <span class="token operator">+=</span> <span class="token number">1</span>
        <span class="token keyword">if</span> cur_pos <span class="token operator">==</span> pos<span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">:<
点赞