0% found this document useful (0 votes)
25 views30 pages

B.tech (AIML DS) 1 2 Python Lab Manual

The document outlines the syllabus for the Python Programming Laboratory course for B.Tech. CSE (AI and ML) at JNTU Hyderabad, detailing course objectives, outcomes, and weekly lab exercises. It includes various programming tasks such as calculating compound interest, checking character types, and implementing digital logic gates. Additionally, it lists textbooks and reference materials for further study.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views30 pages

B.tech (AIML DS) 1 2 Python Lab Manual

The document outlines the syllabus for the Python Programming Laboratory course for B.Tech. CSE (AI and ML) at JNTU Hyderabad, detailing course objectives, outcomes, and weekly lab exercises. It includes various programming tasks such as calculating compound interest, checking character types, and implementing digital logic gates. Additionally, it lists textbooks and reference materials for further study.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

R22 [Link].

CSE (AI and ML) Syllabus JNTU Hyderabad

CS206ES: PYTHON PROGRAMMING LABORATORY


[Link]. I Year II Sem. LTPC
0122
Course Objectives:
 To install and run the Python interpreter
 To learn control structures.
 To Understand Lists, Dictionaries in python
 To Handle Strings and Files in Python
Course Outcomes: After completion of the course, the student should be able to
● Develop the application specific codes using python.
● Understand Strings, Lists, Tuples and Dictionaries in Python
● Verify programs using modular approach, file I/O, Python standard library
● Implement Digital Systems using Python
Note: The lab experiments will be like the following experiment examples
Week -1:
1. i) Use a web browser to go to the Python website [Link] This page contains
informationabout Python and links to Python-related pages, and it gives you the ability to
search the Pythondocumentation.
ii) Start the Python interpreter and type help() to start the online help utility.
2. Start a Python interpreter and use it as a Calculator.
3 i) Write a program to calculate compound interest when principal, rate and number of
periods
aregiven.
ii) Given coordinates (x1, y1), (x2, y2) find the distance between two points
4. Read name, address, email and phone number of a person through the keyboard and print
the details.
Week - 2:
1. Print the below triangle using for loop.
5
44
333
2222
11111
2. Write a program to check whether the given input is digit or lowercase character or
uppercasecharacter or a special character (use 'if-else-if' ladder)
3. Python Program to Print the Fibonacci sequence using while loop
4. Python program to print all prime numbers in a given interval (use break)
Week - 3:
1. i) Write a program to convert a list and tuple into arrays.
ii) Write a program to find common values between two arrays.
2. Write a function called gcd that takes parameters a and b and returns their greatest
common divisor.
3. Write a function called palindrome that takes a string argument and returns true if it is a
palindromeand False otherwise. Remember that you can use the built-in function len to check
the length of a string.
Week - 4:
1. Write a function called is sorted that takes a list as a parameter and returns True if the list
is sortedin ascending order and False otherwise.
2. Write a function called has duplicates that takes a list and returns True if there is any
element thatappears more than once. It should not modify the original list.
i). Write a function called remove_duplicates that takes a list and returns a new list with only
theunique elements from the original. Hint: they don’t have to be in the same order.
ii). The wordlist I provided, [Link], doesn’t contain single letter words. So you might want
to add“I”, “a”, and the empty string.
iii). Write a python code to read dictionary values from the user. Construct a function to
invert itscontent. i.e., keys should be values and values should be keys.
3. i) Add a comma between the characters. If the given word is 'Apple', it should become
'A,p,p,l,e'
ii) Remove the given word in all the places in a string?
iii) Write a function that takes a sentence as an input parameter and replaces the first letter
of everyword with the corresponding upper case letter and the rest of the letters in the word
by corresponding letters in lower case without using a built-in function?
4. Writes a recursive function that generates all binary strings of n-bit length
Week - 5:
1. i) Write a python program that defines a matrix and prints
ii) Write a python program to perform addition of two square matrices
iii) Write a python program to perform multiplication of two square matrices
2. How do you make a module? Give an example of construction of a module using different
geometrical
shapes and operations on them as its functions.
3. Use the structure of exception handling all general purpose exceptions.
Week-6:
1. a. Write a function called draw_rectangle that takes a Canvas and a Rectangle as
arguments anddraws a representation of the Rectangle on the Canvas.
b. Add an attribute named color to your Rectangle objects and modify draw_rectangle so that
ituses the color attribute as the fill color.
c. Write a function called draw_point that takes a Canvas and a Point as arguments and draws
arepresentation of the Point on the Canvas.
d. Define a new class called Circle with appropriate attributes and instantiate a few Circle
[Link] a function called draw_circle that draws circles on the canvas.
2. Write a Python program to demonstrate the usage of Method Resolution Order (MRO) in
multiplelevels of Inheritances.
3. Write a python code to read a phone number and email-id from the user and validate it for
correctness.
Week- 7
1. Write a Python code to merge two given file contents into a third file.
2. Write a Python code to open a given file and construct a function to check for given words
present in
it and display on found.
3. Write a Python code to Read text from a text file, find the word with most number of
occurrences
4. Write a function that reads a file file1 and displays the number of words, number of
vowels, blankspaces, lower case letters and uppercase letters.
Week - 8:
1. Import numpy, Plotpy and Scipy and explore their functionalities.
2. a) Install NumPy package with pip and explore it.
3. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
4. Write a program to implement Half Adder, Full Adder, and Parallel Adder
5. Write a GUI program to create a window wizard having two text labels, two text fields and
two buttonsas Submit and Reset.
TEXT BOOKS:
1. Supercharged Python: Take your code to the next level, Overland
2. Learning Python, Mark Lutz, O'reilly
REFERENCE BOOKS:
1. Python Programming: A Modern Approach, VamsiKurama, Pearson
2. Python Programming A Modular Approach with Graphics, Database, Mobile, and Web
Applications, SheetalTaneja, Naveen Kumar, Pearson
3. Programming with Python, A User’s Book, Michael Dawson, Cengage Learning, India
Edition
4. Think Python, Allen Downey, Green Tea Press
5. Core Python Programming, W. Chun, Pearson
6. Introduction to Python, Kenneth A. Lambert, Cengage
[Link]: 1(a) COMPOUNDINTEREST

Date:

Aim:
Write a program to calculate compound interest when principal, rate and number of periods
are given.
Algorithm:
Step 1: Start
Step 2: Read 3 number for p, n, r
Step 3: Calculate principal * (pow((1 + rate / 100), time))
Step 4: Print “The compound Interest = C.l”
Step 5: Stop

Source Code:
defcompound_interest(principal, rate, time):
Amount = principal * (pow((1 + rate / 100), time))
CI = Amount - principal
print("Compound interest is", CI)
compound_interest(10000, 10.25, 5)
Input:
Enter the principal amount: 3000
Enter rate of interest: 5
Enter time in years: 3
Output:
Compound interest is 472.875

Result:
The Compound interest program is written in python language and executed successfully.
[Link]: 1(b) DISTANCE BETWEEN TWO END POINTS

Date:

Aim:
Write a program to Python Program to Calculate Distance Between Two Points ( Co-
ordinates)
Algorithm:
step 1 : Take a two points as an input from an user.
step 2 : Calculate the difference between the corresponding X-cooridinates
i.e : X2 - X1 and Y-cooridinates i.e : Y2 - Y1 of two points.
step 3 : Apply the formula derived from Pythagorean Theorem
i.e : sqrt((X2 - X1)^2 + (Y2 - Y1)^2)
step 4 : Exit.

Source Code:
x1 = float(input('Enter x1: '))
y1 = float(input('Enter y1: '))
x2 = float(input('Enter x2: '))
y2 = float(input('Enter y2: '))
d = ( (x2-x1)**2 + (y2-y1)**2 ) ** 0.5
print('Distance = %f' %(d))
Output:
Enter x1: 4
Enter y1: 8
Enter x2: 5
Enter y2: 1
Distance = 7.071068

Result:
The Calculate Distance Between Two Points is written in python language and executed
successfully
[Link]: 1(c) PERSONAL DETAILS

Date:

Aim:
Write a python program to display personal details.
Algorithm:
Step1: Initialize the variable for integer, character and string.
Step2: Get the values of the row from the user using Input() stmt.
Step3: Display above values on the screen using print function.
Step4. Stop the program

Source Code:
name=input("Enter your name:")

add=input("Enter your address:")


email=input("Enter your email address:")
phonenumber=int(input("Enter your phone number:"))
print(name)
print(add)
print(email)
print(phonenumber)

Result:
The python program to display the personal details is written and executed successfully
[Link]: 2(a) PRINTING PYRAMID PATTERN

Date:

Aim:
Write a program to Python Program to printing pyramid pattern algorithm in python

5
44
333
2222
11111

Algorithm:
Step 1: First, we get the height of the pyramid rows from the user.
Step 2: In the first loop, we iterate from i = 0 to i = rows.
Step 3: The second loop runs from j = 0 to i + 1. In each iteration of this loop, we print i + 1
number of k without a new line. Here, the row number gives the number of k required to be
printed on that row. For example, in the 2nd row, we print two k. Similarly, in the 3rd row,
we print three k.
Step 4: Once the inner loop ends, we print new line and start printing * in a new line.

Source Code:
rows = int(input("Enter number of rows: "))
k=5
for i in range(rows):
for j in range(i+1):
print(k, end=" ")
print("\n")
k=k-1

Result:
The python program to display the printing pyramid pattern is written and executed
successfully.
[Link]: 2(b) CHECK GIVEN INPUT IS DIGIT OR UPPERCASE OR LOWERCASE
OR SPECIAL CHARACTER
Date:

Aim:
Write a program to check given Input is Digit or Uppercase or Lowercase or Special
Character in python.
Algorithm:
Step 1: Insert a character (by the user)
Step 2: Check whether the character lies between A and Z, if true, print “uppercase”
Step 3: Check whether the character lies between a and z, if true, print “lowercase
Step 4: Check whether the character lies between 0 and 9, if true, print “not a character it is a
number”
Step 5: All other condition are false ,print ” it is a spacial character”
Step 6:stop the program

Source Code:
ch = input("Enter a character: ")
ifch>= '0' and ch<= '9':
print("Digit")
[Link] ():
print("Uppercase character")
[Link] ():
print("Lowercase character")
else:
print("Special character")

Result:
The python program to check given input is digit or uppercase or lowercase or special
character is written and executed successfully.
[Link]: 2(c) FIBONACCI SEQUENCE

Date:

Aim:
Write a Python Program to Print the Fibonacci sequence using while loop

Algorithm:

Step 1: Input the 'n' value until which the Fibonacci series has to be generated

Step 2: Initialize sum = 0, a = 0, b = 1 and count = 1

Step 3: While (count <= n)

Step 4: Print sum

Step 5: Increment the count variable

Step 6: swap a and b

Step 7: sum = a + b

Step 8: while (count > n)

Step 9: End the algorithm

Step 10: Else

Step 11: Repeat from steps 4 to 7

Source Code:
nterms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if nterms<= 0:
print("Please enter a positive integer")
elifnterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count <nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
OUTPUT:
How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8

Result:
The python program to print Fibonacci sequence is written and executed successfully.
[Link]: 2(d) PRIME NUMBERS

Date:

Aim:

Write a Python Program to print all prime numbers in a given interval (use break)

Algorithm:
Step 1: Loop through all the elements in the given range.
Step 2: Check for each number if it has any factor between 1 and itself.
Step 3: If yes, then the number is not prime, and it will move to the next number.
Step 4: If no, it is the prime number, and the program will print it and check for the next
number.
Step 5: The loop will break when it is reached to the upper value.

Source Code:
L = int(input(“Enter the lower value:”)
U = int(input(“Enter the Upper Value:”)
print("Prime numbers between", lower, "and", upper, "are:")
fornum in range(L, U+1)
# all prime numbers are greater than 1
ifnum> 1:
fori in range(2, num):
if (num % i) == 0:
break
else:
print(num)
INPUT : IF lower value = 900, upper value = 1000

OUTPUT:
Prime numbers between 900 and 1000 are:
907
911
919
929
937
941
947
953
967
971
977
983
991
997

Result:
The python program to print all prime numbers in a given interval (use break) is written and
executed successfully.
[Link]: 3(a-1) CONVERT A LIST AND TUPLE INTO ARRAYS

Date:

Aim:
Write a python program to convert a list and tuple into arrays.

Algorithm:

Step1: Use the import keyword to import NumPy module with an alias name.
Step2: Create a variable to store the input tuple.
Step3: Print the input tuple.
Step4: Use the type() function(returns the data type of an object) to print the data type of the
input tuple.
Step5: Use the [Link]() function to convert the input tuple to an array by passing the
input tuple as an argument to it.
Step5: Print the output array after converting the input python tuple to an array.
Step6: Use the type() function(returns the data type of an object) to print the data type of the
resultant output array.
Source code:
import numpy as np
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print("List to array: ")
print([Link](my_list))
my_tuple = ([8, 4, 6], [1, 2, 3])
print("Tuple to array: ")
print([Link](my_tuple))
Output:
List to array:
[1 2 3 4 5 6 7 8]
Tuple to array:
[[8 4 6]
[1 2 3]]

Result:
The python program to print all prime numbers in a given interval (use break) is written and
executed successfully.
[Link]: 3(a-2) FIND COMMON VALUES BETWEEN TWO ARRAYS

Date:

Aim:
Write a python program to find common values between two arrays.

Algorithm:
Step 1: Import numpy.
Step 2: Define two numpy arrays.
Step 3: Find intersection between the arrays using the numpy.intersect1d() function.
Step 4: Print the array of intersecting elements.

Source code:
import numpy as np
array1 = [Link]([0, 10, 20, 40, 60])
print("Array1: ",array1)
array2 = [10, 30, 40]
print("Array2: ",array2)
print("Common values between two arrays:")
print(np.intersect1d(array1, array2))
Output:
Array1: [ 0 10 20 40 60]
Array2: [10, 30, 40]
Common values between two arrays:
[10 40]

Result:
The python program to write a python program to find common values between two arrays is
written and executed successfully.
[Link]: 3(b) FIND THE GREATEST COMMON DIVISOR

Date:

Aim:
Write a function called gcd that takes parameters a and b and returns their greatest common
divisor in python.
Pseudo Code of the Algorithm-
Step 1: Take two inputs, x and y, from the user.
Step 2: Pass the input number as an argument to a recursive function.
Step 3: If the second number is equal to zero (0), it returns the first number.
Step 4: Else it recursively calls the function with the second number as an argument until it
gets the remainder, which divides the second number by the first number.
Step 5: Call or assign the gcd_fun() to a variable.
Step 6: Display the GCD of two numbers.
Step 7: Exit from the program.
Source code:
def gcd_fun (x, y):
if (y == 0): # it divide every number
return x # return x
else:
return gcd_fun (y, x % y)
x =int (input ("Enter the first number: ")) # take first no.
y =int (input ("Enter the second number: ")) # take second no.
num = gcd_fun(x, y) # call the gcd_fun() to find the result
print("GCD of two number is: ")
print(num) # call num

OUTPUT:
Enter the first number:98
Enter the second number:56
GCD of two number is: 14

Result:
The python program to gcd that takes parameters a and b and returns their greatest common
divisor in python is written and executed successfully
[Link]: 3(c) PALINDROME PROGRAM
Date:
Aim:
Write a function called palindrome that takes a string argument and returns True if it
is a palindrome and False otherwise. Remember that you can use the built-in function len to
check the length of a string.
Algorithm:
Step1: Take a string from the user.
Step2: Pass the string as an argument to a recursive function.
Step3: In the function, if the length of the string is less than 1, return True.
Step4: If the last letter is equal to the first letter, recursively call the function with the
argument as the sliced list with the first character and last character removed else return
False.
Step5: Use an if statement if check if the returned value is True of False and print the final
result.
Step6: Exit.
SOURCE CODE:
def is_palindrome(s):
if len(s) < 1:
return True
else:
if s[0] == s[-1]:
return is_palindrome(s[1:-1])
else:
return False
a=str(input("Enter string:"))
if(is_palindrome(a)==True):
print("String is a palindrome!")
else:
print("String isn't a palindrome!")

Output:
Enter string: malayalam
String is a palindrome!
Enter string: muthu
String isn't a palindrome!

Result:
The python program to write a python program to find common values between two arrays is
written and executed successfully
[Link]: 4(a) SORTE THE LIST USING FUNCTION
Date:
Aim:
Write a function called is sorted that takes a list as a parameter and returns True if the list is
sorted in ascending order and False otherwise.

Algorithm:
STEP 1: Define the sorting function
STEP 2: Declare and initialize an array..
STEP 3: By passing the arguments, call the function.
STEP 4: Apply the parameter which you want to sort in an array.
STEP 5: Print the result statements

SOURCE CODE:
defis_sorted(listargs):
if sorted(listargs) == listargs:
return True
else:
return False

listargs=[2,3,4,5]
print(is_sorted(listargs))
listargs=[5,4,3,2]
print(is_sorted(listargs))
listargs=['a','b','c']
print(is_sorted(listargs))
listargs=['c','a','b']
print(is_sorted(listargs))

INPUT:
TEST CASE 1: listargs=[2,3,4,5]
TEST CASE2: listargs=[5,4,3,2]
TEST CASE 3: listargs=['a','b','c']
TEST CASE4: listargs=['c','a','b']

OUTPUT:
test case1: True.
test case 2 : False
test case3: True
test case4: False
Result:
The python program is written for doing the sorting operation in an array and executed
successfully.
[Link]: 4(b) FINDING THE DUPLICATE ELEMENT IN AN ARRAY
Date:

Aim:
Write a function called has duplicates that take a list and returns True if there is any element
that appears more than once. It should not modify the original list

Algorithm:
Step 1- Define a function to find duplicates
Step 2- In the function declare a list that will store all the duplicate integers
Step 3- Run a loop for each element in the list
Step 4- For each integer, run another loop that will check if the same integer is repeated
Step 5- If found the repeated integer will be added to another list using append()
Step 6- Return the list which stores repeated integers

Source Code:
class Solution:
def solution(self, list1):
fori in range(len(list1)):
for j in range(0, i):
if list1[i] == list1[j]:
return 'true'
return 'false'
obj = Solution()
list1 = [1, 2, 3, 4, 8, 2]
print([Link](list1))

INPUT:
list1 = [1, 2, 3, 4, 8, 2]
OUTPUT:
True
Result:
The python program is written for finding the duplicate in an array and executed successfully.
[Link]: 4(b-1) FINDING THE DUPLICATE AND REMVOING THE ELEMENT
IN AN ARRAY
Date:

Aim:
Write a function called remove duplicates that takes a list and returns a new list with only the
unique elements from the original.

Algorithm:
Step1: The list (l) with duplicate elements is taken to find the duplicates.
Step2: An empty list (l1) is taken to store the values of non-duplicate elements from the
given list.
Step3: The for loop is used to access the values in the list (l), and the if condition is used to
check if the elements in the given list (l) are present in the empty list (l1).
Step4: If the elements are not present, those values are appended to the list (l1); else, they are
printed.
Step5: Here, the list (l1) has no duplicates. The values printed are the duplicates from list (l).
Source Code:
defremove_duplicates(t):
"""Return new list with only unique elements."""
a = []
fori in t:
ifi not in a:
[Link](i)
return a

s =[1, 2, 3, 2, 2, 5, 6, 6, 8, 8]
a = remove_duplicates(s)
print(a)
INPUT:
s =[1, 2, 3, 2, 2, 5, 6, 6, 8, 8]
OUTPUT:
a=[1,2,3,5,6,8]

Result:
The python program is written for finding the duplicate in an array and executed successfully.
[Link]: 4(b-2) FINDING THE DUPLICATE AND REMVOING THE ELEMENT
IN AN ARRAY
Date:

Aim:
The wordlist I provided, [Link], doesn’t contain single letter words. So you might want to
add “I”, “a”, and the empty string.
AIM:
ALGORITHM:

SOURCE CODE:
Def make_word_dict():
d = dict()
fin = open('F:\RK\python programs\[Link]','r')
for line in fin:
word = [Link]().lower()
d[word] = word
for letter in ['a', 'i', '']:
d[letter] = letter
return d

word_dict = make_word_dict()
print(word_dict)

OUTPUT:
{'keys are the best words.': 'keys are the best words.', 'a': 'a', 'i': 'i', '': ''}
[Link]: 4(b-2) FINDING THE DUPLICATE AND REMVOING THE ELEMENT
IN AN ARRAY
Date:

Aim:
Write a python code to read dictionary values from the user. Construct a function to invert its
content. i.e., keys should be values and values should be keys.
AIM:
ALGORITHM:

SOURCE CODE:
METHOD-1:
old_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69, 'G': 67, 'H': 23}
new_dict = dict([(value, key) for key, value in old_dict.items()])
print ("Original dictionary is : ")
print(old_dict)
print()
print ("Dictionary after swapping is : ")
print("keys: values")
for i in new_dict:
print(i, " : ", new_dict[i])
OUTPUT:
Original dictionary is :
{'A': 66, 'B': 22, 'C': 45, 'D': 56, 'E': 12, 'F': 69, 'G': 67, 'H': 23}
Dictionary after swapping is :
keys: values
66 : A
22 : B
45 : C
56 : D
12 : E
69 : F
67 : G
23 : H

METHOD-2:
#d = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
#print("Original values of dictionary:",d)
#d_swap = {v: k for k, v in [Link]()}
#print("After swaping:",d_swap)
OUTPUT:
Original values of dictionary: {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
After swaping: {'val1': 'key1', 'val2': 'key2', 'val3': 'key3'}
3. i) Add a comma between the characters. If the given word is 'Apple', it should become
'A,p,p,l,e'
ii) Remove the given word in all the places in a string?
iii) Write a function that takes a sentence as an input parameter and replaces the first letter
of every word with the corresponding upper case letter and the rest of the letters in the word
by corresponding letters in lower case without using a built-in function?

3-i
AIM:
ALGORITHM:
SOURCE CODE:
x = "Apple"
y=''
fori in x:
y += i + ','*1
y = [Link]()
print(repr(y))
INPUT:
X=”Apple”
OUTPUT:
'A,p,p,l,e,'
3-ii Remove the given word in all the places in a string?
AIM:
ALGORITHM:
SOURCE CODE:
print("Enter the String: ")
text = input()
print("Enter a Word to Delete: ")
word = input()
text = [Link](word, "")
print("Strings after removed:")
print(text)
INPUT:
Enter the String:
Hello how are you
OUTPUT:
Enter the String:
Hello how are you
Enter a Word to Delete:
Hello
Strings after removed:
how are you
3-iii
AIM: Write a function that takes a sentence as an input parameter and replaces the first letter
of every word with the corresponding upper case letter and the rest of the letters in the word
by corresponding letters in lower case without using a built-in function?
ALGORITHM:

SOURCE CODE:
def convert(s):
# Create a char array of
# given string
ch = list(s)
fori in range(len(s)):
# If first character of a word is found
if (i == 0 and ch[i] != ' ' or
ch[i] != ' ' and
ch[i - 1] == ' '):
# If it is in lower-case
if (ch[i] >= 'a' and ch[i] <= 'z'):
# Convert into Upper-case
ch[i] = chr(ord(ch[i]) - ord('a') +
ord('A'))
# If apart from first character
# Any one is in Upper-case
elif (ch[i] >= 'A' and ch[i] <= 'Z'):
# Convert into Lower-Case
ch[i] = chr(ord(ch[i]) + ord('a') -
ord('A'))
# Convert the char array
# to equivalent string
st = "".join(ch)
returnst;
# Driver code
if __name__=="__main__":
s = "welcome to python class"
print(convert(s));

INPUT:
s= welcome to python class
OUTPUT:
Welcome To Python Class
4. Writes a recursive function that generates all binary strings of n-bit length

AIM:

ALGORITHM:

SOURCE CODE:
# Function to print the output
Def printTheArray(arr, n):
for i in range(0, n):
print(arr[i], end = " ")
print()
# Function to generate all binary strings
defgenerateAllBinaryStrings(n, arr, i):
ifi == n:
printTheArray(arr, n)
return
# First assign "0" at ith position and try for all other permutations for remaining
positions
arr[i] = 0
generateAllBinaryStrings(n, arr, i + 1)
# And then assign "1" at ith position and try for all other permutations for remaining
positions
arr[i] = 1
generateAllBinaryStrings(n, arr, i + 1)
# Driver Code
if __name__ == "__main__":
n=4
arr = [None] * n
# Print all binary strings
generateAllBinaryStrings(n, arr, 0)
OUTPUT:
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

You might also like