python generation

Asked 1 years ago, Updated 1 years ago, 338 views

from itertools import product  
combis = []  
for i in range(1,5):  
   for j in product([x for x in range(1,5)], repeat=i):  
        combis.append(j)  

looping the cobis

The example code that failed to generate is shown at the top.
The modules at Eater Tools are generators, so I tried to use them well, but they didn't work.

In the end, the desired combis is as follows.

[1], [2], [3], ..[1,1], [1,2], [1,3], 
... 
[1,1,1], [1,1,2], [1,1,3]...[1,1,1,1], [1,1,1,2], ...

I eat a lot of memory unnecessarily.

How do I use this as a generator?

That's what I'm saying.

def combi():
    for i in range(1,5):
        for j in product([x for x in range(1,5)], repeat=i):
            yield(j)

I find a way to do it using the Eater Tools that I don't make.

python

2023-02-26 21:57

1 Answers

I don't know if what you want is right.

I made a generator using List Compensation grammar.

from itertools import product

combis = []

for i in range(1, 5):
    for j in product([x for x in range(1, 5)], repeat=i):
        combis.append(j)

# # print(combis)

combis2 = [j for i in range(1, 5) for j in product([x for x in range(1, 5)], repeat=i)]

for x, y in zip(combis, combis2):
    if x != y:
        print("diff")
else:
    print("same")

combis_gen = (j for i in range(1, 5) for j in product([x for x in range(1, 5)], repeat=i))

print(type(combis_gen))
combis_gen_listed = list(combis_gen)
# # print(combis_gen_listed)


for x, y in zip(combis, combis_gen_listed):
    if x != y:
        print("diff")
else:
    print("same")


2023-02-27 11:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.