fruits =[“Apple”,”Berry”,”Banana”,”Peach”]
Fruit_list =[]print(fruits)while True:
msg = input(“I want to buy:(Quit=q):”)
if msg == “q” or msg==”Q”:
break
else:
if msg in fruits:
Fruit_list.append(msg)
print(f”I want to buy:{Fruit_list}”)
執行結果
學生成績排序
key = lambda是一種匿名函式
students.sort(key=lambda x:x[5],reverse=True) #reverse = True 降序 , reverse = False 升序(默认)
指定 [5] 總分做降序排列(大到小)
reverse = True 降序 , reverse = False 升序(默認)
students=[[1,”Amy”, 100,40,60,0,0,0], [2,”Candy”, 90,95,65,0,0,0], [3,”Susan”, 55,100,45,0,0,0], [4,”Nini”, 98,95,97,0,0,0], [5,”Quen”, 66,15,85,0,0,0], [6,”peggy”, 85,60,65,0,0,0], ]
print(“總分和平均”)
for i in range(len(students)):
students[i][5]=sum(students[i][2:5])
students[i][6]=round((students[i][5]/3),1)
print(students[i])
students.sort(key=lambda x:x[5],reverse=True) #reverse = True 降序 , reverse = False 升序(默认)print(“名次”)
for i in range(len(students)):
if students[i][5] == students[i-1][5]: #跟前面總分一樣的話
students[i][7] = i+0 #名次+0,跟前面名次一樣
else:
students[i][7]= (students[i-1][7])+1 #不然的話就按照上個名次+1名 print(students[i])
students.sort(key=lambda x:x[0]) #reverse = True 降序 , reverse = False 升序(默认)
print(“成績單”)for i in range(len(students)):
print(students[i])
執行結果
雞兔同籠
#雞+兔各有幾隻 35個頭 100隻腳
chicken = 0
while True: r
abbit = 35 – chicken
if 4*rabbit+2*chicken==100:
print(f”chicken={chicken},rabbit={rabbit}”)
break
chicken +=1
執行結果
國王的麥粒
第一盤贏了可得 1粒 2的0次方
第二盤贏了可得 2粒 2的1次方
第三盤贏了可得 4粒 2的2次方
第四盤贏了可得 8粒 2的3次方
第五盤贏了可得 16粒 2的4次方
第六盤贏了可得 32粒 2的5次方
第六四盤贏了可得 ?????粒 2的63次方
sum = 0
for i in range(64):
wheat= 2**i
sum +=wheat
print(f”wheat:{sum}”)
執行結果
執行結果
計算結果相同,但我不太了解書中為何要加上 if 那段
2的0次方也是1
wheat= 2**i 應該就個代替整段了
不太了解