YNWA1992 - 6 months ago 21

Python Question

I have a set, which contains n sets of prime numbers(3):

`>>> sets`

{frozenset({3, 13, 23}), frozenset({17, 2, 13}),

frozenset({19, 2, 3}), frozenset({3, 29, 23}), frozenset({17, 11, 23}),

frozenset({17, 2, 19}), frozenset({11, 17, 3}), frozenset({17, 5, 7})}

I want to create the dictionary with values: prime numbers-triple and keys: the product of three prime numbers.

This is my attempt:

`lists = [list(i) for i in sets]`

products = [reduce(lambda x,y:x*y,i) for i in lists]

dictir = {x:y for x in products for y in sets}

But dictir gives me incorrect result:

`{897: frozenset({17, 5, 7}), 114: frozenset({17, 5, 7}), 595: frozenset({17, 5, 7}), 561: frozenset({17, 5, 7}), 646: frozenset({17, 5, 7}), 2001: frozenset({17, 5, 7}), 442: frozenset({17, 5, 7}), 4301: frozenset({17, 5, 7})}`

Can you help me to correct this?

Answer

You may use `zip()`

but another, more efficient approach would be this:

```
import operator
tuples = ((reduce(operator.mul, i), i) for i in sets)
dictir = dict(tuples)
# Or as a 1 liner
dictir = {reduce(operator.mul, i): i for i in sets}
```

Source (Stackoverflow)

Comments