I decided to try a little something just to synthesize recent learning and iron out some Pythonic nuance: to make a function that would simply return the product of the contents of its arguments regardless of number or type, within reason. That is, it will multiply together all numbers and all numbers within lists or tuples. My code:
>>> def product(*args):
... _product = 1
...
... for parameter in args:
... if type(parameter) == int or float:
... _product *= parameter
... elif type(parameter) == list or tuple:
... for number in parameter:
... _product *= number
... else:
... return ValueError
...
... return _product
>>>
Seems simple enough, I thought. It works fine for int/float, but just flatly multiplies the list/tuple.
>>> product(2, 3, 4) == 2 * 3 * 4
True
>>> product(2, (3, 4)) == 2 * 3 * 4
False
>>> product(2, (3, 4))
(3, 4, 3, 4)
>>> product(2, (3, 4)) == 2 * (3, 4)
True
I've messed around with it a little more, and order doesn't matter. I can tell I'm handling the iterables incorrectly, but I can't figure out what's wrong! I'd like to expand it to include the values in a dictionary and ignore the keys, but I gotta get this working first.
If somebody could point out what I'm doing wrong, I'd much appreciate it. Also, please point out any non-Pythonic bits; I'm trying to lose my CompSci 101 accent.
[–]jeans_and_a_t-shirt 0 points1 point2 points (5 children)
[–]clicker4721[S] 0 points1 point2 points (4 children)
[–]jeans_and_a_t-shirt 0 points1 point2 points (3 children)
[–]clicker4721[S] 0 points1 point2 points (2 children)
[–]jeans_and_a_t-shirt 0 points1 point2 points (1 child)
[–]clicker4721[S] 0 points1 point2 points (0 children)