多次试验得分最低

时间:2017-08-26 19:29:08

标签: python random

嗨,这个代码会产生4组,直到数字1-4,然后根据它们的好坏来评价它们:

import numpy
import math
import random
for i in range(3):
  # everything is in, see the indentation
  members=4
  n_groups =4
  participants=list(range(1,members+1))*n_groups
  #print participants 
  random.shuffle(participants)

  with open('myfile1.txt','w') as tf:
      for i in range(n_groups):
          group = participants[i*members:(i+1)*members]
          for participant in group:
              tf.write(str(participant)+' ')
          tf.write('\n')

  with open('myfile1.txt','r') as tf:
      g = [list(map(int, line.split())) for line in tf.readlines()]
      print(g)




  my_groups =g

  def get_rating(group):
      return len(set(group))

  for each_grp in my_groups:  
      print((get_rating(each_grp)))

  print(sum(len(set(x)) for x in my_groups))

这是输出:

    [[1, 3, 4, 1], [3, 4, 2, 3], [2, 2, 1, 4], [4, 3, 1, 2]]
3
3
3
4
13
[[3, 4, 2, 1], [1, 1, 2, 4], [2, 3, 3, 2], [3, 4, 4, 1]]
4
3
2
3
12
[[3, 2, 3, 1], [4, 2, 3, 3], [2, 4, 1, 2], [4, 4, 1, 1]]
3
3
3
2
11

方括号是4组,每组4个数字以下,所以(1,1,1,1)非常好,因为变化最小,而(1,2,3,3)不太好因为它有3个不同的数字。最后的数字只是将所有4个数字相加。

我想知道是否有办法显示组合与所有组的最低得分,在这种情况下11我运行试验后,这将使我更容易,如我做更多的试验,如2000

2 个答案:

答案 0 :(得分:1)

您可以使用:

:Decision

您还可以使用外部变量来保持最小值:

# let all group of groups be in one array called out

out = [
  [[1, 3, 4, 1], [3, 4, 2, 3], [2, 2, 1, 4], [4, 3, 1, 2]],
  [[3, 4, 2, 1], [1, 1, 2, 4], [2, 3, 3, 2], [3, 4, 4, 1]],
  [[3, 2, 3, 1], [4, 2, 3, 3], [2, 4, 1, 2], [4, 4, 1, 1]]
  ]

# for each group of groups, sum the lengths of it's subgroups lengths and choose the minimum

res = min(sum(len(set(x)) for x in y) for y in out)

print(res) # => 11

答案 1 :(得分:1)

对代码进行轻微的重构,通过定义run()函数,您可以计算出所有运行的运行次数和最小值:

import random

def run(members, n_groups):
    participants = list(range(1,members+1))*n_groups
    random.shuffle(participants)

    # Chunk up the participants
    my_groups = list(zip(*[iter(participants)]*members))
    print(my_groups)

    def get_rating(group):
        return len(set(group))

    # for each_grp in my_groups:
    #     print(get_rating(each_grp))

    score = sum(get_rating(g) for g in my_groups)
    print(score)
    return score

members = 4
n_groups = 4

print(min(run(members, n_groups) for _ in range(3)))

输出:

[(1, 4, 3, 3), (4, 4, 1, 2), (3, 4, 3, 1), (2, 2, 1, 2)]
11
[(4, 3, 3, 4), (1, 3, 1, 2), (4, 2, 1, 4), (1, 2, 2, 3)]
11
[(4, 1, 1, 2), (2, 4, 3, 4), (4, 3, 2, 3), (1, 2, 1, 3)]
12
11