0% found this document useful (0 votes)
15 views1 page

Import Random Def Select (A, K)

This Python code defines a function called "select" that takes a list "A" and integer "k" as inputs. The function uses random selection to choose an element from A to act as a pivot value "x". It then partitions A into lists of elements that are smaller and larger than x. If the length of the smaller list is equal to k-1, it returns x. Otherwise it recursively calls itself on either the smaller or larger list based on if k is within the range of the smaller list length. This implements the selection algorithm to find the kth ordered statistic from a list.

Uploaded by

Pablo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views1 page

Import Random Def Select (A, K)

This Python code defines a function called "select" that takes a list "A" and integer "k" as inputs. The function uses random selection to choose an element from A to act as a pivot value "x". It then partitions A into lists of elements that are smaller and larger than x. If the length of the smaller list is equal to k-1, it returns x. Otherwise it recursively calls itself on either the smaller or larger list based on if k is within the range of the smaller list length. This implements the selection algorithm to find the kth ordered statistic from a list.

Uploaded by

Pablo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

/home/pablo/Dropbox/02 - Docencia/Paradigmas de Programación/code/python/rank.

py

1 import random
2
3 def select(A,k):
4 while True:
5 x = random.choice(A)
6 menores = []
7 mayores = []
8 for y in A:
9 if y < x:
10 menores.append(y)
11 elif y > x:
12 mayores.append(y)
13 if k == len(menores) + 1:
14 return x
15 elif k <= len(menores):
16 A = menores
17 else:
18 A = mayores
19 k = k - len(menores) - 1

1 of 1 02/21/2018 09:48 PM

You might also like