0% found this document useful (0 votes)
85 views23 pages

SUCCESS

The document contains code snippets for various Python programming concepts including: - Factorial, Fibonacci series, palindrome checks using iterative and recursive approaches - Sum of digits, length of string, leap year check - Largest number among 3, odd/even checks, prime number checks - Taking user input for lists, finding max/min in lists, matrix multiplication - Simple and compound interest calculations, subarrays, substrings, subclasses - Sorting algorithms like selection, bubble, merge, quick sorts and searching algorithms like linear and binary searches.
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)
85 views23 pages

SUCCESS

The document contains code snippets for various Python programming concepts including: - Factorial, Fibonacci series, palindrome checks using iterative and recursive approaches - Sum of digits, length of string, leap year check - Largest number among 3, odd/even checks, prime number checks - Taking user input for lists, finding max/min in lists, matrix multiplication - Simple and compound interest calculations, subarrays, substrings, subclasses - Sorting algorithms like selection, bubble, merge, quick sorts and searching algorithms like linear and binary searches.
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/ 23

FACTORIAL PROGRAM

For Particular number

num = int(input())
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print(factorial)

INPUT: 4

OUTPUT: 24

For Series

num = int(input())
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print(factorial,end=" ")

INPUT: 4

OUTPUT: 1 2 6 24

FIBONACCI SERIES

n=int(input())
n1,n2=0,1
c=0
s=0
if n<=0:
print("Enter a Positive number")
elif n==1:
print(n1)
elif n==2:
print(n2)
else:
for i in range(n):
s=n1+n2
n1=n2
n2=s
print(s)

INPUT: 4

OUTPUT: 5

For Series:

n = int(input ())
n1 = 0
n2 = 1
count = 0
if n <= 0:
print ("Please enter a positive integer, the given number is not valid")
elif n == 1:
print(n)
else:
while count < n:
print(n1,end=" ")
nth = n1 + n2
n1 = n2
n2 = nth
count += 1

INPUT: 4

OUTPUT: 0 1 1 2

Palindrome Integer(While)

Method 1

num=int(input())
temp=num
rev=0
while(num>0):
dig=num%10
rev=rev*10+dig
num=num//10
if(temp==rev):
print("The number is palindrome!")
else:
print("Not a palindrome!")

INPUT: 121

OUTPUT: The number is palindrome!

Method 2

Converting to String:

num=int(input())
if(str(num)==str(num)[::-1]):
print("It is a Palindrome")
else:
print("Not a Palindrome")

INPUT: 121

OUTPUT: The number is palindrome!

Sum Of Digits

n=int(input())
r=str(n)
sum=0
for i in range(len(r)):
sum+=int(r[i])
print(sum)

Method 2

n=int(input())
s=0
while n>0:
s+=n%10
n=n//10
print(s)

INPUT: 121

OUTPUT: 4
Length of String

def findLength(string):

count = 0

for i in string:
count+= 1
return count

string = input()
print(findLength(string))

Method 2:

Using len function

a=len(input())
print(a)

INPUT: gokul

OUTPUT: 5

LEAP YEAR OR NOT

year = int(input())

if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("Leap year")
else:
print("Not a Leap year")
else:
print("Leap year")
else:
print("Not a Leap year")

INPUT: 2000

OUTPUT: Leap year

CHECK A NUMBER IS POSITIVE OR NEGATIVE OR ZERO

num = float(input())
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

INPUT: 4

OUTPUT: Positive number

CHECK ARMSTRONG NO OR NOT:

a=int(input())
s=str(a)
sum=0
for i in s:
sum+=(int(i)*int(i)*int(i))
if sum==a:
print("Armstrong number")
else:
print("Not a Armstrong number")

INPUT: 153

OUTPUT: Armstrong number

FIND LARGEST NOS AMONG 3 NOS


num1 = int(input())
num2 = int(input())
num3 = int(input())

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)

INPUT: 5
9
3

OUTPUT: The largest number is 9

ODD OR EVEN

num = int(input())
if (num % 2) == 0:
print("Even")
else:
print("Odd")

INPUT:4

OUTPUT:Even

PRIME NOS OR NOT:

num = int(input())

flag = False
if num > 1:
for i in range(2, num):
if (num % i) == 0:
flag = True
break
if flag:
print("Not a Prime number")
else:
print("Prime number")

INPUT:3

OUTPUT:Prime Number

TAKING A USER-DEFINED INPUT FOR LIST AND PRINT LIST

n=list(map(int,input().split()))
print(*n)

INPUT: 3 1 2 4 5
OUTPUT:Prime Number

USING FOR LOOP

n=int(input())
arr=[]
for i in range(n):
arr.append(int(input()))
for i in arr:
print(i,end=" ")

INPUT:5
3
1
2
4
5
OUTPUT: 3 1 4 2 5

MAXIMUM ELEMENT IN ARRAY(PYTHON LIST)


n=int(input())
arr=[]
for i in range(n):
arr.append(int(input()))
a=0
for i in arr:
if i>a:
a=i
print(a)

INPUT:5
3
1
2
4
5
OUTPUT: 5

MINIMUM ELEMENT IN ARRAY(PYTHON LIST)

n=int(input())
arr=[]
for i in range(n):
arr.append(int(input()))
m=arr[0]
for i in range(1,len(arr)):
if arr[i]<m:
m=arr[i]
print(m)

INPUT:5
3
1
2
4
5
OUTPUT: 1

MATRIX MULTIPLICATION
num = int(input())

for i in range(1, 11):


print(num, 'x', i, '=', num*i)

INPUT: 2

OUTPUT:

2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

SIMPLE INTEREST

def simple_interest(p,t,r):
print('The principal is', p)
print('The time period is', t)
print('The rate of interest is',r)

si = (p * t * r)/100

print('The Simple Interest is', si)


return si

simple_interest(int(input()), int(input()), int(input()))

INPUT:

40
5
10
The principal is 40
The time period is 5
The rate of interest is 10
The Simple Interest is 20.0

COMPOUND INTEREST

def compound_interest(principle, rate, time):

Amount = principle * (pow((1 + rate / 100), time))


CI = Amount - principle
print("Compound interest is", CI)

compound_interest(float(input()), float(input()), float(input()))

INPUT:

40
10
5
Compound interest is 24.42040000000003

SUB ARRAY

def printallSublists(A):

for i in range(len(A)):

for j in range(i, len(A)):

print(A[i: j + 1])

A = [1, 2, 3, 4, 5]
printallSublists(A)

INPUT:

[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[2]
[2, 3]
[2, 3, 4]
[2, 3, 4, 5]
[3]
[3, 4]
[3, 4, 5]
[4]
[4, 5]
[5]

SUBSEQUENCE

def printSubSequences(STR, subSTR=""):

if len(STR) == 0:
print(subSTR, end=" ")
return

printSubSequences(STR[:-1], subSTR + STR[-1])

printSubSequences(STR[:-1], subSTR)
return

STR = "abc"
printSubSequences(STR)

OUTPUT: cba cb ca c ba b a

SUBSTRING

def printAllSubstrings(str):

for i in range(len(str)):

for j in range(i, len(str)):


print(str[i: j + 1], end=' ')
str = "python"
printAllSubstrings(str)

OUTPUT:p py pyt pyth pytho python y yt yth ytho ython t th tho thon h ho hon
o on n

CLASS OOPS CONCEPT EXAMPLE PROGRAM

class cat:

def __init__(self,height=42,name='harry'):
self.name = name
self.height=height

def meow(self):
print('meow')

def change(self,height):
self.height=height
return height

tom=cat('tommy',72)
tom.meow()
tom.change(76)
print(tom.height)

ninja=cat()

print(ninja.name)
print(ninja.height)

INPUT:

meow
76
harry
42

SELECTION SORT

import sys
A = [64, 25, 12, 22, 11]

for i in range(len(A)):

min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j

A[i], A[min_idx] = A[min_idx], A[i]

print ("Sorted array")


for i in range(len(A)):
print("%d" %A[i]),

OUTPUT:

Sorted array
11
12
22
25
64

BUBBLE SORT

def bubbleSort(arr):
n = len(arr)

for i in range(n):

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


if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]

arr = [64, 34, 25, 12, 22, 11, 90]

bubbleSort(arr)

print ("Sorted array is:")


for i in range(len(arr)):
print ("%d" %arr[i]),

OUTPUT:

Sorted array is:


11
12
22
25
34
64
90

MERGE SORT

def mergeSort(arr):
if len(arr) > 1:

mid = len(arr)//2

L = arr[:mid]

R = arr[mid:]

mergeSort(L)

mergeSort(R)

i=j=k=0

while i < len(L) and j < len(R):


if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1

while i < len(L):


arr[k] = L[i]
i += 1
k += 1

while j < len(R):


arr[k] = R[j]
j += 1
k += 1

def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()

if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)

OUTPUT:
Given array is
12 11 13 5 6 7
Sorted array is:
5 6 7 11 12 13

PARTITION SORT

def partition(start, end, array):

pivot_index = start
pivot = array[pivot_index]

while start < end:

while start < len(array) and array[start] <= pivot:


start += 1

while array[end] > pivot:


end -= 1

if(start < end):


array[start], array[end] = array[end], array[start]

array[end], array[pivot_index] = array[pivot_index], array[end]

return end

def quick_sort(start, end, array):

if (start < end):

p = partition(start, end, array)

quick_sort(start, p - 1, array)
quick_sort(p + 1, end, array)

array = [ 10, 7, 8, 9, 1, 5 ]
quick_sort(0, len(array) - 1, array)

print(f'Sorted array: {array}')

OUTPUT: Sorted array: [1, 5, 7, 8, 9, 10]

LINEAR SEARCH

def search(arr, n, x):


for i in range(0, n):
if (arr[i] == x):
return i
return -1

arr = [2, 3, 4, 10, 40]


x = 10
n = len(arr)

result = search(arr, n, x)
if(result == -1):
print("Element is not present in array")
else:
print("Element is present at index", result)

OUTPUT: Element is present at index 3

BINARY SEARCH

def binarySearch (arr, l, r, x):

if r >= l:

mid = l + (r - l) // 2

if arr[mid] == x:
return mid

elif arr[mid] > x:


return binarySearch(arr, l, mid-1, x)

else:
return binarySearch(arr, mid + 1, r, x)

else:
return -1

arr = [ 2, 3, 4, 10, 40 ]
x = 10

result = binarySearch(arr, 0, len(arr)-1, x)


if result != -1:
print ("Element is present at index % d" % result)
else:
print ("Element is not present in array")

OUTPUT: Element is present at index 3

COUNT NO OF OCCURRENCES IN A SORTED ARRAY

def countOccurrences(arr, n, x):


res = 0
for i in range(n):
if x == arr[i]:
res += 1
return res

arr = [1, 2, 2, 2, 2, 3, 4, 7 ,8 ,8]


n = len(arr)
x=2
print (countOccurrences(arr, n, x))

OUTPUT: 4

QUICK SORT

def partition(arr, low, high):


i = (low-1)
pivot = arr[high]

for j in range(low, high):

if arr[j] <= pivot:

i = i+1
arr[i], arr[j] = arr[j], arr[i]

arr[i+1], arr[high] = arr[high], arr[i+1]


return (i+1)
def quickSort(arr, low, high):
if len(arr) == 1:
return arr
if low < high:

pi = partition(arr, low, high)

quickSort(arr, low, pi-1)


quickSort(arr, pi+1, high)

arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
quickSort(arr, 0, n-1)
print("Sorted array is:")
for i in range(n):
print("%d" % arr[i]),

OUTPUT:

Sorted array is:


1
5
7
8
9
10

CHECK WHETHER GIVEN NO IS BINARY

num = int(input("please give a number : "))


while(num>0):
j=num%10
if j!=0 and j!=1:
print("num is not binary")
break
num=num//10
if num==0:
print("num is binary")
OUTPUT:

please give a number : 1001


num is binary

Perfect number program

num = int(input("please give first number a: "))


sum=0
for i in range(1,(num//2)+1):
remainder = num % i
if remainder == 0:
sum = sum + i
if sum == num:
print("given no. is perfect number")
else:
print("given no. is not a perfect number")

OUTPUT:
please give first number a: 5
given no. is not a perfect number

Python program to remove character from string

str = input("please enter a string : ")


ch = input("please enter a character : ")
print(str.replace(ch," "))

OUTPUT:

please enter a string : KAushik


please enter a character : u
KA shik

Python Program to count occurrence of characters in string

ing = input("Please enter String : ")


char = input("Please enter a Character : ")
count = 0
for i in range(len(string)):
if(string[i] == char):
count = count + 1
print("Total Number of occurence of ", char, "is :" , count)

OUTPUT

Please enter String : GOKUL


Please enter a Character : O
Total Number of occurence of O is : 1

Anagram Program

def anagramCheck(str1, str2):


if (sorted(str1) == sorted(str2)) :
return True
else :
return False

str1 = input("Please enter String 1 : ")


str2 = input("Please enter String 2 : ")
if anagramCheck(str1,str2):
print("Anagram")
else:
print("Not an anagram")

OUTPUT:
Please enter String 1 : gokul
Please enter String 2 : lukog
Anagram

Python Program to find missing number in array

arr = []
n = int(input("enter size of array : "))
for x in range(n-1):
x=int(input("enter element of array : "))
arr.append(x)
sum = (n*(n+1))/2;
sumArr = 0
for i in range(n-1):
sumArr = sumArr+arr[i];
print(int(sum-sumArr))

OUTPUT:
enter size of array : 5
enter element of array : 1
enter element of array : 2
enter element of array : 3
enter element of array : 5
4

Program to find duplicates in an Array

arr, occur = [], []


n = int(input("please enter the size of array: "))
for x in range(n):
occur.append(0)
for x in range(n):
element = int(input(f"please enter the element of array element between 0 to {n-1}
:"))
arr.append(element)
occur[arr[x]]=occur[arr[x]]+1
for x in range(n):
if occur[x]>1:
print(f"{x} is repeated {occur[x]} times")

OUTPUT:
please enter the size of array: 4
please enter the element of array element between 0 to 3 :2
please enter the element of array element between 0 to 3 :1
please enter the element of array element between 0 to 3 :0
please enter the element of array element between 0 to 3 :3

Program to remove duplicates from Array

import array
arr, count = [],[]
n = int(input("enter size of array : "))
for x in range(n):
count.append(0)
x=int(input("enter element of array : "))
arr.append(x)
print("Array elements after removing duplicates")
for x in range(n):
count[arr[x]]=count[arr[x]]+1
if count[arr[x]]==1:
print(arr[x])

OUTPUT:

enter size of array : 5


enter element of array : 2
enter element of array : 2
enter element of array : 4
enter element of array : 1
enter element of array : 2
Array elements after removing duplicates
2
4
1

You might also like