mmmaceo
mmmaceo

Reputation: 151

Sum of combined elements from a file

I'm pretty new to Python and I'm stuck in building the logic for my program. I want to learn, but I feel I need some external help. Maybe you guys can help me. This is Homework/Project.

The list (SalesData.txt) looks like this:

And it continues for at least 5 different names. But for the example, this will do.

Basically, I need to come up with a TOTAL of all the numbers and then, a total for every name.

Output :: In this case (using example)

  1. Grand Total = 934 (sum of all the numbers)
  2. Name 1 Total = 511 (sum of numbers for Name 1)
  3. Name 2 Total = 423 (sum of numbers for Name 2)

I know how to get a total sum of a file containing ONLY numbers, but when it comes to a mixture I'm very confused. Also, how can I specified in getting the Total of every single "name". should I use the .isdigit() and .isalpha() to tell the list when to sum and when to not sum?

Any advise will help me! thanks!

UPDATE This is my code so far:

data = []
data = open("SalesData.txt").read().split()
    for i in data:
        s = sum([ float(i) ])
print "Sum=" , s
print "Avg="  , s/len(data)

This only works if the file is all NUMBERS, that's pretty easy to sum the contents.but remember, I'm dealing with a String every 12 numbers. I'm trying to figure how to just do the sum only when it finds a line with a float.

Update #2

I would still like some guidance! I'm beginning to wrap things up in my own way, but I find some very basic trouble (I'm sure)

data = []
data = open("SalesData.txt").read().split()
    for i in data:
        if str(i):
            print 'This one is Letter'
        elif float(i):
            s = sum([ float(i) ])
print "Sum=" , s
print "Avg="  , s/len(data)

I know this example doesn't work and I want to know why. I'm trying to analyze the list. IF 'i' is a string, the program will (in this example print 'Letter') if it's not a string, it will do the regular sum of numbers. I'm taking this program one piece at the time, I want to be able to get a total sum of numbers using the mixed provided list, but I'm stuck in the aspect of analyzing the strings as strings and floats as floats.

Upvotes: 1

Views: 934

Answers (4)

Dave L.
Dave L.

Reputation: 199

Note that .isdigit() will return False if you have a non-integer or negative value (e.g. 342.2 or -342), so that may not be a good mechanism to use.

As Kreativitea noted, int() may be used to discern words from numbers (integers, specifically), but consider that float() would work in the more general case when the numbers may be integer or floating point.

Upvotes: 3

Karl Knechtel
Karl Knechtel

Reputation: 61635

Regarding update #2: there are several logical problems here.

First off, if str(i): does not mean "if i is a string, ...". It means "create a string from i; now, if the resulting string is non-empty, ...".

Second, i comes from data, which is a list of lines of the file. So it must be a string. That's what you get when you read a file. No attempt is made to interpret the various symbols as numbers until you tell the program to.

Third, when such a conversion fails, it will fail by raising an exception. You cannot test for that with an if block. You must use try/except exception handling.

Fourth, you are trying to calculate s every time you get a number, using a one element list with just that number. That's not going to give you a sum of all the numbers. If you wan to sum several numbers, you have to put the numbers together somewhere first.

Fifth, you use len(data) as the count of numbers to divide the sum by. This is wrong since that is the number of lines in your file, and you've already said that some of them might be excluded. You want to count up just the numbers, which again requires putting that list together first.

Write something that can give you the list of numbers first, and then it is a simple matter of using sum and len with that list (once each, outside of the loop).

Upvotes: 0

Lev Levitsky
Lev Levitsky

Reputation: 65831

Assuming the names are unique, you can fill a dict from the file so that keys are names and values are lists of numbers. Then it'll be easy to get sum for each item and also a sum of sums.

To build a dict, you need to put together a simple parser. For instance:

def parse(fname):
    data = {}
    numbers = []
    for line in f:
       # figure out if line has name or number
       if ... # this is a number
           numbers.append(float(line))
       else:
           data[name] = numbers
    return data

This is not full code, because it's a homework question. Also note that you probably need to correctly take care of the very first name you read on the first line.

Upvotes: 0

kreativitea
kreativitea

Reputation: 1791

Since this is homework, I will just give general guidelines.

  1. You don't need to use isdigit or isalpha. What happens when you try to use an int() on something that isn't an integer? Okay, now you have a process that discerns between the two groups.
  2. Will the list of numbers always have the same number of items after it? If not, a while loop might be a good idea.
  3. In either case, what quality does the data have, as in, describe the data in abstract terms. What data structures maps well to that kind of data?
  4. Break up the process; it's better to create two functions that are easy to read than one function that's difficult to read.

Good luck. :)

Upvotes: 2

Related Questions