H. Raydon
H. Raydon

Reputation: 133

Python; If statements, For Loops, File Reading

To be clear, I am not asking anyone to do this for me. I am simply asking a question seeking guidance so I can continue working on this.

We are given a file that gives various weights of packages;

11
25
12
82
20
25
32
35
40
28
50
51
18
48
90

I have to create a program that will count the amount of packages, Categorize them into Small, Medium, and Large, and find the average of the weights. I know I have to use If statements, and for loops to accumulate the weight count and categorize them among each category.

The terms for what is small, med, and large is as follows;

Small < 10 lbs

Medium >= 10 lbs. and < 30 lbs

Large >= 30 lbs.

If no packages of a weight class are entered, report the message “N/A” instead of an average (if you try to divide by 0 you will get an exception).

This is the code I have so far, I cant figure out if I have to include a for loop after the if, elif, and else. Or if what I have is on track.

infile = open("packages.txt", 'r')
count = 0
line = infile.readline()
weight = int(line)
for line in infile:
    if weight < 10:
        count = count + 1
        weight = weight + int(line)
        while weight < 10:
            try:
                avg = weight / count
            except ValueError:
                print("N/A")
    elif weight >= 10:
        if weight < 30:
            weight = weight + int(line)
            count = count + 1
            avg = weight/count
    else:
        weight = weight + int(line)
        count = count + 1
        avg = weight/count

The output has to look something like this

Category    Count    Average
Small       0        N/A
Medium      7        19.9
Large       8        53.5

Again, I am not looking for someone to do this for me. I am looking for the next step and/or tweaks to what I currently have to be able to continue forward. Thank you!

Upvotes: 1

Views: 2210

Answers (3)

Iulian
Iulian

Reputation: 300

First thing I think is better to use with statement when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.

In other words you don't need to call close() method on the file object and you are sure that in case of an exception raise is closed.

So

infile = open("packages.txt", 'r')
#operations on file
...
infile.close()

will be better to use

with open("packages.txt",'r') as infile:
    #following operation 
    #on infile like reading

Average computing

For this operation, you can use a dictionary. This is a map data structure, a set of key,value pairs where key need to be strings (in your case "small","medium","large") and value can be a simple type or another data structure like list,dictionary or object.

While reading the file you will populate the lists with the weights based on if conditional and at the end you can use the the free lists and compute the average using sum() and len().

packages = {"small": [],
            "medium": [],
            "large": []}

with open("packages.txt","r") as packs:
    for pack in packs:
        weight = int(pack)
        if weight < 10:
            packages["small"].append(weight)
        elif weight < 30:
            packages["medium"].append(weight)
        else:
            packages["large"].append(weight)
###Printing the the average###
table_row = "%s\t%i\t%s" # string for formatting output, not the best solution
for key,weights in packages.items():
    print(table_row % (key, len(weights), averageValues(weights)))

Where averageValues() is the following function, that computes the average and return it like a string by how many decimals we want.

def averageValues(values,decimals=1):
    float = "%." +  str(decimals) + "f"
    try:
        avg = sum(values)/len(values)
        return float % avg
    except:
        return "N/A"

Read answers to this question to understand how have an ordered representation of the dictionary, that is an unordered data structure.

Upvotes: 1

PushpikaWan
PushpikaWan

Reputation: 2545

maintain 3 variable to count 3 ranges like weight1Sum,weight2Sum,weight3Sum and initialize it to zero at the very first like weight1Sum = 0

your count variable is ok. You need to add value for weight when it is in range. Then u can divide related weightSum from count to display relevant value.

generally, you need to maintain 3 weights according to the range and update it.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409196

To begin with you need three weight and count variables: One for each category.

Then your reading for the file is a little flawed. Don't start by reading a line, instead just have the loop and assign to weight inside the loop the first thing you do.

Perhaps something like this:

total_small = 0
total_medium = 0
total_large = 0
count_small = 0
count_medium = 0
count_large = 0

for line in infile:
    weight = int(line)

    if weight < 10:
        total_small += weight
        count_small += 1
    # And the same for medium and large as well...

Then after the loop you can easily calculate the average of each category as you print it.

Oh, and you don't check for the upper limit of medium packages, which you need to do.

Upvotes: 0

Related Questions