В обоих случаях вы можете построить свои таблицы так, чтобы они удовлетворяли условиям, вместо того, чтобы генерировать кучу случайных таблиц и надеяться, что они их удовлетворят. Я предполагаю, что все значения должны быть в указанном c наборе, как base = range(2, 46, 2)
. Кроме того, я обязываю все значения быть уникальными в каждой таблице, что является более жестким ограничением, чем то, что вы в последний раз упомянули, но его легче понять.
- Для
table4
:
import random
import numpy as np
base = range(2, 46, 2)
# Generate a table at random
table = np.array(random.sample(base, 9)).reshape(3, 3)
# sort along first axis
table.sort(axis=0)
print table
например,
[[16 8 20]
[24 26 36]
[30 40 42]]
Затем вы можете изменить порядок строк в случайном порядке, если вы не хотите, чтобы самые высокие значения (систематически) в последнем.
Для
table1
,
table2
,
table3
:
import random
from itertools import combinations
from collections import Counter
import numpy as np
base = range(2, 46, 2)
# generate all combinations of 3 elements in 'base'
# as a list of 3-tuple
comb = [x for x in combinations(base, 3)]
# append to each tuple the sum of its elements
sums = [x + (sum(x),) for x in comb]
# list all the sums
possible_sums = [x[3] for x in sums]
# count the occurrences of each sum value
c = Counter(possible_sums)
# keep only the sums which occur at least twice
# and which are not the highest
max_sum = max(possible_sums)
c2 = Counter(x for x in c.elements() if c[x] >= 2 and c[x] < max_sum)
valid_sums = list(c2)
# pick one of those at random
r_sum = random.choice(valid_sums)
# list all the combinations for this sum
combs_for_r_sum = [x[:3] for x in sums if x[3] == r_sum]
# pick 2 among those at random
row1, row2 = random.sample(combs_for_r_sum, 2)
# for row 3, pick a combination with a sum higher than r_sum
sum2 = random.choice([x for x in possible_sums if x > r_sum])
combs_for_sum2 = [x[:3] for x in sums if x[3] == sum2]
row3 = random.choice(combs_for_sum2)
table = np.array(row1 + row2 + row3).reshape(3, 3)
print table
Например,
[[ 2 28 32]
[10 24 28]
[20 42 44]]
Опять же, вы можете изменить порядок строк в случайном порядке, если вы не не хочу, чтобы «самая высокая» строка (систематически) была последней.