iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >100个Python小例子(练习题三)
  • 844
分享到

100个Python小例子(练习题三)

2024-04-02 19:04:59 844人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录实例051:按位与实例052:按位或实例053:按位异或实例054:位取反、位移动实例055:按位取反实例056:画圈实例057:画线实例058:画矩形实例059:画图(丑)实例

前期练习:

100 个 python 小例子(练习题二)

100 个 Python 小例子(练习题一)

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

实例052:按位或

题目:学习使用按位或 | 。

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

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

实例053:按位异或

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

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

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

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

实例055:按位取反

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

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

print(~234)
print(~~234)

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

实例057:画线

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

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

实例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.pack()
    root.mainloop()

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


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

实例060:字符串长度

题目:计算字符串长度。  

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

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

实例062:查找字符串

题目:查找字符串。  

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

实例063:画椭圆

题目:画椭圆。 

程序分析:使用 tkinter

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

实例64:画椭圆、矩形

题目:利用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.pack()
    mainloop()

实例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 = 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()

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

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

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

实例069:报数

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

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

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

实例070:字符串长度II

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

def lenofstr(s):
    return len(s)

print(lenofstr('tanxiaofengsheng'))

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

实例072:创建链表

题目:创建一个链表。

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

实例073:反向输出链表

题目:反向输出一个链表。

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

实例074:列表排序、连接

题目:列表排序及连接。

程序分析:排序可使用sort() 方法,连接可以使用 + 号或 extend() 方法。

a=[2,6,8]
b=[7,0,4]
a.extend(b)
a.sort()
print(a)

例075:不知所云

题目:放松一下,算一道简单的题目。

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)

到此这篇关于100 个 Python 小例子(练习题三)的文章就介绍到这了,更多相关 Python 练习题内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 100个Python小例子(练习题三)

本文链接: https://www.lsjlt.com/news/163354.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 100个Python小例子(练习题三)
    目录实例051:按位与实例052:按位或实例053:按位异或实例054:位取反、位移动实例055:按位取反实例056:画圈实例057:画线实例058:画矩形实例059:画图(丑)实例...
    99+
    2024-04-02
  • 100 个 Python 小例子(练习题四)
    目录实例076:做函数实例077:遍历列表实例078:字典例079:字符串排序实例080:猴子分桃实例081:求未知数实例082:八进制转十进制实例083:制作奇数实例084:连接字...
    99+
    2024-04-02
  • 100 个 Python 小例子(练习题一)
    目录实例001:数字组合 实例002:“个税计算”实例003:完全平方数实例004:这天第几天实例005:三数排序实例006:斐波那契数列实例007:copy实例008:九九乘法表实...
    99+
    2024-04-02
  • 100 个 Python 小例子(练习题二)
    目录实例031:字母识词实例032:反向输出II实例033:列表转字符串实例034:调用函数 实例035:设置输出颜色实例036:算素数实例037:排序实例038:矩阵对角线之和实例...
    99+
    2024-04-02
  • python3 练习题100例 (三)
    题目三:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少? #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 题目三:一个整数,它加上100后...
    99+
    2023-01-30
    练习题
  • python3 练习题100例 (五)
    题目五:输入三个整数x,y,z,请把这三个数由小到大输出。 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 题目五:输入三个整数x,y,z,请把这三个数由小到大输出。""" __...
    99+
    2023-01-30
    练习题
  • python3 练习题100例 (四)
    题目四:输入某年某月某日,判断这一天是这一年的第几天? #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 题目四:输入某年某月某日,判断这一天是这一年的第几天?""" __auth...
    99+
    2023-01-30
    练习题
  • python3 练习题100例 (二)
    题目二:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%...
    99+
    2023-01-30
    练习题
  • 小猿圈python之练习小例子
    每天坚持学习python内容是很重要的,很多人通过看视频学习,但是只是喜欢听老师讲课,听完也都感觉自己都懂了,很满足,真的是这样吗?你真的懂了吗?自己可以做一下小练习测试一下,发现做一个不会一个,为什么呢?小猿圈加加告诉你真相,因为pyt...
    99+
    2023-01-31
    例子 小猿圈 python
  • Python基础练习100题 ( 91
    昨天和大家分享了81-90题,今天继续来刷最后的91-100题 Question 91: Please write a program which accepts a string from console and print it ...
    99+
    2023-01-31
    基础 Python
  • Python基础练习100题 ( 1~
    大家好,好久不见,我最近在Github上发现了一个好东西,是关于夯实Python基础的100道题,原作者是在Python2的时候创建的,闲来无事,非常适合像我一样的小白来练习 对于每一道题,解法都不唯一,我在这里仅仅是抛砖引玉,希望可以...
    99+
    2023-01-31
    基础 Python
  • python练习集100题(21-40)
    题目21:两个乒乓球队进行比赛,各出3人。甲队为a,b,c三人,乙队为x,y,z三人。以抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x、z比,请编程找出三队比赛名单。first_list=['x','y','z']...
    99+
    2023-01-31
    python
  • 100道python经典练习题
    链接:https://pan.baidu.com/s/1K0iuZKJukLoGQ8OBy7xq1Q 提取码:2s6q 链接长期有效,如有疑问,欢迎评论区交流。 ...
    99+
    2023-01-31
    练习题 经典 python
  • Python基础练习100题 ( 71
    昨天和大家分享了61-70题,今天继续来刷71~80题 Question 71: Please write a program to output a random number, which is divisible by 5 and...
    99+
    2023-01-31
    基础 Python
  • Python基础练习100题 ( 51
    昨天和大家分享了41-50题,今天继续来刷51~60题 Question 51: Write a function to compute 5/0 and use try/except to catch the exceptions. ...
    99+
    2023-01-31
    基础 Python
  • Python基础练习100题 ( 21
    昨天和大家分享了前10道题,今天继续来刷21~30 Question 21: A robot moves in a plane starting from the original point (0,0). The robot can ...
    99+
    2023-01-31
    基础 Python
  • Python基础练习100题 ( 81
    昨天和大家分享了71-80题,今天继续来刷81~90题 Question 81: By using list comprehension, please write a program to print the list after r...
    99+
    2023-01-31
    基础 Python
  • Python基础练习100题 ( 41
    大家好,我又回来了,昨天和大家分享了31-40题,今天继续来看41~50题 Question 41: Write a program which can map() to make a list whose elements are s...
    99+
    2023-01-31
    基础 Python
  • Python基础练习100题 ( 31
    昨天和大家分享了21-30题,今天继续来刷31~40题 Question 31: Define a function which can print a dictionary where the keys are number...
    99+
    2023-01-31
    基础 Python
  • Python基础练习100题 ( 61
    昨天和大家分享了51-60题,今天继续来刷61~70题 Question 61: The Fibonacci Sequence is computed based on the following formula: f(n)=0 if ...
    99+
    2023-01-31
    基础 Python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作