作业1:有一堆硬币[10, 8, 5, 3, 27, 99],每次只能拿一个或者两个,求最少多少次可以拿完硬币
ls = [10, 8, 5, 3, 27, 99]
def get_coin():
count = 0
for i in ls:
if i % 2 == 0:
count += i // 2
else:
count += i // 2 + 1
return count
print(get_coin())
作业2:如果两个素数之差为2,这样的两个素数就叫作"孪生数",找出100以内的所有"孪生数".
ls = []
for i in range (2,101):
flag = True
for j in range(2,i):
if i % j==0:
flag = False
break
if flag:
ls.append(i)
index = 0
print(ls)
while index<len(ls) -1 :
first = ls[index]
second = ls[index+1]
if second - first == 2:
print(f"{first}和{second}是孪生数")
index +=1
作业3:给定一个列表,求最大值(不能使用系统api),求最小值,求平均值、求和
ls = [10, 8, 5, 3, 27, 99]
def get_max(ls):
maxNum = ls[0]
for i in ls:
if i>maxNum:
maxNum = i
return maxNum
def get_min(ls):
minNum = ls[0]
for i in ls:
if i<minNum:
minNum = i
return minNum
def get_sum(ls):
sum = 0
for i in ls:
sum += i
return sum
def get_avg(ls):
return get_sum(ls)/len(ls)
print(f"最大值:{get_max(ls)}")
print(f"最小值:{get_min(ls)}")
print(f"列表数字之和:{get_sum(ls)}")
print(f"平均值:{get_avg(ls)}")
#方法一: 利用循环的方式去重
'''
l1 = [1,2,3,4,2,3]
l2 = []
for i in l1:
if i not in l2:
l2.append(i)
print(l2)
'''
#方法二:字典方法去重
l1 = [1,2,3,4,2,4]
d = {}.fromkeys(l1)
print(d.keys())
l1 = [1,2,3]
l2 = [7,9,0]
l1.extend(l2)
print(l1)
作业6: 使用列表判断一个列表是否在另外一个列表中
l1 = [1,2,3,4,0]
l2 = [10,203]
if set(l2)<=set(l1):
print("存在!")
else:
print("不存在!")
效果图就自行尝试吧~
作业7:列表的反转 列表的排序
#反转
l1 = [9,8,7,6]
l1.reverse()
print(l1)
#排序 reverse = True降序;reverse = False升序
l2 = [2,4,5,1,0]
l2.sort(reverse = False)
print(l2)
l3 = [99,66,88,77,100,10]
l3.sort(reverse=True)
print(l3)
import random #生成随机数
def num():
ls = []
for i in range(10):
ls.append(random.randint(0, 10))
return ls
print(num())
users = []
while True:
print("\t\t欢迎登录用户管理系统")
print("\t\t 1、用户注册")
print("\t\t 2、用户登录")
print("\t\t 3、退出系统")
choice = input("请输入您的选择:")
if choice == "1":
while True:
username = input("请输入用户名:")
password = input("请输入密码:")
password_again = input("请再次确认密码:")
if username == None or len(username) == 0:
print("对不起,用户为空")
continue
flag = False
for u in users:
if u.get("username") == username:
print("对不起,该用户已经存在,请重新注册")
flag = True
break
if flag:
continue
if password != password_again:
print("两次密码不一致")
continue
user = {"username": username, "password": password}
users.append(user)
print("用户注册成功,请登录")
print("\n")
break
elif choice == "2":
print("\n")
username = input("请输入用户名:")
password = input("请输入密码:")
for user in users:
if user["username"] == username and user.get("password") == password:
print("尊敬的{},欢迎回来".format(username))
else:
print("对不起,登录失败,请重新登录")
else:
sys.exit()
自行去测试一下吧~