-1

I can't seem to figure out how to get the sum of the values insisde the list/tuples

I've tried using keys and a few other methods, none of which work

#initialise variables
products = []
totalCost = 0.0


#input products and prices funtions
def getInput():
    product_name = input("What is the product?")
    product_price = input("What s the price?")

    return (product_name, product_price)

#collect input
for x in range(5):
    product = getInput()
    products.append(product)

#sort list
products.sort(key=lambda t: t[1], reverse=True)


#show list
def showTable():
    for x in range(5):
        print("Product Name | Price: ", products[x])

#calculate cheapest
def cheapestItem():
    print("The cheapest item in this list is: ", min(products, key = lambda t: t[1]))
    print("Congratulations you get this item free")

    #calculate total
    totalCost = sum(products[1]) - min(products[1])


#main
showTable()
cheapestItem()

I want to get the sum of the prices and subtract the smallest amount from that list.

4 Answers4

1
products = [('a',1),('b',2),('c',30),('d',10),('e',5)]

totalcost = sum([x[1] for x in products]) - min(products, key=lambda x:x[1])[1]

print(totalcost)
Nishant
  • 20,354
  • 18
  • 69
  • 101
1

You have several problems:

You do not have numbers, only strings:

def getInput():
    product_name = input("What is the product?")   # string
    product_price = input("What s the price?")     # string

    return (product_name, product_price)

Fix (just the price input part):

      while True:
          try: 
              product_price = int(input("What s the price?"))
              if product_price <= 0:
                  raise ValueError
              break
          except ValueError:
              print("Not a valid price")

See Asking the user for input until they give a valid response to see other methods how to avoid ValueErrors.

As long as you do not have numbers, '1000' will be less then '2' (alphabetical comparison).

Your cheapest item calculations does not do what it is supposed to do:

Even if you fix your products to have numbers, your totalCost does not work:

product[1] # this is the 2nd element of your list - not the price of it


def cheapestItem():
    print("The cheapest item in this list is: ", min(products, key = lambda t: t[1]))
    print("Congratulations you get this item free")

    #calculate total
    totalCost = sum(products[1]) - min(products[1])

Fix (f.e.):

   # assumes numbers in ("icecream", 42) - not strings
   sortedItems = sorted(products, lambda x:x[1])  # sort by price ascending

   minItem   = sortedItems[0]
   totalCost = sum(item[1] for item in sortedItems[1:])   # don't calc the lowest value
   totalCost = sum(products[1]) - min(products[1])

Using min() would work as well, but by sorting you can use list slicing to sum all but the lowest. If you have huge lists - min() is more optimal:

   minItem = min(products, lambda x:x[1])
   total = sum(item[1] for item in products) - minItem[1]  # reduced by minItems cost

I fixed the code to use parameters provided to the functions and not a global one - also there is no need to min() the products list because you sort it anyway - you can simply slice away the lowest item and deduct its value:

Fixed code & example input:

def getInput():
    product_name = input("What is the product? ")
    while True: 
        try:
            # whole number prices assumed, else use float( input ( ... ))
            product_price = int(input("What s the price? "))
            if product_price <= 0:
                raise ValueError
            break
        except ValueError:
            print("Wrong input - prices must be greater 0 and whole numbers")

    return (product_name, product_price)

def showTable(p):
    for x in p:
        print("Product Name | Price: ", x[0],x[1])

def cheapestItem(p):
    # assumes sorted list of items in p
    print("The cheapest item in this list is: ", p[-1])
    print("Congratulations you get this item free")

    #calculate total
    totalCost = sum(i[1] for i in p[:-1])
    print("Total Cost:", totalCost, "You saved:", p[-1])


products = [] 
for x in range(5):
    product = getInput()
    products.append(product)

# sort list - cheapestItem(..) needs a sorted input to work
products.sort(key=lambda t: t[1], reverse=True)

showTable(products)
cheapestItem(products)

Output:

What is the product? apple
What s the price? 22
What is the product? pear
What s the price? 11
What is the product? kiwi
What s the price? 5
What is the product? pineapple
What s the price? no idea
Wrong input - prices must be greater 0 and whole numbers
What s the price? 100
What is the product? gears
What s the price? 1

Product Name | Price:  pineapple 100
Product Name | Price:  apple 22
Product Name | Price:  pear 11
Product Name | Price:  kiwi 5
Product Name | Price:  gears 1
The cheapest item in this list is:  ('gears', 1)
Congratulations you get this item free
Total Cost: 138 You saved: ('gears', 1)
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

Try this:

#initialise variables
products = []
totalCost = 0.0


#input products and prices funtions
def getInput():
    product_name = input("What is the product?")
    product_price = int(input("What s the price?"))

    return (product_name, product_price)

#collect input
for x in range(5):
    product = getInput()
    products.append(product)

#sort list
products.sort(key=lambda t: t[1], reverse=True)


#show list
def showTable():
    for x in range(5):
        print("Product Name | Price: ", products[x])

#calculate cheapest
def cheapestItem():
    print("The cheapest item in this list is: ", min(price))
    print("Congratulations you get this item free")


price = []
for i in range(len(products)):
    price.append(products[i][1])

totalCost = sum(price) - min(price)
print(totalCost)

#main
showTable()
cheapestItem()

You can't pass a list of tuples to sum(). It take a list of numbers.

Heyran.rs
  • 501
  • 1
  • 10
  • 20
-1

If I got this right, this should work:

products.remove(min(products))
print(sum(products)) 
Nishant
  • 20,354
  • 18
  • 69
  • 101
Atom
  • 28
  • 5