0% found this document useful (0 votes)
2 views28 pages

Python Programs

The document provides various Python programs demonstrating fundamental programming concepts, including calculating the area of a circle, finding the LCM of two numbers, calculating the power of a number, and solving quadratic equations. It also covers string manipulation, matrix addition, and creating arrays, along with examples and outputs for each program. The content is structured to help users understand and implement basic Python programming techniques.

Uploaded by

sharmila.s
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)
2 views28 pages

Python Programs

The document provides various Python programs demonstrating fundamental programming concepts, including calculating the area of a circle, finding the LCM of two numbers, calculating the power of a number, and solving quadratic equations. It also covers string manipulation, matrix addition, and creating arrays, along with examples and outputs for each program. The content is structured to help users understand and implement basic Python programming techniques.

Uploaded by

sharmila.s
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/ 28

Python Programs

1. Python program to find the area of a circle:

The area of a circle can simply be evaluated using the following


formula.
Area = pi * r2
where r is radius of circle

# Python program to find Area of a circle

def findArea(r):

PI = 3.142
return PI * (r*r);

# Driver method
print("Area is %.6f" % findArea(5));

Output
Area is 78.550000

2.

# Python Program to find the L.C.M. of two input number

def compute_lcm(x, y):

# choose the greater number


if x > y:
greater = x

else:
greater = y

while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1

return lcm

num1 = 54
num2 = 24

print("The L.C.M. is", compute_lcm(num1, num2))

Output

The L.C.M. is 216

Note: To test this program, change the values of num1 and num2 .

This program stores two number in num1 and num2 respectively. These
numbers are passed to the compute_lcm() function. The function returns the
L.C.M of two numbers.

In the function, we first determine the greater of the two numbers since the
L.C.M. can only be greater than or equal to the largest number. We then
use an infinite while loop to go from that number and beyond.
In each iteration, we check if both the numbers perfectly divide our number.
If so, we store the number as L.C.M. and break from the loop. Otherwise,
the number is incremented by 1 and the loop continues.

Program to Compute LCM Using GCD


# Python program to find the L.C.M. of two input number

# This function computes GCD


def compute_gcd(x, y):

while(y):
x, y = y, x % y
return x

# This function computes LCM


def compute_lcm(x, y):
lcm = (x*y)//compute_gcd(x,y)
return lcm

num1 = 54
num2 = 24
print("The L.C.M. is", compute_lcm(num1, num2))
Run Code

The output of this program is the same as before. We have two


functions compute_gcd() and compute_lcm() . We require G.C.D. of the
numbers to calculate its L.C.M.
So, compute_lcm() calls the function compute_gcd() to accomplish this.
G.C.D. of two numbers can be calculated efficiently using the Euclidean
algorithm.

Python Program to find power of a Number:


def CalculatePower(N,X):
P=1
for i in range(1, X+1):
P=P*N
return P

N,X=2,3
print(CalculatePower(N,X))
N,X=3,4
print(CalculatePower(N,X))

Output:
8
81

Method 2: Recursive Approach


Here we have used a recursive function calc_power() to calculate
the power of a given number using recursion. This function will
return 1 if power is 0, which is base condition for the function.

def calc_power(N, p):

if p == 0:

return 1

return N * calc_power(N, p-1)

print(calc_power(4, 2))

Output
16

Python Program to find Factors of a number :

For example, the factors of number 15 are

1 * 15 = 15

3 * 5 = 15

5 * 3 = 15

15 * 1 = 15

1, 3, 5, 15 are the factors of 15.

Source Code
# Python Program to find the factors of a number

# This function computes the factor of the argument passed


def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)

num = 320

print_factors(num)
Run Code

Output

The factors of 320 are:

1
2
4
5
8
10
16
20
32
40
64
80
160
320

Note: To find the factors of another number, change the value of num .

In this program, the number whose factor is to be found is stored in num ,

which is passed to the print_factors() function. This value is assigned to


the variable x in print_factors() .

In the function, we use the for loop to iterate from i equal to x . If x is


perfectly divisible by i , it's a factor of x .

Python program to count the number of occurrances in a string:

Python Program to Count the


Number of Occurrence of a
Character in String
In this example, you will learn to count the number of occurrences of a
character in a string.

To understand this example, you should have the knowledge of the


following Python programming topics:
 Python Strings
Example 1: Using a for loop
count = 0

my_string = "Programiz"
my_char = "r"

for i in my_string:
if i == my_char:
count += 1

print(count)
Run Code

Output

In the above example, we have found the count of 'r' in 'Programiz' . The
for-loop loops over each character of my_string and the if condition checks
if each character of my_string is 'r' . The value of count increases if there
is a match.

Example 2: Using method count()


my_string = "Programiz"
my_char = "r"

print(my_string.count(my_char))
Run Code

Output

2
count() counts the frequency of the character passed as parameter.

Python Program to Solve Quadratic


Equation
This program computes roots of a quadratic equation when coefficients a, b
and c are known.

To understand this example, you should have the knowledge of the


following Python programming topics:
 Python Data Types
 Python Basic Input and Output
 Python Operators

The standard form of a quadratic equation is:

ax2 + bx + c = 0, where
a, b and c are real numbers and
a ≠ 0

The solutions of this quadratic equation is given by:

(-b ± (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)

Source Code
# Solve the quadratic equation ax**2 + bx + c = 0

# import complex math module


import cmath
a = 1
b = 5
c = 6

# calculate the discriminant


d = (b**2) - (4*a*c)

# find two solutions


sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))


Run Code

Output

Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)

We have imported the cmath module to perform complex square root. First,
we calculate the discriminant and then find the two solutions of the
quadratic equation.
You can change the value of a , b and c in the above program and test this
program.

Python Program to Swap Two


Variables
Source Code: Using a temporary variable
# Python program to swap two variables

x = 5
y = 10

# To take inputs from the user


#x = input('Enter value of x: ')
#y = input('Enter value of y: ')

# create a temporary variable and swap the values


temp = x
x = y
y = temp

print('The value of x after swapping: {}'.format(x))


print('The value of y after swapping: {}'.format(y))
Run Code

Output

The value of x after swapping: 10


The value of y after swapping: 5

In this program, we use the temp variable to hold the value of x temporarily. We
then put the value of y in x and later temp in y . In this way, the values get
exchanged.

Source Code: Without Using Temporary Variable


In Python, there is a simple construct to swap variables. The following code does
the same as above but without the use of any temporary variable.

x = 5
y = 10

x, y = y, x
print("x =", x)
print("y =", y)
Run Code

If the variables are both numbers, we can use arithmetic operations to do the same.
It might not look intuitive at first sight. But if you think about it, it is pretty easy to
figure it out. Here are a few examples
Addition and Subtraction

x = x + y
y = x - y
x = x - y

Multiplication and Division

x = x * y
y = x / y
x = x / y

Python Program to Convert


Decimal to Binary, Octal and
Hexadecimal
In this program, you'll learn to convert decimal to binary, octal
and hexadecimal, and display it.

To understand this example, you should have the knowledge of


the following Python programming topics:
 Python Programming Built-in Functions

The decimal system is the most widely used number system.


However, computers only understand binary. Binary, octal and
hexadecimal number systems are closely related, and we may
require to convert decimal into these systems.
The decimal system is base 10 (ten symbols, 0-9, are used to
represent a number) and similarly, binary is base 2, octal is base
8 and hexadecimal is base 16.

A number with the prefix 0b is considered binary, 0o is considered


octal and 0x as hexadecimal. For example:

60 = 0b11100 = 0o74 = 0x3c

Source 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.")
Run Code

Output

The decimal value of 344 is:


0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.

Note: To test the program for other decimal numbers, change the
value of dec in the program.
In this program, we have used built-in
functions bin() , oct() and hex() to convert the given decimal
number into respective number systems.
These functions take an integer (in decimal) and return a string.
Python Program to Add Two
Matrices
In this program, you'll learn to add two matrices using Nested
loop and Next list comprehension, and display it.

To understand this example, you should have the knowledge of


the following Python programming topics:
 Python for Loop
 Python List

In Python, we can implement a matrix as a nested list (list inside a


list). We can treat each element as a row of the matrix.

For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2
matrix. First row can be selected as X[0] and the element in first
row, first column can be selected as X[0][0] .

We can perform matrix addition in various ways in Python. Here


are a couple of them.

Source code: Matrix Addition using Nested


Loop
# Program to add two matrices using nested loop

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

for r in result:
print(r)
Run Code

Output

[17, 15, 4]
[10, 12, 9]
[11, 13, 18]

In this program we have used nested for loops to iterate through


each row and each column. At each point, we add the
corresponding elements in the two matrices and store it in the
result.
Source Code: Matrix Addition using Nested
List Comprehension
# Program to add two matrices using list comprehension

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

result = [[X[i][j] + Y[i][j] for j in range(len(X[0]))] for i in


range(len(X))]

for r in result:
print(r)
Run Code

The output of this program is the same as above. We have used


nested list comprehension to iterate through each element in the
matrix.

Output:

[17, 15, 4]

[10, 12, 9]

[11, 13, 18]

Python Program to Access Index


of a List Using for Loop
In this example, you will learn to access the index of a list using a
for loop.

To understand this example, you should have the knowledge of


the following Python programming topics:
 Python for Loop
 Python List
 Python enumerate()

Example 1: Using enumerate


my_list = [21, 44, 35, 11]

for index, val in enumerate(my_list):


print(index, val)
Run Code

Output

0 21
1 44
2 35
3 11

Using enumerate() , we can print both the index and the values.
 Pass two loop variables index and val in the for loop. You can
give any name to these variables.
 Print the required variables inside the for loop block.

The function of enumerate() is to add a counter (i.e. index ) to the


iterate and return it. If you want to learn more about enumerate() ,

please visit Python enumerate().

Example 2: Start the indexing with non zero


value
my_list = [21, 44, 35, 11]

for index, val in enumerate(my_list, start=1):


print(index, val)
Run Code

Output

1 21
2 44
3 35
4 11

The value of the parameter start provides the starting index.


Example 3: Without using enumerate()
my_list = [21, 44, 35, 11]

for index in range(len(my_list)):


value = my_list[index]
print(index, value)
Run Code

Output

0 21
1 44
2 35
3 11

You can access the index even without using enumerate() .

 Using a for loop, iterate through the length of my_list . Loop


variable index starts from 0 in this case.
 In each iteration, get the value of the list at the
current index using the statement value = my_list[index] .

 Print the value and index .

Python Array
Creating Python Arrays
To create an array of numeric values, we need to import
the array module. For example:
import array as arr
a = arr.array('d', [1.1, 3.5, 4.5])
print(a)
Run Code
Output

array('d', [1.1, 3.5, 4.5])

Here, we created an array of float type. The letter d is a type


code. This determines the type of the array during creation.
Commonly used type codes are listed as follows:

Code C Type Python Type Min bytes

b signed char int 1

B unsigned char int 1

u Py_UNICODE Unicode 2

h signed short int 2

H unsigned short int 2

i signed int int 2

I unsigned int int 2

l signed long int 4

L unsigned long int 4

f float float 4

d double float 8

We will not discuss different C types in this article. We will use


two type codes in this entire article: i for integers and d for floats.
Note: The u type code for Unicode characters is deprecated since
version 3.3. Avoid using as much as possible.

Accessing Python Array Elements


We use indices to access elements of an array:

import array as arr


a = arr.array('i', [2, 4, 6, 8])

print("First element:", a[0])


print("Second element:", a[1])
print("Last element:", a[-1])
Run Code

Output

First element: 2
Second element: 4
Last element: 8

Note: The index starts from 0 (not 1) similar to lists.

Slicing Python Arrays


We can access a range of items in an array by using the slicing
operator : .
import array as arr
numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]
numbers_array = arr.array('i', numbers_list)

print(numbers_array[2:5]) # 3rd to 5th


print(numbers_array[:-5]) # beginning to 4th
print(numbers_array[5:]) # 6th to end
print(numbers_array[:]) # beginning to end
Run Code

Output

array('i', [62, 5, 42])


array('i', [2, 5, 62])
array('i', [52, 48, 5])
array('i', [2, 5, 62, 5, 42, 52, 48, 5])

Changing and Adding Elements


Arrays are mutable; their elements can be changed in a similar
way as lists.

import array as arr

numbers = arr.array('i', [1, 2, 3, 5, 7, 10])

# changing first element


numbers[0] = 0
print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])

# changing 3rd to 5th element


numbers[2:5] = arr.array('i', [4, 6, 8])
print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10])
Run Code

Output

array('i', [0, 2, 3, 5, 7, 10])


array('i', [0, 2, 4, 6, 8, 10])
We can add one item to the array using the append() method, or
add several items using the extend() method.
import array as arr

numbers = arr.array('i', [1, 2, 3])

numbers.append(4)
print(numbers) # Output: array('i', [1, 2, 3, 4])

# extend() appends iterable to the end of the array


numbers.extend([5, 6, 7])
print(numbers) # Output: array('i', [1, 2, 3, 4, 5, 6, 7])
Run Code

Output

array('i', [1, 2, 3, 4])


array('i', [1, 2, 3, 4, 5, 6, 7])

We can also concatenate two arrays using + operator.


import array as arr

odd = arr.array('i', [1, 3, 5])


even = arr.array('i', [2, 4, 6])

numbers = arr.array('i') # creating empty array of integer


numbers = odd + even

print(numbers)
Run Code

Output

array('i', [1, 3, 5, 2, 4, 6])

Removing Python Array Elements


We can delete one or more items from an array using
Python's del statement.
import array as arr

number = arr.array('i', [1, 2, 3, 3, 4])

del number[2] # removing third element


print(number) # Output: array('i', [1, 2, 3, 4])

del number # deleting entire array


print(number) # Error: array is not defined
Run Code

Output

array('i', [1, 2, 3, 4])


Traceback (most recent call last):
File "<string>", line 9, in <module>
print(number) # Error: array is not defined
NameError: name 'number' is not defined

We can use the remove() method to remove the given item,


and pop() method to remove an item at the given index.
import array as arr

numbers = arr.array('i', [10, 11, 12, 12, 13])

numbers.remove(12)
print(numbers) # Output: array('i', [10, 11, 12, 13])

print(numbers.pop(2)) # Output: 12
print(numbers) # Output: array('i', [10, 11, 13])
Run Code

Output

array('i', [10, 11, 12, 13])


12
array('i', [10, 11, 13])

Check this page to learn more about Python array and array
methods.
Python Lists Vs Arrays
In Python, we can treat lists as arrays. However, we cannot
constrain the type of elements stored in a list. For example:

# elements of different types


a = [1, 3.5, "Hello"]

If you create arrays using the array module, all elements of the
array must be of the same numeric type.

import array as arr


# Error
a = arr.array('d', [1, 3.5, "Hello"])

Output

Traceback (most recent call last):


File "<string>", line 3, in <module>
a = arr.array('d', [1, 3.5, "Hello"])
TypeError: must be real number, not str

When to use arrays?


Lists are much more flexible than arrays. They can store elements
of different data types including strings. And, if you need to do
mathematical computation on arrays and matrices, you are much
better off using something like NumPy.
So, what are the uses of arrays created from the Python array
module?

The array.array type is just a thin wrapper on C arrays which


provides space-efficient storage of basic C-style data types. If you
need to allocate an array that you know will not change, then
arrays can be faster and use less memory than lists.
Unless you don't really need arrays (array module may be needed
to interface with C code), the use of the array module is not
recommended.

Check if All Elements in Array are Equal in


Python
With Python, we can check if all elements in a list are equal by converting the list
to a set and checking if the set has length 1.

def checkAllElementsEqual(lst):
return len(set(lst)) == 1

print(checkAllElementsEqual([0,1,2,3,4]))
print(checkAllElementsEqual([0,0,0,0,0]))

#Output:
False
True

When working with collections of data in a Python program, it’s possible you
want to check if all elements in an array are equal.

Arrays in Python are called lists, and we can easily check if all elements in a list
are equal.

To check if all items in a list are equal, the easily way is to convert the list to a set
and check the set’s length. If the length of the set is 1, then we know that all
elements are equal.

Below is a simple function in Python of how to check if all elements of a list are
the same.
def checkAllElementsEqual(lst):
return len(set(lst)) == 1

print(checkAllElementsEqual([0,1,2,3,4]))
print(checkAllElementsEqual([0,0,0,0,0]))

#Output:
False
True

There are a few other ways you can check if all elements in a list are equal in
Python which you can read about below.

Using a Loop to Check if All Elements in a List are the


Same in Python
Another method we can use to check if all elements in a list are the same is to
use a for loop.

To check if all items in a list are equal with a loop, we just check if all elements
are equal to the first element.

Below is a Python function which will check if all elements of a list are equal
with a for loop.

def checkAllElementsEqual(lst):
for x in lst:
if lst[0] != x:
return False
return True

print(checkAllElementsEqual([0,1,2,3,4]))
print(checkAllElementsEqual([0,0,0,0,0]))

#Output:
False
True

Copy
Using count() to Check if All Items in a List are the
Same in Python
Another way we can check if all items in a list are equal is with the help of
the count() function.

The count() function in Python gives us the count of how many times a
particular value is found in a list.

If a list has all equal values, then the count of the first value should equal the
length of the list.

Below is how to check if all elements in a list are equal with the help of
the count() function.

def checkAllElementsEqual(lst):
return lst.count(lst[0]) == len(lst)

print(checkAllElementsEqual([0,1,2,3,4]))
print(checkAllElementsEqual([0,0,0,0,0]))

#Output:
False
True

Using all() to Determine if All Elemenets in a List are


Equal with Python
The last way to determine if all elements in a list are equal that I want to share
with you is uses the all() function.

all() returns True is all values in a list are True, and False is not all values in a list
are True.

We can check if all values in a list are equal to the first element and pass this
to all()
Below is a Python function which will check if all elements of a list are equal
with the all() function.

def checkAllElementsEqual(lst):
return all(x == lst[0] for x in lst)

print(checkAllElementsEqual([0,1,2,3,4]))
print(checkAllElementsEqual([0,0,0,0,0]))

#Output:
False
True

Hopefully this article has been useful for you to check if all elements in a list are
equal using Python.

Check whether array is subset of another


array or not

In this program we will Check whether array is subset of another array or


not in Python. A subset is defined as a set whose elements are all
members of another set. We will input two arrays and check whether the
second array is subset of first array and display accordingly

Method Discussed :

 Method 1 : Using nested loops

 Method 2 : Using sorting and binary search.

 Method 3 : Using sorting and merging.


 Method 4 : Using Hashing

 Method 5 : Using Union concept

Method 1 :

 Run a loop for loo from index 0 to length of arr2

 Run a inner loop from index 0 to length of arr2

 If(arr2[i]==arr1[j]), then break the inner loop

 Check if(j==m) then return 0.

 Otherwise, return 1.

Method 1 : Code in Python


#Write a Program to Check whether array is subset of another array or not
def isSubset(arr1, arr2, m, n):
i=0
j=0
for i in range(n):
for j in range(m):
if(arr2[i] == arr1[j]):
break

if (j == m):
return 0
return 1

# Driver code
arr1 = [11, 12, 13, 21, 30, 70]
arr2 = [11, 30, 70, 12]

m = len(arr1)
n = len(arr2)

if(isSubset(arr1, arr2, m, n)):


print("arr2[] is subset of arr1[] ")
else:
print("arr2[] is not a subset of arr1[]")
Output :
arr2[] is subset of arr1[]
Related Pages

Find maximum product sub-array in a given array

Finding Arrays are disjoint or not

Determine can all numbers of an array be made equal


Finding Minimum sum of absolute difference of given array

Sort an array according to the order defined by another array

You might also like