Question

I am stuck with this coding problem from edx coding python 4.4.6: #This is a long...

I am stuck with this coding problem from edx coding python 4.4.6:

#This is a long one -- our answer is 20 lines of code, but
#yours will probably be longer. That's because it's one of the
#more authentic problems we've done so far. This is a real
#problem you'll start to face if you want to start creating
#useful programs.
#
#One of the reasons that filetypes work is that everyone
#agrees how they are structured. A ".png" file, for example,
#always contains "PNG" in the first four characters to
#assure the program that the file is actually a png. If these
#standards were not set, it would be hard to write programs
#that know how to open and read the file.
#
#Let’s define a new filetype called ".cs1301".
#In this file, every line should be structured like so:
#
#number assignment_name grade total weight
#
#In this file, each component will meet the following
#description:
#
# - number: an integer-like value of the assignment number
#
# - assignment_name: a string value of the assignment name
#
# - grade: an integer-like value of a student’s grade
#
# - total: an integer-like value of the total possible
# number of points
#
# - weight: a float-like value ranging from 0 to 1
# representing the percent of the student’s grade this
# assignment is worth. All the weights should add up to 1.
#
#Each component should be separated with exactly one space.
#A good sample file is available to view as
#"sample.cs1301".
#
#Write a function called format_checker that accepts a
#filename and returns True if the file contents accurately
#conform to the described format. Otherwise the function
#should return False. In other words, it should return True
#if:
#
# - Each line has five elements separated by spaces, AND
# - The first, third, and fourth elements are integers, AND
# - The fifth element is a decimal number, AND
# - All the fifth elements add to 1.
#
#You can make changes to test.cs1301 to test your function,
#or test it with sample.cs1301. Right now, running it on
#sample.cs1301 should return True, and on test.cs1301
#should return False.
#
#Hint 1: .split() will likely help separate each line into
#its components.
#Hint 2: .split() returns a list. So, if you were to do
#something like say split_line = line.split(), then
#split_line[0] would give the first item, split_line[1] would
#give the second item, etc.
#Hint 3: If you're having trouble, try breaking it down by
#parts. First check the file to see if it has the right
#number of items per line, then whether the items are of
#the correct type, then whether the fifth elements add to
#1. Remember, you know how to do each individual check
#(checking types, adding numbers, finding list lengths) --
#the hard part is knitting this all together into one bigger
#solution.


#Write your function here!

#Test your function below. With the original values of these
#files, these should print True, then False:
print(format_checker("sample_1.cs1301"))
print(format_checker("sample_2.cs1301"))


0 0
Add a comment Improve this question Transcribed image text
Answer #1

Note: The required code for the function format_checker() is highlighted in grey and bold.

#This is a long one -- our answer is 20 lines of code,

#but yours will probably be longer. That's because it's

#one of the more authentic problems we've done so far.

#This is a real problem you'll start to face if you want

#to start creating useful programs.

#

#One of the reasons that filetypes work is that everyone

#agrees how they are structured. A ".png" file, for

#example, always contains "PNG" in the first four

#characters to assure the program that the file is

#actually a png. If these standards were not set, it

#would be hard to write programs that know how to open

#and read the file.

#

#Let’s define a new filetype called ".cs1301".

#In this file, every line should be structured like so:

#

#number assignment_name grade total weight

#

#In this file, each component will meet the following

#description:

#

# - number: an integer-like value of the assignment

#   number

#

# - assignment_name: a string value of the assignment

#   name

#

# - grade: an integer-like value of a student’s grade

#

# - total: an integer-like value of the total possible

#   number of points

#

# - weight: a float-like value ranging from 0 to 1

# representing the percent of the student’s grade this

# assignment is worth. All the weights should add up to 1.

#

#Each component should be separated with exactly one

#space.

#A good sample file is available to view as

#"sample.cs1301".

#

#Write a function called format_checker that accepts a

#filename and returns True if the file contents

#accurately confirm to the described format. Otherwise

#the function should return False. In other words, it

#should return True if:

#

# - Each line has five elements separated by spaces, AND

# - The first, third, and fourth elements are integers,

#   AND

# - The fifth element is a decimal number, AND

# - All the fifth elements add to 1.

#

#You can make changes to test.cs1301 to test your

#function, or test it with sample.cs1301. Right now,

#running it on sample.cs1301 should return True, and on

#test.cs1301 should return False.

#

#Hint 1: .split() will likely help separate each line

#into its components.

#Hint 2: .split() returns a list. So, if you were to do

#something like say split_line = line.split(), then

#split_line[0] would give the first item, split_line[1]

#would give the second item, etc.

#Hint 3: If you're having trouble, try breaking it down

#by parts. First check the file to see if it has the

#right number of items per line, then whether the items

#are of the correct type, then whether the fifth elements

#add to 1. Remember, you know how to do each individual

#check (checking types, adding numbers, finding list

#lengths) -- the hard part is knitting this all together

#into one bigger solution.

#Screenshot of the code:

#Sample Input File (sample_1.cs1301):

#Sample Input File (sample_2.cs1301):

#Sample Output:

#Code to copy:

#Write your function here!

#Define the function format_checker() having a file name

#as function parameter.

def format_checker(filename):

    #Open the file in read mode.

    infile = open(filename, 'r')

    #Read all lines of the file.

    fileLines = infile.readlines()

   

    #Close the file.

    infile.close()

    #Declare and initialize required variable to store

    #the total of weights.

    totalWeight = 0

    #Start a while loop over the lines read from the

    #file.

    for currentLine in fileLines:

       

        #Split the current line through spaces.

        split_line = currentLine.split(' ')

        #If the length of the splitted line or list of

        #items of the current line is not 5, then return

        #false.

        if(len(split_line) != 5):

            return False

       

        #Start a try/except block.

        try:

            #Chnage the type of item at 0, 2, 3 index to

            #integer from string and the type of item at

            #4th index will be chnaged to float from

            #string.

            split_line[0] = int(split_line[0])

            split_line[2] = int(split_line[2])

            split_line[3] = int(split_line[3])

            split_line[4] = float(split_line[4])

          

            #If the item at 4th index i.e. weight is not

            #in the range 0 and 1, then return false.

            if(split_line[4] < 0 or split_line[4] > 1):

                return False

       

        #Start the except block and return false, if

        #there is any type mismatch.

        except:

            return False

       

        #Add the item at 4th index i.e. weight to the

        #totalWeight.

        totalWeight = totalWeight + split_line[4]

   

    #If the value of the totalWeight is not equal to 1,

    #then return false.

    if(totalWeight != 1):

        return False

    #Otherwisem return true.   

    return True

#Test your function below. With the original values of

#these files, these should print True, then False:

print(format_checker("sample_1.cs1301"))

print(format_checker("sample_2.cs1301"))

Sample Input File (sample_1.cs1301):

1 assignment_1 85 100 0.05

2 assignment_2 80 100 0.05

3 assignment_3 95 100 0.05

4 assignment_4 95 100 0.05

5 assignment_5 80 100 0.05

6 exam_1 85 86 0.1

7 assignment_6 100 100 0.05

8 assignment_7 97 100 0.05

9 exam_2 89 100 0.1

10 assignment_8 93 100 0.05

11 assignment_9 99 100 0.05

12 exam_3 92 100 0.1

13 final_exam 95 100 0.25

Sample Input File (sample_2.cs1301):

Hey kid!

Did you know that dragons love tacos?

Add a comment
Know the answer?
Add Answer to:
I am stuck with this coding problem from edx coding python 4.4.6: #This is a long...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I am having a little trouble with my Python3 code today, I am not sure what...

    I am having a little trouble with my Python3 code today, I am not sure what I am doing wrong. Here are the instructions: and here is my code: update: I have seen I did not close x in sumFile and I am still only getting a 2/10 on the grader. any help appreciated. Lab-8 For today's lab you going to write six functions. Each function will perform reading and/or write to a file Note: In zybooks much like on...

  • Python Programming QUESTION 16 Which of the following is an example of a Keyword in Python?...

    Python Programming QUESTION 16 Which of the following is an example of a Keyword in Python? elif class for All of the above QUESTION 17 Which of the following is not an acceptable variable name in Python? 2ndVar $amount Rich& ard None of the above are acceptable variable names QUESTION 18 The number 1 rule in creating programs is ___________________- Write the code first Think before you program Let the compiler find you syntax errors There are no rules just...

  • In Python 4. outputWordPointPairs(pointWordList, filename, toFile) NO return (just prints a formatted list or writes it...

    In Python 4. outputWordPointPairs(pointWordList, filename, toFile) NO return (just prints a formatted list or writes it to file). NOTE: Your function should add the .txt extension to the filename before opening a file with that name. Write a function which will output the (pointValue, word) pairs in pointWordList to the shell or to a file depending on the bool value toFile. Note the order of elements of the tuple is (pointValue, word) not (word, pointValue). Find out why this specific...

  • Python The Python "<" and ">" comparison operators can be used to compare which string variable...

    Python The Python "<" and ">" comparison operators can be used to compare which string variable has a greater value based on comparing the ASCII codes of the characters in each string, one by one. To take some examples: "tets" > "test" returns True because the third letter of the first string, "t", has a greater value than the third letter of the second string, "s". "testa" > "test" returns True because—while the first four letters in both words are...

  • Write a complete C++ program that reads students names and their test scores from an input...

    Write a complete C++ program that reads students names and their test scores from an input text file. The program should output each student’s name followed by the test scores and the relevant grade in an output text file. It should also find and display on screen the highest/lowest test score and the name of the students having the highest/lowest test score, average and variance of all test scores. Student data obtained from the input text file should be stored...

  • I need help with this python programming exercise, please! thanks in advance Create a Python script...

    I need help with this python programming exercise, please! thanks in advance Create a Python script file called hw4.py. Add your name at the top as a comment, along with the class name and date. Both exercises should be in this file, with a comment before each of them to mark it. Ex. 1. Write a program that inputs an integer number from the user, then prints a letter "O" in ASCII art using a width of 5 and the...

  • PYTHON 3 Object Oriented Programming ***a9q3.py file below*** class GradeItem(object): # A Grade Item is anything...

    PYTHON 3 Object Oriented Programming ***a9q3.py file below*** class GradeItem(object): # A Grade Item is anything a course uses in a grading scheme, # like a test or an assignment. It has a score, which is assessed by # an instructor, and a maximum value, set by the instructor, and a weight, # which defines how much the item counts towards a final grade. def __init__(self, weight, scored=None, out_of=None): """ Purpose: Initialize the GradeItem object. Preconditions: :param weight: the weight...

  • Write a C/C++ program that simulate a menu based binary number calculator. This calculate shall have the following three...

    Write a C/C++ program that simulate a menu based binary number calculator. This calculate shall have the following three functionalities: Covert a binary string to corresponding positive integers Convert a positive integer to its binary representation Add two binary numbers, both numbers are represented as a string of 0s and 1s To reduce student work load, a start file CSCIProjOneHandout.cpp is given. In this file, the structure of the program has been established. The students only need to implement the...

  • In Python and in one file please. (Simple functions with an expressions) Create a function called...

    In Python and in one file please. (Simple functions with an expressions) Create a function called load_inventory(filename). The filename argument in this case specifies the name of a file that contains all the inventory/product information for the store, including product names, descriptions, prices, and stock levels. This function should clear any information already in the product list (i.e., a fresh start) and then re-initialize the product list using the file specified by the filename argument. You can structure your file...

  • In Python and in one file please. (Simple functions with an expressions) Create a function called load_inventory(filenam...

    In Python and in one file please. (Simple functions with an expressions) Create a function called load_inventory(filename). The filename argument in this case specifies the name of a file that contains all the inventory/product information for the store, including product names, descriptions, prices, and stock levels. This function should clear any information already in the product list (i.e., a fresh start) and then re-initialize the product list using the file specified by the filename argument. You can structure your file...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT