在Python中洗牌?

时间:2016-04-12 18:04:33

标签: python loops

我在一个基本的Python编程课程中,我被困住了。我们必须使用列表的长度而不是a来生成适当范围内的索引值i和j 硬编码的数字,并确保列表元素仅在它使列表更接近排序顺序时交换,从最低到最左边。

到目前为止,我有:

from random import*

def main():
    LENGTH= 25
    shuffleList= 1000
    numList= [0] * LENGTH

    for num in range(0,len(numList)):
        rand= randint(-100,100)
        numList[num] += rand
    print("List before shuffling:")
    print numList  

    for i in range(0, len(numList)):
        min = i
        shuffleList += 1

    for j in range(-1, len(numList)):
        shuffleList +=1

现在我不知道从这一点开始该做什么。感谢。

4 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

import numpy
LENGTH=25
random_list = numpy.random.randint(-100,100,LENGTH) #Generate random list
for i in range(random_list): # for each index in list as i
    for j in range(random_list): # for each index in list as j
        if lrandom_listst[i] > random_list[j]: # if we should swap
           random_list[i],random_list[j] = random_list[j],random_list[i] # do swap

这不是一个很好的排序列表的算法......也许就是这一点

答案 2 :(得分:0)

这可能很有用:http://blog.codinghorror.com/shuffling/

也许是这样的:( Pseodocode Credit:Wikipdia)

for i from n−1 downto 1 do
 j ← random integer such that 0 ≤ j ≤ i
 exchange a[j] and a[i]

https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

答案 3 :(得分:0)

我认为“更有秩序”你只是意味着左手边上升到右手边。一个简单的方法就是选择两个随机索引,比较它们,如果左侧较高,则切换它们。

我可以压缩这个功能,但是为了让你更好地理解,我把它留在了更详细的形式:

import random

def check_sort(items, predicate=lambda x, y: x <= y):
    return all(predicate(items[i],items[i+1]) for i in range(len(items)-1))

numbers = [i for i in range(0, 100)]
random.shuffle(numbers)
changes = 0
generations = 0
while not check_sort(numbers):
    generations += 1
    x, y = random.randint(0, len(numbers) - 1), random.randint(0, len(numbers) - 1)
    x, y = (x, y) if x > y else (y, x)
    if numbers[x] < numbers[y]:
        changes += 1
        tmp = numbers[y]
        numbers[y] = numbers[x]
        numbers[x] = tmp

print("Generations: {}\nChanges: {}".format(generations, changes))