1

So I have two lists:

  • typeList — list of strings of transaction types (addition, subtraction)
  • valueList — List of values either added or subtracted.

as both value and type are appended to the list at the same index, I need to make a function to calculate the sum of the total value added and the total value subtracted, but I've been really stuck on it for ages trying to get my head around just how to do it. desiredType is just the type of transaction that is being looked for. As you'll see, I called my function twice with each type. I understand that the index values need to be obtained and used between the two lists but not sure how to sum the values up.

def showInfo(typeList, valueList, desiredType):
     for i in range(len(valueList)):
         if typeList[i] == desiredType:
             total = total + valueList[i]
             return (total)

Call to the function:

 if choice == "I": #Prints transaction information
     print (showInfo(transactionTypes,transactionAmounts, "Addition"))
     print (showInfo(transactionTypes,transactionAmounts, "Subtraction"))

Any help would be appreciated as well as an explanation on how it's done.

4castle
  • 28,713
  • 8
  • 60
  • 94
ytkjxgfn
  • 21
  • 3

2 Answers2

1

You can zip together those 2 lists, then you don't have to keep track of the index you're looking at:

def transaction_total(types, amounts, desired_type):
    total = 0
    for transaction_type, amount in zip(types, amounts):
        if transaction_type == desired_type:
            total += amount
    return total

However, you're really just filtering values and summing them. Python makes this cleaner using generator expressions and the sum function:

def transaction_total(types, amounts, desired_type):
    return sum(amount for transaction_type, amount in zip(types, amounts)
               if transaction_type == desired_type)
Peter Wood
  • 21,348
  • 4
  • 53
  • 90
0

If you need to keep your data unmodified, you can just make your function more efficient (just one call) :

def showInfo(typeList, valueList):
     for i in range(len(valueList)):
         if typeList[i] == "Addition":
             total_add = total_add + valueList[i]
         else:
             total_sub = total_sub - valueList[i]
     return (total_add, total_sub)
jumpy
  • 120
  • 5