菜鸟教程python3100题_Python作业留底--《菜鸟教程》练习和习题

写这个是希望有个学习督促,毕竟自己前前后后拖拉了太多时间。希望正在和我一样初学的菜鸟都互相交流,要不自己一个坚持挺难,加上年纪大。

2019.11.12菜鸟教程Python 100例-1

import time

"""

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

程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。

"""

start_time=time.perf_counter()

output=[]

constant=['1','2','3','4']

for item in range(110,445):

chr=str(item)

if chr[0]==chr[1] or chr[1]==chr[2] or chr[0]==chr[2] \

or chr[0] not in constant or chr[1] not in constant or chr[2] not in constant:

continue

else:

output.append(item)

end_time=time.perf_counter()

print (len(output))

print (output)

print (end_time-start_time)

2019.11.19菜鸟教程Python 100例-2

def Calculation_of_bonuse(profit):

if profit>0 and profit<=10:

bonus=profit*0.01

elif profit>10 and profit<=20:

bonus = 10*0.01+(profit-10)*0.075

elif profit>20 and profit<=40:

bonus = 10*0.01+10*0.075+(profit-20)*0.05

elif profit>40 and profit<=60:

bonus = 10*0.01+10*0.075+20*0.05+(profit-40)*0.03

elif profit>60 and profit<=100:

bonus = 10*0.01+10*0.075+20*0.05+20*0.03+(profit-60)*0.015

elif profit>100:

bonus = 10*0.01+10*0.075+20*0.05+20*0.03+40*0.015+(profit-100)*0.01

print (bonus*10000)\

if __name__=="__main__":

profit=eval(input("The month's profit(RMB:万元):"))

Calculation_of_bonuse(profit)

"""别人使用列表嵌套和字典方式完成,牛掰"""

num=eval(input('请输入公司利润(万):'))

object={100:0.01,60:0.015,40:0.03,20:0.05,10:0.075,0:0.1}

profit_tags=object.keys()

profit=0

for key in profit_tags:

if num > key:

profit +=(num-key)*object.get(key)

num =key

print ('奖金为:{}万元'.format(profit))

2019.12.16菜鸟教程Python 100例-3

"""一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?假设该数为 x。"""

for k in range(1,13):

n=84/k-k/2#在混合计算时,Python会把整型转换成为浮点数

if int(n)==n:

x=pow(n,2)-100

print (x)

2019.12.23菜鸟教程内部例子再现

"""将给定的字符串倒序后输出"""

str_1 = input("请输入一个字符串:")

new_list=[]

for i in range(len(str_1),0,-1):

new_list.append(str_1[i-1])

print(''.join(new_list))

2019.12.24菜鸟教程内部例子再现

input_info=input('请输入一组数字:')#输入的字符串123

new_of_str='〇一二三四五六七八九'#比对组

old_of_str='0123456789'

for i in old_of_str:#从old_of_str中逐一跳出字符串来比对

"""将old_of_str的对应单个字符(存在0123456789中的)替换为s中对应的单个字符,eval(i)将表达式i执行,最终变为列表new_of_str的索引值"""

input_info=input_info.replace(i,new_of_str[eval(i)])

print(input_info)

2020.1.2菜鸟教程Python 100例-4

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

#第一版本——————————————————————————————————————————

date=input('请输入日期(参照2019.1.1格式):')

date_list=date.split('.')

year=date_list[0]

month=date_list[1]

day=date_list[2]

def if_leapyear(year):

"""

:param self: 非整百年数除以4,无余为闰,有余为平;②整百年数除以400,无余为闰有余平

1-12月分别为31天,29天,31天,30天,31天,30天,31天,31天,30天,31天,30天,31天

:param year:year

:return:返回一个字典格式每月天数

"""

year_tag={}

if (eval(year) % 4 == 0 and eval(year) % 100 != 0) or (eval(year) % 400 == 0 and eval(year) % 3200 != 0) or eval(year) % 172800 == 0:

return {1:31,2:29,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}

else:

return {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}

year_tag=if_leapyear(year)

day_1=0;day_2=0

for i in year_tag:

if i < eval(month):

day_1 = day_1 + year_tag[i]

elif i==eval(month):

day_2=eval(day)

else:

break

days=day_1+day_2

print(f'这一天是这一年的第{days}天')

#第二版本----------------------------------------------------------------------------------

date=input('请输入日期(参照2019.1.1格式):')

date_list=date.split('.')

year=date_list[0]

month=date_list[1]

day=date_list[2]

def if_leapyear(year):

"""

:param self: 非整百年数除以4,无余为闰,有余为平;②整百年数除以400,无余为闰有余平

1-12月分别为31天,29天,31天,30天,31天,30天,31天,31天,30天,31天,30天,31天

:param year:year

:return:返回一个字典格式每月天数

"""

year_tag={}

if (eval(year) % 4 == 0 and eval(year) % 100 != 0) or (eval(year) % 400 == 0 and eval(year) % 3200 != 0) or eval(year) % 172800 == 0:

return {1:31,2:29,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}

else:

return {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}

year_tag=if_leapyear(year)

day_1=0;day_2=0

days=eval(day)

for i in year_tag:

if i < eval(month):

days +=year_tag[i]

else:

break

print(f'这一天是这一年的第{days}天')

2020.1.12菜鸟教程Python 100例-5

inputs=input("输入整数:")

input_list=inputs.split(',')

output_list=[eval(i) for i in input_list]

output_list.sort()

print(output_list)

2020.1.14菜鸟教程Python 100例-6

#数列:0、1、1、2、3、5、8、13、21、34、……

def fib_1(n):

a,b=0,1

for i in range(n-1):

a,b=b,a+b#先运算b,a+b再赋值

print(f'(第{i+1}次循环)')

print(a,b)

#print(id(a),id(b))

#return a

#print(fib_1(4))

def fib_2(n):#错误方法1

a,b=0,1

for i in range(n-1):

a=b

b=a+b

print(f'(第{i+1}次循环)')

print(a,b)

#print(id(a), id(b))

#return a

#print(fib_2(4))

def fib_3(n):#递归

if n==1:

return 0

elif n==1 or n==2:

return 1

else:

return fib_3(n-1)+fib_3(n-2)

#print(fib_3(5))

2020.2.2菜鸟教程Python 100例-7

import time

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

lists=['国贸','CBD','天阶','我爱我家','链接地产']

list_1=[]

list_2=[]

list_3=[]

start_time_1=time.perf_counter()

list_1=[i for i in lists]

end_time_1=time.perf_counter()

times_1=end_time_1-start_time_1

print(f'方法2:{list_1}')

print(f'方法2:{times_1}')

start_time_2=time.perf_counter()

list_2=lists[:]

end_time_2=time.perf_counter()

times_2=end_time_2-start_time_2

print(f'方法2:{list_2}')

print(f'方法2:{times_2}')

start_time_3=time.perf_counter()

import copy

list_3=lists.copy()

end_time_3=time.perf_counter()

times_3=end_time_3-start_time_3

print(f'方法3:{list_3}')

print(f'方法3:{times_3}')

"""深浅拷贝都是对源对象的复制,占用不同的内存空间;前提是源对象不可变如果源对象只有一级目录的话,源做任何改动,不影响深浅拷贝对象如果源对象不止一级目录的话,源做任何改动,都要影响浅拷贝,但不影响深拷贝序列对象的切片其实是浅拷贝,即只拷贝顶级的对象建议结合以下两篇文章了解深浅拷贝的差异:https://www.jb51.net/article/67149.htmhttps://www.cnblogs.com/xueli/p/4952063.html"""

2020.2.2菜鸟教程Python 100例-8

for i in range(1,10):

for j in range(1,i+1):

print(f'{i}*{j}={i*j}',end=' ')

print()

2020.2.2菜鸟教程Python 100例-9

import time

start_time=time.perf_counter()

for i in range(1,10):

for j in range(1,i+1):

print(f'{i}*{j}={i*j}',end=' ')

time.sleep(1)

print()

end_time=time.perf_counter()

times=end_time-start_time

print(times)

2020.2.2菜鸟教程Python 100例-12

import math

def prima_nums(n):

max_n=int(math.sqrt(n)+1)

if n==1:

return print(n)

for i in range(2,max_n):

if n % i == 0:

break

return print(n)

for i in range(101,201):

prima_nums(i)

2020.2.2菜鸟教程Python 100例-13

#打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,

# 其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。

import math

def function_daffodil(n):

index_1=n//100

index_2=(n-index_1*100)//10

index_3=n-index_1*100-index_2*10

if n==math.pow(index_1,3)+math.pow(index_2,3)+math.pow(index_3,3):

print(n)

for i in range(100,1000):

function_daffodil(i)

"""#这个方法将数字和数字串转换,利用字符串的列表性质进行取数,奥力给!for i in range(100, 1000):s = str(i)if int(s[0]) ** 3 + int(s[1]) ** 3 + int(s[2]) ** 3 == i:print(i)"""

2020.2.10菜鸟教程Python 100例-14

def function_factoring(n):

factors = []

while n!=1:

for i in range(2, n + 1):

ele=divmod(n,i)

if ele[1]==0:#如果余数为零则添加进数组

n=int(ele[0])#将商作为测试数字进一步迭代来计算

factors.append(i)

break

return factors

a=function_factoring(8)

print(a)

2020.2.11菜鸟教程Python 100例-17

letter=0

letters=[]

num=0

nums=[]

blank=0

blanks=[]#无意义

other=0

others=[]

strings=input('Please enter a series of strings:')

for i in range(0,len(strings)):

if strings[i].isnumeric():#判断是否是数字

num +=1

nums.append(strings[i])

elif strings[i].isalpha():#判断是否是字母

letter +=1

letters.append(strings[i])

elif strings[i].isspace():#判断是否是空格

blank +=1

else:

other +=1

others.append(strings[i])

print(f'There are{letter}letters in the strings.{letters}')

print(f'There are{num}numbers in the strings.{nums}')

print(f'There are{blank}blanks in the strings.')

print(f'There are{other}other_strings in the strings.{others}')

#这个用正则来做的方法才是王道啊!!奥里给!

import re

strings=input('Please enter a series of strings:')

letters=re.findall('[a-zA-Z]',strings)

letter=len(letters)

nums=re.findall('[0-9]',strings)

num=len(nums)

spaces=re.findall(' ',strings)

space=len(spaces)

others=re.findall('[^a-zA-Z0-9]',strings)

other=len(others)

print(f'There are{letter}letters in the strings.{letters}')

print(f'There are{num}numbers in the strings.{nums}')

print(f'There are{space}blanks in the strings.')

print(f'There are{other}other_strings in the strings.{others}')

2020.2.11菜鸟教程Python 100例-18

#字符串复制概念

nums=input("Please enter a positive integer:")

layers=int(input('Please enter the number of layers:'))

sums=0

i=1

while i<(layers+1):

a=int(nums*i)

i +=1

sums +=a

print(sums)

#计算角度

import math

nums=input("Please enter a positive integer:")

layers=int(input('Please enter the number of layers:'))

tempt=0

i=0

total=0

while i<(layers):

tempt +=math.pow(10,i)

i +=1

total +=tempt

sums=int(nums)*total

print(sums)

2020.2.13菜鸟教程Python 100例-19

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

def Perfect_nums(n):

sum=0

for i in range(1,n):

if n%i==0:

sum +=i

if sum==n:

print(n)

for i in range(1,1001):

Perfect_nums(i)

2020.2.13菜鸟教程Python 100例-20

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

import math

def Dropping_height(n):

#n,反弹次数

sums=0

i=0

while i<(n+1):

drop_height=math.pow(0.5,i)*100

i +=1

rise_height=math.pow(0.5,i)*100

sums +=drop_height+rise_height

return (sums,drop_height)#可以返回元组对象,用以返回多个返回值

n=int(input('Please enter the amount of bounces:'))

a=Dropping_height(n)

print(f'在第10次落地时,共经过{a[0]}米;第10次反弹{a[1]}')

2020.5.6菜鸟教程Python 100例-21

"""

猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个

第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。

到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。

"""

n= 10

count = 0

resulte = 1

while n > 1:

resulte = (resulte+1)*2

n -= 1

count += 1

print(resulte)

print(count)

2020.5.7菜鸟教程Python 100例-22

#网页留言内排名第一的这位小哥解答,在我理解能力范围内无懈可击

team_1 = ['a', 'b', 'c']

team_2 = ['x', 'y', 'z']

for a in team_2:

for b in team_2:

for c in team_2:

if a != b and b != c and c !=a and a != "x" and c != "x" and c != "z":

tempt = (a, b, c)

print(f'a:{tempt[0]}, b:{tempt[1]}, c:{tempt[2]}')

2020.5.10菜鸟教程Python 100例-23

#打印菱形图案

def print_diamond(size):

diamond = [f'{"*" * (i * 2 + 1):^{size}}' for i in range((size // 2) + 1)]

for i in diamond:

print(i)

for i in diamond[-2::-1]:

print(i)

print_diamond(6)

2020.5.10菜鸟教程Python 100例-24 (2020.6.18重新看过)

def function():

i = 1

numerator, denominator = 2, 1

total = 0

while i <= 20:

fraction = numerator / denominator

total += fraction

numerator, denominator = numerator + denominator, numerator

i += 1

return print(total)

function()

2020.5.12菜鸟教程Python 100例-25

#求1+2!+3!+...+20!的和。

def factorial(n):

total = 1

for i in range(1, n+1):

total *= i

return total

def accumulate(m):

n = 1

sums = 0

while n <= m:

resulte = factorial(n)

sums += resulte

n += 1

return sums

res = accumulate(2)

print(res)

2020.5.13菜鸟教程Python 100例-26

#利用递归方法求5!

def factorial(n):

total = 0

if n == 1:

return 1

else:

total = n*factorial(n-1)

return total

result = factorial(3)

print(result)

2020.5.13菜鸟教程Python 100例-27

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

# 前期一直想不通,建议先正序考虑,从手写递归推导式来开始

# strs[0]+function(strs, 1)......最后在end终结

strs = "abcde"

index = 0

def print_strs_order(strs, index):# 先正序输出

if index == len(strs):

return

print(strs[index])

print_strs_order(strs, index+1)

print_strs_order(strs, index)

strs = "abcde"

index = len(strs)-1

def print_strs_reverse(strs, index):

if index == -1:

return

print(strs[index])

print_strs_reverse(strs, index-1)

print_strs_reverse(strs, index)

"""

def output(s, l):

if l == 0:

return

print(s[l - 1])

output(s, l - 1)

s = input('Input a string:')

l = len(s)

output(s, l)

"""

2020.5.13菜鸟教程Python 100例-28

"""

有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。

问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。

问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?

"""

def estimate_age(n):

if n == 1:

return 10

return estimate_age(n-1) + 2

age = estimate_age(5)

print(age)

"""

def age(n):

return 10 if not n-1 else age(n-1)+2

#教程里面高赞的模式,这一步用简易条件判断,not n-1 是个布尔值判断,即任何非零,空,None,{},[],()都是真

print(age(5))

"""

2020.5.13菜鸟教程Python 100例-29

"""

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

程序分析:学会分解出每一位数。

"""

numbers = input("Enter a positive integer:")

lis = list(numbers)

print(f'Figures:{len(lis)}')

print(f'Each numbers:\r')

for i in lis[::-1]:

print(f'{i}',end=' ')

2020.5.13菜鸟教程Python 100例-30

"""

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

"""

def is_palindromic_number():

numbers = input("Enter a positive integer:")

lis = list(numbers)

n = len(lis)

for i in range(0, n//2):

if lis[i] == lis[n-i-1]:

return print("This is a palindromic number.")

else:

return print('No')

is_palindromic_number()

"""

#教程高赞解答,这个真是活用了数据结构带来的好处

a = input("输入一串数字: ")

b = a[::-1]

if a == b:

print("%s 是回文"% a)

else:

print("%s 不是回文"% a)

"""

2020.5.14菜鸟教程Python 100例-31

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

#monday,tuesday,wenesday,thursday,friday,saturday,sunday

# 1. 原配第一版

weeks = ['monday', 'tuesday', 'wenesday', 'thursday', 'friday', 'saturday', 'sunday']

def day_of_week(weeks):

input_fir_strs = input("Enter first letter:").lower()

new_weeks = []

count = 0

for item in weeks:

if item.startswith(input_fir_strs):

new_weeks.append(item)

count += 1

if count == 1:

return print(new_weeks[0])

elif count == 0:

return print("Input error!")

else:

input_sec_strs = input("Enter second letter:").lower()

strs = input_fir_strs+input_sec_strs

for item in new_weeks:

if item.startswith(strs):

return print(item)

day_of_week(weeks)

"""

#高赞答案:当初也想到用字典来快速检索,但是想到首字母存在重复,无法使用唯一键值来判断。

#人家这里的解答,就是活用数据结构,字典套字典来使用

weeklist = {'M': 'Monday','T': {'u': 'Tuesday','h':'Thursday'}, 'W': 'Wednesday', 'F':'Friday','S':{'a':'Saturday','u':'Sunday'}}

sLetter1 = input("请输入首字母:")

sLetter1 = sLetter1.upper()

if (sLetter1 in ['T','S']):

sLetter2 = input("请输入第二个字母:")

print(weeklist[sLetter1][sLetter2])

else:

print(weeklist[sLetter1])

"""

"""

# 1.2 根据高赞第二名修改的,当时写的时候就感觉是不是可以用递归啊,但是没想太多

# 使用的时候发现两个容易错误的。第一就是strs 这个全局变量如果没做为参数传入,在函数内调用要发生问题,但具体的缘由我听过,但是忘了,以后再来多理解

# 如果有懂的麻烦给我说下

weeks = ['monday', 'tuesday', 'wenesday', 'thursday', 'friday', 'saturday', 'sunday']

strs = ''

def day_of_week(strs, weeks):

input_strs = input("Enter letter:").lower()

strs = strs+input_strs

new_weeks = []

count = 0

for item in weeks:

if item.startswith(strs):

new_weeks.append(item)

count += 1

if count == 1:

return print(new_weeks[0])

elif count == 0:

return print("Input error!")

else:

day_of_week(strs, new_weeks)

day_of_week(strs, weeks)

"""

2020.5.16 菜鸟教程Python 100例-32

#按相反的顺序输出列表的值

lis_1 = [1,2,3,4,5,6]

lis_2 = reversed(lis_1)

for i in lis_2:

print(i)

2020.5.16 菜鸟教程Python 100例-33

#按逗号分隔列表

lis_1 = [1,2,3,4,5,6]

strs = str(lis_1)

n = len(strs)

print(n)

for i in strs[1:n-1]:

print(i,end='')

"""

#高赞答案是我的这个超级简化版,大哥喝可乐

#repr(obj) 函数,将对象转换为可供解释器读取的形式(看不懂阶段,但是后面解释能懂),返回值是对象的 string 格式

lis_1 = [1,2,3,4,5,6]

for i in repr(lis_1)[1:-1]:#这里不要犯我的低级错误,列表切片是 lis[m:n], 是[m, n)包含m ,半包含n 关系

print(i, end='')

"""

中间有几题太简单没做,有几题看错了,空了补上。

2020.5.17 菜鸟教程Python 100例-37

#全是排序的算法,菜鸟实例有不少这个,准备结合知乎上看到的一篇《python算法:10大经典排序算法》把这块知识系统过一遍。过完再写。

2020.5.17 菜鸟教程Python 100例-38

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

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

row = len(matrix)

column = len(matrix[0])

def calculate_maxtrix(row, column):

new_lis = []

for i in range(row):

for j in range(column):

if i == j:

new_lis.append(matrix[i][j])

print(new_lis)

return sum(new_lis)

res = calculate_maxtrix(row, column)

print(res)

2020.5.18 菜鸟教程Python 100例-39

#排序题,留着后面做

2020.5.18 菜鸟教程Python 100例-40

# 将一个数组逆序输出

def print_reverse_squence(squence):

for item in squence[::-1]:

print(item, end='')

lis = [i for i in range(10)]

print(lis)

print_reverse_squence(lis)

"""

#教案讲解的这个过程适用于二分法查找,a[i],a[N - i - 1] = a[N - i - 1],a[i]要记住是先运算表达式后赋值

if __name__ == '__main__':

a = [9,6,5,4,1]

N = len(a)

print a

for i in range(len(a) / 2):

a[i],a[N - i - 1] = a[N - i - 1],a[i]

print a

"""

2020.5.19 菜鸟教程Python 100例-41

num = 2 #全局变量

def autofunc():

num = 1 #局部变量

print 'internal block num = %d' % num

num += 1

for i in range(3):

print 'The num = %d' % num

num += 1

autofunc()

2020.5.20 菜鸟教程Python 100例-42/43 略过

2020.5.20 菜鸟教程Python 100例-44

# 两个 3 行 3 列的矩阵,实现其对应位置的数据相加,并返回一个新矩阵:

X = [

[12,7,3],

[4 ,5,6],

[7 ,8,9]

]

Y = [

[5,8,1],

[6,7,3],

[4,5,9]

]

"""

# 1.第一版,做出感觉来改

def maxtrix_to_lis(maxtrix):

row = len(maxtrix)

column = len(maxtrix[0])

new_lis = []

for i in range(row):

for j in range(column):

new_lis.append(maxtrix[i][j])

return new_lis

lis_x = maxtrix_to_lis(X)

lis_y = maxtrix_to_lis(Y)

new_lis = map(lambda x, y: x+y, lis_x, lis_y)

for item in new_lis:

print(item, end=" ")

"""

def add_maxtrix(m_1, m_2):

assert (len(m_1) == len(m_2) and len(m_1[0]) == len(m_2[0]))

row = len(m_1)

column = len(m_1)

for i in range(row):

for j in range(column):

m_1[i][j] += m_2[i][j]

return m_1

res = add_maxtrix(X, Y)

print(res)

2020.5.20 菜鸟教程Python 100例-45

# 题目:统计 1 到 100 之和。

sequence = [i for i in range(1,101)]

total = 0

for i in sequence:

total += i

print(res)

"""

# 高赞答案里面用到的 reduce 函数在 python3以后取消,变为 functool 模块中

# 详见菜鸟教程内的说明--“https://www.runoob.com/python/python-func-reduce.html”

import functools

res = functools.reduce(lambda x, y:x+y, range(1,101))

print(res)

"""

2020.5.21 菜鸟教程Python 100例-46

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

key = True

while key:

nums = eval(input("Input a number:"))

if pow(nums, 2) >= 50:

print(nums)

else:

key = False

退出函数的方法,其他答案里面给出了使用 exit()、 quit() 函数;当然使用 break 很简单

建议调用 help 函数看下 exit()、 quit()

2020.5.21 菜鸟教程Python 100例-47

# 两个变量值互换。

var_1 = 998

var_2 = 1024

var_1, var_2 = var_2, var_1#这里我踩过坑,右侧先运行表达式计算,然后才完成赋值

print(var_1)

print(var_2)

2020.5.24 菜鸟教程Python 100例-49

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

dic = {'a':1, 'c':6, 'd':2, 'b':4}

new_dic_1 = sorted(dic.items(), key = lambda x:x[0])

new_dic_2 = sorted(dic.items(), key = lambda x:x[1])

print(f"按照键升序排列{new_dic_1}")

print(f"按照值升序排列{new_dic_2}")

2020.5.24 菜鸟教程Python 100例-61(中间的题目要么太简单,要么画图实在没啥实际应用,忘了搜索很容易上手就没写)

# 题目:打印出杨辉三角形(要求打印出10行如下图)。

"""11 11 2 11 3 3 11 4 6 4 11 5 10 10 5 11 6 15 20 15 6 11 7 21 35 35 21 7 11 8 28 56 70 56 28 8 11 9 36 84 126 126 84 36 9 1"""

import time

def yh_triangel_1(column):

for i in range(1, column+1):

for j in range(1, i+1):

res = _one_column(i, j)

print(res, end=' ')

print()

def _one_column(column, index):

if index == 1 or index == column:#这里给出第一行和第二行的值

return 1

else:

return _one_column(column-1, index-1) + _one_column(column-1, index)

# 方法2 是抄完高赞答案重新写的菜鸟易懂的答案,迭代看起来高大上,但是脑子容易绕晕。运算时间也飙起来啦,详见下面测试

def yh_triangel_2(column):

a = []

for i in range(0, column):

a.append([])

for j in range(0, i+1):

if j == 0 or j == i:

a[i].append(1)

else:

value = a[i-1][j-1] + a[i-1][j]

a[i].append(value)

for item in a:

for j in range(len(item)):

print(item[j], end=' ')

print()

start_time_1 = time.perf_counter()

yh_triangel_1(10)

end_time_1 = time.perf_counter()

time_1 =end_time_1 - start_time_1

start_time_2 = time.perf_counter()

yh_triangel_2(10)

end_time_2 = time.perf_counter()

time_2 =end_time_2 - start_time_2

print(f'method_1:{time_1}')

print(f'method_2:{time_2}')

2020.5.25 菜鸟教程Python 100例-62

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

def ascending_values(n):

i = 0

sequence = []

while i < n:

var = input('Input one number:')

sequence.append(var)

i += 1

sequence.sort()

for item in sequence:

print(item, end=' ')

ascending_values(3)

2020.5.25 菜鸟教程Python 100例-67(中间的画图不做啦)

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

import random

# 1.第一个版本,写的粗糙

sequence = [i for i in range(1, 11)]

random.shuffle(sequence)

print(sequence)

max_n = max(sequence)

min_n = min(sequence)

for index, value in enumerate(sequence):

if value == max_n :

max_index = index

if value == min_n :

min_index = index

sequence[max_index], sequence[0] = sequence[0], sequence[max_index]

sequence[min_index], sequence[-1] = sequence[-1], sequence[min_index]

print(sequence)

'''# 2. 第二个版本是看来练习题高赞的答案改进的sequence = [i for i in range(1, 11)]random.shuffle(sequence)print(sequence)for index, value in enumerate(sequence):if sequence[index] == max(sequence):sequence[index], sequence[0] = sequence[0], sequence[index]if sequence[index] == min(sequence):sequence[index], sequence[-1] = sequence[-1], sequence[index]print(sequence)'''

2020.5.26 菜鸟教程Python 100例-68(中间的画图不做啦)

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

# 参考其他练手项目,凯撒密码;同时有篇将列表切片的很有意思,https://www.jianshu.com/p/15715d6f4dad

nums = '123456'

length_nums = len(nums)

lis = list(nums)

offset = 4

new_lis = []

for k, v in enumerate(lis):

index = (k - offset) % length_nums

print(index)

new_lis.append(lis[index])

print(new_lis)

2020.5.27 菜鸟教程Python 100例-69

# 题目:有n个人围成一圈,顺序排号。

# 从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。

n = int(input('Input a number:'))

lis = [i for i in range(1, n+1)]

print(lis)

def function(lis):

i = 1 #这里用函数来重写的话注意, 全局变量和局部变量

while len(lis) != 1:

if i % 3 == 0:

# print(f'元素:{lis.pop(0)}')

lis.pop(0)

# print(f'列表:{lis}')

else:

lis.insert(len(lis), lis.pop(0))

# 如果不是3倍数,转入到末尾,lis.pop(index) 返回删除值并删除掉

i += 1

return print(f'最终结果{lis}')

function(lis)

2020.5.30 菜鸟教程Python 100例-70

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

def function():

strs = input('Input strings:')

return print(f'The length of string:{len(strs)}')

if __name__ == '__main__':

function()

2020.5.30 菜鸟教程Python 100例-71

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

# 学生数据包含:姓名、年龄、性别

# 高赞答案里面用了类,正好复习下前面学的

class Student:

def __init__(self, name, age, sex):

self.name = name

self.age = age

self.sex = sex

def input_st_information():

new_st_information = {}

while True :

name = input('Enter your name:').lower()

age = input('Enter your age:')

sex = input('Enter your sex:').lower()

new_st_information[name] = Student(name, age, sex)

key = input('Exit:Y/N ?')

if key == 'Y':

break

return new_st_information

def output_st_information(new_st_information):

for value in new_st_information.values():

print(value.name ,value.age, value.sex)

st_information = input_st_information()

output_st_information(st_information)

2020.6.1 菜鸟教程Python 100例-75

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:#4

print(64 + i)

"""# 以下是分析过程:i n()0 n(1, 1, 1, 2, 2)1 n(0, 0, 0, 1, 1)2 n(1, 1, 1, 2, 2)3 n(1, 2, 2, 3, 67)4 n(1, 1, 1, 2, 2)"""

2020.6.1 菜鸟教程Python 100例-76

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

n = eval(input('Input a number:'))

def function(n):

# odd, even

if n % 2 == 0 :

return _odd_function(n)

else:

return _even_function(n)

def _odd_function(n):

total = 0

for i in range(2, n+1, 2):

total += 1/(i)

return total

def _even_function(n):

total = 0

for i in range(1, n+1, 2):

total += 1/(i)

return total

result = function(n)

print(result)

2020.6.2 菜鸟教程Python 100例-78

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

person = {"li": 18, "wang": 50, "zhang": 20, "sun": 22}

sorted_by_value = sorted(person.items(), key= lambda x:x[1], reverse=True)

print(sorted_by_value[0][0])

2020.6.3 菜鸟教程Python 100例-80

# 海滩上有一堆桃子,五只猴子来分。

# 第一只猴子把这堆桃子平均分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。

# 第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份,

# 第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子

# 觉得课程内的答案是错的。以下是我的,这个解法前面习题有过,类似斐波那契数列

def function():

n = 0

total = 0

while n != 6:

total = total * 5 + 1

print(total)

n += 1

function()

"""# 测试1:lis = [3906, 781, 156, 31, 6]for k,item in enumerate(lis, start=1):quotient, remainder = divmod(item, 5)[0], divmod(item, 5)[1]print(f'No:{k},quotient:{quotient}, remainder:{remainder}')# 测试2:total = 3121i = 0while i != 5:n, m =divmod(total, 5)print(n, m)total = ni += 1"""

2020.6.3 菜鸟教程Python 100例-81

for x in range(10, 100):

condition_1 = 9 < x < 99

condition_2 = 9 < 8 * x < 99

condition_3 = 100 < 9 * x < 999

# condition_4 = 10000 < 809 * x < 9999

if condition_1 and condition_2 and condition_3:

print(x)

2020.6.4 菜鸟教程Python 100例-83

# 题目:求0—7所能组成的奇数个数

# 算的和教程答案对不上啊?

def _is_even(number):

if number % 2 != 0:

return True

def count_even():

ranges = '76543210'

for i in range(len(ranges)):

cap = int(ranges[:i+1])

counts = 0

for j in range(cap+1):

if _is_even(j):

counts += 1

print(f"{i}figures:{counts}counts")

count_even()

2020.6.4 菜鸟教程Python 100例-85

# 题目:输入一个奇数,然后判断最少几个 9 除于该数的结果为整数

def function_1():

number = eval(input('Enter a even:'))

string = '9'

item = 1

while True:

dividend = eval(string * item)

if dividend % number != 0 :

item += 1

else:

print(dividend)

break

def function_2():

number = eval(input('Enter a even:'))

dividend = 9

while True:

if dividend % number != 0:

dividend = dividend * 10 + 9

else:

print(dividend)

break

function_1()

2020.6.7 菜鸟教程Python 100例-88

# 题目:读取7个数(1—50)的整数值,每读取一个值,程序打印出该值个数的*

def function():

times = eval(input('Times:'))

i = 0

while i < times :

n = eval(input('Input a integer:'))

print('*'*n)

i += 1

function()

2020.6.7 菜鸟教程Python 100例-89

# 题目:某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密规则如下:

# 每位数字都加上5,然后用和除以10的余数代替该数字,再将第一位和第四位交换,第二位和第三位交换。

def encrypted_data(datas):

datas_str = str(datas)

datas_lis = []

for i in datas_str:

number = (int(i) + 5) % 10

datas_lis.append(number)

datas_lis[0], datas_lis[3] = datas_lis[3], datas_lis[0]

datas_lis[1], datas_lis[2] = datas_lis[2], datas_lis[1]

new_datas_str = ''.join([str(j) for j in datas_lis])

new_datas = int(new_datas_str)

return print(new_datas)

encrypted_data(datas = 1234)

2020.6.14 菜鸟教程Python 100例-98

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

def function():

string = input('Input a strings:')

upper_string = string.upper()

with open('E:/Python_data/study_test/test.txt', 'w+', encoding='utf_8') as file:

file.write(upper_string)

function()

2020.6.14 菜鸟教程Python 100例-99

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

def read_file(filename):

with open(filename, 'r+', encoding='utf_8') as file:

context = file.read()

return context

def save_file(context, filename):

with open(filename, 'w+', encoding='utf_8') as file :

file.write(context)

filename_1 = 'E:/Python_data/study_test/test_1.txt'

filename_2 = 'E:/Python_data/study_test/test_2.txt'

filename_3 = 'E:/Python_data/study_test/test_3.txt'

context_1 = read_file(filename_1)

context_2 = read_file(filename_2)

context = ''.join(sorted(context_1 + context_2))

save_file(context, filename_3)

2020.6.14 菜鸟教程Python 100例-100

# 题目:列表转换为字典。

lis = ['a', 'c', 'sd', 'we']

dic = {}

for k, v in enumerate(lis):

dic[k] = v

print(dic)