0% found this document useful (0 votes)
106 views

Factorial Program: For Particular Number

The document contains code snippets for various Python programming concepts including: factorial programs for a number and series, Fibonacci series, palindrome checks, digit sum, string length calculation, leap year check, positive/negative/zero checks, Armstrong number check, largest of 3 numbers, odd/even checks, prime number check, taking user input for a list, maximum and minimum in an array, matrix multiplication, simple and compound interest calculations, subarrays, subsequences, substrings, a basic class definition, selection sort, bubble sort, merge sort, partition sort, linear search, binary search, and quick sort.
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)
106 views

Factorial Program: For Particular Number

The document contains code snippets for various Python programming concepts including: factorial programs for a number and series, Fibonacci series, palindrome checks, digit sum, string length calculation, leap year check, positive/negative/zero checks, Armstrong number check, largest of 3 numbers, odd/even checks, prime number check, taking user input for a list, maximum and minimum in an array, matrix multiplication, simple and compound interest calculations, subarrays, subsequences, substrings, a basic class definition, selection sort, bubble sort, merge sort, partition sort, linear search, binary search, and quick sort.
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/ 17

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)

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

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

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

Method 2

Converting to String:

num=int(input())
if(str(num)==str(num)[::-1]):
print("It is a Palindrome")
else:
print("Not a 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)

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)

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

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

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

FIND LARGEST NOS AMONG 3 NOS


num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))

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)

ODD OR EVEN

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

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

TAKING A USER-DEFINED INPUT FOR LIST AND PRINT LIST

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

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

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)

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)

MATRIX MULTIPLICATION

num = int(input())

for i in range(1, 11):


print(num, 'x', i, '=', num*i)
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()))

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

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)

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)

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)

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)

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]),

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]),

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)

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

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)

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

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))
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]),

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

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

Python program to remove character from string

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


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

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)

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

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

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

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy