Python Homework 2023

1

1
2
3
4
5
6
7
8
9
10
'''
Ask the user to input two variables.
Calculate the sum of them.
Output the results.
'''

var1 = input("enter the first input here: ")
var2 = input("enter the second input here: ")

print(int(var1) + int(var2))

2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
'''

Input: N, M
生成一个有 N (1<N≤100) 个元素的列表,
每个元素是一个随机数 n (1≤n≤2^31 −1),
从这个列表中随机取出 M (1<M≤N) 个数,
对这 M 个数字进行排序,显示
Output: 排序后的这 M 个数字
'''
import random

n_int = int(input("n_"))
m_int = int(input("m_"))

if __name__ == "__main__":
ls = []
for i in range(n_int):
rd_int = random.randint(1, 2 ^ 31 - 1)
ls.append(rd_int)
# print(ls)
ls_m = random.sample(ls, m_int)
# print(ls_m)
ls_m_arr = sorted(ls_m)
print(ls_m_arr)

3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
'''
Description:

句子反转:
给定一个句子(只包含字母和空格),将句子中的单词位置反转,单词用空格分割, 单词之间只有一个空格,句子前后没有空格。
比如:“hello xiao ming”-> “ming xiao hello”

输入描述:可以输入多组数据。每组包含一个句子。
输出描述:最后统一输出每组句子单词反转后形成的句子。
'''

str = input(">>>")

if __name__ == "__main__":
# answer here
ls = str.split(" ")
ls_reverse = ls
ls_reverse.reverse()

str_reverse = ""

for item in ls_reverse:
str_reverse += item
str_reverse += " "

print(str_reverse)

4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
'''
Description:
用字典来模拟一个简单的用户账号注册、登录与退出的程序:
Demo: Login system with User PWD
Registration:
input name&pwd,
Duplicate Checking
Login:
check name&pwd
Quit:
quit
'''

if __name__ == "__main__":
# answer here
# Dict
user = {}
# Mode Select
while True:
mode = input("Please select mode: 1.Register 2.Login 3.Quit")
if mode == "1":
# Register
while True:
print(">> Welcome to register!")
name = input("Please input your name:")
if name in user:
print("The name is already exist!\n")
else:
pwd = input("Please input your password:")
user[name] = pwd
print("Register successfully!\n")
break

elif mode == "2":
# Login
while True:
print(">> Welcome to login!")
name = input("Please input your name:")
if name in user:
pwd = input("Please input your password:")
if user[name] == pwd:
print("Login successfully!\n")
break
else:
print("Wrong password!\n")
else:
print("The name is not exist!\n")

elif mode == "3":
# Quit
print("Quit successfully!\n")
else:
print("Wrong mode code!\n")

5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
'''
Description:

Give a range of integers and find the first ten Palindrome Numbers (回文数字) in this range.

If there are less than 10 outputs, output all the Palindrome Numbers in this range.
'''

if __name__ == "__main__":
# answer here
a, b = map(int, input("Please input the range of integers split with , :").split(","))
print("Find Palindrome Numbers between " + str(a) + "~" + str(b) + "\n")
count = 0
for i in range(a, b + 1):
if str(i) == str(i)[::-1]:
print(i)
count += 1
if count == 10:
break
if count == 0:
print("No Palindrome Numbers in this range!\n")

6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
'''
Description:

Calculate the sum of all the positive even numbers in a list.

Using Functional Programming
Using Higher-order function
Using Anonymous Functions and lambda
'''

from functools import reduce

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

if __name__ == "__main__":
# answer here
seq = filter(lambda x: x % 2 == 0 and x > 0, list)
sum = reduce(lambda x, y: x + y, seq)
print(sum)

7

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
'''
Description:
狼吃羊的游戏

假设游戏场景范围为(x,y),0≤x≤9,0≤y≤9。

游戏生成1只狼和10只羊;
它们的移动方向均随机;
狼的最大移动能力是2(可以随机移动1或2),羊的最大移动能力是1,移动随机沿x轴或y轴进行;
当移动到场景边界,则向反方向移动;
狼初始化体力为100;
狼每移动一次,体力消耗1;
当狼和羊坐标重叠,狼吃掉羊,狼体力增加20;
羊暂不计算体力;
当狼体力值为0或者羊的数量为0,游戏结束。

注意:无需图形界面展示,但要有中间过程输出。
'''
import random


class GameScene:
def __init__(self, x, y):
self.round = 1
self.x = x
self.y = y
self.Wolves = []
self.Sheep = []

def generate_animals(self, num_wolves, num_sheep):
for _ in range(num_wolves):
wolf = Wolf(self)
self.Wolves.append(wolf)
for _ in range(num_sheep):
sheep = Sheep(self)
self.Sheep.append(sheep)

def game_logic(self):
while self.Wolves and self.Sheep:
print(f"==== Round {self.round} ====")
print(f"Wolves: {len(self.Wolves)} Sheep: {len(self.Sheep)}")
for wolf in self.Wolves:
wolf.move()
for sheep in self.Sheep:
sheep.move()
self.display_map()
self.check_collisions()
self.round += 1
print("")

def check_collisions(self):
for wolf in self.Wolves:
print(f">> Wolf at {wolf.get_coordinates()}")
for sheep in self.Sheep:
print(f">> Sheep at {sheep.get_coordinates()}")
if wolf.x == sheep.x and wolf.y == sheep.y:
wolf.eat()
sheep.die()

def game_over(self):
check = len(self.Wolves) == 0 or len(self.Sheep) == 0
# print(f"Game Over:{check}")
return check

def display_map(self):
print("+++" * (self.x + 2) + "+")
# a matrix defualt 0
map = [[0 for _ in range(self.x + 1)] for _ in range(self.y + 1)]
for wolf in self.Wolves:
x, y = wolf.get_coordinates()
map[x][y] += 1
for sheep in self.Sheep:
x, y = sheep.get_coordinates()
map[x][y] += 2
# print(map),0-'· ',1-'W ',2-'S '
for i in range(self.y + 1):
print("|", end=" ")
for j in range(self.x + 1):
if map[i][j] == 0:
print("·", end=" ")
elif map[i][j] == 1:
print("W", end=" ")
elif map[i][j] == 2:
print("S", end=" ")
elif map[i][j] == 3:
print("X", end=" ")
# multiple sheep
elif map[i][j] % 2 == 0 and map[i][j] > 3:
cnt = map[i][j] // 2
print("S" + str(cnt), end=" ")
print("|")
print("+++" * (self.x + 2) + "+")
map.clear()


class Animal:
def __init__(self, game_scene):
self.game_scene = game_scene
self.x = random.randint(0, game_scene.x)
self.y = random.randint(0, game_scene.y)
self.energy = 100

def random_move(self):
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
direction = random.choice(directions)
max_move = self.max_move_ability()
dx, dy = direction
new_x = self.x + dx * random.randint(1, max_move)
new_y = self.y + dy * random.randint(1, max_move)
if 0 <= new_x <= self.game_scene.x:
self.x = new_x
if 0 <= new_y <= self.game_scene.y:
self.y = new_y

def is_at_edge(self):
return self.x == 0 or self.x == self.game_scene.x or self.y == 0 or self.y == self.game_scene.y

def max_move_ability(self):
pass

def get_coordinates(self):
return (self.x, self.y)

def die(self):
pass


class Wolf(Animal):
def __init__(self, game_scene):
super().__init__(game_scene)
self.max_energy = 100
self.energy = self.max_energy
self.max_move = 2

def max_move_ability(self):
return 2

def move(self):
self.energy -= 1
self.random_move()
if self.is_at_edge():
self.random_move()

def eat(self):
self.energy += 20
if self.energy > self.max_energy:
self.energy = self.max_energy

def die(self):
if self.energy == 0:
self.game_scene.Wolves.remove(self)


class Sheep(Animal):
def max_move_ability(self):
return 1

def move(self):
self.random_move()
if self.is_at_edge():
self.random_move()

def die(self):
print(f"Sheep at {self.get_coordinates()} died!")
self.game_scene.Sheep.remove(self)


if __name__ == "__main__":
# answer here
# 创建游戏场景(0-9)
scene = GameScene(4, 4)
scene.generate_animals(1, 5)
# 游戏逻辑
while not scene.game_over():
scene.game_logic()
print("Game Over!")