首页 > 其他分享 >【cs50】lab6&problemset6

【cs50】lab6&problemset6

时间:2023-07-07 17:12:14浏览次数:53  
标签:return cs50 get cents teams problemset6 lab6 print def

(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()

 

标签:return,cs50,get,cents,teams,problemset6,lab6,print,def
From: https://www.cnblogs.com/zhimingyiji/p/17535543.html

相关文章

  • 【哈佛cs50 2022】lab3 & problemSet3【ing】
    (1)lab3如何测试每个代码运行所需要的时间?time./sort1sorted5000.txt sort1sort2sort3sorted5000.txt0.037s0.020s0.045ssorted10000.txt0.058s0.050s0.151ssorted50000.txt1.244s2.238s5.637sreversed5000.txt0.088s0.026s0.045srever......
  • 【cs50 2022】lab1 && problem set1
    |lab1|#include<cs50.h>#include<stdio.h>intmain(void){//TODO:Promptforstartsizeintstart_size;do{start_size=get_int("Startsize:");}while(start_size<9);//TODO:Promptforend......
  • ICT实战系统集成-LAB6-openEuler管理文件系统及存储
    LAB6-openEuler管理文件系统及存储1实验要求1.1添加两块scsi硬盘,大小分别为10G1.2对新添加的硬盘1(如:/dev/sdb)进行MBR分区、格式化、挂载1、使用fdisk对/dev/sdb进行分区:/dev/sdb1为主分区1大小2G、/dev/sb2为扩展分区大小8G,在/dev/sb2的基础上建立扩展分区/dev/sdb5,大小......
  • CS50363内置MOS可升压16V,高效率升压DC-DC转换器
    CS50363E是一款采用CMOS工艺升压型开关稳压器,其主要包括一个参考电压源,一个振荡电路,一个误差放大器,一个相位补偿电路,通过PWM/PFM切换控制电路。CS50363E内置MOS的设计,只需极简的外围电路,可以最大限度的保证电源模块的可靠性以及避免电源模块设计的复杂化。CS50363E最高可提供16V恒......
  • CS50-Python实验5,6
    Week5UnitTestsTestingmytwittr题目描述:测试ProblemSet2中Settingupmytwttr程序;题解:twttr.pydefmain():print("Output:",shorten(input("Input:")))defshorten(word):ans=""foriinword:ifi.lowe......
  • CS50-Python实验3,4
    Week3ExceptionsFuelGauge题目描述:输入分数字符串,判断并输出相应的百分数;特例不足1%输出E,超出99%输出F思路:1,从字符串中取出x,y;2,按题中要求计算输出;题解:whileTrue:try:##取出x,yx,z,y=input("Fraction:")x,y=int(x),int(y)......
  • lab6实验报告
    lab6实验报告一、实验思考题Thinking6.11#include<stdlib.h>2#include<unistd.h>34intfildes[2];5/*bufsizeis100*/6charbuf[100];7intstatus;8......
  • CS144 LAB5~LAB6
    CS144lab5~6最后两个lab了,虽然很多大佬都说剩下的两个lab比起TCP的实现,“简直太简单了”,但是我认为做这两个之前需要补充一些额外的网络知识,不然直接上手去做的话,难度也......
  • lab6、7
    创建一个用户空间的多线程。uthread的入口如下```cintmain(intargc,char*argv[]){a_started=b_started=c_started=0;a_n=b_n=c_n=0;thread_init()......
  • CS144-lab6-the IP router
    lab地址:lab6-doc代码实现:lab6-code1.目标lab6主要要实现一个路由的机制,首先互联网由多个局域网组成(不太严谨的说法),在lab5中我们只能支持在单个局域网中传递消......