The function here just generates a random list of 0s and 1s. It's for later use in a game. So I need to take the list generated by binary_gen and convert it to a string. I've tried using .join but I just get an error message back. Is there any way for me to convert the output from binary_gen to a string? Or is there another way I can generate a random sequence of 0s and 1s?
import random
def random_binary():
min_length = 4
max_length = 8
binary_gen = [random.randrange(0,2,1) for _ in range \
(random.randint(min_length,max_length))]
print (binary_gen)
random_binary()
Update:
import random
def random_binary():
min_length = 4
max_length = 8
binary_gen = [random.randrange(0,2,1) for _ in range \
(random.randint(min_length,max_length))]
binary_string = "".join(binary_gen)
print (binary_string)
random_binary()
And I get: TypeError: sequence item 0: expected str instance, int found
To generate a random string sequence of zeroes and ones of random length from 4 to 8:
>>> from random import randint
>>> ''.join(str(randint(0, 1)) for i in range(randint(4, 8)))
'0010111'
Or, more directly:
>>> from random import choice, randint
>>> ''.join(choice('01') for i in range(randint(4, 8)))
'101101'
To count the number of 1
s in a string of zeroes and ones:
>>> s = '0011100'
>>> len(s.replace('0', ''))
3
Or:
>>> sum(c=='1' for c in s)
3
import random
def random_binary(min_length=4, max_length=8):
size = random.randint(min_length, max_length)
return ''.join(str(random.randint(0, 1)) for _ in range(size))
print(random_binary())
My guess is that the error you got was something like TypeError: sequence item 0: expected str instance, int found
, because you were trying to join numbers instead of strings. The str(...)
above is what makes this code work.
Please try following:
import random
def random_binary():
min_length = 4
max_length = 8
binary_gen = [random.randrange(0,2,1) for _ in range \
(random.randint(min_length,max_length))]
_str = ''
for i in binary_gen:
_str += str(i)
return _str
def count_zeros(s):
count = 0
for i in s:
if i == '0':
count += 1
return count
It generates '111010' string. count_zeros(s)
will return number of zeros in input string
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.