0% found this document useful (0 votes)
17 views

New_python_programs

Uploaded by

Nitheesh Bobby
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)
17 views

New_python_programs

Uploaded by

Nitheesh Bobby
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/ 53

Python Programs:

Simple Python program to find the factorial of a number:


def fact(num):
f=1
for i in range(1,num+1):
f*=i
return f
print(fact(5))
*** Second Method ***(Recursion):
def fact(num):
return 1 if (num ==1 or num ==0) else num*fact(num-1)
print(fact(5))

Python Program to Check Armstrong Number


def is_amstrong(num):
num_str = str(num)
l = len(num_str)
s=0
for digit in num_str:
s += int(digit)**l
if s == num:
return True
else:
return False
n = int(input("Enter a number"))
if(is_amstrong(n)):
print(f" {n} is an amstrong")
else:
print(f" {n} is not an amstrong")

given a list of numbers print the amstrong numbers among


the array in python
def is_amstrong(num):
num_str = str(num)
l = len(num_str)
s = sum(int(digit) ** l for digit in num_str)
return s == num

numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))


amstrong_numbers = [num for num in numbers if is_amstrong(num)]

print("Armstrong numbers in the list:", amstrong_numbers)

Prime number between an interval:


def is_prime(num):
if num <= 1:
return False
elif num == 2:
return True
else:
for i in range(2,num):
if (num%i==0):
return False
return True
a = int(input("enter a number"))
b = int(input("enter a number greater than a"))
if(b>a):
for i in range(a,b+1):
if(is_prime(i)):
print(f"{i} is prime number")
else:
print(f"{i} is not prime number")
else:
print("give a valid interval")

Python Program to Check Prime Number


def is_prime(num):
if num <= 1:
return False
elif num == 2:
return True
else:
for i in range(2,num):
if (num%i==0):
return False
return True
n=int(input("Enter a number"))
if(is_prime(n)):
print(f"{n} is a prime number")
else:
print(f"{n} is not a prime number")
Python Program for n-th Fibonacci number Using
Recursion

def fabi(n):
if n <=0:
return "Enter the correct number"
if n == 1:
return 0
if n == 2:
return 1
else:
return fabi(n-1) + fabi(n-2)
n = int(input("Enter a number"))
print(fabi(n))

Fabinoccii series:
def fabinocii(n):
n1 = 0
n2 = 1
count = 0
while count < n:
print(n1,end = ' ')
nth = n1 + n2
n1 = n2
n2 = nth
count+=1
n = int(input("Enter a number for fabinocii series"))
fabinocii(n)
Fabinocii series in Recursion:
def fibonacci_recursive(n, n1=0, n2=1, count=0):
if count >= n:
return
print(n1, end=' ')
fibonacci_recursive(n, n2, n1 + n2, count + 1)

# Input the number of terms


n = int(input("Enter a number for Fibonacci series: "))
fibonacci_recursive(n)

Leap year or not


def is_leap(year):
if(year%400==0) and (year%100==0):
print(f"{year} is leap year")
elif (year%4==0) and (year%100!=0):
print(f"{year} is leap year")
else:
print(f"{year} is not a leap year")
year=int(input("Enter a year"))
is_leap(year)

Lcm and hcf of two numbers:


def compute_hcf(x,y):
while(y):
x,y=y,x%y
return x
x=int(input("enter a number"))
y=int(input("enter a number"))
print(compute_hcf(x,y))
lcm=(x*y)//compute_hcf(x,y)
print("lcm of the numbers is",lcm)

Print a table:
n=int(input("enter a number"))
for i in range(1,11):
print(n," ","*"," ",i," ","="," ",n*i)

List Programs;
Python program to find Cumulative sum of a
list
The problem statement asks to produce a new list whose i^{th} element will be equal to the sum
of the (i + 1) elements.
Input : list = [10, 20, 30, 40, 50]
Output : [10, 30, 60, 100, 150]

Input : list = [4, 10, 15, 18, 20]


Output : [4, 14, 29, 47, 67]
# Python code to get the Cumulative sum of a list
def Cumulative(lists):
cu_list = []
length = len(lists)
cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)]
return cu_list[1:]
# Driver Code
lists = [10, 20, 30, 40, 50]
print (Cumulative(lists))

Matrix Problems:
Matrix Addtion:
# Input for matrix X
xr = int(input("Enter the number of rows for matrix X: "))
xc = int(input("Enter the number of columns for matrix X: "))
x = []
print("Enter the elements of matrix X:")
for i in range(xr):
row = []
for j in range(xc):
row.append(int(input(f"Element [{i+1}][{j+1}]: ")))
x.append(row)

# Input for matrix Y


yr = int(input("Enter the number of rows for matrix Y: "))
yc = int(input("Enter the number of columns for matrix Y: "))
y = []
print("Enter the elements of matrix Y:")
for i in range(yr):
row = []
for j in range(yc):
row.append(int(input(f"Element [{i+1}][{j+1}]: ")))
y.append(row)
# Check if addition is possible
if xr != yr or xc != yc:
print("Matrix addition is not possible. Both matrices must have the same dimensions.")
else:
# Initialize result matrix
res = [[0] * xc for _ in range(xr)]

# Perform matrix addition


for i in range(xr):
for j in range(xc):
res[i][j] = x[i][j] + y[i][j]

# Display the result


print("Resultant Matrix (Addition):")
for row in res:
print(row)

Matrix Subraction:
# Input for matrix X
xr = int(input("Enter the number of rows for matrix X: "))
xc = int(input("Enter the number of columns for matrix X: "))
x = []
print("Enter the elements of matrix X:")
for i in range(xr):
row = []
for j in range(xc):
row.append(int(input(f"Element [{i+1}][{j+1}]: ")))
x.append(row)

# Input for matrix Y


yr = int(input("Enter the number of rows for matrix Y: "))
yc = int(input("Enter the number of columns for matrix Y: "))
y = []
print("Enter the elements of matrix Y:")
for i in range(yr):
row = []
for j in range(yc):
row.append(int(input(f"Element [{i+1}][{j+1}]: ")))
y.append(row)

# Check if addition is possible


if xr != yr or xc != yc:
print("Matrix addition is not possible. Both matrices must have the same dimensions.")
else:
# Initialize result matrix
res = [[0] * xc for _ in range(xr)]

# Perform matrix subraction


for i in range(xr):
for j in range(xc):
res[i][j] = x[i][j] -y[i][j]

# Display the result


print("Resultant Matrix (Addition):")
for row in res:
print(row)

Matrix Multiplication:
xr = int(input("Enter the number of rows for matrix X: "))
xc = int(input("Enter the number of columns for matrix X: "))
x = []
print("Enter the elements of matrix X:")
for i in range(xr):
row = []
for j in range(xc):
row.append(int(input(f"Element [{i+1}][{j+1}]: ")))
x.append(row)

yr = int(input("Enter the number of rows for matrix Y: "))


yc = int(input("Enter the number of columns for matrix Y: "))
y = []
print("Enter the elements of matrix Y:")
for i in range(yr):
row = []
for j in range(yc):
row.append(int(input(f"Element [{i+1}][{j+1}]: ")))
y.append(row)

# Check if multiplication is possible


if xc != yr:
print("Matrix multiplication is not possible. Columns of X must match rows of Y.")
else:
# Initialize result matrix with zeros
res = [[0] * yc for _ in range(xr)]

# Perform matrix multiplication


for i in range(xr):
for j in range(yc):
for k in range(xc): # or `yr` since xc == yr
res[i][j] += x[i][k] * y[k][j]

# Display the result


print("Resultant Matrix (Multiplication):")
for row in res:
print(row)

Matrix transpose:
xr=int(input("enter no of rows"))
xc=int(input("enter no of columns"))
x=[]
print("Enter the elements of matrix")
for i in range(xr):
row=[]
for j in range(xc):
row.append(int(input()))
x.append(row)
print("Matrix before transpose")
for row in x:
print(row)
print("matrix after transpose")
transpose = [[x[j][i] for j in range(xr)] for i in range(xc)]
for row in transpose:
print(row)

Python | Get Kth Column of Matrix


test_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]

K=2

res = []

for i in range(len(test_list)):
res.append(test_list[i][K])

print("The Kth column of matrix is : " + str(res))

Python Program to Check if a String is


Palindrome or Not
def is_palindrome(stri):
return True if stri.lower()==stri[::-1].lower() else False
print(is_palindrome("Mom"))

Python program to check whether the string is


Symmetrical or Palindrome
string = input("enter a string")
half=len(string)//2
first_str=string[:half]
second_str=string[half:] if len(string)//2==0 else string[half+1]
if first_str == second_str:
print(f"{string} is symmetrical")
else:
print(f"{string} is not symmetrical")

Reverse Words in a Given String in Python


We are given a string and we need to reverse words of a given string
Examples:
Input : str =" geeks quiz practice code"
Output : str = code practice quiz geeks
Input : str = "my name is laxmi"
output : str= laxmi is name my

def rev_sentence(sentence):
words = sentence.split(' ')
reverse_sentence = ' '.join(reversed(words))
return reverse_sentence
sentence=input("enter a sentence")
print(rev_sentence(sentence))

Check if String Contains Substring in Python


# input strings str1 and substr
string = "geeks for geeks" # or string=input() -> taking input from the user
substring = "geeks" # or substring=input()

# splitting words in a given string


s = string.split()
# checking condition
# if substring is present in the given string then it gives output as yes
if substring in s:
print("yes")
else:
print("no")

Python – Words Frequency in String


Shorthands
Input : test_str = 'Gfg is best'
Output : {'Gfg': 1, 'is': 1, 'best': 1}

test_str = input("enter a string")


print("The original string is: " + str(test_str))
res={key:test_str.count(key) for key in test_str.split()}
print("The words frequecy is: " + str(res))

Python program to print even length words in


a string
Input: s = "This is a python language"
Output: This is python language

Input: s = "i am laxmi"


Output: am
n="This is a python language"
#splitting the words in a given string
s=n.split(" ")
for i in s:
#checking the length of words
if len(i)%2==0:
print(i)

Python Program to Accept the Strings Which


Contains all Vowels
Given a string, the task is to check if every vowel is present or not. We consider a vowel to be
present if it is present in upper case or lower case. i.e. ‘a’, ‘e’, ‘i’.’o’, ‘u’ or ‘A’, ‘E’, ‘I’, ‘O’, ‘U’
.
Examples :
Input : geeksforgeeks
Output : Not Accepted
All vowels except 'a','i','u' are not present

Input : ABeeIghiObhkUul
Output : Accepted
All vowels are present

def check(string):
string=string.lower()
vowels=set("aeiou")
s=set({})
for char in string:
if char in vowels:
s.add(char)
else:
pass
if len(s)==len(vowels):
print("Accepted")
else:
print("not accepted")
string = input("enter a string")
check(string)

Python | Count the Number of matching


characters in a pair of string
Given a pair of non-empty strings. Count the number of matching characters in those strings
(consider the single count for the character which have duplicates in the strings).
Examples:
Input : str1 = 'abcdef'
str2 = 'defghia'
Output : 4
(i.e. matching characters :- a, d, e, f)

Input : str1 = 'aabcddekll12@'


str2 = 'bb2211@55k'
Output : 5
(i.e. matching characters :- b, 1, 2, @, k)

str1=input("enter a string")
str2=input("enter a string")
s1=set(str1)
s2=set(str2)
count=0
for i in s1:
if i in s2:
count +=1
print(count)
Remove All Duplicates from a Given String in
Python
def removeDupWithoutOrder(str):
return "".join(set(str))

Find words which are greater than given


length k
A string is given, and you have to find all the words (substrings separated by a space) which are
greater than the given length k.
Examples:
Input : str = "hello geeks for geeks
is computer science portal"
k=4
Output : hello geeks geeks computer
science portal
Explanation : The output is list of all
words that are of length more than k.
def string_k(k,str1):
str_res=[]
text = str1.split(" ")
for x in text:
if(len(x) > k):
str_res.append(x)
return str_res
k=int(input("Enter the value of k"))
str1=input("enter the string")
print(string_k(k,str1))
Python program for removing i-th character
from a string
s = "PythonProgramming"

# Index of the character to remove


i=6

# Removing i-th character


res = s[:i] + s[i+1:]
print(res)

Python | Check if a given string is binary


string or not
Given string str. The task is to check whether it is a binary string or not.
Examples:
Input: str = "01010101010"
Output: Yes

Input: str = "geeks101"


Output: No
def check(str1):
p = set(str1)
s = {'0' , '1'}
if p == s or p == {'0'} or p == {'1'}:
print("yes")
else:
print("no")
str1=input("Enter a string")
check(str1)

Dictionary Programs:

Ways to sort list of dictionaries by values in


Python – Using itemgetter
# Python code to demonstrate the working of sorted()
# and itemgetter

# importing "operator" for implementing itemgetter


from operator import itemgetter

# Initializing list of dictionaries


data_list = [{"name": "Nandini", "age": 20},
{"name": "Manjeet", "age": 20},
{"name": "Nikhil", "age": 19}]

# using sorted and itemgetter to print list sorted by age


print("The list printed sorting by age: ")
print(sorted(data_list, key=itemgetter('age')))

print("\r")

# using sorted and itemgetter to print


# list sorted by both age and name
# notice that "Manjeet" now comes before "Nandini"
print("The list printed sorting by age and name: ")
print(sorted(data_list, key=itemgetter('age', 'name')))

print("\r")

# using sorted and itemgetter to print list


# sorted by age in descending order
print("The list printed sorting by age in descending order: ")
print(sorted(data_list, key=itemgetter('age'), reverse=True))

Python – Extract Unique values dictionary


values
# Python3 code to demonstrate working of
# Extract Unique values dictionary values
# Using set comprehension + values() + sorted()

# initializing dictionary
test_dict = {'gfg': [5, 6, 7, 8],
'is': [10, 11, 7, 5],
'best': [6, 12, 10, 8],
'for': [1, 2, 5]}

# printing original dictionary


print("The original dictionary is : " + str(test_dict))

# Extract Unique values dictionary values


# Using set comprehension + values() + sorted()
res = list(sorted({ele for val in test_dict.values() for ele in val}))

# printing result
print("The unique values list is : " + str(res))

Ways to sort list of dictionaries by values in


Python – Using lambda function
# Python code demonstrate the working of
# sorted() with lambda

# Initializing list of dictionaries


list = [{"name": "Nandini", "age": 20},
{"name": "Manjeet", "age": 20},
{"name": "Nikhil", "age": 19}]

# using sorted and lambda to print list sorted


# by age
print("The list printed sorting by age: ")
print(sorted(list, key=lambda i: i['age']))

print("\r")

# using sorted and lambda to print list sorted


# by both age and name. Notice that "Manjeet"
# now comes before "Nandini"
print("The list printed sorting by age and name: ")
print(sorted(list, key=lambda i: (i['age'], i['name'])))
print("\r")

# using sorted and lambda to print list sorted


# by age in descending order
print("The list printed sorting by age in descending order: ")
print(sorted(list, key=lambda i: i['age'], reverse=True))

Programs:

Matrix search:
def Matrix_search(arr,x):
found=False
for i in range(len(arr)):
for j in range(len(arr[0])):
if x == arr[i][j]:
print(f"element is in {i}th row and {j}th column")
found=True
break
if found:
break
if not found:
print(-1)
Matrix_search([[1,2,3],[4,5,6],[7,8,9]],3)
string reverse: slicing,method,recursion,reverse for loop:
slicing:
def reverseing(string1):
return string1[::-1]
print(reverseing("hello world"))

METHOD:
def reverseing(str):
strrev="".join(reversed(str))
return strrev
str=input("enter a string")
print(reverseing(str))
FOR LOOP:
original_string = "Hello, World!"
reversed_string = ''
for char in original_string:
reversed_string = char + reversed_string
print(reversed_string) # Output: !dlroW ,olleH

REVERSE A FOR LOOP:

# Initializing number from which


# iteration begins
N=6

# using reversed() to perform the back iteration


print ("The reversed numbers are : ", end = "")
for num in reversed(range(N + 1)) :
print(num, end = " ")
original_string = "Hello, World!"
for char in reversed(original_string):
print(char, end='')

RECURRSION:
def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]

s = "Geeksforgeeks"

print("The original string is : ", end="")


print(s)

print("The reversed string(using recursion) is : ", end="")


print(reverse(s))

Strong number:

import math
def strong(num):
num_str=str(num)
sum=0
for i in num_str:
sum+=math.factorial(int(i))
if sum==num:
print(f"{num} is strong number")
else:
print(f"{num} is weak number")
strong(145)

Printing factors :
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)

num = 320

print_factors(num)

Printing Prime factors of a given number:


def prime_factors(num):
while num%2==0:
print(2,end=" ")
num=num//2
for i in range(3,int(num**0.5)+1,2):
while num%i==0:
print(i,end=" ")
num=num//i
if num >2:
print(num,end=" ")
num=int(input("enter a number"))
prime_factors(num)

Pattern Programs:

*****
*****
*****
*****
*****
n=5
for i in range(n):
for j in range(n):
print("*",end=" ")
print()

*
**
***
****
*****
n=5
for i in range(n):
for j in range(i+1):
print("*",end=" ")
print()
*****
****
***
**
*
n=5
for i in range(n):
for j in range(i,n):
print("*",end=" ")
print()

n=5
for i in range(n):
for j in range(i,n):
print(" ",end=" ")
for j in range(i+1):
print("*",end=" ")
print()
n=5
for i in range(n):
for j in range(i+1):
print(" ",end=" ")
for j in range(i,n):
print("*",end=" ")
print()

n=5
for i in range(n):
for j in range(i,n):
print(" ",end=" ")
for j in range(i):
print("*",end=" ")
for j in range(i+1):
print("*",end=" ")
print()

n=5
for i in range(n):
for j in range(i+1):
print(" ",end=" ")
for j in range(i,n-1):
print("*",end=" ")
for j in range(i,n):
print("*",end=" ")
print()
n=5
for i in range(n-1):
for j in range(i,n):
print(" ",end=" ")
for j in range(i):
print("*",end=" ")
for j in range(i+1):
print("*",end=" ")
print()
for i in range(n):
for j in range(i+1):
print(" ",end=" ")
for j in range(i,n-1):
print("*",end=" ")
for j in range(i,n):
print("*",end=" ")
print()

Square and Hollow Patterns:

n=5
for i in range(n):
for j in range(n):
if(j==0 or j==4):
print("*",end=" ")
else:
print(" ",end=" ")
print()

n=5
for i in range(n):
for j in range(n):
if(i==n//2 or j==n//2):
print("*",end=" ")
else:
print(" ",end=" ")
print()
n=5
for i in range(n):
for j in range(n):
if(i==j or i+j==n-1):
print("*",end=" ")
else:
print(" ",end=" ")
print()

n=5
for i in range(n):
for j in range(n):
if(i==0 or j==0 or i==n-1 or j==n-1):
print("*",end=" ")
else:
print(" ",end=" ")
print()

n=5
for i in range(n):
for j in range(i+1):
if(i==n-1 or j==0 or j==i):
print("*",end=" ")
else:
print(" ",end=" ")
print()

n=5
for i in range(n):
for j in range(i,n):
if(i==0 or j==i or j==n-1):
print("*",end=" ")
else:
print(" ",end=" ")
print()

n=5
for i in range(n):
for j in range(i,n):
print(" ",end=" ")
for j in range(i):
if(i==n-1 or j==0):
print("*",end=" ")
else:
print(" ",end=" ")
for j in range(i+1):
if(i==n-1 or j==i):
print("*",end=" ")
else:
print(" ",end=" ")
print()
n=5
for i in range(n-1):
for j in range(i,n-1):
print(" ",end=" ")
for j in range(i):
if(j==0):
print("*",end=" ")
else:
print(" ",end=" ")
for j in range(i+1):
if(j==i):
print("*",end=" ")
else:
print(" ",end=" ")
print()

for i in range(n):
for j in range(i):
print(" ",end=" ")
for j in range(i,n):
if(j==i):
print("*",end=" ")
else:
print(" ",end=" ")
for j in range(i,n-1):
if(j==n-2):
print("*",end=" ")
else:
print(" ",end=" ")
print()

Number Pattern programs:

n=5
k=1
for i in range(n):
for j in range(i+1):
print(k,end=" ")
k+=1
print()
Searching and Sorting Programs:
Linear Search:
Time Complexity:
• Best Case: In the best case, the key might be present at the first index. So the best case
complexity is O(1)
• Worst Case: In the worst case, the key might be present at the last index i.e., opposite to
the end from which the search has started in the list. So the worst-case complexity is
O(N) where N is the size of the list.
• Average Case: O(N)
Auxiliary Space: O(1)
def linear_search(arr,x):
for i in range(len(arr)):
if arr[i]==x:
return i
return -1
arr=list(map(int,input("enter the array elements").split()))
x=int(input("enter the search element"))
res = linear_search(arr,x)
if(res):
print(f"the element is in the {res} th index")
else:
print("element is not present in the array")

Binary Search:(Recursive Approach)


• Time Complexity:
o Best Case: O(1)
o Average Case: O(log N)
o Worst Case: O(log N)
• Auxiliary Space: O(1),
def binary_search(arr,l,h,x):
if l<=h:
mid=(l+h)//2
if(arr[mid]==x):
return mid+1
elif(arr[mid]>x):
return binary_search(arr,l,mid,x)
else:
return binary_search(arr,mid+1,h,x)
else:
return -1
arr=list(map(int,input("Enter array elements").split()))
x=int(input("enter the search element"))
res=binary_search(arr,0,len(arr)-1,x)
if(res==-1):
print("there is no such element")
else:
print(f"The element is found at {res} th position")

Binary Search:(Iterative Approach)


def binarySearch(arr, low, high, x):

while low <= high:

mid = low + (high - low) // 2

# Check if x is present at mid


if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
low = mid + 1

# If x is smaller, ignore right half


else:
high = mid - 1

# If we reach here, then the element


# was not present
return -1

Sorting:
Insertion Sort Algorithm
Time Complexity of Insertion Sort
• Best case: O(n) , If the list is already sorted, where n is
the number of elements in the list.
• Average case: O(n 2 ) , If the list is randomly ordered
• Worst case: O(n 2 ) , If the list is in reverse order
def insertion(arr):
for i in range(1,len(arr)):
key=arr[i]
j=i-1
while j>=0 and key < arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=key
return arr
arr=list(map(int,input("enter the array elements").split()))
print(insertion(arr))

Merge Sort
Complexity Analysis of Merge Sort:
• Time Complexity:
o Best Case: O(n log n), When the array is already sorted or nearly sorted.
o Average Case: O(n log n), When the array is randomly ordered.
o Worst Case: O(n log n), When the array is sorted in reverse order.
• Auxiliary Space: O(n),
def merge_sort(arr):
if len(arr)>1:
mid=len(arr)//2
left_half=arr[:mid]
right_half=arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k]=left_half[i]
i+=1
else:
arr[k]=right_half[j]
j+=1
k+=1
while i < len(left_half):
arr[k]=left_half[i]
i+=1
k+=1
while j < len(right_half):
arr[k]=right_half[j]
j+=1
k+=1
arr=list(map(int,input("Enter array elements").split()))
merge_sort(arr)
print("sorted array is: ",arr)

Quick Sort
Time Complexity:
• Best Case: (Ω(n log n)), Occurs when the pivot element divides the array into two equal
halves.
• Average Case (θ(n log n)), On average, the pivot divides the array into two parts, but not
necessarily equal.
• Worst Case: (O(n²)), Occurs when the smallest or largest element is always chosen as
the pivot (e.g., sorted arrays).
• def quick_sort(arr):
• # Base case: arrays with 0 or 1 element are already sorted
• if len(arr) <= 1:
• return arr

• # Choose the pivot (using the first element as pivot)
• pivot = arr[0]

• # Partitioning the array into two halves
• left = [x for x in arr[1:] if x <= pivot]
• right = [x for x in arr[1:] if x > pivot]

• # Recursively sort the left and right halves and combine them with the pivot
• return quick_sort(left) + [pivot] + quick_sort(right)

• # Example usage
• arr = [3, 23, 1, 45, 67, 2, 6]
• print(quick_sort(arr))

Selection Sort
Complexity Analysis of Selection Sort
Time Complexity: O(n2) ,as there are two nested loops:
• One loop to select an element of Array one by one = O(n)
• Another loop to compare that element with every other Array element = O(n)
• Therefore overall complexity = O(n) * O(n) = O(n*n) = O(n2)
Auxiliary Space: O(1)

def selection(arr):
n=len(arr)
for i in range(n-1):
min_idx=i
for j in range(i+1,n):
if(arr[j]<arr[min_idx]):
min_idx=j
arr[i],arr[min_idx]=arr[min_idx],arr[i]
arr=list(map(int,input("Enter array elements").split()))
selection(arr)
print("The sorted array is: ",arr)

Bubble Sort Algorithm


Time Complexity: O(n2)
Auxiliary Space: O(1)
def bubble(arr):
n=len(arr)
for i in range(n):
swapped = False
for j in range(0,n-i-1):
if(arr[j]>arr[j+1]):
arr[j],arr[j+1]=arr[j+1],arr[j]
swapped=True
if(swapped==False):
break
arr=list(map(int,input("Enter the array elements").split()))
bubble(arr)
print("The sorted array is: ",arr)

Dsa Programs:
Stack implementation using arrays.
Stack Implementation
class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return len(self.stack) == 0
def push(self, item):
self.stack.append(item)
def pop(self):
if self.is_empty():
raise IndexError("pop from empty stack")
return self.stack.pop()
def peek(self):
if self.is_empty():
raise IndexError("peek from empty stack")
return self.stack[-1]

def size(self):
return len(self.stack)

def __str__(self):
return str(self.stack)

# Example usage
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print("Stack:", stack)
print("Pop:", stack.pop())
print("Peek:", stack.peek())
print("Size:", stack.size())
print("Is empty:", stack.is_empty())
Output:
Stack: [1, 2, 3]
Pop: 3
Peek: 2
Size: 2
Is empty: False
Implementing stack using linkedlist:
class Node:
def __init__(self, data):
self.data = data
self.next = None

class Stack:
def __init__(self):
self.top = None

def is_empty(self):
return self.top is None

def push(self, data):


new_node = Node(data)
new_node.next = self.top
self.top = new_node

def pop(self):
if self.is_empty():
return "Stack is empty"
popped_node = self.top
self.top = self.top.next
return popped_node.data

def peek(self):
if self.is_empty():
return "Stack is empty"
return self.top.data

def display(self):
if self.is_empty():
return "Stack is empty"
current = self.top
stack_elements = []
while current:
stack_elements.append(current.data)
current = current.next
return stack_elements

# Example usage:
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)

print("Stack after pushing elements:", stack.display())


print("Top element:", stack.peek())
print("Popped element:", stack.pop())
print("Stack after popping an element:", stack.display())
Stack after pushing elements: [30, 20, 10]
Top element: 30
Popped element: 30
Stack after popping an element: [20, 10]

You might also like