0% found this document useful (0 votes)
5 views59 pages

Python Programs

The document lists various Python programs categorized into general programs, looping programs, and pattern programs, covering a wide range of functionalities such as finding GCD, LCM, implementing algorithms, and manipulating data structures. Each program includes a brief description and example usage. The content serves as a comprehensive reference for Python programming tasks.
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)
5 views59 pages

Python Programs

The document lists various Python programs categorized into general programs, looping programs, and pattern programs, covering a wide range of functionalities such as finding GCD, LCM, implementing algorithms, and manipulating data structures. Each program includes a brief description and example usage. The content serves as a comprehensive reference for Python programming tasks.
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/ 59

PYTHON PROGRAMS

GENERAL PROGRAMS
1. Find the GCD (Greatest Common Divisor) of Two Numbers
2. LCM (Least Common Multiple) of Two Numbers
3. Binary Search Algorithm
4. Find the Sum of a Geometric Series
5. Calculate Compound Interest
6. Merge Two Sorted Lists
7. Remove Duplicates from a List
8. Flatten a Nested List
9. Generate Fibonacci Sequence
10. Check if a Number is Perfect
11. Check if a Number is a Happy Number
12. Find the Second Largest Element in a List
13. Count Vowels and Consonants in a String
14. Remove Punctuation from a String
15. Find the Longest Word in a Sentence
16. Transpose a Matrix
17. Count the Frequency of Elements in a List
18. Rotate a List by K Elements
19. Check if Two Strings are Isomorphic
20. Find the Intersection of Two Lists
21. Binary to Decimal Conversion
22. Decimal to Binary Conversion
23. Sort a List of Tuples by the Second Element
24. Calculate the Area of Different Geometric Shapes (Circle, Triangle, Rectangle)
25. Check if a String is a Pangram
26. Generate a Random Password
27. Check if a Given Number is a Fibonacci Number
28. Implement a Stack using a List
29. Implement a Queue using a List
30. Find the Union of Two Lists
31. Check if a String is a Subsequence of Another String
32. Find the Maximum Product of Two Integers in a List
33. Implement Depth-First Search (DFS) for a Graph
34. Implement Breadth-First Search (BFS) for a Graph
35. Merge Intervals
36. Find the Kth Largest Element in a List
37. Calculate the Median of a List
38. Check if a Matrix is a Magic Square
39. Calculate the Power of a Number using Recursion
40. Find the Longest Common Subsequence (LCS) of Two Strings
41. Palindrome Check
42. Bubble Sort Algorithm
43. Count the Number of Words in a String
44. Find the Maximum Element in a 2D List
45. Calculate the Sum of Elements in a List
46. Calculate the Sum of Natural Numbers
47. Find the GCD of Two Numbers using Euclidean Algorithm
48. Rock, Paper, Scissors Game
49. Convert Kilometers to Miles
50. Simulate a Simple ATM System
51. Simple Alarm Clock
52. Check whether is a Leap Year or not.
53. Count Words in a Sentence
54. Reverse a String
55. Convert Decimal to Roman Numerals
56. Check if a String is an Isogram
57. Funny Chatbot with Random Quotes
58. Convert Celsius to Fahrenheit
59. Simple To-Do List Program
60. Calculate the Area of a Circle

LOOPING PROGRAMS
1. Basic for Loop
2. Basic while Loop
3. for Loop with List
4. while Loop with break
5. for Loop with continue
6. Nested for Loop
7. Looping Through a Dictionary
8. Using enumerates in a for Loop
9. Using zip in a for Loop
10. Using List Comprehensions
11. Looping with itertools
12. while Loop with try and except
13. Error Handling in Loops
14. Simple if Statement
15. if-else Statement
16. if-elif-else Statement
17. Nested if Statements
18. Using if Statement with Logical Operators
19. Using if-elif Statement with String Comparison
20. Break Statement
21. Continue Statement
22. Pass Statement
23. Try-Except-Finally Block
24. Loop with Else
25. Looping with a Decrementing Range
26. Looping with a Step Value
27. Looping with a Generator
28. Looping with a Recursion
29. Looping with a Conditional
30. Looping Through a List of Tuples
31. Looping Through a Range with Conditional Logic (Fizz & Buzz)
32. Looping with itertools.permutations
33. Looping with itertools.combinations
34. Using a List as a Queue in a Loop
35. Using itertools.cycle with a Condition

PATTERN PROGRAMS
1. Right-Angled Triangle Pattern
2. Inverted Right-Angled Triangle Pattern
3. Pyramid Pattern
4. Diamond Pattern
5. Number Pyramid Pattern
6. Pascal's Triangle
7. Floyd's Triangle
8. Checkerboard Pattern
9. Inverted Number Pattern
10. Right-Angled Triangle with Numbers
11. Character Pattern: Right Triangle
12. Hollow Square Pattern
13. Hollow Pyramid Pattern
14. Butterfly Pattern
15. Hourglass Pattern
16. Spiral Number Pattern
17. Zigzag Pattern
18. Hollow Diamond Pattern
19. Diamond with Name in Center
20. Diamond Star Pattern
21. Hollow Rhombus Pattern
22. Palindrome Pattern
23. Alphabet Pattern (A-Z)
24. Printing a Square Pattern
1. Find the GCD (Greatest Common Divisor) of Two Numbers
def gcd(a, b):
while b:
a, b = b, a % b
return a

# Example usage
num1 = 48
num2 = 18
result = gcd(num1, num2)
print(f"The GCD of {num1} and {num2} is {result}")

Output: The GCD of 48 and 18 is 6

2. LCM (Least Common Multiple) of Two Numbers


def gcd(a, b):
while b:
a, b = b, a % b
return a

def lcm(a, b):


return abs(a * b) // gcd(a, b)

# Example usage
num1 = 48
num2 = 18
result = lcm(num1, num2)
print(f"The LCM of {num1} and {num2} is {result}")

Output: The LCM of 48 and 18 is 144

3. Binary Search Algorithm


def binary_search(arr, target):
low = 0
high = len(arr) - 1

while low <= high:


mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

# Example usage
sorted_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target_value = 7
result = binary_search(sorted_list, target_value)

if result != -1:
print(f"The target value {target_value} is at index {result}.")
else:
print(f"The target value {target_value} is not in the list.")

Output: The target value 7 is at index 6.

4. Find the Sum of a Geometric Series


def geometric_series_sum(a, r, n):
if r == 1:
return a * n
else:
return a * (1 - r**n) / (1 - r)

# Example usage
a = 3 # First term
r = 2 # Common ratio
n = 4 # Number of terms

result = geometric_series_sum(a, r, n)
print(f"The sum of the geometric series with first term {a}, common ratio {r}, and {n}
terms is {result:.2f}")

Output: The sum of the geometric series with first term 3, common ratio 2, and 4
terms is 45.00

5. Calculate Compound Interest


def calculate_compound_interest(P, r, n, t):
A = P * (1 + r / n) ** (n * t)
return A
# Example usage
P = 1000 # Principal amount
r = 0.05 # Annual interest rate (5%)
n = 4 # Number of times interest is compounded per year (quarterly)
t = 5 # Number of years

amount = calculate_compound_interest(P, r, n, t)
print(f"The amount after {t} years is ${amount:.2f}")

Output: The amount after 5 years is $1280.08

6. Merge Two Sorted Lists


def merge_sorted_lists(list1, list2):
# Initialize pointers for both lists
i, j = 0, 0
merged_list = []

# Traverse both lists and compare elements


while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
merged_list.append(list1[i])
i += 1
else:
merged_list.append(list2[j])
j += 1

# If there are remaining elements in list1, append them


while i < len(list1):
merged_list.append(list1[i])
i += 1

# If there are remaining elements in list2, append them


while j < len(list2):
merged_list.append(list2[j])
j += 1

return merged_list

# Example usage:
list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]

merged_list = merge_sorted_lists(list1, list2)


print("Merged Sorted List:", merged_list)

Output: Merged Sorted List: [1, 2, 3, 4, 5, 6, 7, 8]

7. Remove Duplicates from a List


def remove_duplicates(original_list):
unique_list = []
for item in original_list:
if item not in unique_list:
unique_list.append(item)
return unique_list

# Example usage
my_list = [1, 2, 3, 2, 4, 5, 1, 3, 6]
result = remove_duplicates(my_list)
print(f"The original list is: {my_list}")
print(f"The list after removing duplicates is: {result}")

Output: The original list is: [1, 2, 3, 2, 4, 5, 1, 3, 6]


The list after removing duplicates is: [1, 2, 3, 4, 5, 6]

8. Flatten a Nested List


def flatten_list(nested_list):
flattened_list = []
for element in nested_list:
if isinstance(element, list):
flattened_list.extend(flatten_list(element))
else:
flattened_list.append(element)
return flattened_list

# Example usage
nested_list = [1, [2, 3], [4, [5, 6]], 7, [8, 9, [10]]]
flattened = flatten_list(nested_list)
print(f"The original nested list is: {nested_list}")
print(f"The flattened list is: {flattened}")

Output: The original nested list is: [1, [2, 3], [4, [5, 6]], 7, [8, 9, [10]]]
The flattened list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

9. Generate Fibonacci Sequence


def fibonacci_sequence(n):
# Initialize first two Fibonacci numbers
fib_sequence = [0, 1]

# Generate Fibonacci sequence


for i in range(2, n):
next_fib = fib_sequence[-1] + fib_sequence[-2]
fib_sequence.append(next_fib)

return fib_sequence
# Example usage
terms = 10 # Number of terms in the Fibonacci sequence
fibonacci = fibonacci_sequence(terms)
print(f"The Fibonacci sequence of {terms} terms is: {fibonacci}")

Output: The Fibonacci sequence of 10 terms is: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

10. Check if a Number is Perfect


def is_perfect_number(number):
if number <= 0:
return False

sum_of_divisors = 0
for i in range(1, number):
if number % i == 0:
sum_of_divisors += i

return sum_of_divisors == number

# Example usage
num = 28
result = is_perfect_number(num)

if result:
print(f"{num} is a perfect number.")
else:
print(f"{num} is not a perfect number.")

Output: 28 is a perfect number.

11. Check if a Number is a Happy Number


def is_happy_number(number):
seen = set()
while number != 1 and number not in seen:
seen.add(number)
number = sum(int(digit)**2 for digit in str(number))
return number == 1

# Example usage
num = 19
result = is_happy_number(num)

if result:
print(f"{num} is a happy number.")
else:
print(f"{num} is not a happy number.")

Output: 19 is a happy number.

12. Find the Second Largest Element in a List


def second_largest_element(arr):
# Initialize the first and second largest elements
first = second = float('-inf')

# Traverse the list to find the second largest element


for num in arr:
if num > first:
second = first
first = num
elif num > second and num != first:
second = num

return second

# Example usage
my_list = [10, 20, 4, 45, 30, 50, 25]
result = second_largest_element(my_list)
print(f"The second largest element in the list is: {result}")

Output: The second largest element in the list is: 45

13. Count Vowels and Consonants in a String


def count_vowels_and_consonants(string):
vowels = "aeiouAEIOU"
vowel_count = 0
consonant_count = 0

for char in string:


if char.isalpha():
if char in vowels:
vowel_count += 1
else:
consonant_count += 1

return vowel_count, consonant_count

# Example usage
input_string = "Hello World! How are you?"
vowels, consonants = count_vowels_and_consonants(input_string)
print(f"The string '{input_string}' has {vowels} vowels and {consonants} consonants.")

Output: The string 'Hello World! How are you?' has 7 vowels and 12 consonants.

14. Remove Punctuation from a String


import string

def remove_punctuation(input_string):
# Define the set of punctuation characters
punctuations = string.punctuation

# Remove punctuation characters from the string


no_punctuation_string = input_string.translate(str.maketrans('', '', punctuations))

return no_punctuation_string

# Example usage
input_string = "Hello! How are you doing today? I'm doing well, thank you!"
cleaned_string = remove_punctuation(input_string)
print(f"Original string: {input_string}")
print(f"String after removing punctuation: {cleaned_string}")

Output:
Original string: Hello! How are you doing today? I'm doing well, thank you!
String after removing punctuation: Hello How are you doing today Im doing well
thank you.

15. Find the Longest Word in a Sentence


def find_longest_word(sentence):
# Split the sentence into words
words = sentence.split()

# Initialize variables to keep track of the longest word and its length
longest_word = ""
max_length = 0

# Iterate through each word in the list


for word in words:
# Check if the current word is longer than the previously found longest word
if len(word) > max_length:
longest_word = word
max_length = len(word)
return longest_word
# Example usage
input_sentence = "Hello from the other side"
longest_word = find_longest_word(input_sentence)
print(f"The longest word in the sentence '{input_sentence}' is: {longest_word}")

Output: The longest word in the sentence 'Hello from the other side' is: Hello

16. Transpose a Matrix


def transpose_matrix(matrix):
rows = len(matrix)
cols = len(matrix[0]) if matrix else 0

# Initialize a new matrix with swapped dimensions


transposed = [[0 for _ in range(rows)] for _ in range(cols)]

# Fill the transposed matrix


for i in range(rows):
for j in range(cols):
transposed[j][i] = matrix[i][j]

return transposed

# Example usage
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

transposed_matrix = transpose_matrix(matrix)
print("Original Matrix:")
for row in matrix:
print(row)

print("\nTransposed Matrix:")
for row in transposed_matrix:
print(row)

Output:
Original Matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Transposed Matrix:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]

17. Count the Frequency of Elements in a List


def count_frequency(arr):
frequency_dict = {}

# Count frequency of each element in the list


for element in arr:
if element in frequency_dict:
frequency_dict[element] += 1
else:
frequency_dict[element] = 1

return frequency_dict

# Example usage
my_list = [1, 2, 3, 2, 2, 4, 5, 1, 3]
frequency = count_frequency(my_list)

# Print the frequency of each element


for key, value in frequency.items():
print(f"Element {key} occurs {value} times")

Output:
Element 1 occurs 2 times
Element 2 occurs 3 times
Element 3 occurs 2 times
Element 4 occurs 1 times
Element 5 occurs 1 times

18. Rotate a List by K Elements


def rotate_list(arr, k):
# Calculate actual rotation index within bounds
k = k % len(arr)

# Rotate the list using slicing


rotated_list = arr[-k:] + arr[:-k]

return rotated_list
my_list = [1, 2, 3, 4, 5]
k=2
rotated = rotate_list(my_list, k)
print(f"The list {my_list} rotated by {k} elements is: {rotated}")

Output: The list [1, 2, 3, 4, 5] rotated by 2 elements is: [4, 5, 1, 2, 3]

19. Check if Two Strings are Isomorphic


def are_isomorphic(str1, str2):
if len(str1) != len(str2):
return False

mapping = {}
mapped_chars = set()

for char1, char2 in zip(str1, str2):


if char1 in mapping:
if mapping[char1] != char2:
return False
else:
if char2 in mapped_chars:
return False
mapping[char1] = char2
mapped_chars.add(char2)

return True

string1 = "egg"
string2 = "add"
result = are_isomorphic(string1, string2)

if result:
print(f"The strings '{string1}' and '{string2}' are isomorphic.")
else:
print(f"The strings '{string1}' and '{string2}' are not isomorphic.")

Output: The strings 'egg' and 'add' are isomorphic.

20. Find the Intersection of Two Lists


def find_intersection(list1, list2):
set1 = set(list1)
set2 = set(list2)
intersection = set1.intersection(set2)
return list(intersection)
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
intersection = find_intersection(list1, list2)
print(f"The intersection of {list1} and {list2} is: {intersection}")

Output: The intersection of [1, 2, 3, 4, 5] and [4, 5, 6, 7, 8] is: [4, 5]

21. Binary to Decimal Conversion


def binary_to_decimal(binary):
decimal = 0
power = len(binary) - 1

for digit in binary:


decimal += int(digit) * (2 ** power)
power -= 1

return decimal

binary_number = "101010"
decimal_number = binary_to_decimal(binary_number)
print(f"The binary number {binary_number} is equivalent to decimal: {decimal_number}")

Output: The binary number 101010 is equivalent to decimal: 42

22. Decimal to Binary Conversion


def decimal_to_binary(decimal):
if decimal == 0:
return "0"

binary = ""
while decimal > 0:
remainder = decimal % 2
binary = str(remainder) + binary
decimal //= 2

return binary

decimal_number = 42
binary_number = decimal_to_binary(decimal_number)
print(f"The decimal number {decimal_number} is equivalent to binary: {binary_number}")

Output: The decimal number 42 is equivalent to binary: 101010

23. Sort a List of Tuples by the Second Element


def sort_tuples_by_second_element(list_of_tuples):
sorted_list = sorted(list_of_tuples, key=lambda x: x[1])
return sorted_list

list_of_tuples = [(1, 5), (3, 2), (2, 8), (5, 1), (4, 3)]
sorted_tuples = sort_tuples_by_second_element(list_of_tuples)
print("Sorted list of tuples by the second element:")
for tpl in sorted_tuples:
print(tpl)

Output:
Sorted list of tuples by the second element:
(5, 1)
(3, 2)
(4, 3)
(1, 5)
(2, 8)

24. Calculate the Area of Different Geometric Shapes (Circle, Triangle, Rectangle)
Circle Area Calculation:
import math
def circle_area(radius):
return math.pi * radius ** 2

# Example usage for circle


radius = 5
area_circle = circle_area(radius)
print(f"The area of the circle with radius {radius} is: {area_circle:.2f}")

Triangle Area Calculation:


def triangle_area(base, height):
return 0.5 * base * height

# Example usage for triangle


base = 6
height = 4
area_triangle = triangle_area(base, height)
print(f"The area of the triangle with base {base} and height {height} is: {area_triangle}")

Rectangle Area Calculation:


def rectangle_area(length, width):
return length * width

# Example usage for rectangle


length = 7
width = 3
area_rectangle = rectangle_area(length, width)
print(f"The area of the rectangle with length {length} and width {width} is:
{area_rectangle}")

Output:
The area of the circle with radius 5 is: 78.54
The area of the triangle with base 6 and height 4 is: 12.0
The area of the rectangle with length 7 and width 3 is: 21

25. Check if a String is a Pangram


import string
def is_pangram(input_string):
return set(string.ascii_lowercase) <= set(input_string.lower())

# Example usage
input_str1 = "The quick brown fox jumps over the lazy dog"
input_str2 = "Hello world"

print(f"'{input_str1}' is a pangram: {is_pangram(input_str1)}")


print(f"'{input_str2}' is a pangram: {is_pangram(input_str2)}")

Output:
'The quick brown fox jumps over the lazy dog' is a pangram: True
'Hello world' is a pangram: False

26. Generate a Random Password


import random
import string
def generate_random_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password

# Example usage
password = generate_random_password()
print(f"Generated random password: {password}")

Output: Generated random password: j>7N=2nV?lY{ (Randomly generates a new


password everytime.)

27. Check if a Given Number is a Fibonacci Number


import math
def is_perfect_square(x):
s = int(math.sqrt(x))
return s * s == x

def is_fibonacci_number(n):
# A number n is Fibonacci if and only if one or both of (5*n*n + 4) or (5*n*n - 4) is a
perfect square
return is_perfect_square(5 * n * n + 4) or is_perfect_square(5 * n * n - 4)

# Example usage
number = 8
if is_fibonacci_number(number):
print(f"{number} is a Fibonacci number.")
else:
print(f"{number} is not a Fibonacci number.")

Output: 8 is a Fibonacci number.

28. Implement a Stack using a List


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 not self.is_empty():
return self.stack.pop()
else:
raise IndexError("pop from empty stack")

def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
raise IndexError("peek from empty stack")

def size(self):
return len(self.stack)
# Example usage
stack = Stack()

stack.push(1)
stack.push(2)
stack.push(3)

print("Current stack:", stack.stack)


print("Pop item:", stack.pop())
print("Peek item:", stack.peek())
print("Current stack after operations:", stack.stack)
print("Stack size:", stack.size())

Output:
Current stack: [1, 2, 3]
Pop item: 3
Peek item: 2
Current stack after operations: [1, 2]
Stack size: 2

29. Implement a Queue using a List


class Queue:
def __init__(self):
self.items = []

def is_empty(self):
return self.items == []

def enqueue(self, item):


self.items.append(item)

def dequeue(self):
if self.is_empty():
return None
return self.items.pop(0)

def peek(self):
if self.is_empty():
return None
return self.items[0]

def size(self):
return len(self.items)
# Example usage:
queue = Queue()

# Enqueue some elements


queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)

print("Queue size:", queue.size()) # Output: Queue size: 3


print("Front element:", queue.peek()) # Output: Front element: 1

# Dequeue elements
print("Dequeued item:", queue.dequeue()) # Output: Dequeued item: 1
print("Dequeued item:", queue.dequeue()) # Output: Dequeued item: 2

print("Queue size after dequeue:", queue.size()) # Output: Queue size after dequeue: 1

Output:
Queue size: 3
Front element: 1
Dequeued item: 1
Dequeued item: 2
Queue size after dequeue: 1

30. Find the Union of Two Lists


def find_union(list1, list2):
# Convert lists to sets to remove duplicates
set1 = set(list1)
set2 = set(list2)

# Find union of two sets


union_set = set1.union(set2)

# Convert union set back to list


union_list = list(union_set)

return union_list

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
union = find_union(list1, list2)
print(f"The union of {list1} and {list2} is: {union}")

Output: The union of [1, 2, 3, 4, 5] and [3, 4, 5, 6, 7] is: [1, 2, 3, 4, 5, 6, 7]


31. Check if a String is a Subsequence of Another String
def is_subsequence(str1, str2):
it = iter(str2)
return all(char in it for char in str1)

# Example usage
string1 = "abc"
string2 = "ahbgdc"
result = is_subsequence(string1, string2)

if result:
print(f"'{string1}' is a subsequence of '{string2}'.")
else:
print(f"'{string1}' is not a subsequence of '{string2}'.")

Output: 'abc' is a subsequence of 'ahbgdc'.

32. Find the Maximum Product of Two Integers in a List


def max_product_of_two(nums):
if len(nums) < 2:
return None

# Initialize variables to store maximum and second maximum values


max1 = float('-inf')
max2 = float('-inf')
min1 = float('inf')
min2 = float('inf')

# Traverse the list to find maximum and second maximum values


for num in nums:
if num >= max1:
max2 = max1
max1 = num
elif num > max2:
max2 = num

if num <= min1:


min2 = min1
min1 = num
elif num < min2:
min2 = num

# Maximum product could be max1*max2 or min1*min2 (if all numbers are negative)
return max(max1 * max2, min1 * min2)

# Example usage
numbers = [3, 4, 1, 2, 5, 6, -2, -3]
max_product = max_product_of_two(numbers)
print(f"The maximum product of two integers in the list {numbers} is: {max_product}")

Output: The maximum product of two integers in the list [3, 4, 1, 2, 5, 6, -2, -3] is:
30

33. Implement Depth-First Search (DFS) for a Graph


from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)

def add_edge(self, u, v):


self.graph[u].append(v)

def dfs(self, v, visited):


visited[v] = True
print(v, end=' ')

for neighbor in self.graph[v]:


if not visited[neighbor]:
self.dfs(neighbor, visited)

def dfs_traversal(self, start):


visited = [False] * (max(self.graph) + 1)
self.dfs(start, visited)
print() # Print new line for clarity

# Example usage
graph = Graph()

# Adding edges
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 2)
graph.add_edge(2, 0)
graph.add_edge(2, 3)
graph.add_edge(3, 3)

print("DFS traversal starting from vertex 2:")


graph.dfs_traversal(2)

Output:
DFS traversal starting from vertex 2:
2013

34. Implement Breadth-First Search (BFS) for a Graph


from collections import defaultdict, deque
class Graph:
def __init__(self):
self.graph = defaultdict(list)

def add_edge(self, u, v):


self.graph[u].append(v)

def bfs(self, start):


visited = [False] * (max(self.graph) + 1)
queue = deque([start])
visited[start] = True

while queue:
vertex = queue.popleft()
print(vertex, end=' ')

for neighbor in self.graph[vertex]:


if not visited[neighbor]:
queue.append(neighbor)
visited[neighbor] = True

# Example usage
graph = Graph()

# Adding edges
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 2)
graph.add_edge(2, 0)
graph.add_edge(2, 3)
graph.add_edge(3, 3)
print("BFS traversal starting from vertex 2:")
graph.bfs(2)

Output:
BFS traversal starting from vertex 2:
2031

35. Merge Intervals


def merge_intervals(intervals):
# Sort intervals based on the start time
intervals.sort(key=lambda x: x[0])

merged = []
for interval in intervals:
# If the list of merged intervals is empty or if the current
# interval does not overlap with the previous, append it.
if not merged or merged[-1][1] < interval[0]:
merged.append(interval)
else:
# There is overlap, so merge the current and previous intervals.
merged[-1][1] = max(merged[-1][1], interval[1])

return merged

# Example usage
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
merged_intervals = merge_intervals(intervals)
print("Merged intervals:", merged_intervals)

Output: Merged intervals: [[1, 6], [8, 10], [15, 18]]

36. Find the Kth Largest Element in a List


import heapq
def find_kth_largest(nums, k):
# Use a min-heap of size k
min_heap = []

# Push the first k elements into the min-heap


for num in nums[:k]:
heapq.heappush(min_heap, num)

# For the remaining elements, push into the heap if larger than the smallest element
for num in nums[k:]:
if num > min_heap[0]:
heapq.heappushpop(min_heap, num)

# The root of the heap is the kth largest element


return min_heap[0]
# Example usage
nums = [3, 2, 1, 5, 6, 4]
k=2
kth_largest = find_kth_largest(nums, k)
print(f"The {k}th largest element in the list {nums} is: {kth_largest}")

Output: The 2th largest element in the list [3, 2, 1, 5, 6, 4] is: 5

37. Calculate the Median of a List


def calculate_median(nums):
nums.sort()
n = len(nums)

if n % 2 == 1:
# If the length of nums is odd, return the middle element
median = nums[n // 2]
else:
# If the length of nums is even, return the average of the middle two elements
median = (nums[n // 2 - 1] + nums[n // 2]) / 2

return median

# Example usage
nums1 = [1, 3, 2, 5, 4]
nums2 = [1, 2, 3, 4, 5, 6]

median1 = calculate_median(nums1)
median2 = calculate_median(nums2)

print(f"The median of {nums1} is: {median1}")


print(f"The median of {nums2} is: {median2}")

Output:
The median of [1, 3, 2, 5, 4] is: 3
The median of [1, 2, 3, 4, 5, 6] is: 3.5

38. Check if a Matrix is a Magic Square


def is_magic_square(matrix):
n = len(matrix)

# Calculate the sum of the first row (this will be our magic constant)
magic_constant = sum(matrix[0])

# Check rows
for row in matrix:
if sum(row) != magic_constant:
return False

# Check columns
for col in range(n):
column_sum = 0
for row in range(n):
column_sum += matrix[row][col]
if column_sum != magic_constant:
return False

# Check main diagonal


diagonal_sum = 0
for i in range(n):
diagonal_sum += matrix[i][i]
if diagonal_sum != magic_constant:
return False

# Check secondary diagonal


diagonal_sum = 0
for i in range(n):
diagonal_sum += matrix[i][n - 1 - i]
if diagonal_sum != magic_constant:
return False

return True

# Example usage
matrix1 = [
[8, 1, 6],
[3, 5, 7],
[4, 9, 2]
]
matrix2 = [
[2, 7, 6],
[9, 5, 1],
[4, 3, 8]
]

if is_magic_square(matrix1):
print("matrix1 is a Magic Square.")
else:
print("matrix1 is not a Magic Square.")
if is_magic_square(matrix2):
print("matrix2 is a Magic Square.")
else:
print("matrix2 is not a Magic Square.")

Output:
matrix1 is a Magic Square.
matrix2 is not a Magic Square.

39. Calculate the Power of a Number using Recursion


def power(x, y):
if y == 0:
return 1
elif y == 1:
return x
else:
return x * power(x, y - 1)

# Example usage
base = 3
exponent = 4
result = power(base, exponent)
print(f"{base} raised to the power of {exponent} is: {result}")

Output: 3 raised to the power of 4 is: 81

40. Find the Longest Common Subsequence (LCS) of Two Strings


def longest_common_subsequence(s1, s2):
m = len(s1)
n = len(s2)

# Create a 2D list to store the lengths of LCSs


dp = [[0] * (n + 1) for _ in range(m + 1)]

# Fill the dp table


for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

# Reconstruction of the LCS


lcs_length = dp[m][n]
lcs = []
i, j = m, n
while i > 0 and j > 0:
if s1[i - 1] == s2[j - 1]:
lcs.append(s1[i - 1])
i -= 1
j -= 1
elif dp[i - 1][j] >= dp[i][j - 1]:
i -= 1
else:
j -= 1

# Return the LCS string reversed


return ''.join(lcs[::-1])

# Example usage
string1 = "ABCDGH"
string2 = "AEDFHR"
lcs = longest_common_subsequence(string1, string2)
print(f"The Longest Common Subsequence of '{string1}' and '{string2}' is: {lcs}")

Output: The Longest Common Subsequence of 'ABCDGH' and 'AEDFHR' is: ADH

41. Palindrome Check


def is_palindrome(s):
s = s.lower() # Convert to lowercase for case insensitivity
return s == s[::-1]

# Example usage
string = "Madam"
if is_palindrome(string):
print(f"'{string}' is a palindrome")
else:
print(f"'{string}' is not a palindrome")

Output: 'Mam' is a palindrome

42. Bubble Sort Algorithm


def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
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 not swapped:
break

# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array:", arr)

Output: Sorted array: [11, 12, 22, 25, 34, 64, 90]

43. Count the Number of Words in a String


def count_words(string):
words = string.split()
return len(words)

input_string = "Hello, how are you today?"


word_count = count_words(input_string)
print(f"The number of words in the string is: {word_count}")

Output: The number of words in the string is: 5

44. Find the Maximum Element in a 2D List


def find_max_2d_list(matrix):
max_element = float('-inf')
for row in matrix:
for element in row:
if element > max_element:
max_element = element
return max_element

matrix = [
[3, 5, 7],
[2, 6, 8],
[1, 4, 9]
]
max_element = find_max_2d_list(matrix)
print(f"The maximum element in the 2D list is: {max_element}")

Output: The maximum element in the 2D list is: 9

45. Calculate the Sum of Elements in a List


def sum_of_elements(lst):
return sum(lst)

# Example usage
numbers = [1, 2, 3, 4, 5]
total = sum_of_elements(numbers)
print(f"The sum of elements in the list is: {total}")

Output: The sum of elements in the list is: 15


46. Calculate the Sum of Natural Numbers
def sum_of_natural_numbers(n):
return n * (n + 1) // 2

number = 10
print(f"The sum of the first {number} natural numbers is:
{sum_of_natural_numbers(number)}")

Output: The sum of the first 10 natural numbers is: 55

47. Find the GCD of Two Numbers using Euclidean Algorithm


def gcd(a, b):
while b:
a, b = b, a % b
return a

a, b = 48, 18
print(f"The GCD of {a} and {b} is: {gcd(a, b)}")

Output: The GCD of 48 and 18 is: 6

48. Rock, Paper, Scissors Game


import random

def play_rps():
choices = ['rock', 'paper', 'scissors']
computer_choice = random.choice(choices)
user_choice = input("Enter rock, paper, or scissors: ").lower()

if user_choice not in choices:


return "Invalid choice! Please choose rock, paper, or scissors."
if user_choice == computer_choice:
return f"Both players selected {user_choice}. It's a tie!"
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "paper" and computer_choice == "rock") or \
(user_choice == "scissors" and computer_choice == "paper"):
return f"You win! {user_choice.capitalize()} beats {computer_choice}."
else:
return f"You lose! {computer_choice.capitalize()} beats {user_choice}."

print(play_rps())

Output: Enter rock, paper, or scissors: rock


You win! Rock beats scissors.

49. Convert Kilometers to Miles


def kilometers_to_miles(km):
return km * 0.621371
km = 10
miles = kilometers_to_miles(km)
print(f"{km} kilometers is equal to {miles} miles.")

Output: 10 kilometers is equal to 6.21371 miles.

50. Simulate a Simple ATM System


class ATM:
def __init__(self, balance=0):
self.balance = balance

def deposit(self, amount):


self.balance += amount
return f"Deposited {amount}. New balance: {self.balance}"

def withdraw(self, amount):


if amount > self.balance:
return "Insufficient funds"
self.balance -= amount
return f"Withdrew {amount}. New balance: {self.balance}"

def check_balance(self):
return f"Current balance: {self.balance}"

# Example usage
atm = ATM(100)
print(atm.deposit(50))
print(atm.withdraw(30))
print(atm.check_balance())
print(atm.withdraw(150))

Output: Deposited 50. New balance: 150


Withdrew 30. New balance: 120
Current balance: 120
Insufficient funds

51. Simple Alarm Clock


import time
import winsound

def set_alarm(alarm_time):
print(f"Alarm set for {alarm_time}")
while True:
current_time = time.strftime("%H:%M:%S")
if current_time == alarm_time:
print("Wake up!")
for _ in range(5):
winsound.Beep(1000, 1000)
break
time.sleep(1)
# Example usage
# Please set the alarm time as per your current time in HH:MM:SS format
alarm_time = "15:30:00"
set_alarm(alarm_time)

Output:
Alarm set for 15:30:00
[Beep sounds]

52. Check whether is a Leap Year or not.


def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False

years = [2000, 2004, 2100, 2021]

for year in years:


if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")

Output:
2000 is a leap year.
2004 is a leap year.
2100 is not a leap year.
2021 is not a leap year.

53. Count Words in a Sentence


def count_words(sentence):
words = sentence.split()
return len(words)

sentence = "Hello, how are you today?"


word_count = count_words(sentence)
print(f"The sentence '{sentence}' has {word_count} words.")

Output: The sentence 'Hello, how are you today?' has 5 words.

54. Reverse a String


def reverse_string(s):
return s[::-1]
# Example usage
original_string = "Hello, World!"
reversed_string = reverse_string(original_string)
print(f"Original string: {original_string}")
print(f"Reversed string: {reversed_string}")

Output: Original string: Hello, World!


Reversed string: !dlroW ,olleH

55. Convert Decimal to Roman Numerals


def decimal_to_roman(num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syms = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_num = ''
i=0
while num > 0:
for _ in range(num // val[i]):
roman_num += syms[i]
num -= val[i]
i += 1
return roman_num

# Example usage
number = 3549
roman = decimal_to_roman(number)
print(f"Roman numeral for {number}: {roman}")

Output: Roman numeral for 3549: MMMDXLIX

56. Check if a String is an Isogram


def is_isogram(word):
seen = set()
for char in word.lower():
if char.isalpha():
if char in seen:
return False
seen.add(char)
return True

# Example usage
string1 = "Machine"
string2 = "Algorithm"
string3 = "Python"

print(f"{string1} is an isogram: {is_isogram(string1)}")


print(f"{string2} is an isogram: {is_isogram(string2)}")
print(f"{string3} is an isogram: {is_isogram(string3)}")

Output: Machine is an isogram: False


Algorithm is an isogram: True
Python is an isogram: True

57. Funny Chatbot with Random Quotes


import random

def get_random_quote():
quotes = [
"I'm not arguing, I'm just explaining why I'm right.",
"I'm on a seafood diet. I see food and I eat it.",
"Why don’t scientists trust atoms? Because they make up everything!",
"I told my wife she was drawing her eyebrows too high. She looked surprised.",
"Parallel lines have so much in common. It’s a shame they’ll never meet.",
"I threw a boomerang a few years ago. I now live in constant fear.",
"My wife told me to stop impersonating a flamingo. I had to put my foot down."
]
return random.choice(quotes)

def funny_chatbot():
print("Hello! I'm your funny chatbot. Type 'exit' to end the conversation.")
while True:
user_input = input("You: ")
if user_input.lower() == 'exit':
print("Chatbot: Goodbye! Have a funny day!")
break
print(f"Chatbot: {get_random_quote()}")

# Start the chatbot


funny_chatbot()

Output:
Hello! I'm your funny chatbot. Type 'exit' to end the conversation.
You: Hi there!
Chatbot: I'm not arguing, I'm just explaining why I'm right.
You: Tell me a joke.
Chatbot: Why don’t scientists trust atoms? Because they make up everything!
You: That's funny!
Chatbot: My wife told me to stop impersonating a flamingo. I had to put my foot
down.
You: exit
Chatbot: Goodbye! Have a funny day!

58. Convert Celsius to Fahrenheit


def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32

celsius = 25
fahrenheit = celsius_to_fahrenheit(celsius)
print(f"{celsius}°C is equal to {fahrenheit}°F")

Output: 25°C is equal to 77.0°F

59. Simple To-Do List Program


import asyncio

async def todo_list():


tasks = []
while True:
task = input("Enter a task (or 'done' to finish): ")
if task.lower() == 'done':
break
tasks.append(task)

print("\nYour to-do list:")


for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")

asyncio.run(todo_list())

Output:
Enter a task (or 'done' to finish): Buy groceries
Enter a task (or 'done' to finish): Walk the dog
Enter a task (or 'done' to finish): done
Your to-do list:
1. Buy groceries
2. Walk the dog

60. Calculate the Area of a Circle


def area_of_circle(radius):
return 3.14159 * radius ** 2

radius = 5
area = area_of_circle(radius)
print(f"The area of a circle with radius {radius} is: {area}")

Output: The area of a circle with radius 5 is: 78.53975

LOOPING PROGRAMS

1. Basic for Loop


# Program to print each character in a string
text = "Python"
for char in text:
print(char)

Output:
P
y
t
h
o
n

2. Basic while Loop


# Loop while a condition is true
count = 0
while count < 5:
print(count)
count += 1

Output:
0
1
2
3
4

3. for Loop with List


# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Output:
apple
banana
cherry

4. While Loop with break


# Use break to exit the loop
count = 0
while True:
print(count)
count += 1
if count >= 5:
break

Output:
0
1
2
3
4

5. for Loop with continue


# Use continue to skip an iteration
for i in range(5):
if i == 2:
continue
print(i)

Output:
0
1
3
4

6. Nested for Loop


# Nested loop example
for i in range(3):
for j in range(3):
print(f'i: {i}, j: {j}')

Output:
i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
i: 1, j: 1
i: 1, j: 2
i: 2, j: 0
i: 2, j: 1
i: 2, j: 2
7. Looping Through a Dictionary
# Loop through a dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}
for key, value in person.items():
print(f'{key}: {value}')

Output: name: Alice


age: 25
city: New York

8. Using enumerate in a for Loop


# Using enumerate to get index and value
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f'Index: {index}, Color: {color}')

Output: Index: 0, Color: red


Index: 1, Color: green
Index: 2, Color: blue

9. Using zip in a for Loop


# Using zip to iterate over multiple lists
names = ["John", "Jane", "Doe"]
scores = [85, 90, 78]
for name, score in zip(names, scores):
print(f'{name} scored {score}')

Output: John scored 85


Jane scored 90
Doe scored 78

10. Using List Comprehensions


# List comprehension with a loop
squares = [x ** 2 for x in range(5)]
print(squares)

Output: [0, 1, 4, 9, 16]


11. Looping with itertools
import itertools
# Using itertools to create an infinite loop
counter = itertools.count(start=0, step=2)
for i in range(5):
print(next(counter))

Output:
0
2
4
6
8

12. while Loop with try and except


# Handling errors within a loop
numbers = [10, 20, 0, 30]
for number in numbers:
try:
result = 100 / number
print(f'100 / {number} = {result}')
except ZeroDivisionError:
print(‘Cannot divide by zero')

Output:
100 / 10 = 10.0
100 / 20 = 5.0
Cannot divide by zero
100 / 30 = 3.3333333333333335

13. Error Handling in Loops


# Program to handle errors in a loop
values = ["10", "20", "thirty", "40"]
for value in values:
try:
num = int(value)
print(f"Converted {value} to {num}")
except ValueError:
print(f"Error: {value} is not a number")
Output:
Converted 10 to 10
Converted 20 to 20
Error: thirty is not a number
Converted 40 to 40

14. Simple if Statement


# Program to check if a number is positive
number = 10
if number > 0:
print(f"{number} is positive")

Output: 10 is positive

15. if-else Statement


# Program to check if a number is positive or negative
number = -5
if number > 0:
print(f"{number} is positive")
else:
print(f"{number} is negative")

Output: -5 is negative

16. if-elif-else Statement


# Program to check if a number is positive, negative, or zero
number = 0
if number > 0:
print(f"{number} is positive")
elif number < 0:
print(f"{number} is negative")
else:
print(f"{number} is zero")

Output: 0 is zero
17. Nested if Statements
# Program to check if a number is positive, negative, zero, and even or odd
number = -4
if number >= 0:
if number == 0:
print(f"{number} is zero")
else:
print(f"{number} is positive")
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
else:
print(f"{number} is negative")
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")

Output:
-4 is negative
-4 is even

18. Using if Statement with Logical Operators


# Program to check if a number is within a specific range
number = 25
if 10 <= number <= 30:
print(f"{number} is within the range 10 to 30")
else:
print(f"{number} is outside the range 10 to 30")

Output: 25 is within the range 10 to 30

19. Using if-elif Statement with String Comparison


# Program to check the category of an animal
animal = "dog"
if animal == "cat":
print("This is a cat")
elif animal == "dog":
print("This is a dog")
else:
print("This is another type of animal")

Output: This is a dog


20. Break Statement
# Program to find the first number greater than 10 in a list
numbers = [4, 7, 10, 11, 15]
for num in numbers:
if num > 10:
print(f"First number greater than 10: {num}")
break

Output: First number greater than 10: 11

21. Continue Statement


# Program to print only odd numbers from 1 to 10
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)

Output:
1
3
5
7
9

22. Pass Statement


# Program with a placeholder in a loop
for i in range(5):
if i == 2:
pass # Placeholder for future code
else:
print(i)

Output:
0
1
3
4

23. Try-Except-Finally Block


# Program to handle division by zero error
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed")
finally:
print("This will execute no matter what")

Output:
Error: Division by zero is not allowed
This will execute no matter what

24. Loop with Else


# Loop with an else clause
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 6:
print("Found 6!")
break
else:
print("6 not found in the list.")

Output:
6 not found in the list.

25. Looping with a Decrementing Range


# Looping with a decrementing range
for i in range(10, 0, -1):
print(i)

Output:
10
9
8
7
6
5
4
3
2
1
26. Looping with a Step Value
# Looping with a step value
for i in range(0, 10, 2):
print(i)

Output:
0
2
4
6
8

27. Looping with a Generator


# Looping with a generator
def countdown(n):
while n > 0:
yield n
n -= 1

for num in countdown(5):


print(num)
Output:
5
4
3
2
1

28. Looping with a Recursion


# Looping with recursion
def recursive_print(n):
if n <= 0:
return
print(n)
recursive_print(n - 1)

recursive_print(5)

Output:
5
4
3
2
1

29. Looping with a Conditional


# Looping with a conditional
i=1
while i <= 10:
if i % 2 == 0:
print(f'{i} is even')
else:
print(f'{i} is odd')
i += 1

Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even

30. Looping Through a List of Tuples


# Looping through a list of tuples
coordinates = [(1, 2), (3, 4), (5, 6)]
for x, y in coordinates:
print(f'x: {x}, y: {y}')

Output:
x: 1, y: 2
x: 3, y: 4
x: 5, y: 6

31. Looping Through a Range with Conditional Logic


# Looping through a range with conditional logic
for i in range(1, 21):
if i % 3 == 0 and i % 5 == 0:
print(f'{i}: FizzBuzz')
elif i % 3 == 0:
print(f'{i}: Fizz')
elif i % 5 == 0:
print(f'{i}: Buzz')
else:
print(i)

Output:
1
2
3: Fizz
4
5: Buzz
6: Fizz
7
8
9: Fizz
10: Buzz
11
12: Fizz
13
14
15: FizzBuzz
16
17
18: Fizz
19
20: Buzz

32. Looping with itertools.permutations


import itertools
# Using itertools.permutations to generate all permutations
letters = 'ABC'
permutations = itertools.permutations(letters)
for perm in permutations:
print(''.join(perm))
Output:
ABC
ACB
BAC
BCA
CAB
CBA

33. Looping with itertools.combinations


import itertools
# Using itertools.combinations to generate all combinations
letters = 'ABC'
combinations = itertools.combinations(letters, 2)
for comb in combinations:
print(''.join(comb))

Output:
AB
AC
BC

34. Using a List as a Queue in a Loop


# Using a list as a queue
queue = ["first", "second", "third"]
while queue:
item = queue.pop(0)
print(f' Processing: {item}')

Output:
Processing: first
Processing: second
Processing: third

35. Using itertools.cycle with a Condition


import itertools
# Using itertools.cycle with a condition
colors = ["red", "green", "blue"]
cycled_colors = itertools.cycle(colors)
for i in range(7):
color = next(cycled_colors)
print(color)

Output:
red
green
blue
red
green
blue
red

PATTERN PROGRAMS

1. Right-Angled Triangle Pattern


# Program to print a right-angled triangle pattern
n=5
for i in range(1, n+1):
print('*' * i)

Output:
*
**
***
****
*****

2. Inverted Right-Angled Triangle Pattern


# Program to print an inverted right-angled triangle pattern
n=5
for i in range(n, 0, -1):
print('*' * i)

Output:
*****
****
***
**
*

3. Pyramid Pattern
# Program to print a pyramid pattern
n=5
for i in range(1, n+1):
print(' ' * (n-i) + '*' * (2*i-1))

Output:
*
***
*****
*******
*********

4. Diamond Pattern
# Program to print a diamond pattern
n=5
# Upper part of the diamond
for i in range(1, n+1):
print(' ' * (n-i) + '*' * (2*i-1))

# Lower part of the diamond


for i in range(n-1, 0, -1):
print(' ' * (n-i) + '*' * (2*i-1))

Output:
*
***
*****
*******
*********
*******
*****
***
*

5. Number Pyramid Pattern


# Program to print a number pyramid pattern
n=5
for i in range(1, n+1):
for j in range(1, i+1):
print(j, end=' ')
print('')

Output:
1
12
123
1234
12345

6. Pascal's Triangle
# Program to print Pascal's triangle
def print_pascals_triangle(n):
for i in range(n):
for j in range(n-i+1):
print(end=" ")

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

n=5
print_pascals_triangle(n)

Output:
1
11
111
1211
13311

7. Floyd's Triangle
# Program to print Floyd's triangle
n=5
num = 1
for i in range(1, n+1):
for j in range(1, i+1):
print(num, end=' ')
num += 1
print('')

Output:
1
23
456
7 8 9 10
11 12 13 14 15

8. Checkerboard Pattern
# Program to print a checkerboard pattern
n=5
for i in range(n):
for j in range(n):
if (i + j) % 2 == 0:
print('X', end=' ')
else:
print('O', end=' ')
print('')

Output:
XOXOX
OXOXO
XOXOX
OXOXO
XOXOX

9. Inverted Number Pattern


# Program to print an inverted number pattern
n=5
for i in range(n, 0, -1):
for j in range(1, i + 1):
print(j, end='')
print()

Output:
12345
1234
123
12
1

10. Right-Angled Triangle with Numbers


# Program to print a right-angled triangle with numbers
n=5
for i in range(1, n + 1):
for j in range(1, i + 1):
print(i, end='')
print()

Output:
1
22
333
4444
55555

11. Character Pattern: Right Triangle


# Program to print a right triangle character pattern
n=5
alphabet = 65 # ASCII value of 'A'
for i in range(n):
for j in range(i+1):
print(chr(alphabet + j), end='')
print()

Output:
A
AB
ABC
ABCD
ABCDE

12. Hollow Square Pattern


# Program to print a hollow square pattern
n=5
for i in range(n):
if i == 0 or i == n-1:
print('*' * n)
else:
print('*' + ' ' * (n-2) + '*')

Output:
*****
* *
* *
* *
*****

13. Hollow Pyramid Pattern


# Program to print a hollow pyramid pattern
n=5
for i in range(1, n + 1):
if i == 1:
print(' ' * (n - i) + '*')
elif i == n:
print('*' * (2 * n - 1))
else:
print(' ' * (n - i) + '*' + ' ' * (2 * i - 3) + '*')

Output:
*
**
* *
* *
*********

14. Diamond Number Pattern


# Program to print a diamond number pattern
n=5
# Upper part of diamond
for i in range(1, n+1):
print(' ' * (n-i) + ''.join(str(j) for j in range(1, i+1)) + ''.join(str(j) for j in range(i-1, 0,
-1)))
# Lower part of diamond
for i in range(n-1, 0, -1):
print(' ' * (n-i) + ''.join(str(j) for j in range(1, i+1)) + ''.join(str(j) for j in range(i-1, 0,
-1)))

Output:
1
121
12321
1234321
123454321
1234321
12321
121
1

15. Butterfly Pattern


# Program to print a butterfly pattern
n=5
# Upper part of butterfly
for i in range(1, n+1):
print('*' * i + ' ' * (2*(n-i)) + '*' * i)
# Lower part of butterfly
for i in range(n, 0, -1):
print('*' * i + ' ' * (2*(n-i)) + '*' * i)

Output:
* *
** **
*** ***
**** ****
**********
**********
**** ****
*** ***
** **
* *
16. Hourglass Pattern
# Program to print an hourglass pattern
n=5
# Upper part of hourglass
for i in range(n, 0, -1):
print(' ' * (n-i) + '*' * (2*i-1))
# Lower part of hourglass
for i in range(2, n+1):
print(' ' * (n-i) + '*' * (2*i-1))
Output:
*********
*******
*****
***
*
***
*****
*******
*********

17. Spiral Number Pattern


# Program to print a spiral number pattern
n=5
matrix = [[0]*n for _ in range(n)]
num = 1
left, right = 0, n-1
top, bottom = 0, n-1

while left <= right and top <= bottom:


for i in range(left, right+1):
matrix[top][i] = num
num += 1
top += 1
for i in range(top, bottom+1):
matrix[i][right] = num
num += 1
right -= 1
for i in range(right, left-1, -1):
matrix[bottom][i] = num
num += 1
bottom -= 1
for i in range(bottom, top-1, -1):
matrix[i][left] = num
num += 1
left += 1

for row in matrix:


print(' '.join(map(str, row)))
Output:
12345
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

18. Zigzag Pattern


# Program to print a zigzag pattern
n=9
zigzag_height = 3
for i in range(zigzag_height):
for j in range(n):
if (i + j) % (zigzag_height - 1) == 0:
print('*', end='')
else:
print(' ', end='')
print()

Output:
* * *
* ** *
** **

19. Hollow Diamond Pattern


# Hollow diamond pattern
n=5
for i in range(1, n+1):
for j in range(n-i):
print(' ', end='')
for j in range(2*i-1):
if j == 0 or j == 2*i-2:
print('*', end='')
else:
print(' ', end='')
print()
for i in range(n-1, 0, -1):
for j in range(n-i):
print(' ', end='')
for j in range(2*i-1):
if j == 0 or j == 2*i-2:
print('*', end='')
else:
print(' ', end='')
print()

Output:
*
**
* *
* *
* *
* *
* *
**
*

20. Diamond with Name in Center


# Diamond with name in center pattern
name = "PYTHON"
n=6
mid = n // 2
for i in range(n):
if i < mid:
spaces = mid - i
stars = 2 * i + 1
elif i == mid:
spaces = 0
stars = len(name)
else:
spaces = i - mid
stars = 2 * (n - i) - 1
print(' ' * spaces + '*' * stars)
print(name.center(n))

Output:
*
***
*****
PYTHON
*****
***
*

21. Diamond Star Pattern


# Diamond star pattern
rows = 5
for i in range(1, rows + 1):
print(' ' * (rows - i) + '* ' * i)
for i in range(rows - 1, 0, -1):
print(' ' * (rows - i) + '* ' * i)

Output:
*
**
***
****
*****
****
***
**
*

22. Hollow Rhombus Pattern


# Hollow rhombus pattern
rows = 5
for i in range(rows):
print(' ' * (rows - i - 1) + '*' * rows if i == 0 or i == rows - 1 else '*' + ' ' * (rows - 2)
+ '*')

Output:
*****
* *
* *
* *
*****

23. Palindrome Pattern


# Palindrome pattern
n=5
for i in range(1, n+1):
print(' ' * (n-i), end='')
for j in range(1, i+1):
print(j, end='')
for j in range(i-1, 0, -1):
print(j, end='')
print()

Output:
1
121
12321
1234321
123454321

24. Alphabet Pattern (A-Z)


# Alphabet pattern (A-Z)
n=5
ascii_value = 65 # ASCII value of 'A'
for i in range(1, n+1):
for j in range(1, i+1):
print(chr(ascii_value), end=' ')
ascii_value += 1
print()

Output:
A
BC
DEF
GHIJ
KLMNO

25. Printing a Square Pattern


def print_square(n):
for i in range(n):
for j in range(n):
print("*", end=" ")
print()
# Example usage
print_square(5)

Output:
*****
*****
*****
*****
*****

You might also like