New_python_programs
New_python_programs
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)
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]
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)
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)
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)
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)
K=2
res = []
for i in range(len(test_list)):
res.append(test_list[i][K])
def rev_sentence(sentence):
words = sentence.split(' ')
reverse_sentence = ' '.join(reversed(words))
return reverse_sentence
sentence=input("enter a sentence")
print(rev_sentence(sentence))
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)
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))
Dictionary Programs:
print("\r")
print("\r")
# initializing dictionary
test_dict = {'gfg': [5, 6, 7, 8],
'is': [10, 11, 7, 5],
'best': [6, 12, 10, 8],
'for': [1, 2, 5]}
# printing result
print("The unique values list is : " + str(res))
print("\r")
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
RECURRSION:
def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]
s = "Geeksforgeeks"
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)
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()
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()
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")
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)
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 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)