在函数中始终使用random.choice获得相同的输出

时间:2018-03-20 17:21:57

标签: python-3.x

我尝试使用for-loop来执行我的功能,但它总是一样的结果。

import random

def main(arr):
  result = random.choice(arr)
  ...some code...

  return len(result)

for i in range(100):
  main(arr)

我只能从停止/运行终端获得差异结果。谁知道为什么?

我的问题与此问题相同。 random.choice always same

import random

results = []
with open('kargerMinCut.txt') as inputfile:
for line in inputfile:
    results.append(line.strip().split('\t'))


def contract(arr):

  while len(arr) > 2:

    # Generate random number in list of lists
    # ranList = random.choice(arr)
    ranList = arr[np.random.choice(len(arr))]
    ranNum = random.choice(ranList[1:])

    # retrieve the index of the random number
    listIndex = arr.index(ranList)

    for i in range(0, len(arr)):
        if arr[i][0] == ranNum:
            targetList = i
            break
    target = ranList[0]
    for i in range(0, len(arr)):
        if i == listIndex:
            arr[i].pop(0)
            arr[i] = [x for x in arr[i] if x != ranNum]
        elif i == targetList:
            arr[i] = [x for x in arr[i] if x != target]
        else:
            for index, item in enumerate(arr[i]):
                if item == target:
                    arr[i][index] = ranNum
    arr[targetList] += arr[listIndex]
    del arr[listIndex]

return len(arr[0])-1

arr会是这样的

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

1 个答案:

答案 0 :(得分:0)

我不知道你在功能中做了什么,但我得到了正常的结果。在问题中你与刚刚使用种子的人联系了什么。这是一种伪随机,它为您提供相同的随机输出。以下是link深入了解伪随机

的知识
import random

arr = [1,2,3,4,5]

def main(arr):
    result = random.choice(arr)
    print(result)

for i in range(100):
    main(arr)

结果必须是:

1
3
5
3
4
3
1
4
4
3
2