KEMBAR78
Programming Basics: C & Python | PDF | String (Computer Science) | Ascii
0% found this document useful (0 votes)
206 views10 pages

Programming Basics: C & Python

Uploaded by

khushi
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)
206 views10 pages

Programming Basics: C & Python

Uploaded by

khushi
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/ 10

Write a code to reverse a number

Python
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))

Write the code to find the Fibonacci series upto the


nth term.
C

Python
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()

Write code of Greatest Common Divisor


C

Python
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)

Write code of Perfect number


C

Python
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”)

Write code to Check if two strings are Anagram or not


C

Python
#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’)

Write code Check if the given string is Palindrome or


not
C

Python
#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')

Write code to Calculate frequency of characters in a


string
C

Python
#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')
Write code to check if two strings match where one
string contains wildcard characters
C

Python
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))
}

How is the merge sort algorithm implemented?


C

// Program for Merge Sort


class Main {
// this function display the array
public static void display(int[] arr, int size)
{
for(int i = 0; i < size; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
// main function of the program
public static void main(String[] args)
{
int[] a = {12, 8, 4, 14, 36, 64, 15, 72, 67, 84};

int size = a.length;


display(a, size);

mergeSort(a, 0, size - 1);


display(a, size);
}

// this function apply merging and sorting in the array


static 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 sub-arrays


mergeSort(a, left, mid);
mergeSort(a, mid + 1, right);
merge(a, left, mid, right);
}
}
// after sorting this function merge the array
static 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 sub-arrays


int L[] = new int[n1];
int R[] = new int[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 sub-array

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++;
}
}
}

Write to code to check whether a given year is leap


year or not.
C

Python
year = int(input("Enter Year:"))
if (year%400 == 0) or (year%4==0 and year%100!=0):
print("Leap Year")
else:
print("Not a Leap Year")

Find non-repeating characters in a string


C

Python
import .util.*;

class Solution
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
System.out.println ("Enter the string");

String str = sc.next (); //Taking input as a string from the user
int freq[] = new int[256];

//Calculating frequency of each character


for (int i = 0; i < str.length (); i++)
freq[str.charAt (i)]++;

System.out.println ("The non repeating characters are : ");

for (int i = 0; i < 256; i++)


if (freq[i] == 1) //finding the character whose frequency is 1
System.out.print ((char) i + " ");
}
}

Write a code to replace a substring in a string.


C

Python
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)

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


rank in the array
C

Python
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)

Write a code to find circular rotation of an array by K


positions.
C
Python
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

Write a code to find non-repeating elements in an


array.
C

Python
# 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)

Write a code to check for the longest palindrome in an


array.
C

Python
# 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))

Write a code to find the factorial of a number.


C

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

Write the code to for Armstrong number


C

Python
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")

Write a program to find the sum of Natural Numbers


using Recursion.
C
Python
def getSum(num):
if num == 1:
return 1
return num + getSum(num-1)

num = 5
print(getSum(num))

Write a Program to Find the Sum of Natural Numbers


using Recursion.
C

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

Write code to check a String is palindrome or not?


C

Python
# 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")

Write a program for Binary to Decimal to conversion


C

Python
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))

Write a program to check whether a character is a


vowel or consonant
C

Python
#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")

Write a code to find Find the ASCII value of a


character
C

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

Write a code to Remove all characters from string


except alphabets
C

Python
#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)

Write a code to find Fibonacci Series using Recursion


C

Python
#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