Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select an item from a set in Python

I am looking to select one item from a set. It does not matter which item it is, but I want it to be the same item every time the function is called.

For example, if I had the set:

my_set = set(["ABC","ABC inc", "ABC ltd"])

Then I want to return any one of those, but the same one whenever the function is run. [i.e. so I would always get "ABC", or always get "ABC inc" whenever I ran with the above set.] If I was using lists, I would just take the first item, but sets don't have a first per se.

This is in contrast to selecting randomly [e.g. How do I pick 2 random items from a Python set? ] where it will change every time it is run.

like image 370
kyrenia Avatar asked Sep 10 '15 21:09

kyrenia


2 Answers

What about converting to list and sorting?

my_list = list(my_set)
my_list.sort()
chosen_element = my_list[0]
like image 71
dorverbin Avatar answered Oct 01 '22 10:10

dorverbin


you could use a function with memoization

def get_random(my_set,memo={}):
    if id(my_set) not in memo:
       memo[id(my_set)] = random.choice(list(my_set))
    return memo[id(my_set)]

a_set = set([1,2,3,4,5])
print get_random(a_set)
print get_random(a_set)

this would always give you the same value as long as you passed in a_set ... (a different set would give a different answer)

if you wanted to make sure the item was still in the set you could change the memo if check

def get_random(my_set,memo={}):
    if id(my_set) not in memo or memo[id(my_set)] not in my_set:
       memo[id(my_set)] = random.choice(list(my_set))
    return memo[id(my_set)]
like image 22
Joran Beasley Avatar answered Oct 01 '22 10:10

Joran Beasley