Write A Program of Bubble Sort
Write A Program of Bubble Sort
def bubble(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
def r_list(arr):
for i in arr:
print(i, end=" ")
print()
if __name__ == '__main__':
arr = [64, 34, 25, 12, 22, 11, 90]
print("Unsorted list:")
r_list(arr)
bubble(arr)
print("Sorted list:")
r_list(arr)
1
#OUTPUT
Unsorted list:
64 34 25 12 22 11 90
Sorted list:
11 12 22 25 34 64 90
2
#Programs based on Random Module
import random
def shuffle_list(my_list):
shuffled_list = my_list[:]
random.shuffle(shuffled_list)
return shuffled_list
original_list = [1, 2, 3, 4, 5]
shuffled_list = shuffle_list(original_list)
print("Original:", original_list)
print("Shuffled:", shuffled_list)
#Output
Original: [1, 2, 3, 4, 5]
Shuffled: [1, 3, 4, 2, 5]
3
#Generate a Random integer
import random
#Output
Random number: 38
4
#Choose a Random Element
import random
def choose(elements):
return random.choice(elements)
#Output
5
#Increment in Count using global Keyword
counter = 0
def increment():
global counter
counter += 1
def main():
print("Initial Counter Value:", counter)
increment()
print("After 1st Increment:", counter)
increment()
print("After 2nd Increment:", counter)
if __name__ == "__main__":
main()
#Output
Initial Counter Value: 0
After 1st Increment: 1
After 2nd Increment: 2
6
#Passing Immutable data type through functions
def process(data):
try:
data[0] = 'new value' # Attempt to modify data at index 0
except TypeError as e:
print(f'Error: {e}')
immutable_tup = (1, 2, 3, 4, 5)
modified_tup = process(immutable_tup)
7
#Output
Error:’tuple’ object does not support item assignment
Original Tuple: (1, 2, 3, 4, 5)
Modified Tuple: ('new value', 2, 3, 4, 5)
def modify(lst):
lst.append('new item')
my_list = [1, 2, 3]
print("Before Modification:", my_list)
modify(my_list)
print("After Modification:", my_list)
#Output
8
#Menu driven program for List
def display_menu():
print("\nMenu:")
print("1. Append an item")
print("2. Insert an item at a specific index")
print("3. Remove an item")
print("4. Pop an item")
print("5. Find the index of an item")
print("6. Count occurrences of an item")
print("7. Sort the list")
print("8. Reverse the list")
print("9. Display the list")
print("0. Exit")
def main():
my_list = input("Enter elements separated by spaces:
").split()
while True:
display_menu()
choice = input("Enter your choice: ")
9
if choice == '1':
item = input("Enter item to append: ")
my_list.append(item)
10
if my_list: # Check if the list is not empty
print(f"Popped item: {my_list.pop()}")
else:
print("List is empty")
11
elif choice == '8':
my_list.reverse()
print("List reversed")
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
12
#Output
Menu:
1. Append an item
2. Insert an item at a specific index
3. Remove an item
4. Pop an item
5. Find the index of an item
6. Count occurrences of an item
7. Sort the list
8. Reverse the list
9. Display the list
0. Exit
Enter your choice: 4
Popped item: 5
13
#Menu driven program for string
def string_operations():
string = ""
while True:
print("\nString Operations Menu:")
print("1. Input a String")
print("2. Print the Current String")
print("3. Reverse the String")
print("4. Convert to Uppercase")
print("5. Convert to Lowercase")
print("6. Check if Palindrome")
print("7. Exit")
if choice == '1':
string = input("Enter a string: ")
14
elif choice == '3':
print("Reversed string:", string[::-1])
else:
15
print("Invalid choice. Please try again.")
if __name__ == "__main__":
string_operations()
#Output
Enter a new string:String
String Operations Menu:
1. Input a String
2. Print the Current String
3. Reverse the String
4. Convert to Uppercase
5. Convert to Lowercase
6. Check if Palindrome
7. Exit
Enter your choice: 4
Uppercase string:STRING
16
#Program using parameterized,default and key
if age:
print(f"My {animal_type} is {age} years old.")
17
# Using all types of arguments including keyword
arguments
describe_pet("Rex", "cat", 5, color='brown', size='Large')
#OUTPUT
I have a cat.
My cat's name is Willie.
I have a Dog.
My Dog's name is Buddy.
I have a cat.
18
My cat's name is Rex.
My cat is 5 years old.
My cat's color is brown.
My cat's size is Large.
I have a cat.
My cat's name is Bella.
My cat's color is black.
I have a rabbit.
My rabbit's name is Max.
My rabbit is 3 years old.
My rabbit's breed is Lop.
My rabbit's favorite food is carrots.
19
#PROGRAM to count ME AND MY IN Text file
return word_count
filename = 'story.txt'
words_to_count = ['me', 'my']
counts = count_words(filename, words_to_count)
print(counts)
#OUTPUT
{'me': 7, 'my': 7}
20
#Questions based on function
def add_no(a, b):
sum = a + b
print("Sum:", sum)
add_no(54, 34)
#OUTPUT
Sum: 88
---------------------------------------------------------------------------
def square(num):
sq = num * num
return sq
Square = square(13)
print('Square:', Square)
#OUTPUT
Square: 169
21
def calc(a, b):
sum = a + b
print("Addition:", sum)
N = 65
n = 32
c = calc(N, n) # This will print the sum but c will be None
#OUTPUT
Addition: 97
def increment(n):
n.append([4])
return n
22
#OUTPUT
def table(num):
for i in range(1, 6):
print(num, 'X', i, '=', num * i)
n = 69
table(n)
#OUTPUT
69 X 1 = 69
69 X 2 = 138
69 X 3 = 207
69 X 4 = 276
69 X 5 = 345
23
def generate_random():
import random
return random.randint(1, 143)
random_n = generate_random()
print("Number:", random_n)
#OUTPUT
Number:13
def update(x=69):
x += 12
print('x =', x)
x = 96
update()
print('x =', x)
24
#OUTPUT
x = 81
x = 96
s = 'WELCOME'
def change(T):
T = 'HELLO'
print(T, end='@')
change(s)
print(s)
#OUTPUT
HELLO@WELCOME
a = 10
def call():
global a
a = 13
25
b = 14
print(a)
#OUTPUT
13
25*50!100!25
ans = 'y'
while ans == 'y':
# Get student details
rno = int(input("Enter roll no: "))
26
name = input("Enter name: ")
marks = float(input("Enter marks: "))
#Output
27
Program to append data in file created in previous file
import pickle
ans = 'y'
while ans == 'y':
# Get student details
rno = int(input("Enter roll no: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))
28
pickle.dump(stu, stufile)
#Output
29
#Program to read objects and display them
import pickle
try:
while True:
# Load the dictionary from the binary file
stu = pickle.load(stufile)
print(stu)
except EOFError:
# This exception is raised when the end of the file is
reached
stufile.close()
#Output
{'Rollno': 3, 'Name': 'Anant', 'Marks': 100.0}
{'Rollno': 4, 'Name': 'anurag', 'Marks': 60.0}
30