簡體   English   中英

我如何以隨機順序運行多個函數x次?

[英]How do I run several functions in a random order for x amount of times?

我正在創建一個包含10個問題的測驗,並且我希望以下功能能夠運行10次。 這是我目前的解決方案,但每個功能只運行一次。 每個功能都是一個不同的問題。

def sumchoice():
    sums = [add(), sub(), multiply()]
    for _ in range(10):
        sums

我想要做的是以隨機順序運行函數,但總共只能運行十次。 我曾考慮過使用while循環,但這似乎行不通。

無需調用函數,而是將它們存儲在列表中。

import random

def sumchoice():
    sums = [add, sub, multiply]
    for _ in range(10):
        fun = random.choice(sums) # This picks one function from sums list
        fun() # This calls the picked function

您在創建列表時正在調用所有功能。 您應該從列表中刪除parantheses ()並在for循環內調用它們:

import random

def add():
    print "add"

def sub():
    print "sub"

def multiply():
    print "multiply"

sums = [add, sub, multiply]
for _ in range(10):
    random.choice(sums)()

結果:

multiply
add
multiply
sub
sub
multiply
multiply
sub
sub
sub

可以使用一個名為operator and random的內置模塊,該operator模塊可以用於二進制運算,而random可以用於獲取隨機選擇和隨機數。 並且有一個名為apply的內置函數,也可以使用。

>>> help(apply)


Help on built-in function apply in module __builtin__:

apply(...)
    apply(object[, args[, kwargs]]) -> value

    Call a callable object with positional arguments taken from the tuple args,
    and keyword arguments taken from the optional dictionary kwargs.
    Note that classes are callable, as are instances with a __call__() method.

    Deprecated since release 2.3. Instead, use the extended call syntax:
        function(*args, **keywords).

這是另一種方法。

from operator import add, sub, mul, div
import random

binaryOps = (add, sub, mul, div )
#nums = ( int(raw_input('Enter number 1: ')), int(raw_input('Enter number 2: ')))
nums = (random.randint(0, 1000), random.randint(0, 1000))

def method_choice(nums):
    op = random.choice(binaryOps)
    return nums[0], nums[1], apply(op, nums)

for iteration in range(10):
    print method_choice(nums)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM