Hey there! Sign in to join this conversationNew here? Join for free
    Offline

    20
    ReputationRep:
    (Original post by bigmansouf)
    you forgot to remove the \n newline at the end
    Oh. I was thinking that readlines did that automatically(ie. reduce(lambda x, y: x+y, [x.split("\r") for x in fin.read().split("\n")])). Oh well, easily fixed.
    Code:
    def open_file(file_name):
        return [x.strip() for x in open(file_name).readlines()]
    • Thread Starter
    Offline

    20
    ReputationRep:
    Q: Part 1: Read file and create dictionary

    (50 points possible)
    Write a function named create_grades_dict that accepts a string as the name of a file. Assuming that the file is a text file which includes name and grades of students, your function should read the file and return a dictionary with the exact format as shown below: The format of the input file is:

    Student ID, Last_name, Test_x, grade, Test_x, grade, ..
    Student ID, Last_name, Test_x, grade, Test_x, grade, ..
    Student ID, Last_name, Test_x, grade, Test_x, grade, ..
    ....
    An example of the input file is shown below. Sample Input Output Assuming that the input file "student_grades.txt" contains the following text:
    1000123456, Rubble, Test_3, 80, Test_4 , 80
    1000123459, Chipmunk, Test_4, 96, Test_1, 86 , Quiz_1 , 88
    Notes:
    Items are seperated by comma and one or more spaces may exist between the items.
    The "ID" of each student is unique. Two students may have the same Name (but IDs will be different)
    The "Name" of each student will only include a last name with no punctuation. Maximum of 15 characters.
    There will be an integer grade for each test (0-100)
    There are only four valid tests, i.e. Test_1, Test_2, Test_3, Test_4. There may be other grades in the file and you should ignore those grades.
    Each student may have missing grade(s) for the tests. A missing grades should be considered as 0.
    Grades may not be in order i.e. Test_3 may appear before Test_1.
    Your function should read the input file, calculate the average test grade for each student and return a dictionary with the following format:
    {'Student_ID':[Last_name,Test_1_grade,Test_2_gr ade,Test_3_grade,Test_4_grade,av erage], ...}
    For example in the case of sample input file shown above, your function should return the following dictionary:
    {'1000123456': ['Rubble', 0, 0, 80, 80, 40.0], '1000123459': ['Chipmunk', 86, 0, 0, 96, 45.5]}

    A:
    Spoiler:
    Show
    Code:
    def create_grades_dict(file_name):
        my_dictionary = {}
        
        # make a connection to the file 
        file_pointer = open(file_name, 'r')
        data = file_pointer.readlines()
        
        #iterate through each line in te data
        
        for line in data:
            values_lst = []
            lst = line.strip().split(",")
            for item in lst:
                item1 = item.strip()
                num = lst.index(item)
                lst.insert(num, item1)
                lst.remove(item)
            
            student_ID = lst[0]
            last_name = lst[1]
            tests = ["Test_1","Test_2", "Test_3", "Test_4"]
            count = 0
            total = 0
            while count >= 4:
                if tests[count] in lst:
                    pos = lst.index(tests[count])
                    values_lst.append(int(lst[pos + 1]))
                    total += int(lst[pos + 1])
                elif test[count] not in lst:
                    values_lst.append(0)
                    total += 0
                count += 1
            average = total/ 4.0
            values_lst.append(average)
            my_dictionary[student_ID] = values_list
        return my_dictionary
    • Thread Starter
    Offline

    20
    ReputationRep:
    Q:
    Write a function called print_grades that accepts the name of a file (string) as input argument. Assuming the format of the file is the same as the file in part 1, your function should call the function that you developed in part 1 to read the file and create the grades dictionary. Using the grades dictionary, your function should print the names, grades, and averages of students with the exact format shown below. Notice that you are asked to write a function (NOT a program) and that function prints the grades. Your function should return None after printing the grades.

    Sample Input file:

    1000123456, Rubble, Test_3, 80, Test_4 , 80, quiz , 90
    1000123210, Bunny, Test_2, 100, Test_1, 100,Test_3 , 100 ,Test_4 , 100
    1000123458, Duck, Test_1, 86, Test_5 , 100 , Test_2 ,93 ,Test_4, 94
    Your program's output should be:

    ID | Name | Test_1 | Test_2 | Test_3 | Test_4 | Avg. |
    1000123210 | Bunny | 100 | 100 | 100 | 100 | 100.00 |
    1000123456 | Rubble | 0 | 0 | 80 | 80 | 40.00 |
    1000123458 | Duck | 86 | 93 | 0 | 94 | 68.25 |
    Notes:
    Column titles are all centered
    The printed output is sorted in ascending order based on the student IDs
    Each column is seperated from a neighboring column(s) by three characters ' | ' (space vertical_bar space).
    IDs are always 10 characters and they are left justified (not counting the boundary characters)
    Names are left justified (maximum of 16 characters, not counting the boundary characters).
    Grades and averages are right justified. The width of the columns for the grades and averages is 6 characters (not counting the boundary characters).
    Averages are right justified with two digits of accuracy after the decimal point.
    Hint: Use the function which you developed in part 1 to read the input file and create a dictionary. Use .format() to format the output.

    A:
    Spoiler:
    Show
    Code:
    # Type your code here
    def create_grades_dict(file_name):
        # insert the code from your function in part 1 here
    
    
    # Your main program starts below this line
    def print_grades(file_name):
        # Call your create_grades_dict() function to create the dictionary
        grades_dict=create_grades_dict(file_name)
        column_title = ["ID", "Name", "Test_1", "Test_2", "Test_3", "Test_4", "Avg."]
        for item in column_titles:
            if len(item) == 2:
                print("{0:^15s} | ".format(item, end="")
            elif item == "Name":
                print ("{:^20s} | ".format(item, end="")
            elif len(item) > 2:
                print ("{0:^8s} | ".format(item, end="")
            
        for key, value in grades_dict:
            print ("{0:<15d} | ".format(key, end+ "")
            if type(value) is str:
                print ("{0:<20s} | ".format(value, end="")
            elif type(value) is int:
                print ("{0:>8d} | ".format(value, end="")
            elif type(value) is float:
                print("{0:>6.2f} | ".format(value)
    • Thread Starter
    Offline

    20
    ReputationRep:
    Q: Write a function named list_to_tuples that receives a two dimensional list of strings as parameter and returns a tuple of tuples where the content of each inner list is reversed as shown below: For example if the two dimensional list received by the function is

    [['mean', 'really', 'is', 'jean'],
    ['world', 'my', 'rocks', 'python']]
    Then, your function should return a tuple of tuples as shown below:
    (('jean', 'is', 'really', 'mean'), ('python', 'rocks', 'my', 'world'))


    A:
    Spoiler:
    Show
    Code:
    def list_to_tuples(MY_LIST):
        MY_LIST[0].reverse()
        MY_LIST[1].reverse()
        tup = tuple(MY_LIST[0])
        tup1 = tuple(MY_LIST[1])
        return (tup, tup1)
    • Thread Starter
    Offline

    20
    ReputationRep:
    Q:
    Write a function named formatted_print that receives a dictionary as argument. The keys of the dictionary will be the names of the students and the values of the dictionary will be their average scores. Your function should print this information exactly as specified below :

    For example if the dictionary received by the function is

    {'john':34.480, 'eva':88.5, 'alex':90.55, 'tim': 65.900}
    Then your function should print:
    alex 90.55
    eva 88.50
    tim 65.90
    john 34.48
    Note:
    The names have to be accommodated within 10 spaces and they are left justified.
    The scores are floats and they should be right justified in 6 spaces with two digits after the decimal point.
    All this information has to be sorted (descending order) by the scores of the students. Notice how alex has the highest score and appears first and john has the lowest score and appears last.

    A:
    Spoiler:
    Show
    Code:
    from collections import OrderedDict
    def formatted_print(my_dictionary):
        d = {'john':34.480, 'eva':88.5, 'alex':90.55, 'tim': 65.900}
        f = OrderedDict(sorted(d.items(), key=lambda t: t[1], reverse = True))
        lst =  f.items()
        for item in lst:
            print ("{0:<10}      {1:>6.2f}".format((item[0]), item[1]))
    formatted_print({'john':34.480, 'eva':88.5, 'alex':90.55, 'tim': 65.900})
    • Thread Starter
    Offline

    20
    ReputationRep:
    Q: Mini-project description - Rock-paper-scissors-lizard-Spock

    Rock-paper-scissors is a hand game that is played by two people. The players count to three in unison and simultaneously "throw” one of three hand signals that correspond to rock, paper or scissors. The winner is determined by the rules:

    Rock smashes scissors
    Scissors cuts paper
    Paper covers rock
    Rock-paper-scissors is a surprisingly popular game that many people play seriously (see the Wikipedia article for details). Due to the fact that a tie happens around 1/3 of the time, several variants of Rock-Paper-Scissors exist that include more choices to make ties less likely.

    Rock-paper-scissors-lizard-Spock (RPSLS) is a variant of Rock-paper-scissors that allows five choices. Each choice wins against two other choices, loses against two other choices and ties against itself. Much of RPSLS's popularity is that it has been featured in 3 episodes of the TV series "The Big Bang Theory". The Wikipedia entry for RPSLS gives the complete description of the details of the game.

    In our first mini-project, we will build a Python function rpsls(name) that takes as input the string name, which is one of "rock", "paper", "scissors", "lizard", or "Spock". The function then simulates playing a round of Rock-paper-scissors-lizard-Spock by generating its own random choice from these alternatives and then determining the winner using a simple rule that we will next describe.

    While Rock-paper-scissor-lizard-Spock has a set of ten rules that logically determine who wins a round of RPSLS, coding up these rules would require a large number (5x5=25) of if/elif/else clauses in your mini-project code. A simpler method for determining the winner is to assign each of the five choices a number:

    0 — rock
    1 — Spock
    2 — paper
    3 — lizard
    4 — scissors
    In this expanded list, each choice wins against the preceding two choices and loses against the following two choices (if rock and scissors are thought of as being adjacent using modular arithmetic).



    A:
    Spoiler:
    Show
    Code:
    import random
    # Rock-paper-scissors-lizard-Spock template
    
    
    # The key idea of this program is to equate the strings
    # "rock", "paper", "scissors", "lizard", "Spock" to numbers
    # as follows:
    #
    # 0 - rock
    # 1 - Spock
    # 2 - paper
    # 3 - lizard
    # 4 - scissors
    
    # helper functions
    
    def name_to_number(name):
        if name == "rock":
            num = 0
        elif name == "Spock":
            num = 1
        elif name == "paper":
            num = 2
        elif name == "lizard":
            num = 3
        elif name == "scissors":
            num = 4 
        return num
          
    def number_to_name(number):
        if number == 0:
            name = "rock"
        elif number == 1:
            name = "Spock"
        elif number == 2: 
            name = "paper"
        elif number == 3: 
            name = "lizard"
        elif number == 4:
            name = "scissors"
        else: 
            return "Error"
        return name 
    
    def rpsls(player_choice): 
        print 
        print "Player's choice is " + player_choice
        player_number = name_to_number(player_choice)
        comp_number = random.randrange(0, 5)
        comp_name = number_to_name(comp_number)
        print "Computer's choics is " +comp_name
        modulo_num  = (player_number - comp_number) % 5
        
        # if, elif  statement to determine the winner 
        if modulo_num == 0:
            print "Draw"
        elif (modulo_num == 1) or (modulo_num == 2) or (modulo_num == -3) \
        or (modulo_num == -4):
            print "Player wins"
        elif (modulo_num == -1) or (modulo_num == -2) or (modulo_num == 3) \
        or (modulo_num == 4):
            print "Computer wins"
            
    rpsls("rock")
    rpsls("Spock")
    rpsls("paper")
    rpsls("lizard")
    rpsls("scissors")
    • Thread Starter
    Offline

    20
    ReputationRep:
    Mini-project description - “Guess the number” game

    One of the simplest two-player games is “Guess the number”. The first player thinks of a secret number in some known range while the second player attempts to guess the number. After each guess, the first player answers either “Higher”, “Lower” or “Correct!” depending on whether the secret number is higher, lower or equal to the guess. In this project, you will build a simple interactive program in Python where the computer will take the role of the first player while you play as the second player.

    Note: Answer using event driven programming

    Answer :
    Spoiler:
    Show
    Code:
    # template for "Guess the number" mini-project
    # input will come from buttons and an input field
    # all output for the game will be printed in the console
    import random
    import simplegui
    limit = 100
    # helper function to start and restart the game
    def new_game():
        # initialize global variables used in your code here
        global secret_number
        global limit
        secret_number = random.randrange(0, limit)
        return 
    def tries():
        global guess_limit
        if limit == 100:
            guess_limit = 7
        elif limit == 1000:
            guess_limit = 10
        return guess_limit
    def decrement():
        global guess_limit 
        guess_limit -= 1
        return guess_limit
    
    
    # define event handlers for control panel
    def range100():
        # button that changes the range to [0,100) and starts a new game 
        print "New Game. Range is from 0 to 100."
        global limit
        limit = 100
        global guess_limit
        guess_limit = tries()
        print "Number of guesses left is ", guess_limit
        new_game()
        return
        
    def range1000():
        global limit
        limit = 1000
        global guess_limit
        guess_limit = tries()
        print "Number of guesses left is ", guess_limit
    
        new_game()
        return 
    
    def input_guess(guess):
        guess_number = int(guess)
        print "Guess was " + guess
        global guess_limit
        # comparing numbers 
        if secret_number < guess_number:
            print "Lower!"
            print "Number of guesses left is", decrement()
        elif secret_number == guess_number:
            print "Correct!    Well done"
            print "Number of guesses left is", decrement()
            
        elif secret_number > guess_number:
            print "Higher!"
            print "Number of guesses left is", decrement()
        if  guess_limit == 0:
            print "Sorry you have no more guesses left"
            print "the number you were looking for is "+ str(secret_number)
        return 
            
           
        
    # create frame
    
    frame = simplegui.create_frame("Guess the number", 300, 300)
    
    # register event handlers for control elements and start frame
    frame.add_input("Guess the number", input_guess, 100)
    frame.add_button("Range is from 0 to 100", range100, 100)
    frame.add_button("Range is from 0 to 1000", range1000, 100)
                     
    
    
    # call new_game 
    new_game()
    
    
    # always remember to check your completed program against the grading rubric
    .
    • Thread Starter
    Offline

    20
    ReputationRep:
    Q: Mini-project description - "Stopwatch: The Game"

    Our mini-project for this week will focus on combining text drawing in the canvas with timers to build a simple digital stopwatch that keeps track of the time in tenths of a second. The stopwatch should contain "Start", "Stop" and "Reset" buttons.

    Answer:

    Note use codeskulptor to code your answer

    Spoiler:
    Show
    Code:
    # template for "Stopwatch: The Game"
    import simplegui
    
    # define global variables
    time = 0
    height = 500
    width = 500
    counter_1 = 0
    counter_2 = 0
    # define helper function format that converts time
    # in tenths of seconds into formatted string A:BC.D
    def format(time):
        form = "A:BC.D"
        str_time = str(time)
        if len(str_time) == 1:
            D = time
            return ("0:00." + str(D))
        elif len(str_time)== 2:
            D = str_time[-1]
            C = str_time[0]
            return ("0:0" + C +"." +D)
        elif 99 < time < 600:
            str_time = str(time)
            return ("0:" + str_time[0:2] +"."+ str_time[-1])
        elif time >= 600:
            A = time // 600
            result_mod = time % 600
            if len(str(result_mod)) >= 1:
                if result_mod == 0:
                    str_result = str(result_mod)
                    return (str(A)+ ":" + str(result_mod) + str(result_mod) + "." + str(result_mod))
                if result_mod >= 1:
                    str_result = str(result_mod)
                    return (str(A)+":"+"0"+str_result[0]+"."+str_result[-1])
            elif len(str(result_mod)) == 3:
                str_result = str(result_mod)	
                return (str(A)+":"+str_result[:2] +"."+str_result[-1])
            
        
    # define event handlers for buttons; "Start", "Stop", "Reset"
    def start():
        timer.start()
    def stop():
        global counter_1, counter_2
        timer.stop()
        if time % 10 == 0:
            counter_1 += 1
        counter_2 += 1
        
    def reset():
        global time
        timer.stop()
        time = 0 
        
        
    # define event handler for timer with 0.1 sec interval
    def create_timer():
        global time
        time += 1 
        
    
    # define draw handler
    def draw_handler(canvas):
        global width, height 
        canvas.draw_text(format(time), [width//2, height//2],24, "White")
        str_counter_1 = str(counter_1)
        str_counter_2 = str(counter_2)
        canvas.draw_text(str_counter_1+"/"+str_counter_2, [480,15],12, "Yellow")
    
    # create frame
    frame = simplegui.create_frame("stopwatch", height, width)
    timer = simplegui.create_timer(100, create_timer)
    frame.set_draw_handler(draw_handler)
    # register event handlers
    start_button = frame.add_button("Start", start, 50)
    stop_button = frame.add_button("Stop", stop, 50)
    reset_button = frame.add_button("Reset", reset, 50)
    
    
    # start frame
    frame.start()
    • Thread Starter
    Offline

    20
    ReputationRep:
    Q: Develop and test python program that displays the day of the week for a holiday event such New Year's Eve for the year entered by the user

    Answer:
    Spoiler:
    Show
    Code:
    # holiday program
    from math import floor 
    import re
    terminate = False
    #ask the user to input the day, month, year using format 18/05/1992
    user = input( "Enter your holiday in format (14/05/1992): ")
    
    while not terminate:
        regex = re.compile(r'\d\d/\d\d/\d\d\d\d')
        find = regex.search(user)
        if find == None:
            user = input( "Enter your holiday in format (14/05/1992): ")
    
        else:
            lst = user.split("/")
            terminate = True
    
    # initializing the variable day, month, year 
    day = int(lst[0])
    month = int(lst[1])
    year = int(lst[-1])
    
    
    #initialize variables of century_digits
    century_digits = int(lst[-1][:2])
    year_digits = int(lst[-1][2:])
    
    if (year % 4 == 0) and (not (year % 100 == 0) or year % 400):
        leap_year = True
    else:
        leap_year = False
    value = year + floor(year / 4)
    if century_digits == 18:
        value += 2
    elif century_digits == 20:
        value += 6
    
    
    if month == 1 and not leap_year:
        value += 1
    elif month == 2:
        if leap_year:
            value += 3 
        else:
            value += 4
    elif month == 3 or 11:
        value += 4
    elif month == 4 or 7:
        value += 0
    elif month == 5:
        value += 2
    elif month == 6:
        value += 5 
    elif month == 8:
        value += 3 
    elif month == 10:
        value += 1 
    elif month == 9 or 12:
        value += 6
    
    value = (value + day) % 7 
    
    daylst = ("Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", \
              )
    if value == 1:
        holiday = daylst[0]
    elif value == 2:
        holday = daylst[1]
    elif value == 3:
        holiday = daylst[2]
    elif value == 4: 
        holiday = daylst[3]
    elif value == 5: 
        holiday = daylst[4]
    elif value == 6: 
        holiday = daylst[5]
    elif value == 0:
        holiday = daylst[6]
    
    
    
    
    print("The event " + user + " will occur on a " + holiday)
 
 
 
Poll
Do you agree with the PM's proposal to cut tuition fees for some courses?

The Student Room, Get Revising and Marked by Teachers are trading names of The Student Room Group Ltd.

Register Number: 04666380 (England and Wales), VAT No. 806 8067 22 Registered Office: International House, Queens Road, Brighton, BN1 3XE

Write a reply...
Reply
Hide
Reputation gems: You get these gems as you gain rep from other members for making good contributions and giving helpful advice.