Madno
Madno

Reputation: 910

Trying to swap items in a list in Python

I have a list like the following:

mylist = [['0010', 0.9], ['1111', 2.03], ['1101', 2.04], ['0010', 0.90]]

I want to make an operation of each two consecutive pair of these elements, mainly the binary part. So for mylist[0][0] (which is 0010) and mylist[1][0] (which is 1111), I want to generate a random number for each bit, and if that number is smaller than 0.8, swap each corresponding bits in the two consecutive strings. (No overlapping)

So let's say for simplicity that i am getting 0.4 probability all the time, then my strings should become:

0010 ---> 1111 mylist[0][0]
1111 ---> 0010 mylist[1][0]
Done comparing two strings.
---------------
1101 ---> 0010 mylist[2][0]
0010 ---> 1101 mylist[3][0]
Done comparing two strings.

The second part (the 0.9 and 2.03 and similar) is not important, but it's just there as a structure.

My attempt was as follows:

mylist = [['0010', 0.9], ['1111', 2.03], ['1101', 2.04], ['0010', 0.90]]
numberoftotalstrings = 4
lengthofbits = 4

for i in range(0, numberoftotalstrings, 2):
  currentword = list(mylist[i][0])
  nextword = list(mylist[i+1][0])

  for j in range(0, lengthofbits, 1):
    x = random.uniform(0,1)
    print (x)
    if x <= 0.8:
      tmp = currentword[j]
      currentword[j] = nextword[j]
      nextword[j] = tmp
  tmp1 = "".join(currentword)
  tmp2 = "".join(nextword)

  mylist[i][0] = tmp1
  mylist[i+1][0] = tmp2

But sadly it doesn't seem to produce working results, as some swapping operations should have happened and the other way around. I don't understand what's the missing part?

Upvotes: 1

Views: 89

Answers (1)

DarrylG
DarrylG

Reputation: 17156

It seems your code produces the expected result.

Test 1: Hardcoding x = 0.4, produces your stated output.

Test 2: Code Rewrite produces the same output

Refactored Code

Following is a rewrite of your code that produces the same output.

Note: Tested by using random.seed(1023) before running new and original code so they have the same random number sequence

def swap(x, y):
  z = [[yi, xi] if random.uniform(0,1) <= 0.8 else [xi, yi] for xi, yi in zip(x, y)]
  a, b = zip(*z)
  return ''.join(a), ''.join(b)

for i in range(0, len(mylist), 2):
  mylist[i][0], mylist[i+1][0] = swap(mylist[i][0], mylist[i+1][0])

Upvotes: 1

Related Questions