Open In App

Python Program to Generate Random binary string

Last Updated : 17 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python program for random
# binary string generation
 
 
import random
 
 
# Function to create the
# random binary string
def rand_key(p):
   
    # Variable to store the
    # string
    key1 = ""
 
    # Loop to find the string
    # of desired length
    for i in range(p):
         
        # randint function to generate
        # 0, 1 randomly and converting
        # the result into str
        temp = str(random.randint(0, 1))
 
        # Concatenation the random 0, 1
        # to the final result
        key1 += temp
         
    return(key1)
 
# Driver Code
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):
    # Generate a random number with n bits
    number = random.getrandbits(n)
    # Convert the number to binary
    binary_string = format(number, '0b')
    return binary_string
 
# Test the function
n = 7
print("Random binary string of length {}: {}".format(n, generate_binary_string(n)))
#This code is contributed by Edula Vinay Kumar Reddy


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.



Similar Reads

Python Program to Generate Random String With Uppercase And Digits
Generating a series of random strings can help create security codes. Besides, there are many other applications for using a random string generator, for instance, obtaining a series of numbers for a lottery game or slot machines. A random string generator generates an alphanumeric string consisting of random characters and digits. Let's see how we
3 min read
Python | Generate random string of given length
The issue of generation of random numbers is quite common, but sometimes, we have applications that require us to better that and provide some functionality of generating a random string of digits and alphabets for applications such as passwords. Let's discuss certain ways in which this can be performed in Python. Here, we will use Random string ge
3 min read
Python Random - random() Function
There are certain situations that involve games or simulations which work on a non-deterministic approach. In these types of situations, random numbers are extensively used in the following applications: Creating pseudo-random numbers on Lottery scratch cardsreCAPTCHA on login forms uses a random number generator to define different numbers and ima
3 min read
Python | Generate random numbers within a given range and store in a list
Given lower and upper limits, Generate random numbers list in Python within a given range, starting from 'start' to 'end', and store them in the list. Here, we will generate any random number in Python using different methods. Examples: Input: num = 10, start = 20, end = 40 Output: [23, 20, 30, 33, 30, 36, 37, 27, 28, 38] Explanation: The output co
5 min read
Python - Generate random number except K in list
Sometimes, while working with python, we can have a problem in which we need to generate random number. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random number from a list except K. Lets discuss certain ways in which this task can be performed. Method #1: Using choice() + list comprehen
3 min read
Python | Generate random number except K in list
Sometimes, while working with Python, we can have a problem in which we need to generate random numbers. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random numbers from a list except K. Let's discuss certain ways in which this task can be performed. Method #1 : Using choice() + list compr
6 min read
How to generate a random color for a Matplotlib plot in Python?
Handling huge dataset requires libraries and methods that can be used to store, analyze and manipulate the datasets. Python is a popular choice when it comes to data science and analytics. Data scientists prefer Python due to its wide library support that contains functions which can be used to work with datasets to create graphs and charts. Matplo
3 min read
How to generate a random number between 0 and 1 in Python ?
The use of randomness is an important part of the configuration and evaluation of modern algorithms. Here, we will see the various approaches for generating random numbers between 0 ans 1. Method 1: Here, we will use uniform() method which returns the random number between the two specified numbers (both included). Code: C/C++ Code import random pr
1 min read
How to generate a random letter in Python?
In this article, let's discuss how to generate a random letter. Python provides rich module support and some of these modules can help us to generate random numbers and letters. There are multiple ways we can do that using various Python modules. Generate a random letter using a string and a random module The string module has a special function as
1 min read
How to generate a random phone number using Python?
In this article, we will learn how to generate a random phone number using Python. In general, Indian phone numbers are of 10 digits and start with 9, 8, 7, or 6. Approach: We will use the random library to generate random numbers.The number should contain 10 digits.The first digit should start with 9 or 8 or 7 or 6, we will use randint() method.Th
1 min read
Practice Tags :