ytkjxgfn
ytkjxgfn

Reputation: 21

Function problems

So I have two lists:

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.

Upvotes: 1

Views: 80

Answers (2)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

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)

Upvotes: 1

jumpy
jumpy

Reputation: 126

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)

Upvotes: 0

Related Questions