如何获得随机函数的固定值?

时间:2017-05-09 06:33:03

标签: python random

我正在尝试从两个随机选择的列表中获取常用元素的数量,您可以在本文底部的代码中看到。

问题在于

print(count_matching_numbers(generate_numbers(), draw_winning_numbers()))

上述打印功能的结果基于def。打印机内部的功能独立生成输出,而不是

def generate_numbers():
    result = random.sample(range(1, 46), 6)
    result.sort()
    return result

def draw_winning_numbers():
    win = generate_numbers()
    for i in win:
        bonus = random.randint(1, 45)
        bonus not in win
    win.append(bonus)
    return win

简而言之,我想获得随机函数的固定输出。 我该怎么做才能解决问题?

提前谢谢!

import random

def generate_numbers():
    result = random.sample(range(1, 46), 6)
    result.sort()
    return result

def draw_winning_numbers():
    win = generate_numbers()
    for i in win:
        bonus = random.randint(1, 45)
        bonus not in win
    win.append(bonus)
    return win

def count_matching_numbers(list1, list2):
    return len(set(list1) & set(list2))


print(generate_numbers())
print(draw_winning_numbers())
print(count_matching_numbers(generate_numbers(), draw_winning_numbers()))

1 个答案:

答案 0 :(得分:1)

问题是在三个print内部,该函数将独立调用。您可以将函数结果赋给某个变量,然后将变量传递给最后一个函数,如下所示:

import random

def generate_numbers():
    result = random.sample(range(1, 46), 6)
    result.sort()
    return result

def draw_winning_numbers():
    win = generate_numbers()
    for i in win:
        bonus = random.randint(1, 45)
        bonus not in win
    win.append(bonus)
    return win

def count_matching_numbers(list1, list2):
    return set(list1) & set(list2)

from_generate = generate_numbers() # call function only once
from_draw_winning = draw_winning_numbers() # call function only once

print(from_generate)
print(from_draw_winning)
print(count_matching_numbers(from_generate, from_draw_winning))

输出将是:

[3, 16, 23, 24, 34, 35]
[3, 11, 22, 23, 34, 39, 36]
set([34, 3, 23])