Python Program to Generate Random binary string
Last Updated :
17 Mar, 2023
Given a number n, the task is to generate a random binary string of length n.
Examples:
Input: 7
Output: Desired length of random binary string is: 1000001
Input: 5
Output: Desired length of random binary string is: 01001
Approach
- Initialize an empty string, say key
- Generate a randomly either “0” or “1” using randint function from random package.
- Append the randomly generated “0” or “1” to the string, key
- Repeat step 2 and 3 for the desired length of the string
Below is the implementation.
Python3
import random
def rand_key(p):
key1 = ""
for i in range (p):
temp = str (random.randint( 0 , 1 ))
key1 + = temp
return (key1)
n = 7
str1 = rand_key(n)
print ( "Desired length random binary string is: " , str1)
|
Output:
Desired length random binary string is: 1000001
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Using random.getrandbits():
Python3
import random
def generate_binary_string(n):
number = random.getrandbits(n)
binary_string = format (number, '0b' )
return binary_string
n = 7
print ( "Random binary string of length {}: {}" . format (n, generate_binary_string(n)))
|
Output
Random binary string of length 7: 1010000
Explanation:
The random.getrandbits(n) function generates a random number with n bits.
The format() function is used to convert the number to binary format. The format string ‘0b’ specifies that the output should be in binary form.
Time Complexity: O(n), where n is the number of bits in the binary string.
Auxiliary Space: O(n), where n is the number of bits in the binary string. This is the space required to store the binary string.
Please Login to comment...