mardi 5 juillet 2016

Strange output using random python

i have this problem where i sort a list based on randomness. how the algorithm works is two select a random number between 0 to N-1 (N is length of list) and swap with a iterating index.

i have two different algorithms like this.

import random

def algo1(xx):
    for i in xrange(len(xx)):
        p = random.randrange(i, len(xx))  # random number between i and len(xx) - 1
        xx[i], xx[p] = xx[p], xx[i]
    return xx

def algo2(yy):
    for i in xrange(len(yy)):
        p = random.randrange(0, len(yy))  # random number between 0 and len(xx) - 1
        yy[i], yy[p] = yy[p], yy[i]
    return yy


k = range(5)
print algo1(k) 
print algo2(k)

here everything works fine. i print the return values from algo1 and algo2.

But when i store the return values in variables

z1 = algo1(k)
z2 = algo2(k)
print z1
print z2

they both contain the same list. how many times i run they show the same return values

see this video https://www.youtube.com/watch?v=ZBjlnaCLKsQ&feature=youtu.be




Aucun commentaire:

Enregistrer un commentaire