Dianne
Dianne

Reputation: 47

Random numbers in string

Why when my string has a small size, the random numbers 0 and 1 are more visible, and when the string has its second (longer) value, it becomes a string of 0?

import random
#F = "(~1V3V~5V~7)^(~1V~3V5V~6V~7)"
F = "(~1V3V~5V~7)^(~1V~3V5V~6V~7)^(1V2V~4V~6V7)^(1V2V~4V~5V~7)^(2V5)^(~1V2V3V~5V6V~7)^(2V~3V4V~5V7)"


for x in F:
    if x.isdigit():
        F = F.replace(x, str(random.randint(0, 1)))

print(F)

OUTPUT:

First string:
run(1): (~1V0V~0V~1)^(~1V~0V0V~0V~1)
run(2): (~0V0V~0V~0)^(~0V~0V0V~0V~0) # all characters are 0?? Why isn't all random numbers value between 0 and 1?
run(3): (~0V1V~0V~1)^(~0V~1V0V~0V~1)

Second string:
run(1): (~0V0V~0V~0)^(~0V~0V0V~0V~0)^(0V0V~0V~0V0)^(0V0V~0V~0V~0)^(0V0)^(~0V0V0V~0V0V~0)^(0V~0V0V~0V0)
run(2): (~0V0V~0V~0)^(~0V~0V0V~0V~0)^(0V0V~0V~0V0)^(0V0V~0V~0V~0)^(0V0)^(~0V0V0V~0V0V~0)^(0V~0V0V~0V0)
run(3): (~0V0V~0V~0)^(~0V~0V0V~0V~0)^(0V0V~0V~0V0)^(0V0V~0V~0V~0)^(0V0)^(~0V0V0V~0V0V~0)^(0V~0V0V~0V0)

I want each number in the string to be a random value of 0 or 1. And I don't understand what's wrong. A little help?

Upvotes: 0

Views: 83

Answers (2)

manju-dev
manju-dev

Reputation: 434

Few things:

  • It is not good practice to modify the variable you are iterating over inside the loop.
  • My interpretation of the problem is: iterate over given string, replace the encountered digits with 0 or 1 at random. F.replace will replacing all instance of the encountered number(x) in the string in above code. Corrct me if i'm wrong.
import random
F = "(~1V3V~5V~7)^(~1V~3V5V~6V~7)"

new_F = ''
for x in F:
  if x.isdigit():
    new_F += str(random.randint(0, 1))
  else:
    new_F += x

print(new_F)

Upvotes: 3

Sayse
Sayse

Reputation: 43300

Its not completely random because you're only really taking into account the last replace by assigning the value back to F, instead you should just use a string join and comprehension to treat each letter individually instead of reassigning the value back to F

"".join(str(random.randint(0, 1) if x.isdigit() else x for x in F)

Upvotes: 2

Related Questions