python练习题(四)

56、画图,学用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(0, 26):
    canvas.create_oval(310 - k, 250 - k, 310 + k, 250 + k, width=1)
    k += j
    j += 0.3

mainloop()

57、画图,学用line画直线

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

58、画图,学用rectangle画方形



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

59、画图,综合例子

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(501):
    for i in range(17):
        a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k
        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')
    for j in range(51):
        a = (2 * 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()

60、计算字符串长度

s='like'
print(len(s))

61、打印出杨辉三角形(要求打印出10行如下图)。

  arr = [1]
    print(1)
    while len(arr)<10:                           # [1,1]
        a = [0]+arr                              # [0,1,1]
        b = arr+[0]                              # [1,1,0]
        arr = [a[i]+b[i] for i in range(len(a))] # [1,2,1]
        s = [str(i) for i in arr]
        print(' '.join(s))


62、查找字符串

sStr1 = 'abcdefg'
sStr2 = 'cde'
print(sStr1.find(sStr2))

63、画椭圆

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

64、利用ellipse 和 rectangle 画图

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

65、一个最优美的图案

from tkinter import *
import math
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()

66、输入3个数a,b,c,按大小顺序输出

l=[]
for n in range(1,4):
    k=input('请输入%s个整数\n'%n)
    l.append(k)
l.sort(reverse=True)
print(l)

67、输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组

a=[5,8,12,10]
i = a.index(max(a))
a[0],a[i] = a[i],a[0]
i = a.index(min(a))
a[-1],a[i] = a[i],a[-1]
print(a)

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

s=[1,2,3,5,6,7,8]
num=int(input('请输入一个小于6的整数'))
s1=s[-num:]+s[:-num]
print(s1)

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

n = int(input('请输入人数:'))
li_c = list(range(1, n + 1))    # 将所有人放入一个数组
print(li_c)#打印列表
count = 0    # 设置一个变量,用于计算报数
while len(li_c) > 1:# 当数组中至少有2个元素时进行循环
    li_co=li_c[:] # 把原数组拷贝到新数组中,用于限制内层循环次数
    for i in range(0, len(li_co)):    # 内层循环开始,从第一个人开始报数
        count = count + 1         # 每报一次,count计数器加1

        if count % 3 == 0:# 如果count能被3整除,则是报到3的人
            print(li_co[i])  #打印报数的人
            li_c.remove(li_co[i]) # 把报到3的人移除原数组,进行下一次循环
            

print('最后留下的是原来的第 {} 号。'.format(li_c[0]))

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

def fun(s):
       return len(s)
if __name__=='__main__':
    num=input('请输入一个字符串')
    print(fun(num))

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

student = []
for i in range(5):
    student.append(['','',[]])
 
def input_stu(stu):
    for i in range(N):
        stu[i][0] = raw_input('input student num:\n')
        stu[i][1] = raw_input('input student name:\n')
        for j in range(3):
            stu[i][2].append(int(raw_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)

72、列表排序及连接

if __name__ == '__main__':
    a = [1,3,2]
    b = [3,4,5]
    a.sort()     # 对列表 a 进行排序
    print a
 
    # 连接列表 a 与 b
    print a+b
    
    # 连接列表 a 与 b
    a.extend(b)
    print a

76、编写一个函数,输入n为偶数时,调用函数求1/2+1/4+…+1/n,当输入n为奇数时,调用函数1/1+1/3+…+1/n


def fun(n):
    if n%2==0:
        sum = 0
        for i in range(2,n+1,2):
            sum+=1/i
        return sum

    else:
        sum=0
        for i in range(1,n+1,2):
            sum+=1/i
        return sum
if __name__=='__main__':
    num=int(input('请输入一个大于0的整数\n'))
    print(fun(num))

77、循环输出列表

l=[1,2,3,4,5]
for i in l:
    print(i)

78、找到年龄最大的人,并输出。请找出程序中有什么问题

if __name__ == '__main__':
    person = {"li":18,"wang":50,"zhang":20,"sun":22}
    m = 'li'
    for key in person.keys():
        if person[m] < person[key]:
            m = key
 
    print '%s,%d' % (m,person[m])

79、字符串排序

if __name__ == '__main__':
    str1 = raw_input('input string:\n')
    str2 = raw_input('input string:\n')
    str3 = raw_input('input string:\n')
    print str1,str2,str3
    
    if str1 > str2 : str1,str2 = str2,str1
    if str1 > str3 : str1,str3 = str3,str1
    if str2 > str3 : str2,str3 = str3,str2
 
    print 'after being sorted.'
    print str1,str2,str3

80、海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子平均分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?

# 第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?
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)

81、809*??=800*??+9*?? 其中??代表的两位数, 809*??为四位数,8*??的结果为两位数,9*??的结果为3位数。求??代表的两位数,及809*??后的结果。

for i in range(10,200):
    if 8*i >=10 and 8*i<100  and 9*i>=100 and 9*i<1000  and 809*i>=1000 and 809*i<10000:82
        print(i, i * 809)
        print(809*i==800*i+9*i)
      # if int(len(str(8*i)))==2 and  int(len(str(9*i)))==3  and int(len(str(809*i)))==4:
      #       print(i,i*809)

83、八进制转换为十进制

print(bin(10))         #十转二
print(oct(10))         #十转八
print(hex(10))         #十转16
print(int('10',8))     #八转十
print(int('10',2))     #二转十
print(int('10',16))    #16转十

84、连接字符串

mylist = ['Brazil', 'Russia', 'India', 'China']
s='##'.join(mylist)
print(s)

85、输入一个奇数,然后判断最少几个 9 除于该数的结果为整数。

if __name__ == '__main__':
    zi = int(raw_input('输入一个数字:\n'))
    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)

86、两个字符串连接程序

if __name__ == '__main__':
    a = "hello"
    b = "python"
 
    # 连接字符串
    c = a + b
    print c

83、求0—7所能组成的奇数个数

组成1位数是4个。

组成2位数是7*4个。

组成3位数是7*8*4个。

组成4位数是7*8*8*4个
s = 1
sum=0
for i in range(1,9):
     if i ==1:
        s = 4
     elif i ==2:
        s =4*7
     if i>2:
        s *=8

     sum+=s
     print( '%d位数的奇数个数为%d'%(i,s))
     print ('总和为:sum=%d'%sum)

87、回答结果(结构体变量传递)

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'
    f(a)
    print a.x,a.c

88、读取7个数(1—50)的整数值,每读取一个值,程序打印出该值个数的*

if __name__ == '__main__':
    n = 1
    while n <= 7:
        a = int(raw_input('input a number:\n'))
        while a < 1 or a > 50:
            a = int(raw_input('input a number:\n'))
        print a * '*'
        n += 1

89、某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密规则如下:每位数字都加上5,然后用和除以10的余数代替该数字,再将第一位和第四位交换,第二位和第三位交换。

l=[]
for n in range(1,5):
  num_str=input('请输入第%s位整数'%n)
  l.append(num_str)
  l[n-1]=(int(l[n-1])+5)%10
# print(l)
l[0],l[3]=l[3],l[0]
l[1],l[2]=l[2],l[1]
print(l)

90、列表使用实例

#list  
#新建列表  
testList=[10086,'中国移动',[1,2,4,5]]  
  
#访问列表长度  
print len(testList)  
#到列表结尾  
print testList[1:]  
#向列表添加元素  
testList.append('i\'m new here!')  
  
print len(testList)  
print testList[-1]  
#弹出列表的最后一个元素  
print testList.pop(1)  
print len(testList)  
print testList  
#list comprehension  
#后面有介绍,暂时掠过  
matrix = [[1, 2, 3],  
[4, 5, 6],  
[7, 8, 9]]  
print matrix  
print matrix[1]  
col2 = [row[1] for row in matrix]#get a  column from a matrix  
print col2  
col2even = [row[1] for row in matrix if  row[1] % 2 == 0]#filter odd item  
print col2even

91、时间函数

if __name__ == '__main__':
    import time
    print time.ctime(time.time())
    print time.asctime(time.localtime(time.time()))
    print time.asctime(time.gmtime(time.time()))

if __name__ == '__main__':
    import time
    start = time.clock()
    for i in range(10000):
        print i
    end = time.clock()
    print 'different is %6.3f' % (end - start)

92、时间函数举例4,一个猜数游戏,判断一个人反应快慢


def tm094():
    import time,random
    print('《猜大小0-1000之间》')
    x = random.randint(0,1000)
    flag = input('是否开始(y/n):')
    if flag=='y':
        s = time.time()
        while 1:
            m = int(input('请输入数字:'))
            if m>x:
                print('大了')
            elif m

93、字符串日期转换为易读的日期格式

from dateutil import parser
dt = parser.parse("Aug 28 2015 12:00AM")
print dt

94、计算字符串出现的次数

if __name__ == '__main__':
    str1 = raw_input('请输入一个字符串:\n')
    str2 = raw_input('请输入一个子字符串:\n')
    ncount = str1.count(str2)
    print ncount

95、从键盘输入一些字符,逐个把它们写到磁盘文件上,直到输入一个 # 为止

with open('num.txt','w+') as f:
    while True:
        s=input('请输入')
        f.write(s)
        if s=='#':
            break
f.close()

96、 从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件"test"中保存

s=input('请输入一个字符').upper()
with open('test.txt','w+') as f:
    f.write(s)
f.close()

97、有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列), 输出到一个新文件C中

with open('num.txt','r+') as f:
    s=open('test.txt','r+')
    m=open('s.txt','w+')
    a=f.read()
    b=s.read()
    c=list(a+b)
    num=''.join(c)
    m.write(num)
f.close()
s.close()
m.close()

98、列表转换为字典

i = ['a', 'b']
l = [1, 2]
print dict([i,l])

你可能感兴趣的:(练习题)