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.

Follow

A Python solution 

@zingbretsen now you are stretching me. I have never seen rotate() but I can intuit what it does. I also have not used lamda's. But what is happening in the reduce() call? I assume the lamda takes 2 values how is that acting on the list? Or is the lamda being passed into the reduce call ... time to read about reduce :)

@Absinthe book.pythontips.com/en/latest/

I think that gives a good breakdown of map, filter, and reduce, which are common in functional programming.

@Absinthe The lambda is basically an anonymous function. It's passed in to the reduce call. Reduce calls that repeatedly until you're left with only one value.

@zingbretsen yeah, I looked it up. Works nice, perhaps I will try it with the list comprehension that I suggested.

@Absinthe Yeah, MapReduce is (well, was) pretty widely used for "big data" processing

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.