###basic loop and condition problem
##print the first n natural number
n = int(input("Enter a number: "))
for i in range(1, n + 1):
print(i, end=" ")
##Print the sum of the first n natural numbers
n = int(input("Enter a number: "))
sum_n = sum(range(1, n + 1))
print(f"The sum of the first {n} natural numbers is {sum_n}")
##Check if a number is prime
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
print(f"{num} is not a prime number")
break
else:
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
##Print all prime numbers up to n
n = int(input("Enter a number: "))
for num in range(2, n + 1):
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
break
else:
print(num, end=" ")
##Check if a number is even or odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
##Print the Fibonacci series up to n terms
n = int(input("Enter the number of terms: "))
a, b = 0, 1
print("Fibonacci series:", end=" ")
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
##Count the number of digits in a number
num = int(input("Enter a number: "))
count = 0
while num > 0:
num //= 10
count += 1
print(f"The number has {count} digits")
##Reverse a number
num = int(input("Enter a number: "))
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print(f"Reversed number: {reversed_num}")
##Check if a number is a palindrome
num = int(input("Enter a number: "))
original_num = num
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
if original_num == reversed_num:
print(f"{original_num} is a palindrome")
else:
print(f"{original_num} is not a palindrome")
##Find the factorial of a number
num = int(input("Enter a number: "))
factorial = 1
for i in range(1, num + 1):
factorial *= i
print(f"The factorial of {num} is {factorial}")
###Pattern Printing
##Print a right-angled triangle pattern of *
n = int(input("Enter the number of rows: "))
for i in range(1, n + 1):
print("*" * i)
##Print an inverted triangle pattern of *
n = int(input("Enter the number of rows: "))
for i in range(n, 0, -1):
print("*" * i)
##Print a pyramid pattern of numbers
n = int(input("Enter the number of rows: "))
for i in range(1, n + 1):
print(" " * (n - i) + " ".join(str(x) for x in range(1, i + 1)))
##Print a diamond pattern of *
n = int(input("Enter the number of rows: "))
# Upper half
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))
# Lower half
for i in range(n - 1, 0, -1):
print(" " * (n - i) + "*" * (2 * i - 1))
##Print Pascal’s triangle
n = int(input("Enter the number of rows: "))
for i in range(n):
print(" " * (n - i), end="")
num = 1
for j in range(i + 1):
print(num, end=" ")
num = num * (i - j) // (j + 1)
print()
###Array-Based Problems
##Find the maximum and minimum in an array
arr = list(map(int, input("Enter array elements separated by space: ").split()))
print(f"Maximum: {max(arr)}, Minimum: {min(arr)}")
##Calculate the sum of elements in an array
arr = list(map(int, input("Enter array elements separated by space: ").split()))
print(f"Sum of array elements: {sum(arr)}")
##Find the second largest number in an array
arr = list(map(int, input("Enter array elements separated by space: ").split()))
unique_arr = list(set(arr)) # Remove duplicates
unique_arr.sort()
if len(unique_arr) < 2:
print("No second largest element exists.")
else:
print(f"Second largest element: {unique_arr[-2]}")
##Rotate an array by k positions
arr = list(map(int, input("Enter array elements separated by space: ").split()))
k = int(input("Enter the number of positions to rotate: "))
k %= len(arr) # Handle rotations greater than array size
rotated_array = arr[-k:] + arr[:-k]
print(f"Array after rotation: {rotated_array}")
##Count the frequency of elements in an array
arr = list(map(int, input("Enter array elements separated by space: ").split()))
freq = {}
for num in arr:
freq[num] = freq.get(num, 0) + 1
for key, value in freq.items():
print(f"Element {key}: Frequency {value}")
###String-Based Problems [Don’t use predefined methods of Python]
##Reverse a string
string = input("Enter a string: ")
reversed_string = ""
for char in string:
reversed_string = char + reversed_string
print(f"Reversed string: {reversed_string}")
##Check if a string is a palindrome
string = input("Enter a string: ")
if string == string[::-1]:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
#Count vowels and consonants in a string
string = input("Enter a string: ").lower()
vowels = "aeiou"
vowel_count = consonant_count = 0
for char in string:
if char.isalpha():
if char in vowels:
vowel_count += 1
else:
consonant_count += 1
print(f"Vowels: {vowel_count}, Consonants: {consonant_count}")
##Remove duplicate characters from a string
string = input("Enter a string: ")
result = ""
for char in string:
if char not in result:
result += char
print(f"String after removing duplicates: {result}")
##Find the frequency of characters in a string
string = input("Enter a string: ")
freq = {}
for char in string:
freq[char] = freq.get(char, 0) + 1
for key, value in freq.items():
print(f"Character '{key}': Frequency {value}")
###Number Manipulation
##Check if a number is an Armstrong number
num = int(input("Enter a number: "))
sum_of_powers = sum(int(digit) ** len(str(num)) for digit in str(num))
if num == sum_of_powers:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
##Print all Armstrong numbers up to n
n = int(input("Enter the upper limit: "))
print("Armstrong numbers up to", n, ":")
for i in range(n + 1):
if i == sum(int(digit) ** len(str(i)) for digit in str(i)):
print(i, end=" ")
print()
##Generate all permutations of digits in a number
from itertools import permutations
num = input("Enter a number: ")
perms = [''.join(p) for p in permutations(num)]
print(f"All permutations of {num}: {', '.join(perms)}")
##Find the greatest common divisor (GCD) of two numbers
def gcd(a, b):
while b:
a, b = b, a % b
return a
a, b = map(int, input("Enter two numbers separated by space: ").split())
print(f"GCD of {a} and {b} is {gcd(a, b)}")
##Find the least common multiple (LCM) of two numbers
def gcd(a, b):
while b:
a, b = b, a % b
return a
def lcm(a, b):
return a * b // gcd(a, b)
a, b = map(int, input("Enter two numbers separated by space: ").split())
print(f"LCM of {a} and {b} is {lcm(a, b)}")
###Matrix Manipulation
##Print the transpose of a matrix
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
matrix = []
print("Enter the matrix elements row by row:")
for i in range(rows):
row = list(map(int, input().split()))
matrix.append(row)
transpose = [[matrix[j][i] for j in range(rows)] for i in range(cols)]
print("Transpose of the matrix:")
for row in transpose:
print(*row)
##Check if a matrix is symmetric
rows = int(input("Enter the number of rows (and columns, since it's a square
matrix): "))
matrix = []
print("Enter the matrix elements row by row:")
for i in range(rows):
row = list(map(int, input().split()))
matrix.append(row)
is_symmetric = True
for i in range(rows):
for j in range(rows):
if matrix[i][j] != matrix[j][i]:
is_symmetric = False
break
if is_symmetric:
print("The matrix is symmetric.")
else:
print("The matrix is not symmetric.")
##Calculate the sum of the diagonal elements of a matrix
n = int(input("Enter the size of the square matrix: "))
matrix = []
print("Enter the matrix elements row by row:")
for i in range(n):
row = list(map(int, input().split()))
matrix.append(row)
diagonal_sum = sum(matrix[i][i] for i in range(n))
print(f"Sum of diagonal elements: {diagonal_sum}")
##Check the matrix program to find whether a syntax is identity
n = int(input("Enter the size of the square matrix: "))
matrix = []
print("Enter the matrix elements row by row:")
for i in range(n):
row = list(map(int, input().split()))
matrix.append(row)
is_identity = True
for i in range(n):
for j in range(n):
if i == j and matrix[i][j] != 1:
is_identity = False
break
elif i != j and matrix[i][j] != 0:
is_identity = False
break
if is_identity:
print("The matrix is an identity matrix.")
else:
print("The matrix is not an identity matrix.")
##Multiply two matrices
def input_matrix(name):
rows = int(input(f"Enter the number of rows for {name}: "))
cols = int(input(f"Enter the number of columns for {name}: "))
print(f"Enter the elements of {name} row by row:")
matrix = []
for i in range(rows):
row = list(map(int, input().split()))
matrix.append(row)
return matrix, rows, cols
matrix1, rows1, cols1 = input_matrix("Matrix 1")
matrix2, rows2, cols2 = input_matrix("Matrix 2")
if cols1 != rows2:
print("Matrix multiplication is not possible.")
else:
result = [[0 for _ in range(cols2)] for _ in range(rows1)]
for i in range(rows1):
for j in range(cols2):
for k in range(cols1):
result[i][j] += matrix1[i][k] * matrix2[k][j]
print("Result of matrix multiplication:")
for row in result:
print(*row)
###Logical and Miscellaneous Problems
##Check if a number is a perfect number
n = int(input("Enter a number: "))
divisors_sum = sum(i for i in range(1, n) if n % i == 0)
if divisors_sum == n:
print(f"{n} is a perfect number.")
else:
print(f"{n} is not a perfect number.")
##Count trailing zeroes in a factorial
def count_trailing_zeroes(n):
count = 0
while n >= 5:
n //= 5
count += n
return count
num = int(input("Enter a number: "))
print(f"Number of trailing zeroes in {num}! is {count_trailing_zeroes(num)}")
##Print the binary representation of a number
num = int(input("Enter a number: "))
binary_representation = ""
while num > 0:
binary_representation = str(num % 2) + binary_representation
num //= 2
print("Binary representation:", binary_representation)
##Find the sum of digits in a number
num = int(input("Enter a number: "))
digit_sum = 0
while num > 0:
digit_sum += num % 10
num //= 10
print(f"Sum of digits: {digit_sum}")
##Calculate the power of a number using loops
base = int(input("Enter the base: "))
exponent = int(input("Enter the exponent: "))
result = 1
for _ in range(exponent):
result *= base
print(f"{base} raised to the power of {exponent} is {result}")
###Advanced Loop-Based Challenges
##Find the longest sequence of consecutive 1s in a binary array
binary_array = list(map(int, input("Enter the binary array (space-separated):
").split()))
max_count = 0
current_count = 0
for num in binary_array:
if num == 1:
current_count += 1
max_count = max(max_count, current_count)
else:
current_count = 0
print(f"The longest sequence of consecutive 1s is: {max_count}")
##Count the number of subarrays with a given sum.
arr = list(map(int, input("Enter the array (space-separated): ").split()))
target_sum = int(input("Enter the target sum: "))
count = 0
for i in range(len(arr)):
current_sum = 0
for j in range(i, len(arr)):
current_sum += arr[j]
if current_sum == target_sum:
count += 1
print(f"Number of subarrays with sum {target_sum}: {count}")
##Generate all subsets of an array
from itertools import combinations
arr = list(map(int, input("Enter the array (space-separated): ").split()))
subsets = []
for r in range(len(arr) + 1):
subsets.extend(combinations(arr, r))
print("All subsets:")
for subset in subsets:
print(subset)
##Print all prime factors of a number
def prime_factors(n):
factors = []
while n % 2 == 0:
factors.append(2)
n //= 2
for i in range(3, int(n**0.5) + 1, 2):
while n % i == 0:
factors.append(i)
n //= i
if n > 2:
factors.append(n)
return factors
num = int(input("Enter a number: "))
print("Prime factors:", prime_factors(num))
##Solve the "FizzBuzz" problem
n = int(input("Enter the range for FizzBuzz: "))
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
###Algorithmic Challenges
##Check if a number is a happy number
def is_happy_number(n):
visited = set()
while n != 1 and n not in visited:
visited.add(n)
n = sum(int(digit) ** 2 for digit in str(n))
return n == 1
num = int(input("Enter a number: "))
if is_happy_number(num):
print(f"{num} is a Happy Number")
else:
print(f"{num} is not a Happy Number")
##Python program to enter two numbers and using below concept
##Number 1 = 562 , Number 2 = 123 .
##Final result : (5+1)6 | (6+2)8 | (2+3)5 = 685
def compute_logic(num1, num2):
digits1 = list(map(int, str(num1)))
digits2 = list(map(int, str(num2)))
result = ''.join(str(d1 + d2) for d1, d2 in zip(digits1, digits2))
return result
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("Final result:", compute_logic(num1, num2))
##Check if an array is sorted
def is_sorted(arr):
return arr == sorted(arr)
arr = list(map(int, input("Enter the array (space-separated): ").split()))
if is_sorted(arr):
print("The array is sorted")
else:
print("The array is not sorted")
##Merge two sorted arrays
def merge_sorted_arrays(arr1, arr2):
i, j = 0, 0
merged = []
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
merged.append(arr1[i])
i += 1
else:
merged.append(arr2[j])
j += 1
merged.extend(arr1[i:])
merged.extend(arr2[j:])
return merged
arr1 = list(map(int, input("Enter the first sorted array (space-separated):
").split()))
arr2 = list(map(int, input("Enter the second sorted array (space-separated):
").split()))
print("Merged sorted array:", merge_sorted_arrays(arr1, arr2))
##Input a number and add one to each digit.
##Number = 571 and Updated No = 682
def add_one_to_digits(n):
return int(''.join(str(int(digit) + 1) for digit in str(n)))
num = int(input("Enter a number: "))
print("Updated number:", add_one_to_digits(num))