0% found this document useful (0 votes)
45 views45 pages

Soti

The document provides various coding tasks along with their solutions in Python and C. Tasks include reversing a number, generating Fibonacci series, finding the GCD, checking for perfect numbers, determining anagrams, checking palindromes, calculating character frequency, and implementing sorting algorithms like bubble sort and merge sort. It also covers checking leap years, finding non-repeating characters, replacing substrings, and implementing heap sort.

Uploaded by

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

Soti

The document provides various coding tasks along with their solutions in Python and C. Tasks include reversing a number, generating Fibonacci series, finding the GCD, checking for perfect numbers, determining anagrams, checking palindromes, calculating character frequency, and implementing sorting algorithms like bubble sort and merge sort. It also covers checking leap years, finding non-repeating characters, replacing substrings, and implementing heap sort.

Uploaded by

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

1.

Write a code to reverse a number


To reverse a number, you need to take the digits of the number and
rearrange them in the opposite order.

 Start by converting the number to a string, reverse that string,

and then convert it back to an integer. This will give you the

reversed version of the original number.

 Example: If the number is 908701, take digits from last → 1, 0,

7, 8, 0, 9 → and make it 107809.

num = int(input("Enter the Number:"))


temp = num
reverse = 0
while num > 0:
remainder = num % 10
reverse = (reverse * 10) + remainder
num = num // 10

print("The Given number is {} and Reverse is


{}".format(temp, reverse))

2. Write the code to find the Fibonacci series upto the nth term.
This problem asks to generate the Fibonacci sequence up to the nth
term. In this sequence, each number is the sum of the two preceding
ones, starting from 0 and 1.

 The goal is to calculate and display all Fibonacci numbers from

the 0th to the nth term.

 Example for n = 10:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34
(Writing: Start with 0 and 1 → 0+1=1 → 1+1=2 → 1+2=3 → 2+3=5 →
and so on.)

num = int(input("Enter the Number:"))


n1, n2 = 0, 1
print("Fibonacci Series:", n1, n2, end=" ")
for i in range(2, num):
n3 = n1 + n2
n1 = n2
n2 = n3
print(n3, end=" ")

print()

3. Write code of Greatest Common Divisor


This problem asks to find the Greatest Common Divisor (GCD) of two
given numbers. The GCD of two numbers is the largest positive integer
that divides both numbers without leaving a remainder.

 The Euclidean algorithm is a popular method for efficiently

computing the GCD.

 Example: Find GCD of 36 and 60:

The common divisors of 36 and 60 are 1, 2, 3, 4, 6, 9, 12, 18, 36

and 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60.

The largest common divisor is 12.

num1 = int(input("Enter First Number:"))


num2 = int(input("Enter Second Number:"))

def gcdFunction(num1, num2):


if num1 > num2:
small = num2
else:
small = num1
for i in range(1, small+1):
if (num1 % i == 0) and (num2 % i == 0):
gcd = i
print("GCD of two Number: {}".format(gcd))

gcdFunction(num1, num2)
4. Write code of Perfect number

 A perfect number is a positive integer that is equal to the sum of

its proper divisors, excluding the number itself.

 Example: Is 28 a perfect number?

The divisors of 28 are 1, 2, 4, 7, 14.

Sum of divisors: 1 + 2 + 4 + 7 + 14 = 28, so 28 is a perfect

number.
n = int(input(“Enter any number: “))
sump= 0
for i in range(1, n):
if(n % i == 0):
sump= sump + i
if (sump == n):
print(“The number is a Perfect number”)
else:
print(“The number is not a Perfect number”)

5. Write code to Check if two strings are Anagram or not


Two strings are called anagrams if they contain the same characters in
the same frequencies, but possibly in different orders.

 This code checks whether two given strings are anagrams of each

other.
 Example: Are “listen” and “silent” anagrams?

Sort both:
“listen” → “eilnst”

“silent” → “eilnst”
Both are the same, so “listen” and “silent” are anagrams.

#take user input


String1 = input(‘Enter the 1st string :’)
String2 = input(‘Enter the 2nd string :’)
#check if length matches
if len(String1) != len(String2):
#if False
print(‘Strings are not anagram’)
else:
#sorted function sort string by characters
String1 = sorted(String1)
String2 = sorted(String2)
#check if now strings matches
if String1 == String2:
#if True
print(‘Strings are anagram’)
else:
print(‘Strings are not anagram’)

6. Write code Check if the given string is Palindrome or not


A palindrome is a word, phrase, or sequence that reads the same
backward as forward, ignoring spaces, punctuation, and capitalization.

 This code checks if a given string is a palindrome.

 Example for a palindrome:

“madam” — reads the same backward as forward


#take user input
String1 = input('Enter the String :')
#initialize string and save reverse of 1st string
String2 = String1[::-1]
#check if both matches
if String1 == String2:
print('String is palindromic')
else:
print('Strings is not palindromic')

7. Write code to Calculate frequency of characters in a string


This problem asks to calculate the frequency of each character in a
given string.

 The goal is to determine how many times each character appears

in the string.

 Example for string “hello”:

o ‘h’ appears 1 time

o ‘e’ appears 1 time

o ‘l’ appears 2 times

o‘o’ appears 1 time


#take user input
String = input('Enter the string :')
#take character input
Character = input('Enter character :')
#initiaalize int variable to store frequency
frequency = 0
#use count function to count frequency of character
frequency = String.count(Character)
#count function is case sencetive
#so it print frequency of Character according to given
Character
print(str(frequency) + ' is the frequency of given
character')
8. Write code to check if two strings match where one string
contains wildcard characters
This problem checks if two strings match where one string contains
wildcard characters. The wildcards are:

 * for any sequence of characters (including an empty sequence).

 ? for exactly one character.

 Example:

o“he?lo” matches “hello”, but not “healo”.


def solve(a,b):
n,m=len(a),len(b)
if n==0 and m==0:
return True
if n > 1 and a[0] == '*' and m == 0:
return False
if (n > 1 and a[0] == '?') or (n != 0 and m !=0 and a[0]
== b[0]):
return solve(a[1:],b[1:]);
if n !=0 and a[0] == '*':
return solve(a[1:],b) or solve(a,b[1:])
return False

9. Write a code for bubble sort


Bubble Sort is a simple sorting algorithm that repeatedly steps through
the list, compares adjacent elements, and swaps them if they are in
the wrong order.

 The process continues until the list is sorted.

 Example for list [5, 3, 8, 4, 2]:

After sorting, the list will be [2, 3, 4, 5, 8].


#include<stdio.h>

/* Function to print array */


void display(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Main function to run the program


int main() {
int array[] = {
5,
3,
1,
9,
8,
2,
4,
7
};
int size = sizeof(array) / sizeof(array[0]);

printf("Before bubble sort: \n");


display(array, size);

int i, j, temp;
for (i = 0; i < size - 1; i++) {

// Since, after each iteration righmost i elements are


sorted
for (j = 0; j < size - i - 1; j++)
if (array[j] > array[j + 1]) {
temp = array[j]; // swap the element
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
printf("After bubble sort: \n");
display(array, size);
return 0;
}

10. How is the merge sort algorithm implemented?


Merge Sort is a divide-and-conquer algorithm that splits the list into
smaller sublists, sorts each sublist, and then merges the sorted
sublists.

 The process continues recursively until the entire list is sorted.

 Example for list [5, 3, 8, 4, 2]:

After sorting, the list will be [2, 3, 4, 5, 8].


#include<stdio.h>

void mergeSort(int[], int, int);


void merge(int[], int, int, int);

void display(int arr[], int size) {


int i;
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

void main() {
int a[10] = {
11,
9,
6,
19,
33,
64,
15,
75,
67,
88
};
int i;
int size = sizeof(a) / sizeof(a[0]);
display(a, size);

mergeSort(a, 0, size - 1);


display(a, size);
}

void mergeSort(int a[], int left, int right) {


int mid;
if (left < right) {
// can also use mid = left + (right - left) / 2
// this can avoid data type overflow
mid = (left + right) / 2;

// recursive calls to sort first half and second half


subarrays
mergeSort(a, left, mid);
mergeSort(a, mid + 1, right);
merge(a, left, mid, right);
}
}

void merge(int arr[], int left, int mid, int right) {


int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;

// create temp arrays to store left and right subarrays


int L[n1], R[n2];

// Copying data to temp arrays L[] and R[]


for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

// here we merge the temp arrays back into arr[l..r]


i = 0; // Starting index of L[i]
j = 0; // Starting index of R[i]
k = left; // Starting index of merged subarray

while (i < n1 && j < n2) {


// place the smaller item at arr[k] pos
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
// Copy the remaining elements of L[], if any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
// Copy the remaining elements of R[], if any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

11. Write to code to check whether a given year is leap year or


not.
A leap year is a year that is divisible by 4, but not divisible by 100,
unless it is also divisible by 400.

 This code checks whether a given year is a leap year based on

this rule.

 Example:

o 2020 is a leap year (divisible by 4).

o 1900 is not a leap year (divisible by 100 but not 400).


2000 is a leap year (divisible by 400).
o
#include <stdio.h>

int main() {
int year;
scanf("%d", & year);

if (year % 400 == 0)
printf("%d is a Leap Year", year);

else if (year % 4 == 0 && year % 100 != 0)


printf("%d is a Leap Year", year);

else
printf("%d is not a Leap Year", year);

return 0;
}

12. Find non-repeating characters in a string


This problem asks to find the characters in a string that appear only
once, i.e., the non-repeating characters.

 These characters are unique and do not appear multiple times in

the string.

 Example for string “swiss”:

Non-repeating characters are ‘w’ and ‘i’, since ‘s’ repeats.


o
#take user input
String = "prepinsta"
for i in String:
#initialize a count variable
count = 0
for j in String:
#check for repeated characters
if i == j:
count+=1
#if character is found more than 1 time
#brerak the loop
if count > 1:
break
#print for nonrepeating characters
if count == 1:
print(i,end = " ")

13. Write a code to replace a substring in a string.


This problem asks to replace a substring within a string with another
substring.

 The goal is to find all occurrences of the target substring and


replace them with the desired one.
 Example for string “hello world”:
Replacing “world” with “Python” results in “hello Python”.
o
string=input("Enter String :\n")
str1=input("Enter substring which has to be replaced :\n")
str2=input("Enter substring with which str1 has to be
replaced :\n")
string=string.replace(str1,str2)
print("String after replacement")
print(string)

14. Write a code for Heap sort.


Heap Sort is a comparison-based sorting algorithm that uses a binary
heap data structure. It works by building a max-heap (or min-heap)
from the input data and then repeatedly extracting the maximum
element from the heap and placing it at the end of the array.

 This process is done until the heap is empty.

 Example for list [5, 3, 8, 4, 2]:

After sorting, the list will be [2, 3, 4, 5, 8].


#include<stdio.h> // including library files
int temp;

void heapify(int arr[], int size, int i)//declaring functions


{
int max = i;
int left = 2*i + 1;
int right = 2*i + 2;

if (left < size && arr[left] >arr[max])


max= left;

if (right < size && arr[right] > arr[max])


max= right;

if (max!= i)
{
// performing sorting logic by using temporary variable
temp = arr[i];
arr[i]= arr[max];
arr[max] = temp;
heapify(arr, size, max);
}
}

void heapSort(int arr[], int size)// providing definition to heap


sort
{
int i;
for (i = size / 2 - 1; i >= 0; i--)
heapify(arr, size, i);
for (i=size-1; i>=0; i--)
{
// swaping logic
temp = arr[0];
arr[0]= arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}

void main() // defining main()


{
int arr[] = {58, 134, 3, 67, 32, 89, 15, 10,78, 9};
// array initializing with their elements.
int i;
int size = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, size);

printf("printing sorted elements\n"); // printing the sorted array


for (i=0; i<size; ++i)
printf("%d\n",arr[i]);
}

15. Write a code to replace each element in an array by its rank in


the array
This problem asks to replace each element in an array by its rank in
the array.

 The rank of an element is its position in the sorted array (with ties

assigned the same rank).

 Example for array [40, 10, 20, 30]:

After replacing each element by its rank, the array will be [4, 1, 2,

3] (after sorting, the elements are [10, 20, 30, 40], so ranks are

[1, 2, 3, 4]).
def changeArr(input1):

newArray = input1.copy()
newArray.sort()

for i in range(len(input1)):
for j in range(len(newArray)):
if input1[i]==newArray[j]:
input1[i] = j+1;
break;

# Driver Code
arr = [100, 2, 70, 12 , 90]
changeArr(arr)
# Print the array elements
print(arr)
16. Write a code to find circular rotation of an array by K
positions.
This problem asks to find the circular rotation of an array by K
positions.

 In a circular rotation, elements that are moved from the end of


the array are appended to the beginning.
 Example for array [1, 2, 3, 4, 5] and K = 2:
After rotating the array by 2 positions, the result will be [4, 5, 1,
2, 3].
def rotateArray(arr, n, d):
temp = []
i = 0
while (i < d):
temp.append(arr[i])
i = i + 1
i = 0
while (d < n):
arr[i] = arr[d]
i = i + 1
d = d + 1
arr[:] = arr[: i] + temp
return arr

17. Write a code to find non-repeating elements in an array.


This problem asks to find the elements in an array that appear only
once, i.e., the non-repeating elements.

 These elements are unique and do not appear multiple times in

the array.

 Example for array [4, 5, 4, 3, 6, 3, 7]:

o Non-repeating elements are [5, 6, 7], since ‘4’ and ‘3’

repeat.
# Python 3 program to count unique elements
def count(arr, n):

# Mark all array elements as not visited


visited = [False for i in range(n)]

# Traverse through array elements


# and count frequencies
for i in range(n):

# Skip this element if already


# processed
if (visited[i] == True):
continue

# Count frequency
count = 1
for j in range(i + 1, n, 1):
if (arr[i] == arr[j]):
visited[j] = True
count += 1
if count == 1 :
print(arr[i]);

# Driver Code
arr = [10, 30, 40, 20, 10, 20, 50, 10]
n = len(arr)
count(arr, n)

18. Write a code to check for the longest palindrome in an array.


This problem asks to find the longest palindrome in an array of strings.
A palindrome is a word, phrase, or sequence that reads the same
backward as forward.

 The goal is to identify the longest string in the array that is a

palindrome.
 Example for array [“racecar”, “level”, “hello”, “madam”,

“world”]:

The longest palindrome is “racecar”.


# Function to check if n is palindrome
def isPalindrome(n):

divisor = 1
while (int(n / divisor) >= 10):
divisor *= 10

while (n != 0):
leading = int(n / divisor)
trailing = n % 10

if (leading != trailing):
return False

n = int((n % divisor) / 10)

divisor = int(divisor / 100)


return True

# Function to find the largest palindromic element


def largestPalindrome(arr, n):
currentMax = -1

for i in range(0, n, 1):


if (arr[i] > currentMax and isPalindrome(arr[i])):
currentMax = arr[i]

return currentMax

# Driver Code

arr = [1, 232, 5545455, 909090, 161]


n = len(arr)

# print required answer


print(largestPalindrome(arr, n))
19. Write a code to find the factorial of a number.
This problem asks to find the factorial of a given number. The factorial
of a non-negative integer n is the product of all positive integers less
than or equal to n. It is denoted as n!.

 For example:
5! = 5 × 4 × 3 × 2 × 1 = 120

0! = 1 (by definition).

num = 5
output = 1
for i in range(2,num+1):
output*=i
print(output)

20. Write the code to for Armstrong number


An Armstrong number (or Narcissistic number) is a number that is
equal to the sum of its own digits each raised to the power of the
number of digits.

 For example:

o 153 is an Armstrong number because 1^3 + 5^3 + 3^3 =

153.

o 370 is an Armstrong number because 3^3 + 7^3 + 0^3 =

370.

number = 371
num = number
digit, sum = 0, 0
length = len(str(num))
for i in range(length):
digit = int(num%10)
num = num/10
sum += pow(digit,length)
if sum==number:
print("Armstrong")
else:
print("Not Armstrong")
21. Write a program to find the sum of Natural Numbers using
Recursion.
This problem asks to find the sum of the first n natural numbers using
recursion. The sum of the first n natural numbers is given by the
formula 1 + 2 + 3 + … + n.

 For example:
Sum of first 5 natural numbers: 1 + 2 + 3 + 4 + 5 = 15.

def getSum(num):
if num == 1:
return 1
return num + getSum(num-1)

num = 5
print(getSum(num))

22. Write a program to add Two Matrices using Multi-dimensional


Array.
This problem asks to add two matrices using a multi-dimensional array.
Matrix addition is done by adding corresponding elements of two
matrices of the same size.

 The sum matrix will have the same dimensions as the input

matrices.
 Example for matrices:

o Matrix A:
[1, 2, 3]
[4, 5, 6]

o Matrix B:
[7, 8, 9]
[10, 11, 12]

o The sum of Matrix A and Matrix B:


[1+7, 2+8, 3+9]
[4+10, 5+11, 6+12]

o Result:
[8, 10, 12]
[14, 16, 18]

C
#include
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);

printf("\nEnter elements of 1st matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

printf("Enter elements of 2nd matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}

// adding two matrices


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}

// printing the result


printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}
return 0;
}

23. Write a Program to Find the Sum of Natural Numbers using


Recursion.
This problem asks to find the sum of the first n natural numbers using
recursion.

 The sum of the first n natural numbers is calculated by

recursively adding the numbers from 1 to n.

 For example:
Sum of the first 5 natural numbers: 1 + 2 + 3 + 4 + 5 = 15.

def recursum(number):
if number == 0:
return number
return number + recursum(number-1)
number, sum = 6,0
print(recursum(number))

24. Write code to check a String is palindrome or not?


This problem asks to check whether a given string is a palindrome or
not.

 A string is considered a palindrome if it reads the same forward

and backward, ignoring spaces, punctuation, and case.

 For example:

o “racecar” is a palindrome because it reads the same

forward and backward.

o “hello” is not a palindrome because it does not read the

same backward.
# function which return reverse of a string

def isPalindrome(s):
return s == s[::-1]

# Driver code
s = "malayalam"
ans = isPalindrome(s)

if ans:
print("Yes")
else:
print("No")

25. Write a program for Binary to Decimal to conversion


This problem asks to convert a binary number (base 2) to its decimal
(base 10) equivalent.

 Each digit in a binary number represents a power of 2, and the

decimal value is the sum of these powers.

 For example:

o Binary 101 is equal to Decimal 5 because:

1 * 2^2 + 0 * 2^1 + 1 * 2^0 = 4 + 0 + 1 = 5.


num = int(input("Enter number:"))
binary_val = num
decimal_val = 0
base = 1
while num > 0:
rem = num % 10
decimal_val = decimal_val + rem * base
num = num // 10
base = base * 2

print("Binary Number is {} and Decimal Number is


{}".format(binary_val, decimal_val))

26. Write a program to check whether a character is a vowel or


consonant
This problem asks to check whether a given character is a vowel or a
consonant. Vowels are the letters a, e, i, o, u (both uppercase and
lowercase). Any other alphabetic character is considered a consonant.

#get user input


Char = input()
#Check if the Char belong to set of Vowels
if (Char == 'a' or Char == 'e' or Char == 'i' or Char == 'o' or
Char == 'u'):
#if true
print("Character is Vowel")
else:
#if false
print("Character is Consonant")

27. Write a code to find an Automorphic number


An Automorphic number is a number whose square ends with the same
digits as the number itself.

 For example:

o 5 is an Automorphic number because 5^2 = 25, and the

last digit is 5.

o 6 is an Automorphic number because 6^2 = 36, and the

last digit is 6.

o 25 is an Automorphic number because 25^2 = 625, and the

last two digits are 25.


#include<stdio.h>

int checkAutomorphic(int num)


{
int square = num * num;

while (num > 0)


{
if (num % 10 != square % 10)
return 0;

// Reduce N and square


num = num / 10;
square = square / 10;
}
return 1;
}

int main()
{
//enter value
int num;
scanf("%d",&num);
//checking condition
if(checkAutomorphic(num))
printf("Automorphic");
else
printf("Not Automorphic");
return 0;
}

28. Write a code to find Find the ASCII value of a character


This problem asks to find the ASCII value of a given character. The
ASCII (American Standard Code for Information Interchange) value of a
character is its integer representation in the ASCII table.

 For example:

o The ASCII value of ‘A’ is 65.

o The ASCII value of ‘a’ is 97.


#user input
Char = input('Enter the character :')
#convert Char to Ascii value
Asciival = ord(Char)
#print Value
print(Asciival)

29. Write a code to Remove all characters from string except


alphabets
This problem asks to remove all characters from a string except for the
alphabets (both uppercase and lowercase). This can be done by
filtering the string and keeping only the alphabetic characters.

#take user input


String1 = input('Enter the String :')
#initialize empty String
String2 = ''
for i in String1:
#check for alphabets
if (ord(i) >= 65 and ord(i) <= 90) or (ord(i) >= 97 and ord(i)
<= 122):
#concatenate to empty string
String2+=i
print('Alphabets in string are :' + String2)

30. Write a code to Print the smallest element of the array


This problem asks to find and print the smallest element in an array.
You can do this by iterating through the array and comparing each
element to find the smallest one.

 Example :

o Given an array: [5, 3, 8, 1, 9, 4]

o The smallest element in the array is 1 because it is the least

value compared to the other elements.


arr = [10, 89, 9, 56, 4, 80, 8]
mini = arr[0]

for i in range(len(arr)):
if arr[i] < mini:
mini = arr[i]

print (mini)

31. Write a code to Reverse the element of the array


This problem asks to reverse the elements of an array. Reversing an
array means arranging the elements in the opposite order, so the last
element becomes the first and so on.

 Example :
o Given an array: [1, 2, 3, 4, 5]

o After reversing the array, it becomes: [5, 4, 3, 2, 1]

o The elements are arranged in the opposite order, where the

last element becomes the first, and so on.


def reverseList(A, start, end):
while start < end:
A[start], A[end] = A[end], A[start]
start += 1
end -= 1
# Driver function to test above function
A = [10, 20, 30, 40, 50]
reverseList(A, 0, 4)
print(A)

32. Write a code to Sort the element of the array


This problem asks to sort the elements of an array in ascending order.
Sorting arranges the elements in order, with the smallest element first
and the largest last.

 Example :

o Given an array of random numbers:

[52, 3, 19, 7, 88, 12, 45, 23, 100, 6, 0, 47]

o After sorting in ascending order, the array becomes:

[0, 3, 6, 7, 12, 19, 23, 45, 47, 52, 88, 100]

o This example contains a mix of larger and smaller numbers,

and sorting arranges them from the smallest (0) to the

largest (100).
# List of Integers
numbers = [10, 30, 40, 20]
# Sorting list of Integers
numbers.sort()

print(numbers)

33. Write a code to Sort the element of the array without sort
method
This problem asks to sort the elements of an array without using the
built-in sort() method. The solution requires using the swap method to
manually arrange the array in ascending order.

 One common way to do this is by using a sorting algorithm like

Bubble Sort, where adjacent elements are compared and

swapped if they are in the wrong order.

 Example:
Given an array:
[4, 2, 9, 1]

 Steps (Bubble Sort with Swap Method):

 First Pass:

o Compare 4 and 2. Since 4 > 2, swap them: [2, 4, 9, 1]

o Compare 4 and 9. No swap needed: [2, 4, 9, 1]

o Compare 9 and 1. Since 9 > 1, swap them: [2, 4, 1, 9]


After the first pass, the largest element 9 is in its correct position.

 Second Pass:
o Compare 2 and 4. No swap needed: [2, 4, 1, 9]

o Compare 4 and 1. Since 4 > 1, swap them: [2, 1, 4, 9]

o After the second pass, 4 is now in its correct position.

 Third Pass:

o Compare 2 and 1. Since 2 > 1, swap them: [1, 2, 4, 9]

o Now the array is fully sorted.

 Final Sorted Array:

[1, 2, 4, 9]
# List of Integers
numbers = [10, 30, 40, 20]

# Sorting list of Integers


numbers.sort()

print(numbers)

34. Write a code to Replace a Substring in a string


This problem asks to replace a specific substring within a string with
another substring. The task is to identify all occurrences of the
substring and replace them with the new one.

 Example :

o Input String:

“I love programming in Python!”

o Substitute:

Replace “Python” with “Java”.


o Output:

“I love programming in Java!”


string=input("Enter String :\n")
str1=input("Enter substring which has to be replaced :\n")
str2=input("Enter substring with which str1 has to be replaced :\n")
string=string.replace(str1,str2)
print("String after replacement")
print(string)

35. Write a code to Remove space from a string


This problem asks to remove all spaces from a given string. The task is
to remove every occurrence of spaces, including leading, trailing, and
any spaces in between the words.

 Example :

o Input String:

“This is a test string”

o Output:

“Thisisateststring”
#take user input
String = "PrepInsta is fabulous"

#Use join function


String = "".join(String.split())

#print String
print("After removing spaces string is :",String)

36. Write a code to Count Inversion


This problem asks to count the number of inversions in an array. An
inversion in an array is a pair of indices (i, j) such that i < j and arr[i] >
arr[j]. The goal is to count how many such pairs exist in the given
array.

Example :

 Given the array [1, 20, 6, 4, 5], we count the number of


inversions where a larger number appears before a smaller one.
 The inversions are: (20, 6), (20, 4), (20, 5), (6, 4), and (6, 5),
totaling 5 inversions.
 Each inversion is counted whenever a pair (i, j) with i < j and
arr[i] > arr[j] is found. Thus, the result is 5.
def inversion(arr):
ans = 0
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[j] < arr[i]:
ans += 1
return ans

array = [6, 3, 5, 2, 7]
print("There are", inversion(array), "possible inversion")

37. Write a code to find consecutive largest


subsequence
This problem asks to find the longest consecutive subsequence in an
unsorted array. A consecutive subsequence is a sequence of numbers
that appear in consecutive order but not necessarily contiguous in the
original array.

Example :

 Input Array:

[100, 4, 200, 1, 3, 2]
 Step 1:

Convert the array to a set for fast lookups:

{100, 4, 200, 1, 3, 2}

 Step 2:

Start checking from each element:

o For 100: Not part of a sequence, so skip.

o For 4: Start a sequence. Find 3, 2, and 1 in the set.

o Sequence found: [1, 2, 3, 4].

 Step 3:

The longest consecutive subsequence is [1, 2, 3, 4].


def LongestConseqSubseq(arr, l):
val = []
c = 0
for i in range(l):
n = 1
while arr[i] + n in arr:
c += 1
n += 1
val.append(c + 1)
c = 0
return max(val)

array = [7, 8, 1, 5, 4, 3]

print("Longest Consecutive Subsequence :", LongestConseqSubseq(array,


len(array)))

38: Write a Program to Find out the Sum of Digits of a Number.


This problem asks to find the sum of the digits of a given number. The
goal is to extract each digit of the number and compute their sum.

Example :
 Input: 12345

 Extract and Add:

o 5+4+3+2+1

 Sum: 15

 Output: The sum of digits is 15.


num = input("Enter Number: ")
sum = 0

for i in num:
sum = sum + int(i)

print(sum)

39: Write a Program to Find out the Power of a Number


This program calculates the power of a number. Given a base a and
exponent b, compute𝑎
(a raised to the power b).

Example :

 Input: Base = 2, Exponent = 5

 Calculation: 2^5 = 2×2×2×2×2

 Result: 32

 Output: 2 raised to the power 5 is: 32


num, power = 3, 2
print(pow(num,power))
Find More Solutions at Python Program to Find out the Power of a
Number

40: Write a Program to Find out the Sum of Digits of a Number.


This program calculates the sum of digits of a given number. It
repeatedly extracts each digit and adds them together.

Example:

 Input: 789

 Digits: 7, 8, 9

 Sum: 7 + 8 + 9 = 24

 Output: Sum of digits of 789 is: 24


num = input("Enter Number: ")
sum = 0

for i in num:
sum = sum + int(i)

print(sum)

41: Write a Program to Add two Fractions


This program adds two fractions and gives the simplified result.

Example:

 Input Fractions: 1/2 and 1/3

 Steps: Cross multiply and add → result is 5/6

 Simplified Result: 5/6


def findGCD(n1, n2):
gcd = 0
for i in range(1, int(min(n1, n2)) + 1):
if n1 % i == 0 and n2 % i == 0:
gcd = i
return gcd

# input first fraction


num1, den1 = map(int, list(input("Enter numerator and
denominator of first number : ").split(" ")))

# input first fraction


num2, den2 = map(int, list(input("Enter numerator and
denominator of second number: ").split(" ")))

lcm = (den1 * den2) // findGCD(den1, den2)

sum = (num1 * lcm // den1) + (num2 * lcm // den2)

num3 = sum // findGCD(sum, lcm)

lcm = lcm // findGCD(sum, lcm)

print(num1, "/", den1, " + ", num2, "/", den2, " = ", num3,
"/", lcm)

42: Write a Program to Find the Largest Element in an Array.


This program finds the largest element present in a given array by
comparing each element.

 It checks all elements one by one and keeps track of the

maximum value found so far.


Example:

 Input Array: [10, 45, 2, 67, 23]

 Compare elements: Find the biggest number.

 Largest Element: 67
 Output: Largest element is: 67
a = [10, 89, 9, 56, 4, 80, 8]
max_element = a[0]

for i in range(len(a)):
if a[i] > max_element:
max_element = a[i]

print (max_element)

43: Write a Program to Find the Roots of a Quadratic Equation


This program finds the roots of a quadratic equation.

 It checks if the roots are real, equal, or complex based on

calculation results.
Example:

 Input: a = 1, b = -3, c = 2

 Process: Find roots. Roots are real and different.

 Roots:2.0 and 1.0

 Output: Roots are real and different: 2.0, 1.0


# Write a program to find roots of a quadratic equation in
Python
import math

def findRoots(a, b, c):

if a == 0:
print("Invalid")
return -1
d = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(d))

if d > 0:
print("Roots are real and different ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif d == 0:
print("Roots are real and same")
print(-b / (2*a))
else: # d<0
print("Roots are complex")
print(- b / (2*a), " + i", sqrt_val)
print(- b / (2*a), " - i", sqrt_val)

# Driver Program
a = 1
b = 4
c = 4

# Function call
findRoots(a, b, c)

44: Write a Program to Find the Prime Factors of a Number.


This program finds all the prime factors of a given number. A prime
factor is a factor that is a prime number.

 The program checks each number and divides the given number

by all possible prime factors until it’s reduced to 1.


Example:

 Input: 56

 Process:
o Divide 56 by 2 → 56 / 2 = 28

o Divide 28 by 2 → 28 / 2 = 14

o Divide 14 by 2 → 14 / 2 = 7

o 7 is prime, so stop here.

o Prime Factors: 2, 2, 2, 7

 Output: Prime factors of 56 are: [2, 2, 2, 7]


def Prime_Factorial(n):
if n < 4:
return n
arr = []
while n > 1:
for i in range(2, int(2+n//2)):
if i == (1 + n // 2):
arr.append(n)
n = n // n
if n % i == 0:
arr.append(i)
n = n // i
break
return arr

n = 210
print(Prime_Factorial(n))

45: Write a Program to Convert Digits to Words.


This program converts a number (digits) into words. For example, the
number 123 should be converted into “One Two Three”.

Example:

 Input: 123
 Process:

o 1 → “One”

o 2 → “Two”

o 3 → “Three”

 Output: Digits 123 in words are: One Two Three


from num2words import num2words

# Most common usage.


print(num2words(11098))

# can also specify this for -th format


print(num2words(11098, to='ordinal'))

46: Write a Program to Find the Factorial of a Number using


Recursion.
This program calculates the factorial of a number using recursion. The
factorial of a number n is the product of all positive integers less than
or equal to n.

Example:

 Input: 5

 Process:

o 5 * factorial(4)

o 4 * factorial(3)

o 3 * factorial(2)

o 2 * factorial(1) (Base case: factorial of 1 is 1)


 Output: Factorial of 5 is: 120
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)

num = 5
print("Factorial of", num, "is", factorial(num))

47: Write a Program to Reverse an Array


This program reverses the elements of an array. It swaps elements
from the beginning and end until the entire array is reversed.

Example:

 Input: [1, 2, 3, 4, 5]

 Process:

o Swap 1 and 5 → [5, 2, 3, 4, 1]

o Swap 2 and 4 → [5, 4, 3, 2, 1]

o Array is reversed.

 Output: Reversed array: [5, 4, 3, 2, 1]


def reverseList(A, start, end):
while start < end:
A[start], A[end] = A[end], A[start]
start += 1
end -= 1
# Driver function to test above function
A = [10, 20, 30, 40, 50]
reverseList(A, 0, 4)
print(A)
48. Write code to check if two strings match where one string
contains wildcard characters
This program checks if two strings match, where one of the strings
may contain wildcard characters.

 The wildcard character * represents any sequence of characters

(including an empty sequence), and ? represents any single

character.
Example:

 Input:

o Pattern: “a*b?e”

o String: “ababe”

 Process:

o * matches “ab”

o ? matches “b”

 Output: Do the strings match? True


def solve(a,b):
n,m=len(a),len(b)
if n==0 and m==0:
return True
if n > 1 and a[0] == '*' and m == 0:
return False
if (n > 1 and a[0] == '?') or (n != 0 and m !=0 and a[0]
== b[0]):
return solve(a[1:],b[1:]);
if n !=0 and a[0] == '*':
return solve(a[1:],b) or solve(a,b[1:])
return False
str1="Prepins*a"
str2="Prepinsta"
print("First string with wild characters :" , str1)
print("Second string without wild characters ::" , str2)
print(solve(str1,str2))

49: Write a Program to find out the Spiral Traversal of a Matrix.


This program finds the spiral traversal of a matrix, where the elements
are visited in a spiral order starting from the top left corner.

 The traversal follows the pattern: left to right, top to bottom, right

to left, and bottom to top, continuously spiraling inward.


Example:

 Input:

o Matrix:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

 Process:

o First row: 1, 2, 3

o Last column: 6, 9

o Last row (reverse): 8, 7

o First column (reverse): 4


o Middle element: 5

 Spiral Traversal: [1, 2, 3, 6, 9, 8, 7, 4, 5]

 Output:

oSpiral traversal: [1, 2, 3, 6, 9, 8, 7, 4, 5]


#include <stdio.h>
#define r 4
#define c 4

int main()
{
int a[4][4] = { { 1, 2, 3, 4 },

{ 5, 6, 7, 8 },

{ 9, 10, 11, 12 },

{ 13, 14, 15, 16 } };

int i, left = 0, right = c-1, top = 0, bottom = r-1;

while (left <= right && top <= bottom) {

/* Print the first row


from the remaining rows */
for (i = left; i <= right; ++i) {
printf("%d ", a[top][i]);
}
top++;

/* Print the last column


from the remaining columns */
for (i = top; i <= bottom; ++i) {
printf("%d ", a[i][right]);
}
right--;

/* Print the last row from


the remaining rows */
if (top <= bottom) { for (i = right; i >= left; --i) {
printf("%d ", a[bottom][i]);
}
bottom--;
}

/* Print the first column from


the remaining columns */
if (left <= right) { for (i = bottom; i >= top; --i) {
printf("%d ", a[i][left]);
}
left++;
}
}

return 0;
}

50. Write a code to find Fibonacci Series using Recursion


This program calculates the Fibonacci series using recursion. In the
Fibonacci series, each number is the sum of the two preceding ones,
starting from 0 and 1.

Example:

 Input: 10

 Process:

o The Fibonacci sequence starts from 0 and 1.

o For n=10, the series is generated as follows:

 fibonacci(0) = 0

 fibonacci(1) = 1

 fibonacci(2) = 1 (0 + 1)
 fibonacci(3) = 2 (1 + 1)

 Continue this until n=10.

 Fibonacci Series: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

 Output: Fibonacci series up to 10 terms: [0, 1, 1, 2, 3, 5, 8, 13,

21, 34]
#Function for nth Fibonacci number
def Fibo(n):
if n<0:
print("Incorrect input")
#1st Fibonacci number is 0
elif n==0:
return 0
#2nd Fibonacci number is 1
elif n==1:
return 1
else:
return Fibo(n-1)+Fibo(n-2)

#Main Program
print(Fibo(9))

You might also like