Question

In: Computer Science

File density.txtPreview the document contains a list of the density in grams per cubic centimeter of...

File density.txtPreview the document contains a list of the density in grams per cubic centimeter of all the planets, plus Pluto. It looks like this: Mercury 5.43 Venus 5.25 Earth 5.52 Mars 3.83 Jupiter 1.33 Saturn 0.71 Uranus 1.24 Neptune 1.67 Pluto 2.05 Write a program named lastname_firstname_density.py that reads the numbers from the file into a list and then calculates and prints, properly labeled: The minimum density The maximum density The average density The median density (Hint: use split() to separate the planet name from the density.) You don’t need a list for the first three of these, but you do need a list to calculate the median. Finding the Median To find the median of a group of n numbers, sort them into order. (Hint: use Python’s sort method). If n is odd, the median is the middle entry. In a list named data this will be element data[(n ‑ 1) // 2]. Note the use of // to do integer division. If n is even, the median is the average of the numbers “surrounding” the middle. For a list named data, this is (data[(n // 2)] + data[(n // 2) ‑ 1]) / 2.0. Your program must work for a file with any number of entries. The file I am providing happens to have an odd number of entries, but if I gave you a similar file for the major moons of Saturn, it would have an even number of entries, and your program would still have to correctly calculate the statistics for that file.

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.

#code

# main method
def main():
    # opening density.txt file. change filename as you like. make sure file exist on the
    # same directory
    file = open('density.txt', 'r')
    # initializing an empty list
    data = []
    # and required variables
    min_density = 0
    max_density = 0
    sum_density = 0
    avg_density = 0
    median_density = 0
    # looping through each line in file
    for line in file:
        # splitting line by ' '
        fields = line.strip().split(' ')
        # ensuring that resultant list has length 2 (planet name and density)
        if len(fields) == 2:
            # parsing second value as density
            density = float(fields[1])
            # appending to list
            data.append(density)
            # if this is first entry, setting this as both min and max
            if len(data) == 1:
                min_density = density
                max_density = density
            else:
                # otherwise updating min and max if needed
                if density > max_density:
                    max_density = density
                if density < min_density:
                    min_density = density
            # adding this to sum
            sum_density += density
    # closing file
    file.close()
    # finding average if count>0
    if len(data) > 0:
        avg_density = sum_density / len(data)
    # sorting the list
    data.sort()
    # if number of elements in data is odd, choosing middle element as median
    if len(data) % 2 != 0:
        median_density = data[len(data) // 2]
    # otherwise finding average of middle two values
    else:
        median_density = (data[(len(data) // 2)] + data[(len(data) // 2) - 1]) / 2.0
    # printing all stats
    print('The minimum density:', min_density)
    print('The maximum density:', max_density)
    print('The average density:', avg_density)
    print('The median density:', median_density)


# calling main()
main()

#output

The minimum density: 0.71
The maximum density: 5.52
The average density: 3.003333333333333
The median density: 2.05

#code screenshot


Related Solutions

Colas per week Bone Mineral Density (grams per cubic centimeter) 0 0.907 0 0.896 1 0.881...
Colas per week Bone Mineral Density (grams per cubic centimeter) 0 0.907 0 0.896 1 0.881 1 0.870 2 0.853 2 0.835 2 0.836 3 0.816 4 0.789 5 0.767 5 0.762 6 0.733 7 0.704 7 0.714 7 0.710 The​ least-squares regression line treating cola consumption per week as the explanatory variable... A) Y with caret = ___x + (___) B) Interpert the slope ___ C) Interpret the​ y-intercept? D) Predict the bone mineral density of the femoral neck...
1. Calculate the number of atoms per cubic centimeter of lead given that the density of...
1. Calculate the number of atoms per cubic centimeter of lead given that the density of lead is 11.3 ?/??3 and its atomic weight is 207.21. 2. Calculate the ionization potential of a singly ionized ?? 4 atom. 3. (a) How much energy would be released if 1 g of deuterium were fused to form helium according to the equation 2? + 2? → ?? 4 + ?? (b) How much energy is necessary to drive the two deuterium nuclei...
Calculate the number of free electrons per cubic centimeter (and per atom) for sodium from resistance...
Calculate the number of free electrons per cubic centimeter (and per atom) for sodium from resistance data (relaxation time 3.1*10-14 s)
Calculate the number of photons per cubic centimeter inside a cavity whose walls are heated to...
Calculate the number of photons per cubic centimeter inside a cavity whose walls are heated to 3000 K. Compare this to the corresponding number at 3 K.
The density of balsa wood is 18.9 pounds per cubic ft. What is the weight, in...
The density of balsa wood is 18.9 pounds per cubic ft. What is the weight, in kg, of a piece of balsa wood 2.0 inches by 4.0 inches by 10.0 inches?
The file Cereals contains the calories and sugar, in grams, in one serving of seven breakfast...
The file Cereals contains the calories and sugar, in grams, in one serving of seven breakfast cereals: Cereal                                                             Calories                             Sugar Kellogg’s all Bran                                         80                                       6 Kellogg’s Corn Flakes                                  100                                     2 Wheaties                                                        100                                     4 Nature’s path Organic Multigrain Flakes 110                                     4 Kellogg’s rice Krispies                                 130                                     4 Post Shredded Wheat Vanilla almond       190                                     11 Kellogg’s Mini Wheats                                200                                     10 a. Compute and interpret the coefficient of correlation, r. b. at the 0.05 level of...
For every course, what document contains a list of the knowledge and skills that you are...
For every course, what document contains a list of the knowledge and skills that you are expected to have for each exam? What particular items should you look for on that document to get an idea of what content is going to be on your exam?
Calculate the density, in grams per liter, of a gas at STP if 3.16 L of...
Calculate the density, in grams per liter, of a gas at STP if 3.16 L of the gas at 28.5 °C and 734.2 mmHg weighs 0.269 g
Calculate the density, in grams per liter, of a gas at STP if 3.16 L of...
Calculate the density, in grams per liter, of a gas at STP if 3.16 L of the gas at 28.5 °C and 734.2 mmHg weighs 0.269 g.
the density of crystalline gypsum is 2.32 g per cubic centimetre. What volume of gypsum is...
the density of crystalline gypsum is 2.32 g per cubic centimetre. What volume of gypsum is generated per year? ( Infact the volume is several times larger because of the porosity of the gypsum produced)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT