Saturday, 15 June 2013

Python array error occures 1-3 times in 100 cases -



Python array error occures 1-3 times in 100 cases -

i have finish ( partially working) programme of problem, function should pick "n" random items 1 array , set them array , if there same elements in array n.1 can't set more 1 of elements in array n.2

code:

import random def pick(n, array): array2 = [] in range(len(array)): if len(array2) == n: break random_index = 0 random_index= random.randint(0,len(array)-1) element = array[random_index] if element not in array2: array2.append(element) homecoming array2

for illustration take array a:

a=['matt', 'john', 'peter', 'john', 'joseph', 'adam', 'steven', 'paul']

and run it, illustration 100 times:

for in range(100): pick(4,a)

you notice, arrays consist of 3 elements , should 4! question why ?

you want change

for in range(len(array)) ## while len(array2) < n: ## or while true: ## infinite loop until break statement executed

your programme take random element len(array) times [and not array, list], , not depend on length of arrary2. there 1 or 2 elements depending on how many times duplicate picked. also, change

if len(array2) == n: break ## if len(array2) == n: homecoming array2

to avoid create clearer happening.

python arrays

No comments:

Post a Comment