cs50x 2024答案 哈佛大学计算机科学和编程艺术入门课程[全网最全!]

需要看题目的访问官网

为了小白更容易看懂代码,我尽量使用python

Week 0 - Scratch

此部分答案需要自己上手实操,官网上有很多案例可以模仿,如果无法访问Scratch可以用微信小游戏开发工具代替 ,熟悉操作就可以

Week 1 - C

Problem 1 

Cash

def main():
    # 获取用户输入的找零金额(以分为单位)
    change = int(input("Change owed: "))

    # 初始化硬币数量
    coins = 0

    # 计算25美分的硬币数量
    coins += change // 25
    change = change % 25

    # 计算10美分的硬币数量
    coins += change // 10
    change = change % 10

    # 计算5美分的硬币数量
    coins += change // 5
    change = change % 5

    # 计算1美分的硬币数量
    coins += change

    # 输出最少硬币数量
    print(coins)


if __name__ == "__main__":
    main()

Mario

n = 8

for m in range(1, n + 1):  # 从1开始计数到n
    print(" " * (n - m)+"#"*m)  # 打印前置空格来实现右对齐

Week 2 - Arrays

Problem 2 

Caesar

import string


def translate_code(txt, m):
    letter_dict = {letter: index for index, letter in enumerate(string.ascii_lowercase, 1)}
    letter_dict.update({letter: index for index, letter in enumerate(string.ascii_uppercase, 1)})
    translate_text = ""
    for char in text:
        if char in letter_dict:
            new_number = (letter_dict[char] + n) % 26
            if char.islower():
                translate_text += string.ascii_lowercase[new_number - 1]
            else:
                translate_text += string.ascii_uppercase[new_number - 1]
        else:
            translate_text += char
    return translate_text


text = input("Enter your text: ")
n = int(input("Enter your key:"))
while text != 'q':
    print(translate_code(text, n))
    text = input("Enter your text:")
    n = int(input("Enter your key:"))

Readability

import re


def count_words(text):
    return len(re.findall(r'\b\w+\b', text))


def count_sentences(text):
    return len(re.findall(r'[.!?]\s*', text))


def compute_coleman_liau_index(letters, sentences, words):
    l = (letters / words) * 100
    s = (sentences / words) * 100
    return 0.0588 * l - 0.296 * s - 15.8


def main():
    text = input("Enter the text: ")

    letters = len(re.findall(r'[a-zA-Z]', text))
    words = count_words(text)
    sentences = count_sentences(text)
    index = compute_coleman_liau_index(letters, sentences, words)

    if index < 1:
        print("Before Grade 1")
    elif index >= 16:
        print("Grade 16+")
    else:
        print(f"Grade {round(index)}")


if __name__ == "__main__":
    main()

Scrabble

# 获取玩家输入
a = input("Player 1, enter your words separated by commas: ")
b = input("Player 2, enter your words separated by commas: ")

# 分割字符串成单词列表
player1 = a.split(",")
player2 = b.split(",")

print("Player 1's words:", player1)
print("Player 2's words:", player2)

# 初始化计分器
count1 = 0
count2 = 0

# 字母及其对应的分数
words = {
    "a": 1, "b": 3, "c": 3, "d": 2, "e": 1, "f": 4, "g": 2, "h": 4, "i": 1, "j": 8, "k": 5, "l": 1, "m": 3, "n": 1,
    "o": 1, "p": 3, "q": 10, "r": 1, "s": 1, "t": 1, "u": 1, "v": 4, "w": 4, "x": 8, "y": 4, "z": 10
}

# 计算 Player 1 的分数
for word in player1:
    for letter in word:  # 遍历单词中的每个字母
        if letter in words:
            count1 += words[letter]

# 计算 Player 2 的分数
for word in player2:
    for letter in word:  # 遍历单词中的每个字母
        if letter in words:
            count2 += words[letter]

# 判断胜负
if count1 > count2:
    print("Player 1 wins!")
elif count1 < count2:
    print("Player 2 wins!")
else:
    print("It's a tie!")

# 输出最终得分
print(f"Player 1's total score: {count1}")
print(f"Player 2's total score: {count2}")

Week 3 - Algorithms

Problem 3

Runoff

MAX = 9
MAX_VOTERS = 100


class Candidate:
    def __init__(self, name):
        self.name = name
        self.votes = 0
        self.eliminated = False


# 全局变量
candidates = []
preferences = []  # 选民的偏好
voter_count = 0
candidate_count = 0


# 记录选民的偏好
def vote(voter, rank, name):
    for i in range(candidate_count):
        if candidates[i].name == name and not candidates[i].eliminated:
            preferences[voter][rank] = i
            return True
    return False


# 统计未被淘汰候选人的票数
def tabulate(n):
    for i in range(voter_count):
        for j in range(n, n+1):
            preferred_candidate = preferences[i][j]
            if not candidates[preferred_candidate].eliminated:
                candidates[preferred_candidate].votes += 1


# 打印获胜者,如果有的话
def print_winner():
    for candidate in candidates:
        if candidate.votes > voter_count / 2:
            print(f"{candidate.name} 是赢家!")
            return True
    return False


# 找出剩下的候选人中票数最少的
def find_min():
    min_votes = voter_count
    for candidate in candidates:
        if not candidate.eliminated and candidate.votes < min_votes:
            min_votes = candidate.votes
    return min_votes


# 检查选举是否在剩下的候选人之间打成平局
def is_tie(min_votes):
    for candidate in candidates:
        if not candidate.eliminated and candidate.votes != min_votes:
            return False
    return True


# 淘汰票数最少的候选人
def eliminate(min_votes):
    n = 0
    for candidate in candidates:
        if candidate.votes == min_votes:
            n += 1
            candidate.eliminated = True
    if n == candidate_count:
        for candidate in candidates:
            candidate.eliminated = False


# 主函数运行选举
def main():
    global voter_count, candidate_count

    # 获取候选人列表
    candidater = input("输入候选人名字: ").split()
    candidate_count = len(candidater)

    if candidate_count < 2:
        print("用法: plurality [候选人 ...]")
        return 1
    if candidate_count > MAX:
        print(f"候选人数量最多为 {MAX}")
        return 2

    # 添加候选人
    for i in range(candidate_count):
        candidates.append(Candidate(candidater[i]))

    # 获取选民数量
    voter_count = int(input("输入选民数量: "))
    if voter_count > MAX_VOTERS:
        print(f"选民数量最多为 {MAX_VOTERS}")
        return 3

    # 初始化偏好列表
    global preferences
    preferences = [[-1 for _ in range(candidate_count)] for _ in range(voter_count)]

    # 获取选民的偏好
    for i in range(voter_count):
        for j in range(candidate_count):
            name = input(f"输入选民 {i + 1} 的第 {j + 1} 偏好: ")
            if not vote(i, j, name):
                print("无效的投票。")
                return 4
    n = 0
    # 不断进行即时决选直到出现赢家
    while n < candidate_count:
        # 统计每一轮的票数
        tabulate(n)

        # 检查是否有赢家
        if print_winner():
            break

        # 找出票数最少的候选人
        min_votes = find_min()

        # 检查是否平局
        if n == candidate_count - 1:
            if is_tie(min_votes):
                print("出现平局!")
                for candidate in candidates:
                    if not candidate.eliminated:
                        print(candidate.name)
                break

        # 淘汰票数最少的候选人
        eliminate(min_votes)

        # 重置票数,进入下一轮
        for candidate in candidates:
            candidate.votes = 0
        n += 1


if __name__ == "__main__":
    main()

Vote

MAX = 9


class Candidate:
    def __init__(self, name):
        self.name = name
        self.votes = 0


# 候选人列表
candidates = []

# 候选人数量
candidate_count = 0


# 判断候选人
def vote(name):
    for candidate in candidates:
        if candidate.name == name:
            candidate.votes += 1
            return True
    return False


# 打印获胜者
def print_winner():
    highest = 0
    for candidate in candidates:
        if candidate.votes > highest:
            highest = candidate.votes
    winners = [candidate.name for candidate in candidates if candidate.votes == highest]
    for winner in winners:
        print(winner)


# 主程序
def main():
    global candidate_count
    candidater = input("Enter candidate name:").split(" ")
    candidate_count = len(candidater)
    if candidate_count < 2:
        print("Usage: plurality [candidate ...]")
        return 1
    if candidate_count > MAX:
        print(f"Maximum number of candidates is {MAX}")
        return 2
    for i in range(candidate_count):
        candidates.append(Candidate(candidater[i]))

    vote_count = int(input("Enter voters number:"))
    for i in range(vote_count):
        name = input("Enter voter name:")

        if not vote(name):
            print("Invalid name")

    print_winner()


if __name__ == "__main__":
    main()

Week 4 - Memery

Problem 4

Flitter

from PIL import Image
import os


def transform(imgName):
    image = imgName
    img = Image.open(image)
    img_all = "重绘" + image
    new = Image.new("L", img.size, 255)
    width, height = img.size
    img = img.convert("L")  # 灰度模式
    Pen_size = 3  # 画笔大小
    Color_Diff = 6  # 颜色差异
    # 遍历每一个像素
    for i in range(Pen_size + 1, width - Pen_size - 1):
        for j in range(Pen_size + 1, height - Pen_size - 1):
            # 原始的颜色
            originalColor = 255
            lcolor = sum([img.getpixel((i - r, j)) for r in range(Pen_size)]) // Pen_size
            rcolor = sum([img.getpixel((i + r, j)) for r in range(Pen_size)]) // Pen_size
            if abs(lcolor - rcolor) > Color_Diff:
                originalColor -= (255 - img.getpixel((i, j))) // 4
                new.putpixel((i, j), originalColor)
            ucolor = sum([img.getpixel((i, j - r)) for r in range(Pen_size)]) // Pen_size
            dcolor = sum([img.getpixel((i, j + r)) for r in range(Pen_size)]) // Pen_size
            if abs(ucolor - dcolor) > Color_Diff:
                originalColor -= (255 - img.getpixel((i, j))) // 4
                new.putpixel((i, j), originalColor)
            acolor = sum([img.getpixel((i - r, j - r)) for r in range(Pen_size)]) // Pen_size
            bcolor = sum([img.getpixel((i + r, j + r)) for r in range(Pen_size)]) // Pen_size
            if abs(acolor - bcolor) > Color_Diff:
                originalColor -= (255 - img.getpixel((i, j))) // 4
                new.putpixel((i, j), originalColor)
            qcolor = sum([img.getpixel((i + r, j - r)) for r in range(Pen_size)]) // Pen_size
            wcolor = sum([img.getpixel((i - r, j + r)) for r in range(Pen_size)]) // Pen_size
            if abs(qcolor - wcolor) > Color_Diff:
                originalColor -= (255 - img.getpixel((i, j))) // 4
                new.putpixel((i, j), originalColor)
    new.save(img_all)
    os.system(img_all)


if __name__ == '__main__':
    imageName = "cili1.jpg"
    transform(imageName)

Recovery

import os

BUFFER_SIZE = 512


def main():
    # Open the input file (binary mode)
    try:
        input_file = open("imgs/card.raw", "rb")
    except FileNotFoundError:
        print("Could not open card.raw.")
        return 1

    # Initialize variables
    buffer = bytearray(BUFFER_SIZE)
    file_count = 0
    picture = None
    jpg_found = False

    # Read the input file in chunks of BUFFER_SIZE bytes
    while True:
        bytes_read = input_file.read(BUFFER_SIZE)
        if len(bytes_read) != BUFFER_SIZE:
            break  # Break if we've read less than a full block (end of file)

        # Check for JPEG signature (0xff 0xd8 0xff 0xeX)
        if (bytes_read[0] == 0xff and bytes_read[1] == 0xd8 and
                bytes_read[2] == 0xff and (bytes_read[3] & 0xe0) == 0xe0):

            # If a previous JPEG file was found, close it
            if jpg_found:
                picture.close()

            # Start a new JPEG file
            jpg_found = True
            filename = f"{file_count:03}.jpg"
            picture = open(filename, "wb")
            file_count += 1

        # If a JPEG has been found, write the buffer to the current file
        if jpg_found:
            picture.write(bytes_read)

    # Close any open files
    input_file.close()
    if picture:
        picture.close()

    return 0


if __name__ == "__main__":
    main()

Volume

import wave
import sys

# Check command-line arguments
if len(sys.argv) != 4:
    print("Usage: python volume.py input.wav output.wav factor")
    sys.exit(1)

# Get the arguments
input_file = sys.argv[1]
output_file = sys.argv[2]
factor = float(sys.argv[3])

# Open the input WAV file
with wave.open(input_file, 'rb') as in_wave:
    # Read audio parameters
    params = in_wave.getparams()
    n_channels = in_wave.getnchannels()
    sampwidth = in_wave.getsampwidth()
    framerate = in_wave.getframerate()
    n_frames = in_wave.getnframes()

    # Read the audio frames (data)
    audio_frames = in_wave.readframes(n_frames)

# Convert byte data to 16-bit integer samples
# Since WAV files use 2-byte samples, we need to process it in that format
import struct

# Unpack audio frames as 16-bit signed integers (assuming 16-bit samples)
samples = struct.unpack("<" + "h" * (n_frames * n_channels), audio_frames)

# Apply volume scaling factor
scaled_samples = [int(sample * factor) for sample in samples]

# Make sure samples stay in the 16-bit range (-32768 to 32767)
scaled_samples = [max(min(sample, 32767), -32768) for sample in scaled_samples]

# Repack scaled samples back into byte data
scaled_audio_frames = struct.pack("<" + "h" * len(scaled_samples), *scaled_samples)

# Write the scaled samples to the output WAV file
with wave.open(output_file, 'wb') as out_wave:
    out_wave.setparams(params)  # Set the same parameters as the input file
    out_wave.writeframes(scaled_audio_frames)

print(f"Audio file '{input_file}' volume scaled by a factor of {factor} and saved to '{output_file}'")

Week 5 - Data structrues

Inheritances

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// Define a person structure
typedef struct person
{
    struct person *parents[2]; // Pointers to the person's parents
    char alleles[2];           // The person's two alleles (e.g., A, B, O)
} person;

// Function prototypes
person *create_family(int generations);
void print_family(person *p, int generation);
void free_family(person *p);
char random_allele();

int main(void)
{
    // Seed the random number generator
    srand(time(0));

    // Create a family with three generations
    person *p = create_family(3);

    // Print the family tree
    print_family(p, 0);

    // Free memory
    free_family(p);

    return 0;
}

// Create a new family tree of the specified number of generations
person *create_family(int generations)
{
    // Allocate memory for a new person
    person *p = malloc(sizeof(person));
    if (p == NULL)
    {
        fprintf(stderr, "Memory allocation failed\n");
        exit(1);
    }

    // If there are generations left to create
    if (generations > 1)
    {
        // Recursively create parents
        p->parents[0] = create_family(generations - 1);
        p->parents[1] = create_family(generations - 1);

        // Randomly assign one allele from each parent
        p->alleles[0] = p->parents[0]->alleles[rand() % 2];
        p->alleles[1] = p->parents[1]->alleles[rand() % 2];
    }
    else
    {
        // Oldest generation: no parents
        p->parents[0] = NULL;
        p->parents[1] = NULL;

        // Randomly assign alleles
        p->alleles[0] = random_allele();
        p->alleles[1] = random_allele();
    }

    return p;
}

// Free memory allocated for a family tree
void free_family(person *p)
{
    if (p == NULL)
    {
        return;
    }

    // Free parents
    free_family(p->parents[0]);
    free_family(p->parents[1]);

    // Free the person itself
    free(p);
}

// Print each family member and their alleles
void print_family(person *p, int generation)
{
    // Base case: If the person is NULL, return
    if (p == NULL)
    {
        return;
    }

    // Indent family members according to generation
    for (int i = 0; i < generation; i++)
    {
        printf("  ");
    }

    // Print the person's generation and alleles
    printf("Generation %i, blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);

    // Print parents recursively
    print_family(p->parents[0], generation + 1);
    print_family(p->parents[1], generation + 1);
}

// Randomly choose a blood type allele
char random_allele()
{
    int r = rand() % 3;
    if (r == 0)
    {
        return 'A';
    }
    else if (r == 1)
    {
        return 'B';
    }
    else
    {
        return 'O';
    }
}

speller

// Implements a spell-checker

#include <ctype.h>

#include <stdio.h>

#include <sys/resource.h>

#include <sys/time.h>

#include "dictionary.h"

// Undefine any definitions
#undef calculate
#undef getrusage

// Default dictionary
#define DICTIONARY "dictionaries/large"

// Prototype
double calculate(const struct rusage * b,
  const struct rusage * a);

int main(int argc, char * argv[]) {
  // Check for correct number of args
  if (argc != 2 && argc != 3) {
    printf("Usage: ./speller [DICTIONARY] text\n");
    return 1;
  }

  // Structures for timing data
  struct rusage before, after;

  // Benchmarks
  double time_load = 0.0, time_check = 0.0, time_size = 0.0, time_unload = 0.0;

  // Determine dictionary to use
  char * dictionary = (argc == 3) ? argv[1] : DICTIONARY;

  // Load dictionary
  getrusage(RUSAGE_SELF, & before);
  bool loaded = load(dictionary);
  getrusage(RUSAGE_SELF, & after);

  // Exit if dictionary not loaded
  if (!loaded) {
    printf("Could not load %s.\n", dictionary);
    return 1;
  }

  // Calculate time to load dictionary
  time_load = calculate( & before, & after);

  // Try to open text
  char * text = (argc == 3) ? argv[2] : argv[1];
  FILE * file = fopen(text, "r");
  if (file == NULL) {
    printf("Could not open %s.\n", text);
    unload();
    return 1;
  }

  // Prepare to report misspellings
  printf("\nMISSPELLED WORDS\n\n");

  // Prepare to spell-check
  int index = 0, misspellings = 0, words = 0;
  char word[LENGTH + 1];

  // Spell-check each word in text
  char c;
  while (fread( & c, sizeof(char), 1, file)) {
    // Allow only alphabetical characters and apostrophes
    if (isalpha(c) || (c == '\'' && index > 0)) {
      // Append character to word
      word[index] = c;
      index++;

      // Ignore alphabetical strings too long to be words
      if (index > LENGTH) {
        // Consume remainder of alphabetical string
        while (fread( & c, sizeof(char), 1, file) && isalpha(c))
        ;

        // Prepare for new word
        index = 0;
      }
    }

    // Ignore words with numbers (like MS Word can)
    else if (isdigit(c)) {
      // Consume remainder of alphanumeric string
      while (fread( & c, sizeof(char), 1, file) && isalnum(c))
      ;

      // Prepare for new word
      index = 0;
    }

    // We must have found a whole word
    else if (index > 0) {
      // Terminate current word
      word[index] = '\0';

      // Update counter
      words++;

      // Check word's spelling
      getrusage(RUSAGE_SELF, & before);
      bool misspelled = !check(word);
      getrusage(RUSAGE_SELF, & after);

      // Update benchmark
      time_check += calculate( & before, & after);

      // Print word if misspelled
      if (misspelled) {
        printf("%s\n", word);
        misspellings++;
      }

      // Prepare for next word
      index = 0;
    }
  }

  // Check whether there was an error
  if (ferror(file)) {
    fclose(file);
    printf("Error reading %s.\n", text);
    unload();
    return 1;
  }

  // Close text
  fclose(file);

  // Determine dictionary's size
  getrusage(RUSAGE_SELF, & before);
  unsigned int n = size();
  getrusage(RUSAGE_SELF, & after);

  // Calculate time to determine dictionary's size
  time_size = calculate( & before, & after);

  // Unload dictionary
  getrusage(RUSAGE_SELF, & before);
  bool unloaded = unload();
  getrusage(RUSAGE_SELF, & after);

  // Abort if dictionary not unloaded
  if (!unloaded) {
    printf("Could not unload %s.\n", dictionary);
    return 1;
  }

  // Calculate time to unload dictionary
  time_unload = calculate( & before, & after);

  // Report benchmarks
  printf("\nWORDS MISSPELLED:     %d\n", misspellings);
  printf("WORDS IN DICTIONARY:  %d\n", n);
  printf("WORDS IN TEXT:        %d\n", words);
  printf("TIME IN load:         %.2f\n", time_load);
  printf("TIME IN check:        %.2f\n", time_check);
  printf("TIME IN size:         %.2f\n", time_size);
  printf("TIME IN unload:       %.2f\n", time_unload);
  printf("TIME IN TOTAL:        %.2f\n\n",
    time_load + time_check + time_size + time_unload);

  // Success
  return 0;
}

// Returns number of seconds between b and a
double calculate(const struct rusage * b,
  const struct rusage * a) {
  if (b == NULL || a == NULL) {
    return 0.0;
  } else {
    return ((((a -> ru_utime.tv_sec * 1000000 + a -> ru_utime.tv_usec) -
          (b -> ru_utime.tv_sec * 1000000 + b -> ru_utime.tv_usec)) +
        ((a -> ru_stime.tv_sec * 1000000 + a -> ru_stime.tv_usec) -
          (b -> ru_stime.tv_sec * 1000000 + b -> ru_stime.tv_usec))) /
      1000000.0);
  }
}

Week 6 - Python

和第一周的问题一样,用python实现

Week 7 - SQL 

这一节用的是sql来解答,建议下载mysql的轻量级替代sqlite3(只有几mb)

Problem 7

songs

SELECT name FROM songs;
SELECT name FROM songs ORDER BY tempo;
SELECT name FROM songs ORDER BY duration_ms DESC LIMIT 5;
SELECT name FROM songs WHERE danceability > 0.75 AND energy > 0.75 AND valence > 0.75;
SELECT AVG(energy) FROM songs;
SELECT name FROM songs WHERE artist_id=54;
SELECT AVG(energy)  FROM songs WHERE artist_id=23
SELECT name FROM songs WHERE name LIKE '%feat.%';

Movies(略)

Fiftycilly 

没有配置cs50环境的可以到我提供的文件里下载fiftyville.db在终端做题

--查看数据--
.table
airports              crime_scene_reports   people
atm_transactions      flights               phone_calls
bakery_security_logs  interviews
bank_accounts         passengers

.schem crime_scene_reports
CREATE TABLE crime_scene_reports (
    id INTEGER,
    year INTEGER,
    month INTEGER,
    day INTEGER,
    street TEXT,
    description TEXT,
    PRIMARY KEY(id)
);

--根据提供的线索找到犯罪纪律--
SELECT * FROM crime_scene_reports
WHERE street = 'Humphrey Street';
80|2021|2|26|Humphrey Street|Theft took place at 03:11. Two people witnessed the event.
113|2021|3|20|Humphrey Street|Credit card fraud took place at 08:41. One person witnessed the incident.
128|2021|4|4|Humphrey Street|Expired parking meter took place at 03:17. Two people witnessed the event.
254|2021|7|6|Humphrey Street|Shoplifting took place at 04:45. Two people witnessed the event.
295|2021|7|28|Humphrey Street|Theft of the CS50 duck took place at 10:15am at the Humphrey Street bakery.
Interviews were conducted today with three witnesses who were present at the time – each of their interview transcripts mentions the bakery.

--案件显示面包店--
.schem interviews;
CREATE TABLE interviews (
    id INTEGER,
    name TEXT,
    year INTEGER,
    month INTEGER,
    day INTEGER,
    transcript TEXT,
    PRIMARY KEY(id)

SELECT * FROM interviews WHERE transcript LIKE '%bakery%';
161|Ruth|2021|7|28|Sometime within ten minutes of the theft, I saw the thief get into a car in the bakery parking lot and drive away. If you have security footage from the bakery parking lot, you might want to look for cars that left the parking lot in that time frame.
162|Eugene|2021|7|28|I don't know the thief's name, but it was someone I recognized. Earlier this morning, before I arrived at Emma's bakery, I was walking by the ATM on Leggett Street and saw the thief there withdrawing some money.
163|Raymond|2021|7|28|As the thief was leaving the bakery, they called someone who talked to them for less than a minute. In the call, I heard the thief say that they were planning to take the earliest flight out of Fiftyville tomorrow. The thief then asked the person on the other end of the phone to purchase the flight ticket.
192|Kiana|2021|5|17|I saw Richard take a bite out of his pastry at the bakery before his pastry was stolen from him.
sqlite> SELECT * FROM bakery_security_logs WHERE year = 2021 AND month = 7 AND day = 28 AND hour = 10 AND minute BETWEEN
15 AND 25;

--第一个证人露丝停车场时间--
SELECT * FROM bakery_security_logs
WHERE year = 2021 AND month = 7 AND day = 28 AND hour = 10 AND minute
BETWEEN 15 AND 25;
260|2021|7|28|10|16|exit|5P2BI95
261|2021|7|28|10|18|exit|94KL13X
262|2021|7|28|10|18|exit|6P58WS2
263|2021|7|28|10|19|exit|4328GD8
264|2021|7|28|10|20|exit|G412CB7
265|2021|7|28|10|21|exit|L93JTIZ
266|2021|7|28|10|23|exit|322W7JE
267|2021|7|28|10|23|exit|0NTHK55

SELECT p.name, bsl.activity, bsl.license_plate, bsl.year, bsl.month, bsl.day, bsl.hour, bsl.minute
FROM bakery_security_logs AS bsl
JOIN people AS p ON p.license_plate = bsl.license_plate
WHERE bsl.year = 2021
    AND bsl.month = 7
    AND bsl.day = 28
    AND bsl.hour = 10
    AND bsl.minute BETWEEN 15 AND 25;
Vanessa|exit|5P2BI95|2021|7|28|10|16
Bruce|exit|94KL13X|2021|7|28|10|18
Barry|exit|6P58WS2|2021|7|28|10|18
Luca|exit|4328GD8|2021|7|28|10|19
Sofia|exit|G412CB7|2021|7|28|10|20
Iman|exit|L93JTIZ|2021|7|28|10|21
Diana|exit|322W7JE|2021|7|28|10|23
Kelsey|exit|0NTHK55|2021|7|28|10|23

--第二个目击者leggett街上的ATM
.schema atm_transactions
CREATE TABLE atm_transactions (
    id INTEGER,
    account_number INTEGER,
    year INTEGER,
    month INTEGER,
    day INTEGER,
    atm_location TEXT,
    transaction_type TEXT,
    amount INTEGER,
    PRIMARY KEY(id)
);

SELECT * FROM atm_transactions
WHERE atm_location = 'Leggett Street'
AND year = 2021
AND month = 7
AND day = 28;
246|28500762|2021|7|28|Leggett Street|withdraw|48
264|28296815|2021|7|28|Leggett Street|withdraw|20
266|76054385|2021|7|28|Leggett Street|withdraw|60
267|49610011|2021|7|28|Leggett Street|withdraw|50
269|16153065|2021|7|28|Leggett Street|withdraw|80
275|86363979|2021|7|28|Leggett Street|deposit|10
288|25506511|2021|7|28|Leggett Street|withdraw|20
313|81061156|2021|7|28|Leggett Street|withdraw|30
336|26013199|2021|7|28|Leggett Street|withdraw|35

SELECT a.*, p.name
FROM atm_transactions AS a
JOIN bank_accounts AS b ON a.account_number = b.account_number
JOIN people AS p ON b.person_id = p.id
WHERE a.atm_location = 'Leggett Street' AND year = 2021 AND a.month = 7 AND a.day = 28 AND a.transaction_type = 'withdraw';
--267|49610011|2021|7|28|Leggett Street|withdraw|50|Bruce
336|26013199|2021|7|28|Leggett Street|withdraw|35|Diana
269|16153065|2021|7|28|Leggett Street|withdraw|80|Brooke
264|28296815|2021|7|28|Leggett Street|withdraw|20|Kenny
288|25506511|2021|7|28|Leggett Street|withdraw|20|Iman
246|28500762|2021|7|28|Leggett Street|withdraw|48|Luca
266|76054385|2021|7|28|Leggett Street|withdraw|60|Taylor
313|81061156|2021|7|28|Leggett Street|withdraw|30|Benista--

--第三个目击证人,电话--
.schema phone_calls;
--CREATE TABLE phone_calls (
    id INTEGER,
    caller TEXT,
    receiver TEXT,
    year INTEGER,
    month INTEGER,
    day INTEGER,
    duration INTEGER,
    PRIMARY KEY(id)
);--

SELECT * FROM phone_calls WHERE year = 2021 AND month = 7 AND day = 28 AND duration <=60;
--221|(130) 555-0289|(996) 555-8899|2021|7|28|51
224|(499) 555-9472|(892) 555-8872|2021|7|28|36
233|(367) 555-5533|(375) 555-8161|2021|7|28|45
234|(609) 555-5876|(389) 555-5198|2021|7|28|60
251|(499) 555-9472|(717) 555-1342|2021|7|28|50
254|(286) 555-6063|(676) 555-6554|2021|7|28|43
255|(770) 555-1861|(725) 555-3243|2021|7|28|49
261|(031) 555-6622|(910) 555-3251|2021|7|28|38
279|(826) 555-1652|(066) 555-9701|2021|7|28|55
281|(338) 555-6650|(704) 555-2131|2021|7|28|54--

SELECT p.name, pc.year, pc.month, pc.day, pc.duration
FROM phone_calls AS pc
JOIN people AS p ON p.phone_number  = pc.caller
WHERE pc.year = 2021 AND pc.month = 7 AND pc.day = 28 AND pc.duration <=60;
--Sofia|2021|7|28|51
Kelsey|2021|7|28|36
Bruce|2021|7|28|45
Kathryn|2021|7|28|60
Kelsey|2021|7|28|50
Taylor|2021|7|28|43
Diana|2021|7|28|49
Carina|2021|7|28|38
Kenny|2021|7|28|55
Benista|2021|7|28|54--

--寻找最近的一趟航班--
SELECT p.name, pc.year, pc.month, pc.day, pc.duration
FROM phone_calls AS pc
JOIN bank_accounts AS b
JOIN people AS p ON p.phone_number  = pc.caller
WHERE pc.year = 2021 AND pc.month = 7 AND pc.day = 28 AND pc.duration <=60;

SELECT * FROM airports;
--1|ORD|O'Hare International Airport|Chicago
2|PEK|Beijing Capital International Airport|Beijing
3|LAX|Los Angeles International Airport|Los Angeles
4|LGA|LaGuardia Airport|New York City
5|DFS|Dallas/Fort Worth International Airport|Dallas
6|BOS|Logan International Airport|Boston
7|DXB|Dubai International Airport|Dubai
8|CSF|Fiftyville Regional Airport|Fiftyville
9|HND|Tokyo International Airport|Tokyo
10|CDG|Charles de Gaulle Airport|Paris
11|SFO|San Francisco International Airport|San Francisco
12|DEL|Indira Gandhi International Airport|Delhi--

SELECT f.*, origin.full_name AS origin_airport, destination.full_name AS destination_airport
FROM flights AS f
JOIN airports origin ON f.origin_airport_id = origin.id
JOIN airports destination ON f.destination_airport_id = destination.id
WHERE origin.id = 8 AND f.year = 2021 AND f.month = 7 AND f.day = 29
ORDER BY f.hour, f.minute;
--36|8|4|2021|7|29|8|20|Fiftyville Regional Airport|LaGuardia Airport
43|8|1|2021|7|29|9|30|Fiftyville Regional Airport|O'Hare International Airport
23|8|11|2021|7|29|12|15|Fiftyville Regional Airport|San Francisco International Airport
53|8|9|2021|7|29|15|20|Fiftyville Regional Airport|Tokyo International Airport
18|8|6|2021|7|29|16|0|Fiftyville Regional Airport|Logan International Airport--

--综合信息
SELECT p.name
FROM bakery_security_logs AS bsl
JOIN people AS p ON p.license_plate = bsl.license_plate
JOIN phone_calls AS pc ON p.phone_number  = pc.caller
JOIN bank_accounts AS b  ON b.person_id = p.id
JOIN atm_transactions AS a ON a.account_number = b.account_number
WHERE bsl.year = 2021
    AND bsl.month = 7
    AND bsl.day = 28
    AND bsl.hour = 10
    AND bsl.minute BETWEEN 15 AND 25
    AND a.atm_location = 'Leggett Street' AND a.year = 2021 AND a.month = 7 AND a.day = 28 AND a.transaction_type = 'withdraw'
    AND pc.year = 2021 AND pc.month = 7 AND pc.day = 28 AND pc.duration < 60;
--Bruce
Diana--

SELECT p.name
FROM people AS p
JOIN  passengers AS ps ON ps.passport_number = p.passport_number
WHERE ps.flight_id = 36
AND p.name IN ('Bruce','Diana');
--Bruce--

SELECT p1.name,p2.name
FROM phone_calls AS pc
JOIN people AS p1 ON p1.phone_number  = pc.caller
JOIN people AS p2 ON p2.phone_number  = pc.receiver
WHERE pc.year = 2021 AND pc.month = 7 AND pc.day = 28 AND pc.duration <=60 AND p1.name = 'Bruce';
--Bruce|Robin--

--The THIEF is: Bruce
The city the thief ESCAPED TO: New York City
The ACCOMPLICE is: Robin--


Week 8 - Html,Css, Javascript

problem 8 

Trivia

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Trivia</title>
  <style>
    .wrapper {
      width: 1000px;
      margin: 0 auto;
    }
    .header {
      background-color: #477BFF;
      width: 100%;
      height: 400px;
      text-align: center;
      align-items: center;
      display: flex;
      color:white;
      font-weight: bolder;
      justify-content: center;
    }
    ul, ol {
      list-style: none;
    }
    .part1 {
      margin-top: 40px;
    }
    .title {
      padding-bottom: 0px;
      border-bottom: dashed 2px rgba(0, 0, 0, 0.418);
    }
    .text {
      margin-top: 20px;
    }
    ul {
      padding: 0;
      display: flex;
      justify-content: space-between;
    }
    a {
      text-decoration: none;
      color: #333;
      cursor: pointer;
    }
    .word {
      height: 30px;
      width: 180px;
      background-color: rgba(135, 207, 235, 0.627);
      text-align: center;
      line-height: 30px;
      transition: background-color 0.3s ease;
    }
    .highlight {
      background-color: #FFD700;
    }
    input[type="submit"] {
      background-color: rgba(135, 207, 235, 0.627);
    }
    .result {
      margin-top: 20px;
      font-size: 18px;
      font-weight: bold;
      color: red;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>Trivia!</h1>
  </div>
  <div class="part1 wrapper">
    <div class="title"><h1>Part 1: Multiple Choice</h1></div>
    <div class="text"><h3>What is the approximate ratio of people to sheep in New Zealand?</h3></div>
    <div class="content">
      <ul>
        <li><a href="#" onclick="selectOption(1)"><div id="option1" class="word">6 people per 1 sheep</div></a></li>
        <li><a href="#" onclick="selectOption(2)"><div id="option2" class="word">3 people per 1 sheep</div></a></li>
        <li><a href="#" onclick="selectOption(3)"><div id="option3" class="word">1 person per 1 sheep</div></a></li>
        <li><a href="#" onclick="selectOption(4)"><div id="option4" class="word">1 person per 3 sheep</div></a></li>
        <li><a href="#" onclick="selectOption(5)"><div id="option5" class="word">1 person per 6 sheep</div></a></li>
      </ul>
    </div>
  </div>

  <div class="part1 wrapper">
    <div class="title"><h1>Part 2: Free Response</h1></div>
    <div class="text"><h3>In which country is it illegal to own only one guinea pig, as a lone guinea pig might get lonely?</h3></div>
    <div class="content">
      <form onsubmit="checkAnswers(event)">
        <input type="text" id="response" placeholder="Type your answer here">
        <input type="submit" value="Check Answer">
      </form>
      <div class="result" id="resultMessage"></div>
    </div>
  </div>

  <div style="height: 500px;"></div>

  <script>
    let selectedOption = null;
    const correctOption = 5; // The correct answer for Part 1: "1 person per 6 sheep"
    const correctResponse = "Switzerland"; // The correct answer for Part 2

    // Function to highlight the selected option
    function selectOption(option) {
      if (selectedOption !== null) {
        document.getElementById(`option${selectedOption}`).classList.remove('highlight');
      }
      selectedOption = option;
      document.getElementById(`option${option}`).classList.add('highlight');
    }

    // Function to check both answers and display results
    function checkAnswers(event) {
      event.preventDefault(); // Prevent form submission

      const userResponse = document.getElementById('response').value.trim();
      let resultMessage = '';
      
      if (selectedOption === correctOption && userResponse.toLowerCase() === correctResponse.toLowerCase()) {
        resultMessage = 'Both answers are correct! Well done!';
      } else {
        if (selectedOption !== correctOption) {
          resultMessage += 'The answer for Part 1 is incorrect. ';
        }
        if (userResponse.toLowerCase() !== correctResponse.toLowerCase()) {
          resultMessage += 'The answer for Part 2 is incorrect.';
        }
      }

      document.getElementById('resultMessage').innerText = resultMessage;

      // Reset the form and selections
      selectedOption = null;
      document.querySelectorAll('.word').forEach(el => el.classList.remove('highlight'));
      document.getElementById('response').value = '';
    }
  </script>
</body>
</html>

Homepage


略,感兴趣的可以做一个自己的个人博客,网上大把教程

Week 9 - Flask

problem 9

Birthday (完整代码放在文件里)

import os

# Import the Flask Framework
from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session

# Configure application
app = Flask(__name__)

# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True

# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///birthdays.db")


@app.route("/", methods=["GET", "POST"])
def index():
    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":
        # Add the user's entry into the database
        name = request.form.get("name")
        month = request.form.get("month")
        day = request.form.get("day")
        db.execute(
            "INSERT INTO birthdays (name, month, day) VALUES(?, ?, ?)", name, month, day)

        return redirect("/")

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        # Display the entries in the database on index.html
        notes = db.execute("SELECT * FROM birthdays")
        return render_template("index.html", notes=notes)
    
if __name__ == "__main__":
    app.run(debug=True)

Finance ((完整代码放在文件里))

import os

from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.security import check_password_hash, generate_password_hash

from helpers import apology, login_required, lookup, usd

# Configure application
app = Flask(__name__)

# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True

# Custom filter
app.jinja_env.filters["usd"] = usd

# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///finance.db")

# Make sure API key is set
if not os.environ.get("API_KEY"):
    raise RuntimeError("API_KEY not set")


@app.after_request
def after_request(response):
    """Ensure responses aren't cached"""
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response


@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""
    return apology("TODO")


@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""
    return apology("TODO")


@app.route("/history")
@login_required
def history():
    """Show history of transactions"""
    return apology("TODO")


@app.route("/login", methods=["GET", "POST"])
def login():
    """Log user in"""

    # Forget any user_id
    session.clear()

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("must provide username", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password", 403)

        # Query database for username
        rows = db.execute("SELECT * FROM users WHERE username = ?", request.form.get("username"))

        # Ensure username exists and password is correct
        if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
            return apology("invalid username and/or password", 403)

        # Remember which user has logged in
        session["user_id"] = rows[0]["id"]

        # Redirect user to home page
        return redirect("/")

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("login.html")


@app.route("/logout")
def logout():
    """Log user out"""

    # Forget any user_id
    session.clear()

    # Redirect user to login form
    return redirect("/")


@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
    """Get stock quote."""
    return apology("TODO")


@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user"""
    return apology("TODO")


@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
    """Sell shares of stock"""
    return apology("TODO")

if __name__ == "__main__":
    app.run(debug=True)

文件地址:cs50.zip - 蓝奏云

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值