【cs50】lab6&problemset6

发布时间 2023-07-07 17:09:27作者: 致命一姬

(1)lab6 world cup

# Simulate a sports tournament

import csv
import sys
import random

# Number of simluations to run
N = 1000000  #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 row in reader:
            row["rating"] = int(row["rating"])
            teams.append(row)

    counts = {

    }
    # TODO: Simulate N tournaments and keep track of win counts
    for i in range(N):
        win_team = simulate_tournament(teams)
        if win_team in counts:
            counts[win_team] += 1
        else:
            counts[win_team] = 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
    while len(teams) > 1:
        teams = simulate_round(teams)
    return teams[0]["team"]


if __name__ == "__main__":
    main()

(2)problemsrt1 : hello

from cs50 import get_string

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

(3)mario-less

from cs50 import get_int

while True:
    try:
        height = get_int("Height: ")
        if height>0 and height<9:
            break
    except:
        print("Error!")
        exit()

for i in range(1,height+1):
    print(' '*(height-i)+'#'*i)

(4)cash

# TODO

from cs50 import get_float

def main():
    dollar = get_dollar()
    cents = int(dollar*100)
    quarters = calculate_quarters(cents)
    cents -= quarters*25
    dimes = calculate_dimes(cents)
    cents -= dimes*10
    nickels = calculate_nickels(cents)
    cents -= nickels*5
    pennies = calculate_pennies(cents)
    cents -= pennies*1
    coin = quarters + dimes + nickels + pennies
    print(coin)




def get_dollar():
    while True:
        try:
            cents = get_float("Change owed: ")
            if cents >= 0:
                break
        except:
            print("error")
            exit()
    return cents

def calculate_quarters(cents):
    return cents // 25

def calculate_dimes(cents):
    return cents//10

def calculate_nickels(cents):
    return cents//5

def calculate_pennies(cents):
    return cents

main()

(5)readability

from cs50 import get_string


def main():
    text = get_string("Text:")
    grade = get_grade(text)
    if grade < 0:
        print("Before Grade 1")
    elif grade >= 16:
        print("Grade 16+")
    else:
        print(f"Grade {grade}")

def get_grade(text):
    letter = 0
    word = 0
    sentence = 0
    number = 0
    check = 0
    n = len(text)
    new_text = text.split(' ')
    word = len(new_text)
    for s in text:
        if s.isalpha():
            letter += 1
        elif s == '.' or s == '!' or s =='?':
            sentence += 1
    #print("letter:",letter)
    #print("sentence:",sentence)
    #print("word:",word)
    L = letter / word * 100
    S = sentence / word * 100
    #print("L:",L)
    #print("S:",S)
    grade = round(0.0588*L- 0.296*S - 15.8)
    return grade


main()

(6)dna

import csv
import sys
from cs50 import get_string


def main():

    # TODO: Check for command-line usage
    n = len(sys.argv)
    if(n == 1 or n == 2):
        text = get_string("Usage:")
        question = text.spilit(' ')
        csvfile = "databases/" + question[-2]
        txtfile = "sequences/" + question[-1]

    elif(n == 3):
        csvfile = sys.argv[-2]
        txtfile = sys.argv[-1]

    else:
        print("check your input")
        exit()


    # TODO: Read database file into a variable
    data = []
    with open(csvfile,"r") as file:
        reader = csv.reader(file)
        for row in reader:
            data.append(row)

    title = data[0][1:]
    #print("title",title)

    # TODO: Read DNA sequence file into a variable

    DNA = []
    with open(txtfile,"r") as file:
        line = file.readline()
        DNA.append(line)
    #print("DNA:",DNA)

    # TODO: Find longest match of each STR in DNA sequence

    count_list = []
    for i in range(len(title)):
        #print("title",title[i])
        longest = longest_match(DNA[0],title[i])
        #print("match",longest)
        count_list.append(longest)



    # TODO: Check database for matching profiles
    flag = 0
    for i in range(1,len(data)):
        number = data[i][1:]
        #print(data[i][0])
        mid = 0
        for j in range(len(count_list)):
            #print(j)
            #print(number[j])
            #print(count_list[j])
            if int(number[j]) == int(count_list[j]):
                mid += 1
            #print(mid)
        if mid == len(count_list):
            #print("mid",mid)
            print(data[i][0])
            flag = 1

        #print("-----")
    if(flag == 0):
        print("no match")
    return


def longest_match(sequence, subsequence):
    """Returns length of longest run of subsequence in sequence."""

    # Initialize variables
    longest_run = 0
    subsequence_length = len(subsequence)
    sequence_length = len(sequence)

    # Check each character in sequence for most consecutive runs of subsequence
    for i in range(sequence_length):

        # Initialize count of consecutive runs
        count = 0

        # Check for a subsequence match in a "substring" (a subset of characters) within sequence
        # If a match, move substring to next potential match in sequence
        # Continue moving substring and checking for matches until out of consecutive matches
        while True:

            # Adjust substring start and end
            start = i + count * subsequence_length
            end = start + subsequence_length

            # If there is a match in the substring
            if sequence[start:end] == subsequence:
                count += 1

            # If there is no match in the substring
            else:
                break

        # Update most consecutive matches found
        longest_run = max(longest_run, count)

    # After checking for runs at each character in seqeuence, return longest run found
    return longest_run


main()