Question to put 2D array variables... (I want to code it so that it doesn't overlap!)

Asked 2 years ago, Updated 2 years ago, 48 views

Hello! I'm Python beginner.

The value of n,s,t,k as a variable in an array such as a n : 20~28/s,t,k : 20~27 I calculated the number of all cases and printed it out with a txt file called Noutput using the sys module.

Here, I want to code so that n, s, t, and k do not overlap each other (for example, if n=20, s, t, k! = 20), but it's too hard. I'd appreciate your help.

import sys

sys.stdout = open('Noutput.txt','w')

n=0
s=0
t=0
k=0   
a=[
  [0,   0,   0,   0,   0,   0,   0,  n],
  [0,   0,   0,   0,   0,   0,   0,  s],
  [0,   0,   0,   0,   0,   0,   0,  t],
  [0,   0,   0,   0,   0,   0,   0],
  [0,   0,   0,   0,   0,   0,   k],
  [0,   0,   0,   0,   0,  27],
  [0,   0,   0,   0, k+1],
  [n, s+1, t+1],
]

for n in range(20,28):
    a[0][7] = n
    a[7][0] = n
    for s in range(20,27):
        a[1][7] = s
        a[7][1] = s+1
        for t in range(20,27):
            a[2][7] = t
            a[7][2] = t+1
            for k in range(20,27):
                a[4][6] = k
                a[6][4] = k+1
                for i in a:
                    for j in i:
                        print(j,end=' ')
                    print()

sys.stdout.close()

python list permutation

2022-09-22 18:10

1 Answers

I think you can use permutations from itertools.

For a simple example, let's say you take two out of 20, 21, 22 and say n, s, respectively. If you do this using itertools permutations:

from itertools import permutations
for a, b in permutations([20, 21, 22], 2):
    print(a, b)

Results

20 21
20 22
21 20
21 22
22 20
22 21

Now what you want is, [20, ..., 28], you take four out of each of these, n, s, t, k. However, if s, t, and k are 28, you can just move on.

from itertools import permutations

f = open('noutput.txt', 'w')

for n, s, t, k in permutations(range(20, 29), 4):
    if 28 in (s, t, k): continue
    a = build_data(n, s, t, k)
    write_data(f, a)
f.close()   

OK?

The build_data and write_data used in the above code are as follows.

def build_data(n, s, t, k):
    return [
        [0,   0,   0,   0,   0,   0,   0,  n],
        [0,   0,   0,   0,   0,   0,   0,  s],
        [0,   0,   0,   0,   0,   0,   0,  t],
        [0,   0,   0,   0,   0,   0,   0],
        [0,   0,   0,   0,   0,   0,   k],
        [0,   0,   0,   0,   0,  27],
        [0,   0,   0,   0, k+1],
        [n, s+1, t+1],
    ]

def write_data(f, a):
    for l in a:
        f.write(' '.join(str(n) for n in l) + '\n')


2022-09-22 18:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.