Question

36) 'readings.txt' is a file that contains 10,000 integer readings from a radiation counter. The lowest...

36) 'readings.txt' is a file that contains 10,000 integer readings from a radiation counter. The lowest reading should be 0. The radiation counter occasionally malfunctions and records a negative number Describe how you would write a segment of code that will determine how many times the radiation counter malfunctioned when making those 10,000 readings. How would you do it if you used a dictionary? How would you do it if you did not use a dictionary?

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

SOLUTION

Before I start I have assumed a few things that aren't mentioned in the problem which I'm specifying in the beginning. Since how the numbers are stored in the file i.e. the delimiter is not specified , I'm assuming that it's being separated by a ',' . Hence making readings.txt looks like : 1,2,3,4,... Therefore we will read the file using the open and split function :

f.read() reads the file content and store it in as a string while the split method splits the strings by using a delimiter, which is ',' in this case . So if the contents of file are 1,2,3,4,5 ,

f.read() will read it all as a single string as '1,2,3,4,5' and split() function will split this string by ',' and convert it to a list as ['1','2','3','4','5'] so its also important to convert all the numbers to int before performing any actions on them.

Code snippet for reading file

f=open("readings.txt","r")

for i in f.read().split(","):     

         #Do something

LOGIC

The questions asks us to count the number of negatives in the file , which is the number of malfunctions by the radiator.

1) USING DICTIONARY

my_dict={'negative':0}
for i in f.read().split(","):
    if int(i)<0:
        my_dict['negative']+=1
print(my_dict['negative'])

Dictionary in python consists of Key and Value(s). We are required to keep a count of negatives in our dictionary therefore I initialized a dictionary called 'my_dict' with a key value pair as 'negative' and 0. Negative is the key to the number of negatives in the text file and we will increase the number as soon we find more negatives in the file. For each element we type case it to int whose reason I've provided above and check if it's lesser than 0. If the number is less than 0 we perform an increment to the 'Negative' value of dictionary by 1 and check the other element. In the end the value for the key 'negative' will be the count of malfunctions happened by the radiator.

2) WITHOUT USING DICTIONARY

r=[int(i) for i in (f.read()).split(",")]
negative=len([i for i in r if i<0])
print(negative)

I've used list comprehension in this part a lot. As we know that the read() function read the contents of a file as a single string and then the split function splits the string by ',' and we get a list of elements which are numbers but are as strings i.e. ['1','2','3','4',....] .

Therefore to change them to integer I did that using list comprehension using:

r=[int(i) for i in (f.read()).split(",")]

It says that for i in the list ['1','2','3','4','5',....] , which is being processed by read() and split() function convert it to int(i) and put all of it in a list. The result are always written in the beginning that is int(i) in this case , then the loop and the conditions which is not present in this case. Therefore this statement will give us :

[1,2,3,4,5....]

Since now we have a list of integers we need to keep only those which are negatives and count them therefore again using list comprehension:

negative=len([i for i in r if i<0])

The statements says that we want the length of the list .The list is i for i in the list r and if the element i is less than 0 then keep it. The output we want is the element i and the loop is in the elements for r and condition is if i<0. It simply says make a list of those elements in r which are less than 0 and tell me the length / count of that list.

Complete Code for the problem

f=open("readings.txt","r")
#using dictionary
d={'negative':0}
for i in f.read().split(","):
    if int(i)<0:
        d['negative']+=1
print(d['negative'])
f=open("readings.txt","r")
#without using dictionary
r=[int(i) for i in (f.read()).split(",")]
negative=len([i for i in r if i<0])
print(negative)

Hope this helps!

Add a comment
Know the answer?
Add Answer to:
36) 'readings.txt' is a file that contains 10,000 integer readings from a radiation counter. The lowest...
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
  • Description: Create a program called numstat.py that reads a series of integer numbers from a file...

    Description: Create a program called numstat.py that reads a series of integer numbers from a file and determines and displays the name of file, sum of numbers, count of numbers, average of numbers, maximum value, minimum value, and range of values. Purpose: The purpose of this challenge is to provide experience working with numerical data in a file and generating summary information. Requirements: Create a program called numstat.py that reads a series of integer numbers from a file and determines...

  • Could anyone help add to my python code? I now need to calculate the mean and...

    Could anyone help add to my python code? I now need to calculate the mean and median. In this programming assignment you are to extend the program you wrote for Number Stats to determine the median and mode of the numbers read from the file. You are to create a program called numstat2.py that reads a series of integer numbers from a file and determines and displays the following: The name of the file. The sum of the numbers. The...

  • IN JAVA PLEASE HELP! ALSO PLEASE ADD COMMENTS Summary Build two classes (Fraction and Fraction Counter)...

    IN JAVA PLEASE HELP! ALSO PLEASE ADD COMMENTS Summary Build two classes (Fraction and Fraction Counter) and a Driver for use in counting the number of unique fractions read from a text file. We'll use the ArrayList class to store our list of unique Fraction Counters. Rather than designing a monolithic chunk of code in main like we did in the previous homework, we'll practice distributing our code into containers (called classes) that you will design specifically to tackle this...

  • CIST 1305 Unit 07 Drop Box Assignment The Assignment ONLY ONE FILE may be turned in for the assig...

    CIST 1305 Unit 07 Drop Box Assignment The Assignment ONLY ONE FILE may be turned in for the assignment. If you make a mistake and need to turn in your work again, you may do so. I will only grade the latest file you turn in. The older ones will be ignored. For instruction on How To do assignments and create the file see the "How To Do Homework" document under the "Start Here" button. You will create a word...

  • Using C++ emulate a sign in procedure. At this stage we do not have a file...

    Using C++ emulate a sign in procedure. At this stage we do not have a file yet that contains those username and password records. You'll hard code a user name and password, and using selection and some string manipulation or comparison you'll go through the sign in process with your user. Some things to consider are: Let us know where we're signing in. Other interactions return to you a black screen with little other than a cursor. How is your...

  • 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="";       ...

  • Language c++ 9.10 Money from File This exercise will read 3 fields from a file for...

    Language c++ 9.10 Money from File This exercise will read 3 fields from a file for an unknown number of rows. It mimics the listing of dollar bills of a particular denomination that belongs to a certain person. The following data read will be read in the following order: wallet owner,number of bills,denomination of bill The wallet owner will be a string, the number of bills and denomination will be ints. Further, the denominations will always be 0,1, 2, 5,...

  • Program 7 File Processing and Arrays (100 points) Overview: For this assignment, write a program that...

    Program 7 File Processing and Arrays (100 points) Overview: For this assignment, write a program that will process monthly sales data for a small company. The data will be used to calculate total sales for each month in a year. The monthly sales totals will be needed for later processing, so it will be stored in an array. Basic Logic for main() Note: all of the functions mentioned in this logic are described below. Declare an array of 12 float/doubles...

  • ****PLEASE CODE IN C++ and line doc explaining what is happening!***** **HERE IS THE INPUT FILE(.txt)*****...

    ****PLEASE CODE IN C++ and line doc explaining what is happening!***** **HERE IS THE INPUT FILE(.txt)***** Ottawa Senators New York Rangers Boston Bruins Montreal Canadiens Montreal Canadiens Toronto Maple Leafs New York Rangers Chicago Blackhawks Montreal Maroons Detroit Red Wings Detroit Red Wings Chicago Blackhawks Boston Bruins New York Rangers Boston Bruins Toronto Maple Leafs Detroit Red Wings Montreal Canadiens Toronto Maple Leafs Montreal Canadiens Toronto Maple Leafs Toronto Maple Leafs Toronto Maple Leafs Detroit Red Wings Toronto Maple Leafs...

  • Question 2: Finding the best Scrabble word with Recursion using java Scrabble is a game in...

    Question 2: Finding the best Scrabble word with Recursion using java Scrabble is a game in which players construct words from random letters, building on words already played. Each letter has an associated point value and the aim is to collect more points than your opponent. Please see https: //en.wikipedia.org/wiki/Scrabble for an overview if you are unfamiliar with the game. You will write a program that allows a user to enter 7 letters (representing the letter tiles they hold), plus...

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