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

Write A Program of Bubble Sort

Uploaded by

anantsharm.44
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views30 pages

Write A Program of Bubble Sort

Uploaded by

anantsharm.44
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

#Sorting a list using Bubble Sorting

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

def generate(start, end):


return random.randint(start, end)

result = generate(10, 50)


print("Random number:", result)

#Output

Random number: 38

4
#Choose a Random Element

import random

def choose(elements):
return random.choice(elements)

elements = ['Mango', 'Apple', 'Banana', 'Strawberry']


chosen_ele = choose(elements)
print("Random element:", chosen_ele)

#Output

Random element: Banana

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}')

# Create a new tuple with 'new value' at index 0

new_data = ('new value',) + data[1:]


return new_data

immutable_tup = (1, 2, 3, 4, 5)
modified_tup = process(immutable_tup)

print("Original Tuple:", immutable_tup)


print("Modified Tuple:", modified_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)

#Passing Mutable data type through function

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

Before Modification: [1, 2, 3]


After Modification: [1, 2, 3, 'new item']

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)

elif choice == '2':


item = input("Enter item to insert: ")
index = int(input("Enter index: "))
if 0 <= index <= len(my_list):
my_list.insert(index, item)
else:
print("Invalid index")

elif choice == '3':


item = input("Enter item to remove: ")
if item in my_list:
my_list.remove(item)
else:
print("Item not found in the list")

elif choice == '4':

10
if my_list: # Check if the list is not empty
print(f"Popped item: {my_list.pop()}")
else:
print("List is empty")

elif choice == '5':


item = input("Enter item to find index of: ")
if item in my_list:
print(f"Index of {item}: {my_list.index(item)}")
else:
print("Item not found in the list")

elif choice == '6':


item = input("Enter item to count occurrences of: ")
print(f"{item} occurs {my_list.count(item)} times in
the list")

elif choice == '7':


my_list.sort()
print("List sorted")

11
elif choice == '8':
my_list.reverse()
print("List reversed")

elif choice == '9':


print(f"Current list: {my_list}")

elif choice == '0':


print("Exiting the program")
break

else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

12
#Output

Enter elements separated by spaces: 1 2 3 4 5

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")

choice = input("Enter your choice: ")

if choice == '1':
string = input("Enter a string: ")

elif choice == '2':


print("Current string:", string)

14
elif choice == '3':
print("Reversed string:", string[::-1])

elif choice == '4':


print("Uppercase string:", string.upper())

elif choice == '5':


print("Lowercase string:", string.lower())

elif choice == '6':


if string == string[::-1]:
print("The string is a Palindrome.")
else:
print("The string is not a Palindrome.")

elif choice == '7':


print("Exiting program")
break

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

def describe_pet(pet_name, animal_type='cat', age=None,


**kwargs):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name}.")

if age:
print(f"My {animal_type} is {age} years old.")

for key, value in kwargs.items():


print(f"My {animal_type}'s {key} is {value}.")

# Function calls using different argument types

# Using only the required argument


describe_pet('Willie')

# Using a mix of required and default arguments


describe_pet('Buddy', 'Dog')

17
# Using all types of arguments including keyword
arguments
describe_pet("Rex", "cat", 5, color='brown', size='Large')

# Using default and keyword arguments, skipping the


optional positional argument
describe_pet('Bella', color='black')

# Using only keyword arguments for additional details


describe_pet('Max', 'rabbit', age=3, breed='Lop',
favorite_food='carrots')

#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

def count_words(filename, words):


word_count = {word: 0 for word in words}

with open(filename, 'r') as file:


for line in file:
for word in words:
word_count[word] +=
line.lower().split().count(word.lower())

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

L = [11, 21, 31]


m = increment(L)
print(L, m)

22
#OUTPUT

[11, 21, 31, [4]] [11, 21, 31, [4]]

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

Program to get data and write on a Binary File


import pickle

# Initialize an empty dictionary


stu = {}

# Open the binary file in write mode


stufile = open('stu.dat', 'wb')

ans = 'y'
while ans == 'y':
# Get student details
rno = int(input("Enter roll no: "))

26
name = input("Enter name: ")
marks = float(input("Enter marks: "))

# Store the details in the dictionary


stu['Rollno'] = rno
stu['Name'] = name
stu['Marks'] = marks

# Write the dictionary to the binary file


pickle.dump(stu, stufile)
ans = input("Want to add more records? (y/n): ").lower()

# Close the binary file after the loop ends


stufile.close()

#Output

Enter roll no: 3


Enter name: Anant
Enter marks: 100
Want to add more records? (y/n): n

27
Program to append data in file created in previous file
import pickle

# Initialize an empty dictionary


stu = {}

stufile = open('stu.dat', 'ab')

ans = 'y'
while ans == 'y':
# Get student details
rno = int(input("Enter roll no: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))

# Store the details in the dictionary


stu['Rollno'] = rno
stu['Name'] = name
stu['Marks'] = marks

# Write the dictionary to the binary file

28
pickle.dump(stu, stufile)

# Ask the user if they want to add more records


ans = input("Want to add more records? (y/n): ").lower()

# Close the binary file after the loop ends


stufile.close()

#Output

Enter roll no: 4


Enter name: Anurag
Enter marks: 60
Want to add more records? (y/n): n

29
#Program to read objects and display them

import pickle

# Open the binary file in read mode


stufile = open('stu.dat', 'rb')

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

You might also like