views:

74

answers:

2

Let's say I have a list in python with several strings in it. I do not know the size. How can I run a loop to do an operation on 2 random elements of this string?

What if I wanted to favour a certain subset of the strings in this randomization, to be selected more often, but still make it possible for them to not be chosen?

+4  A: 

you need to look into random module. It has for example a random.choice function that lets you select a random element from a sequence or a random.sample that selects given number of samples, it's easy to account for different weights too.

SilentGhost
Very interesting, thank you! Are there functions in that library that somehow take weights into account?
Chris
`random.sample` considers each occurrence to be an independent to be a possible selection. You just need to construct your population accordingly.
SilentGhost
Sorry for the questions and thanks for your help. It says that random.sample samples k elements without replacement. This would lead me to believe that it removes them from the list (which is what I want!) but running random.sample(population, 2) until the list is empty goes into an infinite loop :) Why can't I have them removed?
Chris
docs say: *Returns a new list containing elements from the population while leaving the original population unchanged.* It doesn't remove them because sequences are not necessary mutable in python. If you need to remove them you can do that yourself. I guess you have `list` or `set` for the sequence? They have `remove` method.
SilentGhost
Apparently, I can't read. Thanks so much, cap'n
Chris
A: 

explain better your problem, what operations and what elements you're focusing?

regarding the problem with the elements beeing chosen more often, give each string an "chance multiplier", each comparison you multiply a number between 1 and 10 and the chance multiplyer of the string, if the result is higher than X (say... 5), so it select the string, if not, it searches for another string. this way, strings with higher multipliers will have more chance to be selected

Tufo
I'm just going to be running some random string modifications (experimenting with different things) against some binary strings, similar to the way GAs operate on strings with mutation and crossovers. Some strings are going to gain favourability over time, and need to be favoured in the selection process. These strings are wrapped in a class, so adding things like multipliers shouldn't be a problem.
Chris