Tag: cs50 psets 6 mario-more solution

  • Solutions to CS50 Lab 6 and Problem Set 6 (2022)

    Solutions to CS50 Lab 6 and Problem Set 6 (2022)

    Disclaimer: These answers are only for educational purposes only. Please do not use them for cheating. Cheating doesn’t do any good for you!

    In this post, I’m giving you my solutions to CS50 lab 6 and problem set 6 Problems and Recover. Hope these solutions will help you to better understand the problems and be a guide for your solutions too.

    The Solution to CS50 Lab 6 world cup problem (2022)

    For this problem, we have to write a program to run simulations of the Fifa World Cup. So the program just outputs how much percentage of chance each team got to win the game. So the program takes input .csv file and uses the rating of each team it calculates how much percentage of chance each team got to win the game. So, here is my solution to this problem,

    
    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 = []
        filename = sys.argv[1]
        # TODO: Read teams into memory from file
        with open(filename) 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):
            winner = simulate_tournament(teams)
            if winner in counts:
                counts[winner] += 1
            else:
                counts[winner] = 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()

    The solution to CS50 psets 6 Sentimental-Hello problem (2022)

    This is just a simple python program. We just have to write a simple python program that takes our name as input and outputs a greeting message to the console screen.

    This is the code,

    # TODO
    name = input("What is your name? ")
    print(name)
    print("hello, " + name)

    The solution to CS50 psets 6 sentimental-Mario less comfortable problem (2022)

    For this program, we should write a simple python program that prints out a half-pyramid of a specified height. The output looks like the one below.

    $ python mario.py
    Height: 4
       #
      ##
     ###
    ####</pre>

    Here is the solution,

    # TODO
    # get input from user until input is correct
    while True:
        try:
            height = int(input("Height: "))
            if (height >= 1) and (height &lt;= 8):
                break
        except:
            print("", end="")
    spaces = 1
    for j in range(height):
        # print spaces
        for spaces in range(height - j-1):
            print(" ", end="")
        # print hashes
        for i in range(j+1):
            print("#", end="")
        print()

    The solution to CS50 psets 6 sentimental-Mario more comfortable problem (2022)

    As in the previous one, this problem also we have to write a simple python program that takes up a specific height and outputs a double half-pyramid of that height. The output looks like this.

    $ python mario.py
    Height: 4
       #  #
      ##  ##
     ###  ###
    ####  ####

    Here is the solution code,

    # TODO
    from cs50 import get_int
    # get input from user until input is correct
    while True:
        try:
            height = get_int("Height: ")
            if (height >= 1) and (height &lt;= 8):
                break
        except:
            print("", end="")
    for row in range(height):
        for space in range(height - row - 1, 0, -1):
            print(" ", end="")
        # print the left hashes
        for left_hash in range(row + 1):
            print("#", end="")
        # Print the middle seperation spaces
        print("  ", end="")
        # print the right hashes
        for right_hash in range(row + 1):
            print("#", end="")
        print()

    The solution to CS50 psets 6 Sentimental-Cash problem (2022)

    In this problem, we have to implement a python program that calculates the minimum number of coins required to give a user change.

    The output looks like this,

    $ python cash.py
    Change owed: 0.41
    4

    The solution code,

    # TODO
    from cs50 import get_float
    # keep track of coins used
    count = 0
    while True:
        change = get_float("Change owned: ")
        if change > 0:
            break
    # round up to the nearest whole number
    cent = round(change * 100)
    while cent >= 25:
        cent = cent - 25
        count += 1
    while cent >= 10:
        cent = cent - 10
        count += 1
    while cent >= 5:
        cent = cent - 5
        count += 1
    while cent >= 1:
        cent = cent - 1
        count += 1
    print(count)

    The solution to CS50 psets 6 Sentimental-Credit problem (2022)

    For this problem, we have to implement a python program that determines whether a provided credit card number is valid according to Luhn’s algorithm.

    The output looks like this,

    $ python credit.py
    Number: 378282246310005
    AMEX

    Here is the solution code,

    # TODO
    import sys
    def main():
        # Get card number from the user
        credit_card_number = get_credit_card_number()
        # validate the card provided by the user 
        validate_card(credit_card_number)
    # execute until user input a valid credit card number
    def get_credit_card_number():
        # prompt user for card number
        while True:
            card_number = input("Number: ")
            # calculate card length
            try:
                if len(card_number) > 0 and int(card_number):
                    break
            except ValueError:
                continue
        return card_number
    # validate the user input creadit card number
    def validate_card(credit_card_number):
        if len(credit_card_number) &lt; 13 or 16 &lt; len(credit_card_number):
            print("INVALID")
            sys.exit(0)
        even_number, odd_number = 0, 0
        card_number_length = len(credit_card_number)
        # Calculates sum according to Luhn's Algorithm
        if card_number_length % 2 == 0:
            for numbers in range(card_number_length):
                number = int(credit_card_number[numbers])
                if numbers % 2 == 0:
                    multiple = number * 2
                    if multiple >= 10:
                        even_number += multiple // 10
                        even_number += multiple % 10
                    else:
                        even_number += multiple
                else:
                    odd_number += number
        else:
            for numbers in range(card_number_length):
                number = int(credit_card_number[numbers])
                if numbers % 2 != 0:
                    multiple = number * 2
                    if multiple >= 10:
                        even_number += multiple // 10
                        even_number += multiple % 10
                    else:
                        even_number += multiple
                else:
                    odd_number += number
        checksum = (even_number + odd_number) % 10
        # Check for conditions of all companies
        if checksum == 0:
            first_digit = int(credit_card_number[0])
            second_digit = int(credit_card_number[1])
            if first_digit == 3 and second_digit == 4 or second_digit == 7:
                print("AMEX")
            elif first_digit == 5 and 1 &lt;= second_digit &lt;= 5:
                print("MASTERCARD")
            elif first_digit == 4:
                print("VISA")
            else:
                print("INVALID")
    if __name__ == "__main__":
        main()

    The solution to CS50 psets 6 Sentimental-Readability problem (2022)

    For this problem, we have to write a python program that computes the approximate grade level needed to comprehend some text.

    The sample output should look like this,

    $ python readability.py
    Text: Congratulations! Today is your day. You're off to Great Places! You're off and away!
    Grade 3

    The solution code looks like this,

    <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># TODO
    count_letter = 0
    count_word = 1
    count_sentence = 0
    # getting input from user
    text = input("Text: ")
    text_length = len(text)
    # Count the number of letters in the text
    for i in range(text_length):
        if(text[i].isalpha()):
            count_letter += 1
    # Count the number of words in the text
        if(text[i].isspace()):
            count_word += 1
    # count the number of sentence
        if(text[i] == '.' or text[i] == '?' or text[i] == '!'):
            count_sentence += 1
    # calculate index
    calculation = (0.0588 * count_letter / count_word * 100) - (0.296 * count_sentence / count_word * 100) - 15.8
    index = round(calculation)
    if index &lt; 1:
        print("Before Grade 1")
    elif index > 16:
        print("Grade 16+")
    else:
        print(f"Grade {index}")</pre>

    The solution to CS50 psets 6 DNA problem (2022)

    For this problem, we have to write a python program that identifies a person based on their DNA. The output of this python program should look like the below.

    $ python dna.py databases/large.csv sequences/5.txt
    Lavender

    The solution to this DNA problem is,

    import csv
    import sys
    def main():
        # TODO: Check for command-line usage
        if len(sys.argv) != 3:
            print("Usage: python dna.py data.csv sequence.txt")
            exit()
        # TODO: Read database file into a variable
        with open(sys.argv[1]) as database_file:
            reader = csv.DictReader(database_file)
            database = list(reader)
        # TODO: Read DNA sequence file into a variable
        with open(sys.argv[2]) as sequence_file:
            sequence = sequence_file.read()
        # TODO: Find longest match of each STR in DNA sequence
        matches = {}
        for i in database[0]:
            matches[i] = (longest_match(sequence, i))
        # TODO: Check database for matching profiles
        suspect = 'No Match'
        suspect_counter = 1
        for i in range(len(database)):
            for j in matches:
                if str(matches[j]) == database[i][j]:
                    suspect_counter += 1
            if suspect_counter == len(matches):
                suspect = database[i]['name']
                break
            else:
                suspect_counter = 1
        print(suspect)
        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()

    That’s all the questions and answers for Lab 6 and problem set 6. Hope this post helps you!