0

I wonder I can improve my python code to be written shorter. I only use standard library and numpy library. Here is the code.

import numpy as np
x=1
y=2
np.array([(a,b,c) for a in [x,y] for b in [x,y] for c in [x,y]])

As you can see, this program produces all three combinations of elements. There is a similar part in this program like for a in [x, y] and can it be written shorter?

[Edited]

I want to use only standard library and numpy library.

The inputs should be any values like x=3, y=8.

shmpwk
  • 55
  • 1
  • 2
  • 9
  • 1
    Does this answer your question? [Numpy: efficient way to generate combinations from given ranges](https://stackoverflow.com/questions/27286537/numpy-efficient-way-to-generate-combinations-from-given-ranges) – some_programmer Apr 24 '20 at 16:04
  • [Numpy: efficient way to generate combinations from given ranges](https://stackoverflow.com/questions/27286537/numpy-efficient-way-to-generate-combinations-from-given-ranges) is similar in generating a combination of all values. But their input values are continuous number. I want to use any values as input. (I forgot to write this condition in my question, sorry.) – shmpwk Apr 25 '20 at 05:49
  • Based on a similar question [Junkrat](https://stackoverflow.com/users/11135962/junkrat) suggested, I come up with the idea. I wrote the code as one of the answer. – shmpwk Apr 25 '20 at 06:11

2 Answers2

4

Use itertools.product:

from itertools import product

# ...
np.array(list(product((x, y), repeat=3)))
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Honestly I'm not sure this would improve performance by much since you still do a `list(product(...))` i.e a loop comprehension. – Quang Hoang Apr 24 '20 at 16:25
  • Performance was never the issue. Even if `numpy.array` accepted any iterable, it would have to iterate it to create the array. – user2390182 Apr 24 '20 at 16:39
  • But I'm sorry that I was supposed to use only standard library and numpy library, but I could not specify it. – shmpwk Apr 25 '20 at 05:41
  • I mistakenly think that itertools is not in the standard python library, but it is. So, using itertools may be the simplest way now. – shmpwk Jun 23 '20 at 06:35
0

Based on a similar question Junkrat suggested, I come up with the idea. (But it is not simple.)

import numpy as np
x=1
y=2
a = np.array(np.meshgrid([x, y], [x, y], [x, y]))   
a = np.rollaxis(a, 0, 4)         
a = a.reshape((2*2*2, 3))  
shmpwk
  • 55
  • 1
  • 2
  • 9