Question

Santa Claus needs to automate the compiling of the naughty and nice lists. Your program will...

Santa Claus needs to automate the compiling of the naughty and nice lists. Your program will read in each child’s name and their count of major and minor good deeds and their major and minor bad deeds. With that information, compute an overall score and determine if they go on the naughty or nice list.

Major good deeds might be something like shoveling the walk and driveway for the chronologically challenged lady down the street, a minor good deed would be bringing her newspaper up from the drive to the porch on a rainy day. Bad deeds, well, you get the point.

Save the kids_list.txt file to your working folder.

The scoring

In the data file, each child’s name is followed by 4 integers:

Joe Smith 5 12 4 7

where the numbers are, in order: major good deeds, minor good deeds, major bad deeds, minor bad deeds.

Overall score is calculated as follows:

score = 5 * major good + minor good – 10 * major bad – 0.5 * minor bad

If the resulting value is positive, the child will go on the nice list. If negative, on the naughty list. If exactly 0, randomly choose which list (flip of a coin, see below)

Functions

Your program must have the following functions:

read_data( ) given the file name, opens and checks the file, reads each line of the file, consisting of first and last names followed by four numbers, into a list, converts the four number to integer values, adds to overall list of children. Returns the list, empty list if file was empty, or -1 if the file fails to open

naughty_nice( ) given a list with four integers, computes the total score using formula above. Returns True if positive, False if negative, randomly True or False if 0

write_lists( ) given a list containing lists with children’s’ names and True or False to indicate nice or naughty, as well as the names of the nice and naughty files, opens and checks the files, writes each child’s name to the appropriate file. Returns -1 if a file fails to open, total count of records written otherwise.

main( ) may do all the remaining program actions: call read_data, iterate through the chidlrens’ records, passing only the scores to the naughty_nice function. As each child is scored, built list with only names and True or False. Pass score list and output file names to write_lists. Compare return value with count of children to ensure all records written

Error conditions

You must check the return values from read_data and write_lists. A return of -1 indicates the respective file did not open, thus there is no data to process. Display an error message and return at that point.

Also test that the list returned from read_data actually has content, it’s possible the file existed but was empty. If the length of the list is 0, display a message and return at that point.

Test that the number of records written by write_lists matches the number of records in the actual data list.

Files

The kids_list.txt file is formatted as:

Sally Jones 10 15 2 6

Bob Smith 7 22 3 9

Ed Martin 12 20 2 8

good_kids.txt should have the following:

Sally Jones

Bob Smith

Ed Martin

Marty Miller

Martha Raye

Billy Martin

Jane Walters

bad_kids.txt should have the following:

Alan Gollum

Sam Johnson (Sam could be on either list, his score is 0)

John Robertson

Johnny Eller

Rhonda Flack (Rhonda could be on either list, her score is 0)

Kathy Jackson


The lists

The main data list will look like:

[['Sally', 'Jones', 10, 15, 2, 6], ['Bob', 'Smith', 7, 22, 3, 9], ...

A list that is sent to the naughty_nice function will look like:

[10, 15, 2, 6]

The list that is sent to the write_lists function will look like:

[['Sally', 'Jones', True], ['Bob', 'Smith', False]

I'm writing this in Python Geany

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


def read_data(filename):
    # Open file inside try, except in case file could not be opened
    try:
        file_read = open(filename, 'r')
        kids_list = []
        # Iterate over file line by line
        for line in file_read.readlines():
            data = line.strip().split()  # split line. strip is use to remove trailing spaces
            # for values in data from index 2 (means when the score starts) convert each to int
            for i in range(2, len(data)):
                data[i] = int(data[i])
            # append this list data to kids_list
            kids_list.append(data)
        file_read.close()  # close the file
        return kids_list  # return kids list
    except IOError:
        return -1  # return -1


def naughty_nice(score_list):
    # Calculate score and return True, False, random accordingly
    score = 5 * score_list[0] + score_list[1] - 10 * score_list[2] - 0.5 * score_list[3]
    if score > 0:
        return True
    elif score < 0:
        return False
    else:
        return random.choice([True, False])


def write_lists(kids_new_list, nice_file, naughty_file):
    # Open files inside try,except
    try:
        total_records = 0
        file_nice = open(nice_file, 'w')
        file_naughty = open(naughty_file, 'w')

        # Iterate over kids in list, If true write the record in nice file else naughty file
        for kids in kids_new_list:
            if kids[2] is True:
                file_nice.write(kids[0] + ' ' + kids[1] + '\n')
            else:
                file_naughty.write(kids[0] + ' ' + kids[1] + '\n')
            total_records += 1  # Add 1 to total_records

        # close files
        file_nice.close()
        file_naughty.close()
        # return total_records
        return total_records
    except IOError:
        return -1  # return -1


def main():
    kids_list = read_data('kids_list.txt')  # call function to create list
    if kids_list == -1:  # If its -1, print error message and exit
        print("Could not open file!")
        exit(0)
    elif len(kids_list) == 0:  # If list is empty, print message and return
        print('File is empty')
        exit(0)
    else:  # Else, call naughty_nice to get score and built list with only names and True or False
        kids_new_list = []
        for kids in kids_list:
            result = naughty_nice(kids[2:])
            kids_new_list.append([kids[0], kids[1], result])

        # call function to write records
        total = write_lists(kids_new_list, 'good_kids.txt', 'bad_kids.txt')
        if total == -1:  # If -1 , print message and exit
            print('File cannot be opened')
            exit(0)
        else:
            if total == len(kids_list):
                print('All records are written')
                print('Total records:', total)


main()

SCREENSHOT

import random def read_data(filename) : # Open file inside try, except in case file could not be opened try: file_read = open

wli def write_lists (kids_new_list, nice_file, naughty_file): # Open files inside try,except try: total_records = 0 file_nice

elif len (kids_list) == 0: # If list is empty, print message and return print(File is empty) exit(0) else: # Else, call nau

INPUT FILE - kids_list.txt

WN SantaClaus.py x kids_list.txt X Sally Jones 10 15 2 6 Bob Smith 7 22 39 Alan Gollum 2 3 10 9 Ed Martin 12 20 2 8 John Robe

OUTPUT

E:\Practice Python\venv\scripts\pyth All records are written Total records: 6 Process finished with exit code 0

OUTPUT FILE -

good_kids.txt and  bad_kids.txt

bad_kids - Notepad File Edit Format View Help Alan Gollum John Robertson Sam Johnson

good_kids - Notepa File Edit Format Vien Sally Jones Bob Smith Ed Martin

Add a comment
Know the answer?
Add Answer to:
Santa Claus needs to automate the compiling of the naughty and nice lists. Your program will...
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
  • Q1. Write a program to simulate a grocery waiting queue. Your program should ask the user...

    Q1. Write a program to simulate a grocery waiting queue. Your program should ask the user if they want to add a customer to the queue, serve the next customer in the queue, or exit. When a customer is served or added to the queue, the program should print out the name of that customer and the remaining customers in the queue. The store has two queues: one is for normal customers, another is for VIP customers. Normal customers can...

  • PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment...

    PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment the lines please so I can understand. There are short and med files lengths for each the list of names/ids and then search id file. These are the input files: https://codeshare.io/aVQd46 https://codeshare.io/5M3XnR https://codeshare.io/2W684E https://codeshare.io/5RJwZ4 LinkedList ADT to store student records(code is below). Using LinkedList ADT instead of the Python List. You will need to use the Student ADT(code is below) Imports the Student class...

  • Language = C++ How to complete this code? C++ Objects, Structs and Linked Lists. Program Design:...

    Language = C++ How to complete this code? C++ Objects, Structs and Linked Lists. Program Design: You will create a class and then use the provided test program to make sure it works. This means that your class and methods must match the names used in the test program. Also, you need to break your class implementation into multiple files. You should have a car.h that defines the car class, a list.h, and a list.cpp. The link is a struct...

  • PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...

    PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please so I can understand LinkedList ADT: class myLinkedList:     def __init__(self):         self.__head = None         self.__tail = None         self.__size = 0     def insert(self, i, data):         if self.isEmpty():             self.__head = listNode(data)             self.__tail = self.__head         elif i <= 0:             self.__head = listNode(data, self.__head)         elif i >= self.__size:             self.__tail.setNext(listNode(data))             self.__tail = self.__tail.getNext()         else:             current = self.__getIthNode(i - 1)             current.setNext(listNode(data,...

  • Use the csv file on spotify from any date Code from lab2 import java.io.File; import java.io.FileNotFoundException;...

    Use the csv file on spotify from any date Code from lab2 import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class SongsReport {    public static void main(String[] args) {               //loading name of file        File file = new File("songs.csv"); //reading data from this file        //scanner to read java file        Scanner reader;        //line to get current line from the file        String line="";       ...

  • CSC 142 Music Player You will complete this project by implementing one class. Afterwards, your program...

    CSC 142 Music Player You will complete this project by implementing one class. Afterwards, your program will play music from a text file. Objectives Working with lists Background This project addresses playing music. A song consists of notes, each of which has a length (duration) and pitch. The pitch of a note is described with a letter ranging from A to G.   7 notes is not enough to play very interesting music, so there are multiple octaves; after we reach...

  • Please provide the full code...the skeleton is down below: Note: Each file must contain an int...

    Please provide the full code...the skeleton is down below: Note: Each file must contain an int at the beginning, stating the number of records in the file. Afterwards, the number of records in the file will follow. Each record that follows will consist of a last name (String), and a gpa (double). However, to test the error handling of your program, the number of records will not always match the int value. All possible combinations should be tested. 1.) Prompt...

  • Using Merge Sort: (In Java) (Please screenshot or copy your output file in the answer) In...

    Using Merge Sort: (In Java) (Please screenshot or copy your output file in the answer) In this project, we combine the concepts of Recursion and Merge Sorting. Please note that the focus of this project is on Merging and don't forget the following constraint: Programming Steps: 1) Create a class called Art that implements Comparable interface. 2) Read part of the file and use Merge Sort to sort the array of Art and then write them to a file. 3)...

  • Write a C++ program named, gradeProcessor.cpp, that will do the following tasks: -Print welcome message -Generate...

    Write a C++ program named, gradeProcessor.cpp, that will do the following tasks: -Print welcome message -Generate the number of test scores the user enters; have scores fall into a normal distribution for grades -Display all of the generated scores - no more than 10 per line -Calculate and display the average of all scores -Find and display the number of scores above the overall average (previous output) -Find and display the letter grade that corresponds to the average above (overall...

  • The following are screen grabs of the provided files Thanks so much for your help, and have a n...

    The following are screen grabs of the provided files Thanks so much for your help, and have a nice day! My Java Programming Teacher Gave me this for practice before the exam, butI can't get it to work, and I need a working version to discuss with my teacher ASAP, and I would like to sleep at some point before the exam. Please Help TEST QUESTION 5: Tamagotchi For this question, you will write a number of classes that you...

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