Search code examples
pythonjython

multiplication of non integer and integer in a list


Write a program to keep track of how much profit you make. You make $0.25 on each apple, $0.50 on each orange, $0.75 on each banana, and $0.35 on each strawberry. Return an integer representing the profit of fruits.

This is what I did and I received the error was: can't multiply sequence by non-int of type 'float'

def sellFruits(fruits):
  fruitL = []
  a = [0] * .25
  o = [1] * .50
  b = [2] * .75
  s = [3] * .35
  totalFruitProfit = a + o + b + s
  return totalFruitProfit

Test case:

fruits = [1, 1, 1, 1]
profit = sellFruits(fruits)
print profit
1.85

Solution

  • I think what you're looking for is:

    def sellFruits(fruits):
      a = fruits[0] * .25
      o = fruits[1] * .50
      b = fruits[2] * .75
      s = fruits[3] * .35
      totalFruitProfit = a + o + b + s
      return totalFruitProfit
    

    There were several things you were doing that didn't really make sense:

    • You weren't using the fruits parameter anywhere
    • You were creating fruitL = [] and then doing nothing with it
    • [0] * .25 is creating a list, with one item (an integer 0), and trying to multiply that sequence1 by .25. If you were trying to index some list, it wasn't happening.

    So I added fruits before each set of brackets. This way, you're accessing the 0th, 1st, etc. item of the fruits list being passed to sellFruits.

    Note the difference in what I changed:

    • [0] creates a list, with one item, 0.
    • fruits[0] accesses the first item in list (or any sequence, tuple, ...) fruits.

    1 - Multiplying a sequence by an integer duplicates the sequence that many times. [0] * 4, for example, yields [0,0,0,0].