CS50 Week6 Python记录

上课笔记:

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()
i in[, , ]
i in a

printf

print()
print(f"{:}“.format())

scanf

input,输入的为字符串形式

强制类型转换

(int)a

int(a)

if 

{

}

if   :
不用花括号,同样的缩进代表是同一段代码

每个代码结束要有","

不用",",但有":"

&& ||

and, or

if,else

If,elif,else

需要对变量定义数据类型并初始化

for(int i = 0,…,…)

不需要定义数据类型也不需要初始化
for i in …:

try,except,else

没有memory和point指针

引入库

include <>

import …  from …引入某个库中的某个函数
import … 引入某个库中的所有函数

小插曲:

课上的二维码是著名的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"])})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值