【问题标题】:Shuffle a python list without using the built-in function在不使用内置函数的情况下随机播放 python 列表
【发布时间】:2013-07-05 12:56:49
【问题描述】:

我正在编写两个不同的随机播放函数。

第一个 shuffle 函数必须接受一个列表并返回一个新列表,其中的元素随机排列。

这是我迄今为止的第一个随机播放功能-

def shuf(List):
    import random
    newList=[]
    for i in List:
        i=random.randrange(len(List))
        newList+=i
    return newList

第二个 shuffle 函数将一个列表作为参数,并在适当的位置对列表进行 shuffle。

我知道如何使用内置函数,但我不允许使用它。

【问题讨论】:

  • 您愿意分享您所知道的、不允许的以及您在编写这两个不同的 shuffle 函数方面的工作进展吗?
  • 你已经知道你必须实现的算法了吗?您面临什么问题?
  • 请注意,Python 的random.shuffle() 的实现是用Python 编写的,所以您可以直接阅读the source code
  • 这是我到目前为止的第一个 shuffle 函数 - def shuf(List): import random newList=[] for i in List: i=random.randrange(len(List)) newList+ =我返回新列表

标签: python python-3.3


【解决方案1】:

您可能会发现这种洗牌实现适合您的需求。请确保在使用它们之前注意这两个函数之间的区别。

import copy
import random


def main():
    my_list = list(range(10))
    print(my_list)
    print(shuffle(my_list))
    print(my_list)
    shuffle_in_place(my_list)
    print(my_list)


def shuffle(container):
    new_container = copy.copy(container)
    shuffle_in_place(new_container)
    return new_container


def shuffle_in_place(container):
    for index in range(len(container) - 1, 0, -1):
        other = random.randint(0, index)
        if other == index:
            continue
        container[index], container[other] = container[other], container[index]


if __name__ == '__main__':
    main()

【讨论】:

  • 这是一个糟糕的洗牌,因为它有偏见。例如,如果你 shuffle [0, 1, 2] 它只能产生 [1, 0, 2], [2, 1, 0] 和 [0, 2, 1]。
  • 因为算法有偏差,数组必须有两个以上的元素。它的设计并不完美,但至少它强制所有值至少移动一次。
  • @PaulHankin shuffle_in_place 函数终于改正了。
【解决方案2】:

灵感来自随机模块中shuffle的python源代码实现

  import random

  def shuffle(A):
      last_index = len(A) - 1

      while last_index > 0:
          rand_index = random.randint(0, last_index)
          A[last_index], A[rand_index] = A[rand_index], A[last_index]
          last_index -= 1

      return A

【讨论】:

    【解决方案3】:

    计划:从元素 0 开始遍历列表;为它找到一个新的随机位置,比如 6,将 0 的值放入 6 中,将 6 的值放入 0。移动到元素 1 并重复此过程,以此类推直到列表的其余部分

    import random
    iteration = random.randint(2, 100)
    temp_var = 0
    while iteration > 0:
        # We will be swapping the value of i for j.
        # And then setting j to what i was using the temp_var place holder.
        for i in range(1, len(my_list)): # have to use range with len()
            for j in range(1, len(my_list) - i):
                # Using temp_var as my place holder so I don't lose values
                temp_var = my_list[i]
                my_list[i] = my_list[j]
                my_list[j] = temp_var
    
            iteration -= 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-22
      • 2023-01-23
      • 1970-01-01
      • 2015-02-10
      • 2012-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多