上课笔记:
c与python的不同:
c | python | |
定义函数 | int/void,决定函数的返回数据类型 | def,可以返回任意数据类型,也可以不返回 |
string | 其实是char指针,可以更改本身 | 数据类型,不可以更改本身,对其操作实际是系统做了一个副本 |
内存 | 有integer overflow问题,有floating-point inprecision问题 | 没有integer overflow问题,系统自动开辟新空间,自动释放内存;有floating-point inprecision问题 |
数据类型 | int,float,long,short,char,string……. | int,float,string int与float没有数据上限 |
数据结构 | 元组,集合,列表,字典 | |
运行速度 | 快 | 慢, |
文件运行 | int main() | main() |
细节 | if (): | if :不用括号 |
while | i in range() | |
printf | print() | |
scanf | input,输入的为字符串形式 | |
强制类型转换 | (int)a | int(a) |
if { } | if : | |
每个代码结束要有"," | 不用",",但有":" | |
&& || | and, or | |
if,else | If,elif,else | |
需要对变量定义数据类型并初始化 for(int i = 0,…,…) | 不需要定义数据类型也不需要初始化 | |
try,except,else | ||
没有memory和point指针 | ||
引入库 | include <> | import … from …引入某个库中的某个函数 |
小插曲:
课上的二维码是著名的Rick Roll梗
作业
Lab:
# Simulate a sports tournament
import csv
import sys
import random
# Number of simluations to run
N = 1000
def main():
# Ensure correct usage
if len(sys.argv) != 2:
sys.exit("Usage: python tournament.py FILENAME")
teams = []
# TODO: Read teams into memory from file
filename = sys.argv[1]
with open(filename, "r") as file:
reader = csv.DictReader(file)
for line in reader:
line["rating"] = int(line["rating"])
teams.append(line)
print(line)
counts = {}
# TODO: Simulate N tournaments and keep track of win counts
for i in range(N):
winners = simulate_round(teams)
for winner in winners:
name = winner["team"]
if name in counts:
counts[name] += 1
elif name not in counts:
counts[name] = 1
# Print each team's chances of winning, according to simulation
for team in sorted(counts, key=lambda team: counts[team], reverse=True):
print(f"{team}: {counts[team] * 100 / N:.1f}% chance of winning")
def simulate_game(team1, team2):
"""Simulate a game. Return True if team1 wins, False otherwise."""
rating1 = team1["rating"]
rating2 = team2["rating"]
probability = 1 / (1 + 10 ** ((rating2 - rating1) / 600))
return random.random() < probability
def simulate_round(teams):
"""Simulate a round. Return a list of winning teams."""
winners = []
# Simulate games for all pairs of teams
for i in range(0, len(teams), 2):
if simulate_game(teams[i], teams[i + 1]):
winners.append(teams[i])
else:
winners.append(teams[i + 1])
return winners
def simulate_tournament(teams):
"""Simulate a tournament. Return name of winning team."""
# TODO
if __name__ == "__main__":
main()
笔记:
- 打开文件的时候忘记"r"了
- teams列表中是一个个保存键值对的集合
//最初写法 teams.append([line["team"], int(line["rating"])]) //后改成 teams.append({line["team"], int(line["rating"])}) //正确写法应为: line["rating"] = int(line["rating"]) teams.append(line) //或者 teams.append({"team":line["team"], "rating":int(line["rating"])})