Okay, here is another freebie :) I will put in a real one before the end of the weekend.

Basically, you are given a list from which you need to create a new list where each element is the product of all the "OTHER" elements.

I found a few interesting corner cases.

I challenge you to give it a try!

Read the challenge here:

git.qoto.org/Absinthe/productn

My attempt is checked into that repo as well.

A Python solution 

@Absinthe Here is my no-division solution:

```
#!/usr/bin/env python
from collections import deque
from functools import reduce
from random import randint

def get_product_and_rotate(d):
"""Gets product of all but the first items in the queue"""
prod = reduce(lambda a, b: a * b, list(d)[1:])
d.rotate(-1) # Rotates left so that the next
return prod

if __name__ == "__main__":
n_items = randint(2, 10)
input_list = [randint(0, 9) for _ in range(n_items)]
print(input_list)
product_queue = deque(input_list)
print([get_product_and_rotate(product_queue) for _ in input_list])
```

Uses `reduce` for the multiplication, and uses a `deque` (double-ended queue) to rotate the list. I've read that using a deque is actually more efficient than just taking slices out of the list.

A Python solution 

@zingbretsen What about this... as a one liner:

[reduce(lambda a, b: a *b, [ y for x, y in enumerate(list) if x != idx]) for idx, _ in enumerate(list)]

A Python solution 

@zingbretsen This works...

print("One Liner no division")
print([reduce(lambda a, b: a *b,
[ y for x, y in enumerate(random_list) if x != idx])
for idx, _ in enumerate(random_list)])

It's a one liner, except I am sticking to 80 columns so I split it a few times.. still calling it a one liner :)

A Python solution 

@Absinthe looks good.

I'll try to do something with the dynamic programming approach tomorrow or Monday.

For something like multiplication, I don't think it will make much of a difference in the execution time, but for a more expensive operation it would

Follow

A Python solution 

@zingbretsen am pretty sure there is no technical reason not to use division, just to make the problem more complicated. I am getting ready to put up a new one. But feel free to keep playing with this one. I got a new one today, but it seems a little "specific" because they give a python code starting point, and want you to serialize and deserialize a binary tree. I will likely not put that one up as a freebie. Especially since I want to get the new real on up.

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.