1

Is there a way to choose a position of an item in a list and then flip the bit for example

pop = ['1010101', '1000101','1001001','1010101,'110001']

then randomly choose a position in each set of item in the list and flip the bit to 0 to 1 or 1 to 0

so for example, it will go through each item in a list and choose random position in each item, 1010101 will turn into 1000101, second item will turn into 1000101, 1011001, etc.

Banghua Zhao
  • 1,438
  • 1
  • 10
  • 22
Mark Cruz
  • 21
  • 4

1 Answers1

2

You could use random.choice:

import random

random.seed(42)


def flip(s):
    pos = random.choice(range(len(s)))

    r = list(s)
    r[pos] = '1' if r[pos] == '0' else '0'

    return ''.join(r)


pop = ['1010101', '1000101', '1001001', '1010101', '110001']

result = [flip(s) for s in pop]

print(result)

Output

['1010111', '0000101', '0001001', '1010111', '111001']

Everything is done inside the flip function in 3 main steps.

Choose the random position: pos = random.choice(range(len(s))).

Change the bit of the position.

r = list(s)
r[pos] = '1' if r[pos] == '0' else '0'

And finally return a new string by joining the elements of r, return ''.join(r).

Further

  1. Change one character in a string?
  2. Does Python have a ternary conditional operator?
Dani Mesejo
  • 43,691
  • 6
  • 29
  • 53