Danny Yoo said unto the world upon 2005-12-11 22:13:
> 
> On Sun, 11 Dec 2005, Brian van den Broek wrote:
> 
> 
>>I have a case like this toy code:
>>
>>import random
>>list1 = [1,2,3]
>>list2 = ['a', 'b', 'c']
>>item = random.choice(list1 +list2)
>>if item in list1:
>>     others = list2
>>else:
>>     others = list1
> 
> 
> Hi Brian,
> 
> This code works, and as long as you give it a good function name, I think
> it's fine the way it is.
> 
> If we're concerned with efficiency, 

Hi Danny,

thanks for the reply.

My concern wasn't efficiency, but screen space. I'm refactoring some 
code and had a method that was too long. I was trying to fix it while 
avoiding real work :-)

> we might want to change the
> random.choice() call to a random.randrange(), to avoid building the
> concatenation of list1 and list2.  This looks like:
> 
> ####
> def sampleFromTwoLists(list1, list2):
>     """Given two lists, returns a random element out of one of the lists
>     as well as the other list."""
>     index = random.randrange(len(list1) + len(list2))
>     if index < len(list1):
>         return list1[index], list2
>     else:
>          return list2[index - len(list1)], list1
> ####
> 
> Just out of curiosity, are you planning to do some kind of stratified
> sampling with this?

Thanks for the example. Nothing so interesting as that, I'm afraid :-)

I'm just goofing around with a text-based game, so efficiency isn't an 
issue. The two list represent teams of characters and the point of the 
code is to select a random character and oppose them to the other team.


>>Another way occurred to me, but I wonder if I'm being too cute:
>>
>>item = random.choice(list1 +list2)
>>others = [list1, list2][item in list1]
> 
> 
> Too cute.  *grin* Although it's concise, I'm having a hard time reading
> it.

Thanks for the feedback. I still don't trust my intuitions on issues 
like this.

Best to all,

Brian vdB

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to