Python3 program to add two numbers
Python3 program to add two numbers
Example
num1 = 15
num2 = 12
# Adding two nos
sum = num1 + num2
# printing values
print("Sum of {0} and {1} is {2}" .format(num1, num2, sum))
program to find simple interest for given principal amount, time and rate of interest.
program to find simple interest for given principal amount, time and rate of interest.
Example
# We can change values here for
# different inputs
P = int(input())
R = int(input())
T = int(input())
# Calculates simple interest
SI = (P * R * T) / 100
# Print the resultant value of SI
print("simple interest is", SI)
Find the factorial of given number
Find the factorial of given number
Example
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact
num = 5;
print("Factorial of",num,"is",
factorial(num))
Program to find sum of square of first n natural numbers
Program to find sum of square of first n natural numbers
Example
def squaresum(n) : sm = 0 for i in range(1, n+1) : sm = sm + (i * i) return sm n = 4 print(squaresum(n))
Write a Python program to sum of all digits of a number
Write a Python program to sum of all digits of a number
Example
n=int(input("Enter a number:"))
sum=0
while n>0:
rem=n%10
sum=sum+rem
n=int(n/10)
print("The sum of digits of number is:", sum)
Write a program to check a year is a leap year or not using Python
Write a program to check a year is a leap year or not using Python
Example
year=int(input("Enter a Year:"))
if ((year % 100 == 0 and year % 400 == 0) or (year % 100 != 0 and year % 4 == 0)):
print("It is a Leap Year")
else:
print("It is not a Leap Year")
Write a program to convert Days into years, weeks and months using Python
Write a program to convert Days into years, weeks and months using Python
Example
days=int(input("Enter Day:"))
years =(int) (days / 365)
weeks =(int) (days / 7)
months =(int) (days / 30)
print("Days to Years:",years)
print("Days to Weeks:",weeks)
print("Days to Months:",months)
Python program to print all prime number in an interval
Python program to print all prime number in an interval
Example
start = 11 end = 25 for val in range(start, end + 1): # If num is divisible by any number # between 2 and val, it is not prime if val > 1: for n in range(2, val): if (val % n) == 0: break else: print(val)
Python program to find Area of a circle
Python program to find Area of a circle
Example
def findArea(r): PI = 3.142 return PI * (r*r); # Driver method print(findArea(5))
Python 3 code to find sum of elements in given array
Python 3 code to find sum of elements in given array
Example
def _sum(arr,n): # return sum using sum # inbuilt sum() function return(sum(arr)) # driver function arr=[] # input values to list arr = [12, 3, 4, 15] # calculating length of array n = len(arr) ans = _sum(arr,n) # display sum print (\'Sum of the array is \',ans)
Python program to print Even Numbers in a List
Python program to print Even Numbers in a List
Example
# list of numbers list1 = [10, 21, 4, 45, 66, 93] # iterating each number in list for num in list1: # checking condition if num % 2 == 0: print(num, end = " ")
Python program to check if a string is palindrome or not
Python program to check if a string is palindrome or not
Example
def isPalindrome(s):
rev = s[::-1]
# Checking if both string are equal or not
if (s == rev):
return True
return False
# Driver code
s = "malayalam"
ans = isPalindrome(s)
if ans == 1:
print("Yes")
else:
print("No")
function to check if small string is there in big string
function to check if small string is there in big string
Example
def check(string, sub_str):
if (string.find(sub_str) == -1):
print("NO")
else:
print("YES")
# driver code
string = "zeus is a programmer"
sub_str ="zeus"
check(string, sub_str)
Function to find permutations of a given string
Function to find permutations of a given string
Example
from itertools import permutations
def allPermutations(str):
# Get all permutations of string 'ABC'
permList = permutations(str)
# print all permutations
for perm in list(permList):
print (''.join(perm))
# Driver program
if name == "main":
str = 'ABC'
allPermutations(str)
Python3 code to find largest prime factor of number
Python3 code to find largest prime factor of number
Example
import math def maxPrimeFactors (n): maxPrime = -1 while n % 2 == 0: maxPrime = 2 n >>= 1 # equivalent to n /= 2 for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: maxPrime = i n = n / i if n > 2: maxPrime = n return int(maxPrime) n = 15 print(maxPrimeFactors(n)) n = 25698751364526 print(maxPrimeFactors(n))
Python Program to find sum of array
Python Program to find sum of array
Example
# Python 3 code to find sum
# of elements in given array
def _sum(arr,n):
# return sum using sum
# inbuilt sum() function
return(sum(arr))
# driver function
arr=[]
# input values to list
arr = [12, 3, 4, 15]
# calculating length of array
n = len(arr)
ans = _sum(arr,n)
# display sum
print ('Sum of the array is ', ans)
Python Counter| Find all duplicate characters in string
Python Counter| Find all duplicate characters in string
Example
from collections import Counter def find_dup_char(input): WC = Counter(input) j = -1 for i in WC.values(): j = j + 1 if( i > 1 ): print WC.keys()[j], if name == "main": input = 'hellowelcome' find_dup_char(input)
Python Program to find largest element in an array
Python Program to find largest element in an array
Example
# Python3 program to find maximum
# in arr[] of size n
# python function to find maximum
# in arr[] of size n
def largest(arr,n):
# Initialize maximum element
max = arr[0]
# Traverse array elements from second
# and compare every element with
# current max
for i in range(1, n):
if arr[i] > max:
max = arr[i]
return max
# Driver Code
arr = [10, 324, 45, 90, 9808]
n = len(arr)
Ans = largest(arr,n)
print ("Largest in given array is",Ans)
Python Program for Find remainder of array multiplication divided by n
Python Program for Find remainder of array multiplication divided by n
Example
#Input :
#arr[] = {100, 10, 5, 25, 35, 14},
#n = 11
#Output : 9
#Explanation :
#100 x 10 x 5 x 25 x 35 x 14 = 61250000 % 11 = 9
#Code :
# Python3 program to
# find remainder when
# all array elements
# are multiplied.
# Find remainder of arr[0] * arr[1]
# * .. * arr[n-1]
def findremainder(arr, lens, n):
mul = 1
# find the individual
# remainder and
# multiple with mul.
for i in range(lens):
mul = (mul * (arr[i] % n)) % n
return mul % n
# Driven code
arr = [ 100, 10, 5, 25, 35, 14 ]
lens = len(arr)
n = 11
# print the remainder
# of after multiple
# all the numbers
print( findremainder(arr, lens, n))
Python Program to Split the array and add the first part to the end
Python Program to Split the array and add the first part to the end
Example
#Code : # Python program to split array and move first # part to end. def splitArr(arr, n, k): for i in range(0, k): x = arr[0] for j in range(0, n-1): arr[j] = arr[j + 1] arr[n-1] = x # main arr = [12, 10, 5, 6, 52, 36] n = len(arr) position = 2 splitArr(arr, n, position) for i in range(0, n): print(arr[i], end = ' ')
Write a Python program to add two objects if both objects are an integer type.
Write a Python program to add two objects if both objects are an integer type.
Example
# Code:
def add_numbers(a, b):
if not (isinstance(a, int) and isinstance(b, int)):
raise TypeError("Inputs must be integers")
return a + b
print(add_numbers(10, 20))
Write a Python program to compute the distance between the points (x1, y1) and (x2, y2).
Write a Python program to compute the distance between the points (x1, y1) and (x2, y2).
Example
#Code : import math p1 = [4, 0] p2 = [6, 6] distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) ) print(distance)
Write a Python program to access and print a URL's content to the console.
Write a Python program to access and print a URL's content to the console.
Example
# Code:
from http.client import HTTPConnection
conn = HTTPConnection("example.com")
conn.request("GET", "/")
result = conn.getresponse()
# retrieves the entire contents.
contents = result.read()
print(contents)
Write a Python program to check if a number is positive, negative or zero.
Write a Python program to check if a number is positive, negative or zero.
Example
# Code:
num = float(input("Input a number: "))
if num > 0:
print("It is positive number")
elif num == 0:
print("It is Zero")
else:
print("It is a negative number")
Write a Python program to determine the largest and smallest integers, longs, floats.
Write a Python program to determine the largest and smallest integers, longs, floats.
Example
# Code:
import sys
print("Float value information: ",sys.float_info)
print("\nInteger value information: ",sys.int_info)
print("\nMaximum size of an integer: ",sys.maxsize)
Write a Python program to check whether an integer fits in 64 bits.
Write a Python program to check whether an integer fits in 64 bits.
Example
# Code: int_val = 30 if int_val.bit_length() <= 63: print((-2 63).bit_length()) print((2 63).bit_length())
Write a Python program to check whether multiple variables have the same value.
Write a Python program to check whether multiple variables have the same value.
Example
# Code:
x = 20
y = 20
z = 20
if x == y == z == 20:
print("All variables have same value!")
Write a Python program to check whether a variable is integer or string.
Write a Python program to check whether a variable is integer or string.
Example
# Code :
print(isinstance(25,int) or isinstance(25,str))
print(isinstance([25],int) or isinstance([25],str))
print(isinstance("25",int) or isinstance("25",str))
Write a Python program to test if a variable is a list or tuple or a set.
Write a Python program to test if a variable is a list or tuple or a set.
Example
# Code :
#x = ['a', 'b', 'c', 'd']
#x = {'a', 'b', 'c', 'd'}
x = ('tuple', False, 3.2, 1)
if type(x) is list:
print('x is a list')
elif type(x) is set:
print('x is a set')
elif type(x) is tuple:
print('x is a tuple')
else:
print('Neither a list or a set or a tuple.')
Write a Python function that takes a positive integer and returns the sum of the cube of all the positive integers smaller than the specified number.
Write a Python function that takes a positive integer and returns the sum of the cube of all the positive integers smaller than the specified number.
Example
# Ex.: 8 = 73+63+53+43+33+23+13 = 784
Code:
def sum_of_cubes(n):
n -= 1
total = 0
while n > 0:
total += n * n * n
n -= 1
return total
print("Sum of cubes: ",sum_of_cubes(3))
Write a Python program to create a sequence where the first four members of the sequence are equal to one, and each successive term of the sequence is equal to the sum of the four previous ones. Find the Nth member of the sequence.
Write a Python program to create a sequence where the first four members of the sequence are equal to one, and each successive term of the sequence is equal to the sum of the four previous ones. Find the Nth member of the sequence.
Example
# Code : def new_seq(n): if n==1 or n==2 or n==3 or n==4: return 1 return new_seq(n-1) + new_seq(n-2) + new_seq(n-3) + new_seq(n-4) print(new_seq(5)) print(new_seq(6)) print(new_seq(7))
Write a Python program to add two positive integers without using the '+' operator.
Write a Python program to add two positive integers without using the '+' operator.
Example
# Note: Use bitwise operations to add two numbers. # Code : def add_without_plus_operator(a, b): while b != 0: data = a & b a = a ^ b b = data << 1 return a print(add_without_plus_operator(2, 10)) print(add_without_plus_operator(-20, 10)) print(add_without_plus_operator(-10, -20))
Write a Python program to check the priority of the four operators (+, -, *, /).
Write a Python program to check the priority of the four operators (+, -, *, /).
Example
# Code :
from collections import deque
import re
operators = "+-/*"
parenthesis = "()"
priority = {
'+': 0,
'-': 0,
'*': 1,
'/': 1,
}
def test_higher_priority(operator1, operator2):
return priority[operator1] >= priority[operator2]
print(test_higher_priority('*','-'))
print(test_higher_priority('+','-'))
print(test_higher_priority('+','*'))
print(test_higher_priority('+','/'))
print(test_higher_priority('*','/'))
Write a Python program to get the third side of right angled triangle from two given sides.
Write a Python program to get the third side of right angled triangle from two given sides.
Example
# Note: Use bitwise operations to add two numbers.
# Code:
def pythagoras(opposite_side,adjacent_side,hypotenuse):
if opposite_side == str("x"):
return ("Opposite = " + str(((hypotenuse**2) - (adjacent_side**2))**0.5))
elif adjacent_side == str("x"):
return ("Adjacent = " + str(((hypotenuse**2) - (opposite_side**2))**0.5))
elif hypotenuse == str("x"):
return ("Hypotenuse = " + str(((opposite_side**2) + (adjacent_side**2))**0.5))
else:
return "You know the answer!"
print(pythagoras(3,4,'x'))
print(pythagoras(3,'x',5))
print(pythagoras('x',4,5))
print(pythagoras(3,4,5))
Write a Python program to find the median among three given numbers.
Write a Python program to find the median among three given numbers.
Example
# code :
x = input("Input the first number")
y = input("Input the second number")
z = input("Input the third number")
print("Median of the above three numbers -")
if y < x and x < z:
print(x)
elif z < x and x < y:
print(x)
elif z < y and y < x:
print(y)
elif x < y and y < z:
print(y)
elif y < z and z < x:
print(z)
elif x < z and z < y:
print(z)
Python Program to Find Armstrong Number in an Interval
Python Program to Find Armstrong Number in an Interval
Example
# Code: lower = 100 upper = 2000 for num in range(lower, upper + 1): # order of number order = len(str(num)) # initialize sum sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** order temp //= 10 if num == sum: print(num)
Python Program To Display Powers of 2 Using Anonymous Function
Python Program To Display Powers of 2 Using Anonymous Function
Example
# Code:
# Display the powers of 2 using anonymous function
terms = 10
# Uncomment code below to take input from the user
# terms = int(input("How many terms? "))
# use anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))
print("The total terms are:",terms)
for i in range(terms):
print("2 raised to power",i,"is",result[i])
Python Program to Find Numbers Divisible by Another Number
Python Program to Find Numbers Divisible by Another Number
Example
#Code:
# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]
# use anonymous function to filter
result = list(filter(lambda x: (x % 13 == 0), my_list))
# display the result
print("Numbers divisible by 13 are",result)
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Example
# Code:
# Python program to convert decimal into other number systems
dec = 344
print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.")
Python Program to Make a Simple Calculator
Python Program to Make a Simple Calculator
Example
# Code:
# Program make a simple calculator
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# Take input from the user
choice = input("Enter choice(1/2/3/4): ")
# Check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
break
else:
print("Invalid Input")
Python program to interchange first and last elements in a list
Python program to interchange first and last elements in a list
Example
# Examples: # Input : [12, 35, 9, 56, 24] # Output : [24, 35, 9, 56, 12] # Input : [1, 2, 3] # Output : [3, 2, 1] # Code : # Python3 program to swap first # and last element of a list # Swap function def swapList(newList): size = len(newList) # Swapping temp = newList[0] newList[0] = newList[size - 1] newList[size - 1] = temp return newList # Driver code newList = [12, 35, 9, 56, 24] print(swapList(newList))
Python program to swap two elements in a list
Python program to swap two elements in a list
Example
# Examples: # Input : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3 # Output : [19, 65, 23, 90] # Input : List = [1, 2, 3, 4, 5], pos1 = 2, pos2 = 5 # Output : [1, 5, 3, 4, 2] #Code : # Python3 program to swap elements # at given positions # Swap function def swapPositions(list, pos1, pos2): list[pos1], list[pos2] = list[pos2], list[pos1] return list # Driver function List = [23, 65, 19, 90] pos1, pos2 = 1, 3 print(swapPositions(List, pos1-1, pos2-1))
Python | Ways to find length of list
Python | Ways to find length of list
Example
# Code :
# Python code to demonstrate
# length of list
# using naive method
# Initializing list
test_list = [ 1, 4, 5, 7, 8 ]
# Printing test_list
print ("The list is : " + str(test_list))
# Finding length of list
# using loop
# Initializing counter
counter = 0
for i in test_list:
# incrementing counter
counter = counter + 1
# Printing length of list
print ("Length of list using naive method is : " + str(counter))
Check if element exists in list in Python
Check if element exists in list in Python
Example
# Code :
# Python code to demonstrate
# checking of element existence
# using loops and in
# Initializing list
test_list = [ 1, 6, 3, 5, 3, 4 ]
print("Checking if 4 exists in list ( using loop ) : ")
# Checking if 4 exists in list
# using loop
for i in test_list:
if(i == 4) :
print ("Element Exists")
print("Checking if 4 exists in list ( using in ) : ")
# Checking if 4 exists in list
# using in
if (4 in test_list):
print ("Element Exists")
Python | Reversing a List
Python | Reversing a List
Example
# Examples: # Input : list = [10, 11, 12, 13, 14, 15] # Output : [15, 14, 13, 12, 11, 10] # Input : list = [4, 5, 6, 7, 8, 9] # Output : [9, 8, 7, 6, 5, 4] # Code : # Reversing a list using reversed() def Reverse(lst): return [ele for ele in reversed(lst)] # Driver Code lst = [10, 11, 12, 13, 14, 15] print(Reverse(lst))