Practice Makes Perfect - 13.Product



Recently started coding in python and I have a question about my code!

In the excercise Practice Makes Perfect - 13.Product you're asked to make a multiplication:

Define a function called product that takes a list of integers as input and returns the product of all of the elements in the list.

For example: product([4, 5, 5]) should return 100 (because 4 * 5 * 5 is 100).

Don't worry about the list being empty.
Your function should return an integer.

I solved this by doing:

def product(grades):
    score = grades[0]
    for x in grades[1:len(grades)]:
        score = score * x
    return score

print product([4, 5, 5])

But the unofficial answers have the following solution:

def product(x):
    t = 1
    for n in x:
        t *= n
    return t
print product([4, 5, 5])

I was wondering, as I move forward into coding, does the different ways of doing it matter?
Is my option a valid one as long as it works?
Are there any other tips regarding this topic?


I was wondering, as I move forward into coding, does the different ways of doing it matter?

Usually, yes. If you compare two solutions of the same problem you have to look at:

  1. Time complexity - indicator of the amount of time the given function will take to execute.
  2. Space complexity - similar to time complexity but indicates memory use.
  3. Readability - it's hard to remember how the given function works when you use variable names like a, something, wtr, remember that you will usually work in the group of developers.

There is also one more very important factor - speed of development. If you can use a one-liner to solve a pretty trivial problem - go for it! Python is so popular as a secondary language because you can really code in it really fast.

Few words about snippets that you posted. Your solution is slightly better. Time complexity of both solutions is the same, both are linear. Space complexity is also the same. Your solution is simply more readable, but it does not mean much because this is a trivial code, you will not have to refactor it, you will not have to add a new feature to this function.

And now the question - is this a trivial problem? I would say yes and I would just use reduce:

from operator import mul

reduce(mul, grades, 1)


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.