目录

Harvard CS50 学习笔记(六)

摘要
Harvard CS50 学习笔记(六)。

6 Python

6.1 Lecture

6.1.1 Introduction

6.1.2 Python

6.1.3 Hello, world

1
print("Hello, World")
  • Python 中的语句没有分号,不需要分号。

6.1.4 Variables

1
2
answer = get_string("What is your name?")
print("Hello, " + answer)
  • Python 中的变量不需要显式声明类型。

6.1.5 F-strings

1
2
answer = get_string("What is your name?")
print(f"Hello,  {answer}")
  • 新打印语句。

6.1.6 Increment

1
count += 1
  • Python 中没有 ++ ,必须 +=

6.1.7 Conditionals

1
2
3
4
5
6
if x < y:
    print("x is less than y")
elif x > y:
    print("x is greater than y")
else:
    print("x is equal to y")
  1. Python 中的条件语句里的条件不需要括号。
  2. Python 中的条件语句里的执行语句,不需要大括号,用冒号。
  3. Python 中的或不是 || 而是 or

6.1.8 Loops

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
while True:
    print("hello, world")

i = 0
while i < 3:
    print("hello, world")
    i += 1
    
for i in [0, 1, 2]:
    print("hello, world")

for i in range(3):
    print("hello, world")
  1. Python 中的 while 循环,条件不需要括号,执行不需要大括号。
  2. Python 中的 bool 类型需要大写。
  3. Python 中的 for 循环,条件不需要括号,执行不需要大括号。
  4. Python 中的 for 循环可以用 list 替代条件,也可以用 range 类型 替代条件。

6.1.9 Types

/images/Harvard_CS50/Lecture_6/data_types_1.png /images/Harvard_CS50/Lecture_6/data_types_2.png
  1. Python 中的 int 类型没有数值过大而溢出的问题。
  2. Python 中的字符串类型为 str

6.1.10 CS50 Library

1
2
3
4
5
import cs50
from cs50 import get_float
from cs50 import get_int
from cs50 import get_string
from cs50 import get_float, get_int, get_string
  1. Python 中的使用 import 引入包而不是 include,不需要符号。
  2. 可以指定引入部分函数。

6.1.11 Compilation and Interpretation

  1. Python 是解释型语言,不需要先编译再运行。
  2. 编译器也叫 Python

6.1.12 blur.py

  • Python 中不需要主方法(main)。

6.1.13 dictionary.py

6.1.14 hello.py

6.1.15 calculator.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from cs50 import get_int

x = get_int("x: ")
y = get_int("y: ")

# 此结果为float,解决数值丢失问题
z = x / y
print(z)

# 此结果为int,放弃精度部分
z = x // y
print(z)

6.1.16 Exceptions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
try:
    x = int(input(x: ))
except: 
  	print("That is not an int! ")
    exit()
    
try:
    y = int(input(y: ))
except ValueError: 
  	print("That is not an int! ")
    exit()
    
print(x + y)

6.1.17 Floating-Point Imprecision

1
2
3
4
5
6
7
8
from cs50 import get_int

x = get_int("x: ")
y = get_int("y: ")

z = x / y
# 精确到小数点后50位,浮点型精度问题仍然存在
print(f"{z:.50f}")

6.1.18 points.py

6.1.19 agree.py

6.1.20 meow.py

1
2
3
4
def loop(int n): 
  	for i in range(n):
      	print(n)
    return n
  1. Python 中定义函数用关键字 def,不需要显式声明返回值类型。
  2. 无返回即返回 null

6.1.21 mario.py

1
2
3
4
5
6
def get_height():
  	while True:
      	n = get_int("Height: ")
        if n > 0:
          	break
    return n
  1. Python 中,定义在函数里的变量,在定义之后的剩余函数中都是accessible的,无论层级。
  2. Python 中的函数,有指定名称的参数。

6.1.22 Documentation

6.1.23 scores.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from cs50 import get_int

scores = []
for i in range(3):
  	score = get_int("Score: ")
    # 添加元素
    # scores.append(score)
    scores += [score]
    
average = sum(scores) / len(scores)
print(f"Average: {average}")
  • Python 中,list 可以用运算符拼接。

6.1.24 uppercase.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from cs50 import get_string

before = get_string("Before: ")
print("After: ", end="")
for c in before:
  	print(c.upper(), end="")
print()

after = before.upper()
print(f"After, {after}")
  • Python 中可以直接迭代字符串。

6.1.25 Command-line Arguments

/images/Harvard_CS50/Lecture_6/argv_1.png /images/Harvard_CS50/Lecture_6/argv_2.png /images/Harvard_CS50/Lecture_6/argv_3.png
  1. 解释+运行命令 python 不包含在命令行参数中。
  2. argv 是一个 list
  3. list 的迭代可以一部分,称为 list 的切割(slicing)。

6.1.26 Exit Status

/images/Harvard_CS50/Lecture_6/exit_1.png /images/Harvard_CS50/Lecture_6/exit_2.png

6.1.27 numbers.py

/images/Harvard_CS50/Lecture_6/search_1.png
search_1

6.1.28 names.py

/images/Harvard_CS50/Lecture_6/search_2.png
search_2

6.1.29 phonebook.py

/images/Harvard_CS50/Lecture_6/phonebook_1.png /images/Harvard_CS50/Lecture_6/phonebook_2.png

6.1.30 Dictionaries

6.1.31 CSV Files

/images/Harvard_CS50/Lecture_6/csv_1.png /images/Harvard_CS50/Lecture_6/csv_2.png /images/Harvard_CS50/Lecture_6/csv_3.png
/images/Harvard_CS50/Lecture_6/csv_4.png
csv_4

6.1.32 Speech Synthesis

6.1.33 Facial Recognition

6.1.34 Speech Recognition

6.1.35 QR Codes

6.2 Shorts

/images/Harvard_CS50/Lecture_6/Python/python_syntax_1.png
python_syntax_1
/images/Harvard_CS50/Lecture_6/Python/python_syntax_2.png
python_syntax_2
/images/Harvard_CS50/Lecture_6/Python/variables_1.png
variables_1
/images/Harvard_CS50/Lecture_6/Python/variables_2.png
variables_2
/images/Harvard_CS50/Lecture_6/Python/conditionals_1.png
conditionals_1
/images/Harvard_CS50/Lecture_6/Python/conditionals_2.png
conditionals_2
/images/Harvard_CS50/Lecture_6/Python/conditionals_3.png
conditionals_3
/images/Harvard_CS50/Lecture_6/Python/conditionals_4.png
conditionals_4
/images/Harvard_CS50/Lecture_6/Python/loops_1.png
loops_1
/images/Harvard_CS50/Lecture_6/Python/loops_2.png
loops_2
/images/Harvard_CS50/Lecture_6/Python/loops_3.png
loops_3
/images/Harvard_CS50/Lecture_6/Python/lists_1.png
lists_1
/images/Harvard_CS50/Lecture_6/Python/lists_2.png
lists_2
/images/Harvard_CS50/Lecture_6/Python/lists_3.png
lists_3
/images/Harvard_CS50/Lecture_6/Python/lists_4.png
lists_4
/images/Harvard_CS50/Lecture_6/Python/lists_5.png /images/Harvard_CS50/Lecture_6/Python/lists_6.png /images/Harvard_CS50/Lecture_6/Python/lists_7.png
/images/Harvard_CS50/Lecture_6/Python/tuples_1.png
tuples_1
/images/Harvard_CS50/Lecture_6/Python/tuples_2.png
tuples_2
/images/Harvard_CS50/Lecture_6/Python/tuples_3.png
tuples_3
/images/Harvard_CS50/Lecture_6/Python/dictionaries_1.png
dictionaries_1
/images/Harvard_CS50/Lecture_6/Python/dictionaries_2.png
dictionaries_2
/images/Harvard_CS50/Lecture_6/Python/dictionaries_3.png
dictionaries_3
/images/Harvard_CS50/Lecture_6/Python/dictionaries_4.png
dictionaries_4
/images/Harvard_CS50/Lecture_6/Python/dictionaries_5.png
dictionaries_5
/images/Harvard_CS50/Lecture_6/Python/dictionaries_6.png
dictionaries_6
/images/Harvard_CS50/Lecture_6/Python/dictionaries_7.png
dictionaries_7
/images/Harvard_CS50/Lecture_6/Python/print.png
print
/images/Harvard_CS50/Lecture_6/Python/functions_1.png
functions_1
/images/Harvard_CS50/Lecture_6/Python/functions_2.png
functions_2
/images/Harvard_CS50/Lecture_6/Python/objects_1.png
objects_1
/images/Harvard_CS50/Lecture_6/Python/objects_2.png
objects_2
/images/Harvard_CS50/Lecture_6/Python/objects_3.png
objects_3
/images/Harvard_CS50/Lecture_6/Python/objects_4.png
objects_4
/images/Harvard_CS50/Lecture_6/Python/objects_5.png
objects_5
/images/Harvard_CS50/Lecture_6/Python/objects_6.png
objects_6
/images/Harvard_CS50/Lecture_6/Python/objects_7.png
objects_7
/images/Harvard_CS50/Lecture_6/Python/style.png
style
/images/Harvard_CS50/Lecture_6/Python/import_1.png
import_1
/images/Harvard_CS50/Lecture_6/Python/import_2.png
import_2
/images/Harvard_CS50/Lecture_6/Python/python_syntax_3.png
python_syntax_3
/images/Harvard_CS50/Lecture_6/Python/python_syntax_4.png
python_syntax_4
/images/Harvard_CS50/Lecture_6/Python/python_syntax_5.png
python_syntax_5

6.3 Lab 6

 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
# 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 = []
    with open(sys.argv[1], "r") as file:
        reader = csv.DictReader(file)
        for row in reader:
            row["rating"] = int(row["rating"])
            teams.append(row)


    counts = {}
    for team in teams:
        counts[team["team"]] = 0

    for i in range(N):
        name = simulate_tournament(teams)
        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."""
    while len(teams) != 1:
        teams = simulate_round(teams)
    return teams[0]["team"]

if __name__ == "__main__":
    main()

6.4 Problem Set 6

6.4.1 Hello

1
2
3
4
from cs50 import get_string

name = get_string("What is your name?\n")
print(f"hello, {name}")

6.4.2 Mario

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from cs50 import get_int

while True:
    height = get_int("Height: ")

    if height < 1 or height > 8:
        continue
    else:
        for i in range(height):
            for j in range(height - i - 1):
                print(" ", end="")
            for k in range(i + 1):
                print("#", end="")
            print("  ", end="")
            for m in range(i + 1):
                print("#", end="")
            print()
        break

6.4.3 Credit

 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
from cs50 import get_int, get_string


americanExpressLength = 15
masterCardLength = 16
visaLength = 13

americanExpressStarts = [34, 37]
masterCardStarts = [51, 52, 53, 54, 55]
visaStart = 4


def main():
    number = get_string("Number: ")
		# 把号码依次变成数字存到数组
    numbers = [int(c) for c in number]
    count = len(numbers)
    # 开头两位数
    starts = int(str(numbers[0]) + str(numbers[1]))

    valid = validate(numbers)

    if not valid:
        print("INVALID\n")
        exit(1)

    if isAmericanExpress(count, starts):
        print("AMEX\n")
        exit(0)
    elif isMasterCard(count, starts):
        print("MASTERCARD\n")
        exit(0)
    elif isVisa(count, starts, numbers):
        print("VISA\n")
        exit(0)
    else:
        print("INVALID\n")
        exit(1)

# 验证号码是否正确
def validate(numbers):
    nums = [];
    for num in range(len(numbers) - 2, -1, -2):
        i = numbers[num] * 2
        if i < 10:
            nums.append(i)
        else:
            tmp = str(i)
            nums.append(int(tmp[0]))
            nums.append(int(tmp[1]))
    total = sum(nums)
    for num in range(len(numbers) - 1, -1, -2):
        total += numbers[num]
    if int(str(total)[-1]) == 0:
        return True
    else:
        return False


def isAmericanExpress(count, starts):
    return count == americanExpressLength and starts in americanExpressStarts

def isMasterCard(count, starts):
    return count == masterCardLength and starts in masterCardStarts

def isVisa(count, starts, numbers):
    if count == masterCardLength or count == visaLength:
        if numbers[0] == visaStart:
            return True
    return False

if __name__ == "__main__":
    main()

6.4.4 Readability

 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
from cs50 import get_string

text = get_string("Text: ")

letterCount = 0
wordCount = 1
sentenceCount = 0

for c in text:
    if (c >= 'a' and c <= 'z'):
        letterCount += 1
    if (c >= 'A' and c <= 'Z'):
        letterCount += 1
    elif c == ' ':
        wordCount += 1
    elif c == '.' or c == '!' or c == '?':
        sentenceCount += 1

L = letterCount * 100 / wordCount
S = sentenceCount * 100 / wordCount
index = round(0.0588 * L - 0.296 * S - 15.8)

if index < 1:
    print("Before Grade 1")
elif index >= 16:
    print("Grade 16+")
else:
    print("Grade " + str(index))

6.4.5 DNA

 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
import csv
import sys

def main():
    # Ensure correct usage
    if len(sys.argv) != 3:
        sys.exit("Usage: python dna.py data.csv sequence.txt")

    people = []
    genes = []

    # 读文件头
    with open(sys.argv[1], "r") as file:
        reader = csv.reader(file)
        for row in reader:
            for i in range(len(row)):
                if (i + 1) == len(row):
                    break
                genes.append(row[i + 1])
            break

    # 读文件为dict数组
    with open(sys.argv[1], "r") as file:
        reader = csv.DictReader(file)
        for row in reader:
            people.append(row)

    # 读DNA序列
    sequence = open(sys.argv[2]).read()

    # DNA序列连续出现次数最多的数组
    counts = genesCount(sequence, genes)

    # 比较
    result = getResult(counts, people, genes)

    print(result)

# 获取DNA序列连续出现次数最多的数组
def genesCount(sequence, genes):
    counts = []
    for gene in genes:
        total = 0
        tmp = [0]
        for i in range(len(sequence)):
            currentGene = sequence[i:len(gene) + i]
            if currentGene == gene:
                nextGene = sequence[(i + len(gene)):(i + len(gene) + len(gene))]
                if nextGene == gene:
                    total += 1
                    i += len(gene)
                else:
                    tmp.append(total)
                    total = 0
        temp = tmp
        counts.append(max(tmp) + 1)
    return counts

# 比较结果
def getResult(counts, people, genes):

    result = "No match"

    flag = True
    for person in people:
        for i in range(len(counts)):
            gene = genes[i]
            count = counts[i]
            if int(person[gene]) == count:
                flag = True
                continue
            else:
                flag = False
                break
        if flag:
            result = person["name"]
            break
    return result


if __name__ == "__main__":
    main()