Python

Python Programs for Class 12

Python Programs for Class 12 | Python Practical Programs for Class 12 Computer Science

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

CBSE Class 12 Computer Science Python Programs with Output are provided in this tutorial. Students who are pursuing 12th can refer to this page for practical files of python programs in order to prepare and learn well for the board exams. Basically, the Class XII python practical file must have 20 python programs and 5 SQL Queries. But today, in this tutorial, we are going to compile some of the important python programs for class 12 CBSE computer science.

Practicing more and more with the provided python practical programs for Class XII CBSE can make you win in the race of python programming and in your software career too. So, dive into this article completely and start learning python programming language easily and efficiently.

List of Python Programs for Class 12 Practical File with Output PDF

Here are some of the python programs for class 12 pursuing students. Just take a look at them before kickstarting your programming preparation for board exams. Click on the available links and directly jump into the respective python program to understand & continue with other programs that are listed in the CBSE Class 12 Computer Science Python Programming Practical File.

1)Program for Arithmetic Operations in Python

Task is to perform Arithmetic Operations in python

Below is the implementation:

#python program which performs simple arithmetic operations
# given two numbers
# given first number
numberone = 29
numbertwo = 13
# adding the  given two numbers
addnumb = numberone+numbertwo
# printing the result of sum of two numbers
print("Adding the given two numbers", numberone, "+", numbertwo, "=", addnumb)
# subtracting the given two numbers
diffnumb = numberone-numbertwo
# printing the result of difference of two numbers
print("Subtracting the given two numbers",
      numberone, "-", numbertwo, "=", diffnumb)
# multiply the given two numbers
mulnumb = numberone*numbertwo
# printing the result of product of two numbers
print("Multiplying the given two numbers",
      numberone, "*", numbertwo, "=", mulnumb)
# diving the given two numbers
divnumb = numberone+numbertwo
# printing the result of sum of two numbers
print("Dividing the given two numbers",
      numberone, "/", numbertwo, "=", divnumb)

Output:

Adding the given two numbers 29 + 13 = 42
Subtracting the given two numbers 29 - 13 = 16
Multiplying the given two numbers 29 * 13 = 377
Dividing the given two numbers 29 / 13 = 42

2)Program to Generate a Random Number

We’ll write a program that produces a random number between a specific range.

Below is the implementation:

# Program which generates the random number between a specific range.
# importing random module as below
import random
# generating random number
randNumber = random.randint(1, 450)
# print the random number which is generated above
print("Generating random numbers between 1 to 450 = ", randNumber)

Output:

Generating random numbers between 1 to 450 =  420

3)Program to Convert Celsius To Fahrenheit

We will convert the given temp in celsius to fahrenheit as below.

Below is the implementation:

# Python program for converting celsius to fahrenheit temperature.
# given temp in celsius
celsiusTemp = 42.5

# converting the given temp in celsius to fahrenheit temperature
fahrenheitTemp = (celsiusTemp * 1.8) + 32
# print the converted temperature value
print('Converting the given temp in celsius =',
      celsiusTemp, " to Fahrenhiet = ", fahrenheitTemp)

Output:

Converting the given temp in celsius = 42.5  to Fahrenhiet =  108.5

4)Python Program to Check if a Number is Positive, Negative or zero

We will write a program to check if the given number is positive number , negative number or zero using if else conditional statements.

Below is the implementation:

# Python Program to Check if a Number is Positive number, Negative number or zero
# Function which prints whether the given number
#is positive number ,negative number or zero


def checkNumber(given_Num):
    # checking if the given number is positive number
    if(given_Num > 0):
        print("The given number", given_Num, "is positive")
    # checking if the given number is negative number
    elif(given_Num < 0):
        print("The given number", given_Num, "is negative")
    # if the above conditions are not satisfied then the given number is zero
    else:
        print("The given number", given_Num, "is zero")


# given numbers
# given number 1
given_num1 = 169
# passing the given number to checkNumber Function which prints the type of number(+ve,-ve,0)
checkNumber(given_num1)
# given number 2
given_num1 = -374
# passing the given number to checkNumber Function which prints the type of number(+ve,-ve,0)
checkNumber(given_num1)

# given number 3
given_num1 = 0
# passing the given number to checkNumber Function which prints the type of number(+ve,-ve,0)
checkNumber(given_num1)

Output:

The given number 169 is positive
The given number -374 is negative
The given number 0 is zero

5)Python Program to Check if a Number is Odd or Even

We will write a program which checks whether the given number is even number or odd number using if else conditional statements.

Below is the implementation:

# Python Program to Check if a Number is Odd or Even
# Function which prints whether the given number
# is even number ,odd number


def checkNumber(given_Num):
    # checking if the given number is even number
    if(given_Num % 2 == 0):
        print("The given number", given_Num, "is even number")
    # checking if the given number is odd number that is if given number is not even then it is odd number
    else:
        print("The given number", given_Num, "is odd number")


# given numbers
# given number 1
given_num1 = 169
# passing the given number to checkNumber Function which
# prints the type of number(even number or odd number)
checkNumber(given_num1)
# given number 2
given_num1 = 26
# passing the given number to checkNumber Function which
# prints the type of number(even number or odd number)
checkNumber(given_num1)

Output:

The given number 169 is odd number
The given number 26 is even number

6)Python Program to Check Leap Year

We will check whether the given number is leap year or not.

Below is the implementation:

# Python program to check if year is a leap year
# given year
given_year = 2024

if (given_year % 4) == 0:
    if (given_year % 100) == 0:
        if (given_year % 400) == 0:
            print("Given year", given_year, "is leap year")
        else:
            print("Given year", given_year, "is not leap year")
    else:
        print("Given year", given_year, "is leap year")
else:
    print("Given year", given_year, "is not leap year")

Output:

Given year 2024 is leap year

7)Python Program to Find ASCII Value of given_Character

We will find the ascii value of given character in python using ord() function.

Below is the implementation:

# Python Program to Find ASCII Value of given_Character
# given character
given_character = 's'
# finding ascii value of given character
asciiValue = ord(given_character)
# printing ascii value of given character
print(" ascii value of given character", given_character, "=", asciiValue)

Output:

ascii value of given character s = 115

8)Python program to print grades based on marks scored by a student

We will display the grades of students based on given marks using if elif else statements.

Below is the implementation:

# Python program to print grades based on marks scored by a student
# given marks scored by student
given_marks = 68
markGrade = given_marks//10
# cheecking if grade greater than 9
if(markGrade >= 9):
    print("grade A+")
elif(markGrade < 9 and markGrade >= 8):
    print("grade A")
elif(markGrade < 8 and markGrade >= 7):
    print("grade B+")
elif(markGrade < 7 and markGrade >= 6):
    print("grade B")
elif(markGrade < 6 and markGrade >= 5):
    print("grade C+")
else:
    print("Fail")

Output:

grade B

9)Python program to print the sum of all numbers in the given range

Given two ranges(lower limit range and upper limit range) the task is to print the sum of all numbers in the given range.

i)Using for loop

We will use for loop and range function to literate from lower range limit and upper range limit.

Below is the implementation:

# Python program to print the sum of all numbers in the given range
# given lower limit range
lower_range = 17
# given upper limit range
upper_range = 126
# initializing sum of range to 0
rangeSum = 0
# Using for loop to traverse from lower limit range to upper limit range
for i in range(lower_range, upper_range+1):
    rangeSum = rangeSum+i
print("the sum of all numbers between",
      lower_range, "to", upper_range, "=", rangeSum)

Output:

the sum of all numbers between 17 to 126 = 7865

ii)Using mathematical formula of sum of n natural numbers

We we subtract the sum of upper range limit with lower range limit.

sum of n natural numbers =( n * (n+1) ) /2

Below is the implementation:

# Python program to print the sum of all numbers in the given range
# given lower limit range
lower_range = 17
# given upper limit range
upper_range = 126
low_range = lower_range-1
# calculating the sum of natural numbers from 1 to lower limit range
lowSum = (low_range*(low_range+1))/2
# calculating the sum of natural numbers from 1 to upper limit range
highSum = (upper_range*(upper_range+1))/2
# calculating the sum of all numbers between the given range
rangeSum = highSum-lowSum
# printing the sum of all natural numbers between the given range
print("the sum of all numbers between",
      lower_range, "to", upper_range, "=", int(rangeSum))

Output:

the sum of all numbers between 17 to 126 = 7865

10)Python program to print all even numbers in given range

Given two ranges(lower limit range and upper limit range) the task is to print all even numbers in given range

We will use for loop and range function to literate from lower range limit and upper range limit and print all the numbers which are divisible by 2 that  is even numbers

Below is the implementation:

# Python program to print the even numbers in
#  given range(lower limit range and upper limit range)
# given lower limit range
lower_range = 17
# given upper limit range
upper_range = 126
# printing the even numbers in the giveen range using looop
# Iterate from lowe limit range to upper limit range
for numb in range(lower_range, upper_range+1):
    # checking if the number is divisible by 2
    if(numb % 2 == 0):
        # we will print the number if the number is divisible by 2
        print(numb)

Output:

18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100
102
104
106
108
110
112
114
116
118
120
122
124
126

11)Python program to print  star pyramid pattern

We will print the star pyramid using nested for loops

Below is the implementation:

# Python program to print  star pyramid pattern
# given number  of rows
given_rows = 15
for i in range(given_rows+1):
    for j in range(i):
        print("*", end=" ")
    print()

Output:

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * * * 
* * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * * 
* * * * * * * * * * * * 
* * * * * * * * * * * * * 
* * * * * * * * * * * * * * 
* * * * * * * * * * * * * * *

12)Python program to print  number pyramid pattern

We will print the number pyramid using nested for loops

Below is the implementation:

# Python program to print  star pyramid pattern
# given number  of rows
given_rows = 15
for i in range(1, given_rows+1):
    for j in range(1, i+1):
        print(j, end=" ")
    print()

Output:

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
1 2 3 4 5 6 
1 2 3 4 5 6 7 
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8 9 
1 2 3 4 5 6 7 8 9 10 
1 2 3 4 5 6 7 8 9 10 11 
1 2 3 4 5 6 7 8 9 10 11 12 
1 2 3 4 5 6 7 8 9 10 11 12 13 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

13)Python program to print Fibonacci numbers to given limit

Given two ranges(lower limit range and upper limit range) the task is to print all fibonacci numbers in given range

Below is the implementation:

# Python program to print the all the fibonacci numbers in the given range
# given lower limit range
lower_range = 2
# given upper limit range
upper_range = 1000
first, second = 0, 1
# using while loop
while (first < upper_range):
    if(upper_range >= lower_range and first <= upper_range):
        print(first)
    first, second = second, first+second

Output:

0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987

14)Python program to print numbers from 1 to n except 5 multiples

We will use the for loop to print all numbers from 1 to n except 5 multiples.

Below is the implementation:

# Python program to print numbers from 1 to n except 5 multiples
# given number
numb = 49
# using for loop to iterate from 1 to n
for num in range(1, numb+1):
    # if number is not divisible by 5 then print it
    if(num % 5 != 0):
        print(num)

Output:

1
2
3
4
6
7
8
9
11
12
13
14
16
17
18
19
21
22
23
24
26
27
28
29
31
32
33
34
36
37
38
39
41
42
43
44
46
47
48
49

15)Python program to split and join a string

Given a string the task is to split the given string and join the string

Example split the string with ‘@’ character and join with ‘-‘ character.

Below is the implementation:

#python program to split and join a string
# given string
string = "Hello@this@is@BTechGeeks"
# splitting thee given string with @ character
string = string.split('@')
print("After splitting the string the given string =", *string)
# joining the given string
string = '-'.join(string)
print("After joining the string the given string =", string)

Output:

After splitting the string the given string = Hello this is BTechGeeks
After joining the string the given string = Hello-this-is-BTechGeeks

16)Python program to sort the given list

We will sort the given list using sort() function

Below is the implementation:

# Python program to sort the given list
given_list = ["Hello", "This", "Is", "BTechGeeks"]
# printing the list before sorting
print("Before sorting the list given list :")
print(given_list)
# sorting the given list using sort() function
given_list.sort()
# printing thre list after sorting
print("after sorting the list given list :")
print(given_list)

Output:

Before sorting the list given list :
['Hello', 'This', 'Is', 'BTechGeeks']
after sorting the list given list :
['BTechGeeks', 'Hello', 'Is', 'This']

17)Python program to sort a string

Given  list of strings the task is to sort the strings using sort() function.

We will use the split() function to split the string with spaces and store it in list.

Sort the list.

Below is the implementation:

# Python program to sort a string
given_string = "Hello This Is BTechGeeks"
# split the given string using spilt() function(string is separated by spaces)
given_string = given_string.split()
# printing the string before sorting
print("Before sorting the sorting given sorting :")
print(*given_string)
# sorting the given string(list) using sort() function
given_string.sort()
# printing the string after sorting
print("after sorting the string given string :")
print(*given_string)

Output:

Before sorting the sorting given sorting :
Hello This Is BTechGeeks
after sorting the string given string :
BTechGeeks Hello Is This

18)Python Program to Search an element in given list

Given a list and the task is to search for a given element in the list .

We will use the count function to search an element in given list.

If the count is 0 then the element is not present in list

Else the given element is present in list

Below is the implementation:

# Python program to search an element in given list
given_list = ["Hello", "This", "Is", "BTechGeeks"]
# given element to search
element = "BTechGeeks"
# using count function to check whether the given element the present in list or not
countelement = given_list.count(element)
# if count of element is zero then element is not present in list
if(countelement == 0):
    print("The given element", element, "is not present in given list")
else:
    print("The given element", element, "is present in given list")

Output:

The given element BTechGeeks is present in given list

19)Python program to count the frequency of given element in list

Given a list and the task is to find the frequency of a given element in the list .

We will use the count function to find frequency of given element in given list.

Below is the implementation:

# Python program to count the frequency of given element in list
given_list = ["Hello", "BTechGeeks", "This", "Is", "BTechGeeks"]

# given element to search
element = "BTechGeeks"
# using count function to count the given element in list
countelement = given_list.count(element)
# printing the count
print("The given element", element, "occurs",
      countelement, "times in the given list")

Output:

The given element BTechGeeks occurs 2 times in the given list

20)Python program to print list in reverse order

We will use slicing to print the given list in reverse order

Below is the implementation:

# Python program to print list in reverse order
given_list = ["Hello", "This", "Is", "BTechGeeks"]
# printing the list before reversing
print("printing the list before reversing :")
print(given_list)
# reversing the given list
given_list = given_list[::-1]
# printing the list after reversing
print("printing the list after reversing :")
print(given_list)

Output:

printing the list before reversing :
['Hello', 'This', 'Is', 'BTechGeeks']
printing the list after reversing :
['BTechGeeks', 'Is', 'This', 'Hello']

21)Python program to Print odd indexed elements in given list

We will use slicing to print the odd indexed elements in the given list .

Below is the implementation:

# Python program to Print odd indexed elements in given list
given_list = ["Hello", "This", "Is", "BTechGeeks", "Online", "Platform"]
#  odd indexed elements in given list using slicing
odd_elements = given_list[1::2]
# printing the odd indexed elements in given list
for i in odd_elements:
    print(i)

Output:

This
BTechGeeks
Platform

22)Python program for Adding two lists in Python(Appending two lists)

We will use the + operator to add(append) the two lists in python as below:

Below is the implementation:

# Python program for Adding two lists in Python(Appending two lists)
# given list 1
given_list1 = ["Hello", "This", "Is", "BTechGeeks", "Online", "Platform"]
# given list 2
given_list2 = ["Good", "Morning", "Python"]
# adding two lists using + operator
# we add all the elements of second list to first list
given_list1 = given_list1+given_list2
# print the result after adding the two lists
for i in given_list1:
    print(i)

Output:

Hello
This
Is
BTechGeeks
Online
Platform
Good
Morning
Python

23)Python program for finding frequency of each element in the given list

We will use the counter function to calculate the frequency of each element in the given list in efficient way.

Below is the implementation:

# Python program for finding frequency of each element in the given list
# importing counter function from collections
from collections import Counter
# given list which may contains the duplicates
given_list1 = ["Hello", "this", "is", "this", "is", "BTechGeeks", "Hello",
               "is", "is", "this", "BTechGeeks", "is", "this", "Hello", "python"]
# finding frequency of each elements using Counter() function
freqcyCounter = Counter(given_list1)
# printing the frequency of each element
for key in freqcyCounter:
    # frequency of the respective key
    count = freqcyCounter[key]
    # print the element and its frequency
    print("The element", key, "Has frequency =", count)

Output:

The element Hello Has frequency = 3
The element this Has frequency = 4
The element is Has frequency = 5
The element BTechGeeks Has frequency = 2
The element python Has frequency = 1

24)Python program for printing all distinct elements in given list

We will use counter function and print all the keys in it

Below is the implementation:

# Python program for printing all distinct elements in given list
# importing counter function from collections
from collections import Counter
# given list which may contains the duplicates
given_list1 = ["Hello", "this", "is", "this", "is", "BTechGeeks", "Hello",
               "is", "is", "this", "BTechGeeks", "is", "this", "Hello", "python"]
# finding frequency of each elements using Counter() function
freqcyCounter = Counter(given_list1)
# printing the distinct elements of the given list
print("printing the distinct elements of the given list :")
for key in freqcyCounter:
    print(key)

Output:

printing the distinct elements of the given list :
Hello
this
is
BTechGeeks
python

25)Python program to Print even indexed elements in given list

We will use slicing to print the even indexed elements in the given list .

Below is the implementation:

# Python program to Print even indexed elements in given list
given_list = ["Hello", "This", "Is", "BTechGeeks", "Online", "Platform"]
#  odd indexed elements in given list using slicing
odd_elements = given_list[::2]
# printing the even indexed elements in given list
print("printing the even indexed elements in given list :")
for i in odd_elements:
    print(i)

Output:

printing the even indexed elements in given list :
Hello
Is
Online

26)Python program to Print the given list elements in the same line

We have two methods to print the given lists elements in the same line

i)Using end 

Below is the implementation:

# Python program to Print the given list elements in the same line
given_list = ["Hello", "This", "Is", "BTechGeeks", "Online", "Platform"]

# Traveersing the list using for loop
# printing the given list elements
print("printing the given list elements :")
for element in given_list:
    print(element, end=" ")

Output:

printing the given list elements :
Hello This Is BTechGeeks Online Platform

ii)Using * operator

We can use * operator to print all the elements of given list in single line

Below is the implementation:

# Python program to Print the given list elements in the same line
given_list = ["Hello", "This", "Is", "BTechGeeks", "Online", "Platform"]
# printing the given list elements
print("printing the given list elements :")
print(*given_list)

Output:

printing the given list elements :
Hello This Is BTechGeeks Online Platform

27)Python program to count distinct characters in the given string

We will use counter function and print all the keys in it to print all distinct characters in given string

Below is the implementation:

# Python program to count distinct characters in the given string
# importing counter function from collections
from collections import Counter
# given string
string = "Hello@--472BtechGeeks!!;<>?"
# using counter function
distchars = Counter(string)
# Traversing through distchars dictionary
# printing the distinct characters in given string
print("printing the distinct characters in given string", string)
for key in distchars:
    print(key)

Output:

printing the distinct characters in given string Hello@--472BtechGeeks!!;<>?
H
e
l
o
@
-
4
7
2
B
t
c
h
G
k
s
!
;
<
>
?

28)Python program to Sort the given list elements in descending order

We will use the sort() and reverse=True to sort the given list in descending order

Below is the implementation:

# Python program to sort the given list in descending order
given_list = ["Hello", "This", "Is", "BTechGeeks", "online", "platform"]
# printing the list before sorting
print("Before sorting the list given list :")
for i in given_list:
    print(i)
# sorting the given list using sort() function
given_list.sort(reverse=True)
# printing the list after sorting
print("after sorting the list given list  in descending order:")
for i in given_list:
    print(i)

Output:

Before sorting the list given list :
Hello
This
Is
BTechGeeks
online
platform
after sorting the list given list  in descending order:
platform
online
This
Is
Hello
BTechGeeks

29)Python program to print character if ascii value is given

We will use chr function to print character if ascii value is given

Below is the implementation:

# Python program to print character if ascii value is given
# given ascii value
givenvalue = 104
# getting the character having given ascii value
character = chr(givenvalue)
# printing the character having given ascii value
print("The character which is having ascii value", givenvalue, "=", character)

Output:

The character which is having ascii value 104 = h

30)Python program to split the given number into list of digits

We will use map and list function to split the given number into list of digits

Below is the implementation:

# Python program to split the given number into list of digits
# given number
numb = 123883291231775637829
# converting the given number to string
strnu = str(numb)
# splitting the given number into list of digits using map and list functions
listDigits = list(map(int, strnu))
# print the list of digits of given number
print(listDigits)

Output:

[1, 2, 3, 8, 8, 3, 2, 9, 1, 2, 3, 1, 7, 7, 5, 6, 3, 7, 8, 2, 9]

31)Python program to split the given string into list of characters

We will use the list() function to split the given string into list of characters

Below is the implementation:

# Python program to split the given string into list of characters
# given string
string = "HellothisisBtechGeeks"
# splitting the string into list of characters
splitstring = list(string)
# print the list of characters of the given string
print(splitstring)

Output:

['H', 'e', 'l', 'l', 'o', 't', 'h', 'i', 's', 'i', 's', 'B', 't', 'e', 'c', 'h', 'G', 'e', 'e', 'k', 's']

Here the string is converted into a list of characters.

Objectives to Practice Python Programming for Class XII Computer Science CBSE Exam

  • Students should have the understanding power to implement functions and recursion concepts while programming.
  • They study the topics of file handling and utilize them respectively to read and write files as well as other options.
  • Learn how to practice efficient concepts in algorithms and computing.
  • Also, they will be proficient to create Python libraries and utilizing them in different programs or projects.
  • Can learn SQL and Python together with their connectivity.
  • Students can also understand the basics of computer networks.
  • Furthermore, they will have the ability to practice fundamental data structures such as Stacks and Queues.

Must Check: CBSE Class 12 Computer Science Python Syllabus

FAQs on Python Practical Programming for 12th Class CBSE

1. From where students can get the list of python programs for class 12?

Students of class 12 CBSE can get the list of python practical programs with output from our website @ Btechgeeks.com

2. How to download a class 12 CBSE Computer Science practical file on python programming?

You can download CBSE 12th Class Computer science practical file on python programming for free from the above content provided in this tutorial.

3. What is the syllabus for class 12 python programming?

There are 3 chapters covered in the computer science syllabus of class 12 python programs to learn and become pro in it.

  1. Computational Thinking and Programming – 2
  2. Computer Networks
  3. Database Management

Python Programs for Class 12 | Python Practical Programs for Class 12 Computer Science Read More »

Stack Data Structure in Python

Stack Data Structure in Python

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Stacking objects means putting them on top of one another in the English language. This data structure allocates memory in the same manner.

Data structures are essential for organizing storage in computers so that humans can access and edit data efficiently. Stacks were among the first data structures to be defined in computer science. In layman’s terms, a stack is a linear accumulation of items. It is a collection of objects that provides fast last-in, first-out (LIFO) insertion and deletion semantics. It is a modern computer programming and CPU architecture array or list structure of function calls and parameters. Elements in a stack are added or withdrawn from the top of the stack in a “last in, first out” order, similar to a stack of dishes at a restaurant.

Unlike lists or arrays, the objects in the stack do not allow for random access.

Stack Data Structure in Python

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)What is the purpose of Stack and when do we use it?

Stacks are simple data structures which enable us to save and retrieve data successively.

In terms of performance, insert and remove operations should take O(1) time in a suitable stack implementation.

Consider a stack of books to grasp Stack at its most fundamental level. You place a book at the top of the stack, so the first one picked up is the last one added to the stack.

Stacks have many real-world applications; understanding them allows us to address numerous data storage challenges in a simple and effective manner.

Assume you’re a programmer working on a brand-new word processor. You must provide an undo functionality that allows users to reverse their activities all the way back to the start of the session. For this circumstance, a stack is an excellent choice. By pushing it to the stack, we can record every action taken by the user. When a user wants to undo an action, they can pop the appropriate item off the stack.

2)Ways to implement stack data structure in Python?

Python stacks can be implemented in Python by:

  • Using the List data structure that comes with the program. The List data structure in Python has methods for simulating both stack and queue operations.
  • Using the deque library, which combines the functions of a stack and a queue into a single object.
  • using  queue.LifoQueue Class.

As previously stated, we can use the “PUSH” operation to add items to a stack and the “POP” action to remove objects from a stack.

3)Basic methods of stack

The following methods are widely used with the stack in Python.

empty() :If the stack is empty, empty() returns true. It takes time complexity O(1).
size()   : is a function that returns the stack’s length. It takes time complexity O(1).
top() : This function returns the address of the stack’s last member. It takes time complexity O(1).).
push(r) : Pushes the element ‘r’ to the end of the stack – It takes time complexity O(1).
pop() : This procedure removes the stack’s topmost member. It takes time complexity O(1).

4)Working of Stack

The following is how the operations work:

  • The TOP pointer is used to maintain track of the stack’s top member.
  • We set the stack’s value to -1 when we first created it so that we can check if it’s empty by comparing          TOP == -1.
  • When we push an element, the value of TOP is increased, and the new element is placed at the position indicated to by TOP.
  • The element specified by TOP is returned and its value is reduced if an element is popped.
  • We check if the stack is already full before pushing.
  • We verify if the stack is already empty before popping it.

5)Implementation of stack

1)Implementation of integer stack

Below is the implementation:

# implementing stack data structure in Python


# Creating new empty stack
def createStack():
    Stack = []
    return Stack
# Checking if the given stack is empty or not


def isEmptyStack(Stack):
    return len(Stack) == 0


# appending elements to the stack that is pushing the given element to the stack
def pushStack(stack, ele):
    # appending the given element to the stack using append() function
    stack.append(ele)
    # printing the newly inserted/appended element
    print("New element added : ", ele)


# Removing element from the stack using pop() function
def popStack(stack):
  # checking if the stack is empty or not
    if (isEmptyStack(stack)):
        return ("The given stack is empty and we cannot delete the element from the stack")
    # if the stack is not empty then remove / pop() element from the stack
    return stack.pop()

# function which returns the top elememt in the stack


def topStack(stack):
  # returning the top element in the stack
    return stack[-1]


# creating a new stack and performing all operations on the stack
# creating new stack
st = createStack()
# adding some  random elements to the stack
pushStack(st, 5)
pushStack(st, 1)
pushStack(st, 9)
pushStack(st, 2)
pushStack(st, 17)
# removing element from stack
print(popStack(st), "is removed from stack")
# printing the stack after removing the element
print("Printing the stack after modification", st)
# printing the top element from the stack
print("The top element from the stack is ", topStack(st))

Output:

New element added :  5
New element added :  1
New element added :  9
New element added :  2
New element added :  17
17 is removed from stack
Printing the stack after modification [5, 1, 9, 2]
The top element from the stack is  2

2)Implementation of string stack

Below is the implementation of the above approach:

# implementing stack data structure in Python


# Creating new empty stack
def createStack():
    Stack = []
    return Stack
# Checking if the given stack is empty or not


def isEmptyStack(Stack):
    return len(Stack) == 0


# appending elements to the stack that is pushing the given element to the stack
def pushStack(stack, ele):
    # appending the given element to the stack using append() function
    stack.append(ele)
    # printing the newly inserted/appended element
    print("New element added : ", ele)


# Removing element from the stack using pop() function
def popStack(stack):
  # checking if the stack is empty or not
    if (isEmptyStack(stack)):
        return ("The given stack is empty and we cannot delete the element from the stack")
    # if the stack is not empty then remove / pop() element from the stack
    return stack.pop()

# function which returns the top elememt in the stack


def topStack(stack):
  # returning the top element in the stack
    return stack[-1]


# creating a new stack and performing all operations on the stack
# creating new stack
st = createStack()
# adding some  random elements to the stack
pushStack(st, "hello")
pushStack(st, "this")
pushStack(st, "is")
pushStack(st, "BTechGeeks")
pushStack(st, "python")
# removing element from stack
print(popStack(st), "is removed from stack")
# printing the stack after removing the element
print("Printing the stack after modification", st)
# printing the top element from the stack
print("The top element from the stack is ", topStack(st))

Output:

New element added :  hello
New element added :  this
New element added :  is
New element added :  BTechGeeks
New element added :  python
python is removed from stack
Printing the stack after modification ['hello', 'this', 'is', 'BTechGeeks']
The top element from the stack is  BTechGeeks

Related Programs:

Stack Data Structure in Python Read More »

Program to Read a Number n and Compute n+nn+nnn in C++ and Python

Program to Read a Number n and Compute n+nn+nnn in C++ and Python

In the previous article, we have discussed about Program to Clear the Rightmost Set Bit of a Number in C++ and Python. Let us learn Program to Read a Number n and Compute n+nn+nnn in C++ Program and Python.

Given a number n , the task is to calculate the value of n+ nn +nnn in C++ and Python.

Examples:

Example1:

Input:

given number = 8

Output:

The value of 8 + 88 + 888 = 984

Example2:

Input:

given number = 4

Output:

Enter any random number = 4
The value of 4 + 44 + 444 = 492

Example3:

Input:

given number = 9

Output:

The value of 9 + 99 + 999 = 1107

Program to Read a Number n and Compute n+nn+nnn in C++ and Python

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

There are several ways to calculate the value of n + nn + nnn in C++ and  python some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using String Concatenation (Static Input) in Python

Approach:

  • Give the input number as static.
  • Convert the number to a string and save it in a different variable.
  • Add the string twice to concatenate it and store it in another variable.
  • Then multiply the string by three and assign the result to the third variable.
  • Convert the second and third variables’ strings to integers.
  • Add the values from all the integers together.
  • Print the expression’s total value.
  • Exit of program

Below is the implementation:

# given number numb
numb = 8
# converting the given number to string
strnum = str(numb)
# Add the string twice to concatenate it and store it in another variable.
strnum1 = strnum+strnum
# Add the string thrice  to concatenate it and store it in another variable.
strnum2 = strnum+strnum+strnum
# converting the strnum1 and strnum2 from string to integer using int() function
intnum1 = int(strnum1)
intnum2 = int(strnum2)
# Calculating the result value
resultVal = numb+intnum1+intnum2
print("The value of", strnum, "+", strnum1, "+", strnum2, "=", resultVal)

Output:

The value of 8 + 88 + 888 = 984

Method #2:Using String Concatenation (User Input) in Python

Approach:

  • Scan the given number and store it in the numb variable.
  • Convert the number to a string and save it in a different variable.
  • Add the string twice to concatenate it and store it in another variable.
  • Add the string thrice to concatenate it and store it in another variable.
  • Convert the second and third variables strings to integers.
  • Add the values from all the integers together.
  • Print the expression’s total value.
  • Exit of program

Below is the implementation:

# Scan the give number
numb = int(input("Enter any random number = "))
# converting the given number to string
strnum = str(numb)
# Add the string twice to concatenate it and store it in another variable.
strnum1 = strnum+strnum
# Add the string thrice  to concatenate it and store it in another variable.
strnum2 = strnum+strnum+strnum
# converting the strnum1 and strnum2 from string to integer using int() function
intnum1 = int(strnum1)
intnum2 = int(strnum2)
# Calculating the result value
resultVal = numb+intnum1+intnum2
print("The value of", strnum, "+", strnum1, "+", strnum2, "=", resultVal)

Output:

Enter any random number = 4
The value of 4 + 44 + 444 = 492

Method #3:Using String Concatenation (Static Input) in C++

Approach:

  • Give the input number as static.
  • Convert the number to a string  using to_string() function in C++ and save it in a different variable.
  • Add the string twice to concatenate it and store it in another variable.
  • Add the string thrice to concatenate it and store it in another variable.
  • Convert the second and third variables strings to integers using stoi() function.
  • Add the values from all the integers together.
  • Print the expression’s total value.
  • Exit of program

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // given number numb
    int numb = 9;
    // converting the given number to string
    string strnum = to_string(numb);

    // Add the string twice to concatenate it and store it
    // in another variable.
    string strnum1 = strnum + strnum;
    // Add the string thrice to concatenate it and store it
    // in another variable.
    string strnum2 = strnum + strnum + strnum;
    // converting the strnum1 and strnum2 from string to
    // integer using stoi() function
    int intnum1 = stoi(strnum1);
    int intnum2 = stoi(strnum2);
    // Calculating the result value
    int resultVal = numb + intnum1 + intnum2;
    cout << "The value of " << strnum << " + " << strnum1
         << " + " << strnum2 << " = " << resultVal;
    return 0;
}

Output:

The value of 9 + 99 + 999 = 1107

Related Programs:

Program to Read a Number n and Compute n+nn+nnn in C++ and Python Read More »

Program to Check Prime Number

Python Program to Check a Number is Prime or Not

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

Factors of a number:

When two whole numbers are multiplied, the result is a product. The factors of the product are the numbers we multiply.

In mathematics, a factor is a number or algebraic expression that equally divides another number or expression, leaving no remainder.

Prime Number:

A prime number is a positive integer greater than 1 that has no other variables except 1 and the number itself. Since they have no other variables, the numbers 2, 3, 5, 7, and so on are prime numbers.

Given a number , the task is to check whether the given number is prime or not.

Examples:

Example 1:

Input:

number =5

Output:

The given number 5 is prime number

Example 2:

Input:

number =8

Output:

The given number 8 is not prime number

Example 3:

Input:

number =2

Output:

The given number 2 is not prime number

Program to Check Prime Number in Python Programming

Below are the ways to check whether the given number is prime or not:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Using for loop to loop from 2 to N-1 using flag or temp variable

To see if there are any positive divisors other than 1 and number itself, we divide the input number by all the numbers in the range of 2 to (N – 1).

If a divisor is found, the message “number is not a prime number” is displayed otherwise, the message “number is a prime number” is displayed.

We iterate from 2 to N-1 using for loop.

Below is the implementation:

# given number
number = 5
# intializing a temporary variable with False
temp = False
# We will check if the number is greater than 1 or not
# since prime numbers starts from 2
if number > 1:
    # checking the divisors of the number
    for i in range(2, number):
        if (number % i) == 0:
            # if any divisor is found then set temp to true since it is not prime number
            temp = True
            # Break the loop if it is not prime
            break
if(temp):
    print("The given number", number, "is not prime number")
else:
    print("The given number", number, "is prime number")

Output:

The given number 5 is prime number

Explanation:

We checked whether a number is prime or not in this program . Prime numbers are not  those that are smaller than or equal to one. As a result, we only go forward if the number is greater than one.

We check whether a number is divisible exactly by any number between 2 and number – 1. We set temp to True and break the loop if we find a factor in that range, indicating that the number is not prime.

We check whether temp is True or False outside of the loop.

Number is not a prime number if it is True.
If False, the given number is a prime number.

2)Using For Else Statement

To check if number is prime, we used a for…else argument.

It is based on the logic that the for loop’s else statement runs if and only if the for loop is not broken out. Only when no variables are found is the condition satisfied, indicating that the given number is prime.

As a result, we print that the number is prime in the else clause.

Below is the implementation:

# given number
number = 5

# We will check if the number is greater than 1 or not
# since prime numbers starts from 2
if number > 1:
    # checking the divisors of the number
    for i in range(2, number):
        if (number % i) == 0:
            # if any divisor is found then print it is not prime
            print("The given number", number, "is not prime number")
            # Break the loop if it is not prime
            break
    else:
        print("The given number", number, "is prime number")
# if the number is less than 1 then print it is not prime number
else:
    print("The given number", number, "is not prime number")

Output:

The given number 5 is prime number

3)Limitations of above methods in terms of Time Complexity

In these two methods the loop runs from 2 to number N-1.

Hence we can say that the time complexity of above methods are O(n).

What if the number is very large?

Like 10^18 the above methods takes nearly 31 years to execute.

Then How to avoid this?

We can see that the factors of the numbers exist from 1 to N/2 except number itself.

But this also takes nearly 15 yrs to execute.

So to above this we loop till square root of N in next method which gives Time Complexity O(Sqrt(n)).

4)Solution Approach for Efficient Approach

We will improve our program by reducing the number range in which we search for factors.

Our search range in the above program is 2 to number – 1.

The set, range(2,num/2) or range(2,math.floor(math.sqrt(number)) should have been used. The latter range is based on the requirement that a composite number’s factor be less than its square root. Otherwise, it’s a prime number.

5)Implementation of Efficient Approach

In this function, we use Python’s math library to calculate an integer, max_divisor, that is the square root of the number and get its floor value. We iterate from 2 to n-1 in the last example. However, we reduce the divisors by half in this case, as shown. To get the floor and sqrt functions, you’ll need to import the math module.
Approach:

  • If the integer is less than one, False is returned.
  • The numbers that need to be verified are now reduced to the square root of the given number.
  • The function will return False if the given number is divisible by any of the numbers from 2 to the square root of the number.
  • Otherwise, True would be returned.

Below is the implementation:

# importing math module
import math
# function which returns True if the number is prime else not


def checkPrimeNumber(number):
    if number < 1:
        return False
    # checking the divisors of the number
    max_divisor = math.floor(math.sqrt(number))
    for i in range(2, max_divisor+1):
        if number % i == 0:
            # if any divisor is found then return False
            return False
        # if no factors are found then return True
        return True


# given number
number = 5
# passing number to checkPrimeNumber function
if(checkPrimeNumber(number)):
    print("The given number", number, "is prime number")
else:
    print("The given number", number, "is not prime number")

Output:

The given number 5 is prime number

Related Programs:

Python Program to Check a Number is Prime or Not Read More »

Program to Handle Precision Values

Program to Handle Precision Values in Python

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Python treats every number with a decimal point as a double precision floating point number by default. The Decimal is a form of floating decimal point with more precision and a narrower range than the float. It is ideal for monetary and financial calculations. It is also more similar to how humans operate with numbers.

In contrast to hardware-based binary floating point, the decimal module features user-adjustable precision that can be as large as required for a given situation. The precision is set to 28 places by default.

Some values cannot be represented exactly in a float data format. For example, saving the 0.1 value in the float (binary floating point value) variable gives just an approximation of the value. Similarly, the 1/5 number cannot be precisely expressed in decimal floating point format.
Neither type is ideal in general, decimal types are better suited for financial and monetary computations, while double/float types are better suited for scientific calculations.

Handling precision values in Python:

We frequently encounter circumstances in which we process integer or numeric data into any application or manipulation procedures, regardless of programming language. We find data with decimal values using the same procedure. This is when we must deal with accuracy values.

Python has a number of functions for dealing with accuracy values for numeric data. It allows us to exclude decimal points or have customized values based on the position of the decimal values in the number.

Examples:

Example1:

Input:

given_number = 2345.1347216482926    precisionlimit=4

Output:

the given number upto 4 decimal places 2345.1347

Example2:

Input:

given_number = 2345.13    precisionlimit=4

Output:

the given number upto 4 decimal places 2345.1300

Code for Handling Precision Values in Python

There are several ways to handle the precision values in python some of them are:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1:Using % operator

We may format the number as well as specify precision boundaries with the ‘ % ‘ operator. This allows us to customize the precise point restrictions that are included in the final number.

Syntax:

'%.point'%number

Parameters:

point: It denotes the number of points we want after the decimal in the integer.
number : The integer value to be worked on is represented by the number.

Below is the implementation:

# given number
given_number = 2345.1347216482926
# using % operator and printing upto 4 decimal places
ans = '%.4f' % given_number
# print the answer
print("the given number upto 4 decimal places", ans)

Output:

the given number upto 4 decimal places 2345.1347

Method #2:Using format function

We can use the format() function to set limits for precision values, just like we can with the percent operator. We format the data as a string and set the limits for the points to be included after the decimal portion of the number with the format() function.

Syntax:

print ("{0:.pointf}".format(number))

Below is the implementation:

# given number
given_number = 2345.1336327777377
# using % operator and printing upto 5 decimal places
ans = '{0:.5f}' .format(given_number)
# print the answer
print("the given number upto 5 decimal places", ans)

Output:

the given number upto 5 decimal places 2345.13363

Method #3:Using round() function

We can extract and display integer values in a customized format using the Python round() function. As a check for precision handling, we can select the number of digits to be displayed after the decimal point.

Syntax:

round(number, point)

Below is the implementation:

# given number
given_number = 2345.1336327777377
# using % operator and printing upto 4 decimal places
ans = round(given_number, 5)
# print the answer
print("the given number upto 5 decimal places", ans)

Output:

the given number upto 5 decimal places 2345.13363

4)Math functions in Python to handle precision values

Aside from the functions listed above, Python also provides us with a math module that contains a set of functions for dealing with precision values.

The Python math module includes the following functions for dealing with precision values–

1)trunc() function
2)The ceil() and floor() functions in Python
Let us go over them one by one.

Method #4:Using trunc() function

The trunc() function terminates all digits after the decimal points. That is, it only returns the digits preceding the decimal point.

Syntax:

import math
math.trunc(given number)

Below is the implementation:

import math
# given number
given_number = 39245.1336327777377
# truncating all the digits of given number
truncnumber = math.trunc(given_number)
# print the answer
print("the given number after truncating digits", truncnumber)

Output:

the given number after truncating digits 39245

Method #5:Using ceil() and floor() functions

We can round off decimal numbers to the nearest high or low value using the ceil() and floor() functions.

The ceil() function takes the decimal number and rounds it up to the next large number after it. The floor() function, on the other hand, rounds the value to the next lowest value before it.

Below is the implementation:

import math
given_number = 3246.3421

# prining the ceil value of the given number
print('printing ceil value of the given numnber',
      given_number, '=', math.ceil(given_number))

# prining the floor value of the given number
print('printing floor value of the given numnber',
      given_number, '=', math.floor(given_number))

Output:

printing ceil value of the given numnber 3246.3421 = 3247
printing floor value of the given numnber 3246.3421 = 3246

Related Programs:

Program to Handle Precision Values in Python Read More »

Program for Minimum Height of a Triangle with Given Base and Area

Python Program for Minimum Height of a Triangle with Given Base and Area

In the previous article, we have discussed Python Program to Calculate Volume and Surface Area of Hemisphere
Given the area(a) and the base(b) of the triangle, the task is to find the minimum height so that a triangle of least area a and base b can be formed.

Knowing the relationship between the three allows you to calculate the minimum height of a triangle with base “b” and area “a.”

The relationship between area, base, and height:

area = (1/2) * base * height

As a result, height can be calculated as follows:

height = (2 * area)/ base

Examples:

Example1:

Input:

Given area = 6
Given base = 3

Output:

The minimum height so that a triangle of the least area and base can be formed =  4

Example2:

Input:

Given area = 7
Given base = 5

Output:

The minimum height so that a triangle of the least area and base can be formed = 3

Program for Minimum Height of a Triangle with Given Base and Area in Python

Below are the ways to find the minimum height so that a triangle of least area a and base b can be formed:

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Import math module using the import keyword.
  • Give the area as static input and store it in a variable.
  • Give the base as static input and store it in another variable.
  • Create a function to say Smallest_height() which takes the given area and base of the triangle as the arguments and returns the minimum height so that a triangle of least area and base can be formed.
  • Inside the function, calculate the value of (2*gvn_areaoftri)/gvn_baseoftri using the above mathematical formula and store it in another variable.
  • Apply math.ceil() function to the above result and return the minimum height.
  • Pass the given area and base of the triangle as the arguments to the Smallest_height() function and store it in a variable.
  • Print the above result i.e, minimum height so that a triangle of the least area and base can be formed.
  • The Exit of the Program.

Below is the implementation:

# Import math module using the import keyword.
import math

# Create a function to say Smallest_height() which takes the given area and base
# of the triangle as the arguments and returns the minimum height so that a
# triangle of least area and base can be formed.


def Smallest_height(gvn_areaoftri, gvn_baseoftri):
    # Inside the function, calculate the value of (2*gvn_areaoftri)/gvn_baseoftri using
    # the above mathematical formula and store it in another variable.
    rslt = (2*gvn_areaoftri)/gvn_baseoftri
    # Apply math.ceil() function to the above result and return the minimum height.
    return math.ceil(rslt)


# Give the area as static input and store it in a variable.
gvn_areaoftri = 6
# Give the base as static input and store it in another variable.
gvn_baseoftri = 3
# Pass the given area and base of the triangle as the arguments to the Smallest_height()
# function and store it in a variable.
min_heigt = Smallest_height(gvn_areaoftri, gvn_baseoftri)
# Print the above result i.e, minimum height so that a triangle of the least area
# and base can be formed.
print("The minimum height so that a triangle of the least area and base can be formed = ", min_heigt)

Output:

The minimum height so that a triangle of the least area and base can be formed =  4

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Import math module using the import keyword.
  • Give the area as user input using the int(input()) function and store it in a variable.
  • Give the base as user input using the int(input()) function and store it in another variable.
  • Create a function to say Smallest_height() which takes the given area and base of the triangle as the arguments and returns the minimum height so that a triangle of least area and base can be formed.
  • Inside the function, calculate the value of (2*gvn_areaoftri)/gvn_baseoftri using the above mathematical formula and store it in another variable.
  • Apply math.ceil() function to the above result and return the minimum height.
  • Pass the given area and base of the triangle as the arguments to the Smallest_height() function and store it in a variable.
  • Print the above result i.e, minimum height so that a triangle of the least area and base can be formed.
  • The Exit of the Program.

Below is the implementation:

# Import math module using the import keyword.
import math

# Create a function to say Smallest_height() which takes the given area and base
# of the triangle as the arguments and returns the minimum height so that a
# triangle of least area and base can be formed.


def Smallest_height(gvn_areaoftri, gvn_baseoftri):
    # Inside the function, calculate the value of (2*gvn_areaoftri)/gvn_baseoftri using
    # the above mathematical formula and store it in another variable.
    rslt = (2*gvn_areaoftri)/gvn_baseoftri
    # Apply math.ceil() function to the above result and return the minimum height.
    return math.ceil(rslt)


# Give the area as user input using the int(input()) function and store it in a variable.
gvn_areaoftri = int(input("Enter some random number = "))
# Give the base as user input using the int(input()) function and 
# store it in another variable.
gvn_baseoftri = int(input("Enter some random number = "))
# Pass the given area and base of the triangle as the arguments to the Smallest_height()
# function and store it in a variable.
min_heigt = Smallest_height(gvn_areaoftri, gvn_baseoftri)
# Print the above result i.e, minimum height so that a triangle of the least area
# and base can be formed.
print("The minimum height so that a triangle of the least area and base can be formed = ", min_heigt)

Output:

Enter some random number = 7
Enter some random number = 5
The minimum height so that a triangle of the least area and base can be formed = 3

If you are learning Python then the Python Programming Example is for you and gives you a thorough description of concepts for beginners, experienced programmers.

Python Program for Minimum Height of a Triangle with Given Base and Area Read More »

Program to Find Coordinates of Rectangle with Given Points Lie Inside

Python Program to Find Coordinates of Rectangle with Given Points Lie Inside

In the previous article, we have discussed Python Program to Find Number of Rectangles in N*M Grid
Given Two lists X and Y where X[i] and Y[i] represent the coordinate system’s points.

The task is to Find the smallest rectangle in which all of the points from the given input are enclosed, and the sides of the rectangle must be parallel to the Coordinate axis. Print the obtained rectangle’s four coordinates.

Examples:

Example1:

Input:

Given X Coordinates List = [4, 3, 6, 1, -1, 12 Given Y Coordinates List = [4, 1, 10, 3, 7, -1] 

Output:

The first point of Rectangle is [ -1 , -1 ]
The second point of Rectangle is [ -1 , 10 ]
The third point of Rectangle is [ 12 , 10 ]
The fourth point of Rectangle is [ 12 , -1 ]

Example2:

Input:

Given X Coordinates List =  4 8 7 1 6 4 2
Given Y Coordinates List =  5 7 9 8 3 4 2

Output:

The first point of Rectangle is [ 1 , 2 ]
The second point of Rectangle is [ 1 , 9 ]
The third point of Rectangle is [ 8 , 9 ]
The fourth point of Rectangle is [ 8 , 2 ]

Program to Find Coordinates of Rectangle with Given Points Lie Inside in Python

Below are the ways to Find the smallest rectangle in which all of the points from the given input are enclosed in Python:

The logic behind this is very simple and efficient: find the smallest and largest x and y coordinates among all given points, and then all possible four combinations of these values result in the four points of the required rectangle as [Xmin, Ymin], [Xmin, Ymax], [Xmax, Ymax],[ Xmax, Ymin].

Method #1: Using Mathematical Approach(Static Input)

Approach:

  • Give the X coordinates of all the points as a list as static input and store it in a variable.
  • Give the Y coordinates of all the points as another list as static input and store it in another variable.
  • Calculate the minimum value of all the x Coordinates using the min() function and store it in a variable xMinimum.
  • Calculate the maximum value of all the x Coordinates using the max() function and store it in a variable xMaximum.
  • Calculate the minimum value of all the y Coordinates using the min() function and store it in a variable yMinimum.
  • Calculate the maximum value of all the y Coordinates using the max() function and store it in a variable yMaximum.
  • Print the Four Coordinates of the Rectangle using the above 4 calculated values.
  • Print the first point of the rectangle by printing values xMinimum, yMinimum.
  • Print the second point of the rectangle by printing values xMinimum, yMaximum.
  • Print the third point of the rectangle by printing values xMaximum, yMaximum.
  • Print the fourth point of the rectangle by printing values xMaximum, yMinimum.
  • The Exit of the Program.

Below is the implementation:

#Give the X coordinates of all the points as a list as static input 
#and store it in a variable.
XCordinates=[4, 3, 6, 1, -1, 12] 
#Give the Y coordinates of all the points as another list as static input 
#and store it in another variable.
YCordinates =  [4, 1, 10, 3, 7, -1] 

#Calculate the minimum value of all the x Coordinates using the min() function
#and store it in a variable xMinimum.
xMinimum=min(XCordinates)
#Calculate the maximum value of all the x Coordinates using the max() function 
#and store it in a variable xMaximum.
xMaximum=max(XCordinates)
#Calculate the minimum value of all the y Coordinates using the min() function
#and store it in a variable yMinimum.
yMinimum=min(YCordinates)
#Calculate the maximum value of all the y Coordinates using the max() function
#and store it in a variable yMaximum.
yMaximum=max(YCordinates)
#Print the Four Coordinates of the Rectangle using the above 4 calculated values.
#Print the first point of the rectangle by printing values xMinimum, yMinimum.
print('The first point of Rectangle is [',xMinimum,',',yMinimum,']')
#Print the second point of the rectangle by printing values xMinimum, yMaximum.
print('The second point of Rectangle is [',xMinimum,',',yMaximum,']')
#Print the third point of the rectangle by printing values xMaximum, yMaximum.
print('The third point of Rectangle is [',xMaximum,',',yMaximum,']')
#Print the fourth point of the rectangle by printing values xMaximum, yMinimum.
print('The fourth point of Rectangle is [',xMaximum,',',yMinimum,']')

Output:

The first point of Rectangle is [ -1 , -1 ]
The second point of Rectangle is [ -1 , 10 ]
The third point of Rectangle is [ 12 , 10 ]
The fourth point of Rectangle is [ 12 , -1 ]

Method #2: Using Mathematical Approach (User Input)

Approach:

  • Give the X coordinates of all the points as a list as user input using list(),int(),split(),map() functions and store it in a variable.
  • Give the Y coordinates of all the points as another list as user input using list(),int(),split(),map() functions and store it in another variable.
  • Calculate the minimum value of all the x Coordinates using the min() function and store it in a variable xMinimum.
  • Calculate the maximum value of all the x Coordinates using the max() function and store it in a variable xMaximum.
  • Calculate the minimum value of all the y Coordinates using the min() function and store it in a variable yMinimum.
  • Calculate the maximum value of all the y Coordinates using the max() function and store it in a variable yMaximum.
  • Print the Four Coordinates of the Rectangle using the above 4 calculated values.
  • Print the first point of the rectangle by printing values xMinimum, yMinimum.
  • Print the second point of the rectangle by printing values xMinimum, yMaximum.
  • Print the third point of the rectangle by printing values xMaximum, yMaximum.
  • Print the fourth point of the rectangle by printing values xMaximum, yMinimum.
  • The Exit of the Program.

Below is the implementation:

# Give the X coordinates of all the points as a list as user input using list(),int(),split(),map() functions
# and store it in a variable.
XCordinates = list(map(int, input('Enter some random X Coordinates = ').split()))
# Give the Y coordinates of all the points as another list as user input using list(),int(),split(),map() functions
# and store it in another variable.
YCordinates = list(map(int, input('Enter some random Y Coordinates = ').split()))

# Calculate the minimum value of all the x Coordinates using the min() function
# and store it in a variable xMinimum.
xMinimum = min(XCordinates)
# Calculate the maximum value of all the x Coordinates using the max() function
# and store it in a variable xMaximum.
xMaximum = max(XCordinates)
# Calculate the minimum value of all the y Coordinates using the min() function
# and store it in a variable yMinimum.
yMinimum = min(YCordinates)
# Calculate the maximum value of all the y Coordinates using the max() function
# and store it in a variable yMaximum.
yMaximum = max(YCordinates)
# Print the Four Coordinates of the Rectangle using the above 4 calculated values.
# Print the first point of the rectangle by printing values xMinimum, yMinimum.
print('The first point of Rectangle is [', xMinimum, ',', yMinimum, ']')
# Print the second point of the rectangle by printing values xMinimum, yMaximum.
print('The second point of Rectangle is [', xMinimum, ',', yMaximum, ']')
# Print the third point of the rectangle by printing values xMaximum, yMaximum.
print('The third point of Rectangle is [', xMaximum, ',', yMaximum, ']')
# Print the fourth point of the rectangle by printing values xMaximum, yMinimum.
print('The fourth point of Rectangle is [', xMaximum, ',', yMinimum, ']')

Output:

Enter some random X Coordinates = 4 8 7 1 6 4 2
Enter some random Y Coordinates = 5 7 9 8 3 4 2
The first point of Rectangle is [ 1 , 2 ]
The second point of Rectangle is [ 1 , 9 ]
The third point of Rectangle is [ 8 , 9 ]
The fourth point of Rectangle is [ 8 , 2 ]

Remediate your knowledge gap by attempting the Python Code Examples regularly and understand the areas of need and work on them.

Python Program to Find Coordinates of Rectangle with Given Points Lie Inside Read More »

Program for Minimum Perimeter of n Blocks

Python Program for Minimum Perimeter of n Blocks

In the previous article, we have discussed Python Program To Find Area of a Circular Sector
Given n blocks of size 1*1, the task is to find the minimum perimeter of the grid made by these given n blocks in python.

Examples:

Example1:

Input:

Given n value = 6

Output:

The minimum perimeter of the grid made by the given n blocks{ 6 } =  11

Example2:

Input:

Given n value = 9

Output:

The minimum perimeter of the grid made by the given n blocks{ 9 } =  12

Program for Minimum Perimeter of n Blocks in Python

Below are the ways to find the minimum perimeter of the grid made by these given n blocks in python:

Method #1: Using Mathematical Approach (Static Input)

Approach:

  • Import math module using the import keyword.
  • Give the n value as static input and store it in a variable.
  • Create a function to say Minimum_perimtr() which takes the given n value as an argument and returns the minimum perimeter of the grid made by these given n blocks.
  • Calculate the square root of the given n value using the math.sqrt() function and store it in a variable say sqrt_val.
  • Multiply the above result with itself and store it in another variable.
  • Check if the given n value is a perfect square by using the if conditional statement.
  • If it is true, then return the value of above sqrt_val multiplied by 4.
  • Else calculate the number of rows by dividing the given n value by sqrt_val.
  • Add the above sqrt_val with the number of rows obtained and multiply the result by 2 to get the perimeter of the rectangular grid.
  • Store it in another variable.
  • Check whether there are any blocks left using the if conditional statement.
  • If it is true, then add 2 to the above-obtained perimeter of the rectangular grid and store it in the same variable.
  • Return the minimum perimeter of the grid made by the given n blocks.
  • Pass the given n value as an argument to the Minimum_perimtr() function, convert it into an integer using the int() function and store it in another variable.
  • Print the above result which is the minimum perimeter of the grid made by the given n blocks.
  • The Exit of the Program.

Below is the implementation:

# Import math module using the import keyword.
import math

# Create a function to say Minimum_perimtr() which takes the given n value as an
# argument and returns the minimum perimeter of the grid made by these given n blocks.


def Minimum_perimtr(gvn_n_val):
    # Calculate the square root of the given n value using the math.sqrt() function
    # and store it in a variable say sqrt_val.
    sqrt_val = math.sqrt(gvn_n_val)
    # Multiply the above result with itself and store it in another variable.
    sqre_rslt = sqrt_val * sqrt_val

    # Check if the given n value is a perfect square by using the if
    # conditional statement.
    if (sqre_rslt == gvn_n_val):
        # If it is true, then return the value of above sqrt_val multiplied by 4.
        return sqrt_val * 4
    else:
        # Else calculate the number of rows by dividing the given n value by sqrt_val.
        no_of_rows = gvn_n_val / sqrt_val

        # Add the above sqrt_val with the number of rows obtained and multiply the result
        # by 2 to get the perimeter of the rectangular grid.
        # Store it in another variable.
        rslt_perimetr = 2 * (sqrt_val + no_of_rows)

        # Check whether there are any blocks left using the if conditional statement.
        if (gvn_n_val % sqrt_val != 0):
            # If it is true, then add 2 to the above-obtained perimeter of the rectangular
                    # grid and store it in the same variable.
            rslt_perimetr += 2
        # Return the minimum perimeter of the grid made by the given n blocks.
        return rslt_perimetr


# Give the n value as static input and store it in a variable.
gvn_n_val = 6
# Pass the given n value as an argument to the Minimum_perimtr() function, convert
# it into an integer using the int() function and store it in another variable.
fnl_rslt = int(Minimum_perimtr(gvn_n_val))
# Print the above result which is the minimum perimeter of the grid made by the
# given n blocks.
print(
    "The minimum perimeter of the grid made by the given n blocks{", gvn_n_val, "} = ", fnl_rslt)
#include <iostream>
#include<math.h>
using namespace std;
int Minimum_perimtr ( int gvn_n_val ) {
  int sqrt_val = sqrt ( gvn_n_val );
  int sqre_rslt = sqrt_val * sqrt_val;
  if (  sqre_rslt == gvn_n_val  ) {
    return sqrt_val * 4;
  }
  else {
    int no_of_rows = gvn_n_val / sqrt_val;
    int rslt_perimetr = 2 * ( sqrt_val + no_of_rows );
    if ( ( gvn_n_val % sqrt_val != 0 )  ) {
      rslt_perimetr += 2;
    }
    return rslt_perimetr;
  }
}
int main() {
   int gvn_n_val = 6;
 int fnl_rslt = ( int ) Minimum_perimtr ( gvn_n_val );
  cout << "The minimum perimeter of the grid made by the given n blocks{" << gvn_n_val << "} = " << fnl_rslt << endl;
  return 0;
}



Output:

The minimum perimeter of the grid made by the given n blocks{ 6 } =  11

Method #2: Using Mathematical Approach (User Input)

Approach:

  • Import math module using the import keyword.
  • Give the n value as user input using the int(input()) function input and store it in a variable.
  • Create a function to say Minimum_perimtr() which takes the given n value as an argument and returns the minimum perimeter of the grid made by these given n blocks.
  • Calculate the square root of the given n value using the math.sqrt() function and store it in a variable say sqrt_val.
  • Multiply the above result with itself and store it in another variable.
  • Check if the given n value is a perfect square by using the if conditional statement.
  • If it is true, then return the value of above sqrt_val multiplied by 4.
  • Else calculate the number of rows by dividing the given n value by sqrt_val.
  • Add the above sqrt_val with the number of rows obtained and multiply the result by 2 to get the perimeter of the rectangular grid.
  • Store it in another variable.
  • Check whether there are any blocks left using the if conditional statement.
  • If it is true, then add 2 to the above-obtained perimeter of the rectangular grid and store it in the same variable.
  • Return the minimum perimeter of the grid made by the given n blocks.
  • Pass the given n value as an argument to the Minimum_perimtr() function, convert it into an integer using the int() function and store it in another variable.
  • Print the above result which is the minimum perimeter of the grid made by the given n blocks.
  • The Exit of the Program.

Below is the implementation:

# Import math module using the import keyword.
import math

# Create a function to say Minimum_perimtr() which takes the given n value as an
# argument and returns the minimum perimeter of the grid made by these given n blocks.


def Minimum_perimtr(gvn_n_val):
    # Calculate the square root of the given n value using the math.sqrt() function
    # and store it in a variable say sqrt_val.
    sqrt_val = math.sqrt(gvn_n_val)
    # Multiply the above result with itself and store it in another variable.
    sqre_rslt = sqrt_val * sqrt_val

    # Check if the given n value is a perfect square by using the if
    # conditional statement.
    if (sqre_rslt == gvn_n_val):
        # If it is true, then return the value of above sqrt_val multiplied by 4.
        return sqrt_val * 4
    else:
        # Else calculate the number of rows by dividing the given n value by sqrt_val.
        no_of_rows = gvn_n_val / sqrt_val

        # Add the above sqrt_val with the number of rows obtained and multiply the result
        # by 2 to get the perimeter of the rectangular grid.
        # Store it in another variable.
        rslt_perimetr = 2 * (sqrt_val + no_of_rows)

        # Check whether there are any blocks left using the if conditional statement.
        if (gvn_n_val % sqrt_val != 0):
            # If it is true, then add 2 to the above-obtained perimeter of the rectangular
                    # grid and store it in the same variable.
            rslt_perimetr += 2
        # Return the minimum perimeter of the grid made by the given n blocks.
        return rslt_perimetr


# Give the n value as user input using the int(input()) function input and
# store it in a variable.
gvn_n_val = int(input("Enter some random number = "))
# Pass the given n value as an argument to the Minimum_perimtr() function, convert
# it into an integer using the int() function and store it in another variable.
fnl_rslt = int(Minimum_perimtr(gvn_n_val))
# Print the above result which is the minimum perimeter of the grid made by the
# given n blocks.
print(
    "The minimum perimeter of the grid made by the given n blocks{", gvn_n_val, "} = ", fnl_rslt)

Output:

Enter some random number = 9
The minimum perimeter of the grid made by the given n blocks{ 9 } = 12

If you are learning Python then the Python Programming Example is for you and gives you a thorough description of concepts for beginners, experienced programmers.

Python Program for Minimum Perimeter of n Blocks Read More »

Program to Find Number of Rectangles in NM Grid

Python Program to Find Number of Rectangles in N*M Grid

In the previous article, we have discussed Python Program for Minimum Perimeter of n Blocks
Given a grid of size N*M the task is to find the number of rectangles in the given grid in Python.

Examples:

Example1:

Input:

Given N = 6
Given M = 4

Output:

Number of Rectangles in the grid of size { 6 * 4 } : 210

Example2:

Input:

Given N = 4
Given M = 2

Output:

Number of Rectangles in the grid of size { 4 * 2 } : 30

Program to Find Number of Rectangles in N*M Grid in Python

Below are the ways to find the number of rectangles in the given N*M:

Let’s try to come up with a formula for the number of rectangles.

There is one rectangle in a grid of 1*1

There will be 2 + 1 = 3 rectangles if the grid is 2*1.

There will be 3 + 2 + 1 = 6 rectangles if the grid is 3*1

The formula for Number of Rectangles = M(M+1)(N)(N+1)/4

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Give the number N as static input and store it in a variable.
  • Give the number M as static input and store it in another variable.
  • Create a function getCountRect() which accepts given N, M grid sides as arguments and returns the number of rectangles.
  • Inside the getCountRect() function Calculate the number of rectangles using the MatheMatical Formula M(M+1)(N)(N+1)/4 and store it in a variable say reslt.
  • Return the reslt value.
  • Inside the Main Function.
  • Pass the given N, M as arguments to getCountRect() function and store the result returned from the function in a variable say countRect.
  • Print the countRect value.
  • The Exit of the Program.

Below is the implementation:

# Create a function getCountRect() which accepts given N, M grid sides
# as arguments and returns the number of rectangles.


def getCountRect(nVal, mVal):
        # Inside the getCountRect() function Calculate the number of rectangles
    # using the MatheMatical Formula M(M+1)(N)(N+1)/4 
    # and store it in a variable say reslt.
    reslt = (mVal * nVal * (nVal + 1) * (mVal + 1)) / 4
    # Return the reslt value.
    return reslt


# Inside the Main Function.
# Give the number N as static input and store it in a variable.
nVal = 6
# Give the number M as static input and store it in another variable.
mVal = 4
# Pass the given N, M as arguments to getCountRect() function
# and store the result returned from the function in a variable say countRect.
countRect = int(getCountRect(nVal, mVal))
# Print the countRect value.
print(
    'Number of Rectangles in the grid of size {', nVal, '*', mVal, '} :', countRect)
#include <iostream>

using namespace std;
int getCountRect ( int nVal, int mVal ) {
  int reslt = ( mVal * nVal * ( nVal + 1 ) * ( mVal + 1 ) ) / 4;
  return reslt;
}
int main() {
    int nVal = 6;
  int mVal = 4;
  int countRect = ( int ) getCountRect ( nVal, mVal );
  cout << "Number of Rectangles in the grid of size {" << nVal << '*' << mVal << " } is: " << countRect << endl;
  return 0;
}

Output:

Number of Rectangles in the grid of size { 6 * 4 } : 210

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Give the number N as user input using the int(input()) function and store it in a variable.
  • Give the number M as user input using the int(input()) function and store it in another variable.
  • Create a function getCountRect() which accepts given N, M grid sides as arguments and returns the number of rectangles.
  • Inside the getCountRect() function Calculate the number of rectangles using the MatheMatical Formula M(M+1)(N)(N+1)/4 and store it in a variable say reslt.
  • Return the reslt value.
  • Inside the Main Function.
  • Pass the given N, M as arguments to getCountRect() function and store the result returned from the function in a variable say countRect.
  • Print the countRect value.
  • The Exit of the Program.

Below is the implementation:

# Create a function getCountRect() which accepts given N, M grid sides
# as arguments and returns the number of rectangles.


def getCountRect(nVal, mVal):
        # Inside the getCountRect() function Calculate the number of rectangles
    # using the MatheMatical Formula M(M+1)(N)(N+1)/4 
    # and store it in a variable say reslt.
    reslt = (mVal * nVal * (nVal + 1) * (mVal + 1)) / 4
    # Return the reslt value.
    return reslt


# Inside the Main Function.
# Give the number N as user input using the int(input()) function and store it in a variable.
nVal = int(input('Enter Some Random N value = '))
# Give the number M as static input and store it in another variable.
mVal = int(input('Enter Some Random M value = '))
# Pass the given N, M as arguments to getCountRect() function
# and store the result returned from the function in a variable say countRect.
countRect = int(getCountRect(nVal, mVal))
# Print the countRect value.
print(
    'Number of Rectangles in the grid of size {', nVal, '*', mVal, '} :', countRect)

Output:

Enter Some Random N value = 4
Enter Some Random M value = 2
Number of Rectangles in the grid of size { 4 * 2 } : 30

Explore more Example Python Programs with output and explanation and practice them for your interviews, assignments and stand out from the rest of the crowd.

Python Program to Find Number of Rectangles in N*M Grid Read More »

Program To Find Area of a Circular Sector

Python Program To Find Area of a Circular Sector

In the previous article, we have discussed Python Program for Arc Length from Given Angle
A circular sector, also known as a circle sector, is a portion of a disc bounded by two radii and an arc, with the smaller area known as the minor sector and the larger as the major sector.

Given the radius and angle of a circle, the task is to calculate the area of the circular sector in python.

Formula:

Area of sector = (angle/360)*(pi * radius²)

where pi=3.1415….

Examples:

Example1:

Input:

Given radius = 24
Given Angle = 90

Output:

The area of circular sector for the given angle { 90 } degrees =  452.57142857142856

Example2:

Input:

Given radius = 15.5
Given Angle =  45

Output:

The area of circular sector for the given angle { 45.0 } degrees = 94.38392857142857

Program To Find Area of a Circular Sector in Python

Below are the ways to calculate the area of the circular sector for the given radius and angle in python:

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Give the radius as static input and store it in a variable.
  • Give the angle as static input and store it in another variable.
  • Take a variable and initialize its value to 22/7.
  • Check if the given angle is greater than or equal to 360 degrees or not using the if conditional statement.
  • If it is true, then print “Invalid Angle. Please enter the other”.
  • Else, calculate the area of the circular sector using the above given mathematical formula and store it in a variable.
  • Print the area of the circular sector for the given angle.
  • The Exit of the Program.

Below is the implementation:

# Give the radius as static input and store it in a variable.
gvn_radiuss = 24
# Give the angle as static input and store it in another variable.
gvn_angl = 90
# Take a variable and initialize its value to 22/7.
gvn_pi = 22/7
# Check if the given angle is greater than or equal to 360 degrees or not using the
# if conditional statement.
if gvn_angl >= 360:
    # If it is true, then print "Invalid Angle. Please enter the other"
    print("Invalid Angle. Please enter the other")
else:
    # Else, calculate the area of circular sector using the above given mathematical
    # formula and store it in a variable.
    area_of_sectr = (gvn_pi * gvn_radiuss ** 2) * (gvn_angl / 360)
    # Print the area of circular sector for the given angle.
    print("The area of circular sector for the given angle {",
          gvn_angl, "} degrees = ", area_of_sectr)
#include <iostream>
#include<math.h>
using namespace std;

int main() {
 int gvn_radiuss = 24;
   int gvn_angl = 90;
   int gvn_pi = 22 / 7;
  if ( gvn_angl >= 360 ) {
    printf ( "Invalid Angle. Please enter the other\n" );
  }
  else {
     float area_of_sectr = ( gvn_pi * gvn_radiuss * gvn_radiuss ) * ( gvn_angl / 360 );
    printf ( "The area of circular sector for the given angle {%d} degrees = %d\n", gvn_angl, area_of_sectr );
  }

  return 0;
}



Output:

The area of circular sector for the given angle { 90 } degrees =  452.57142857142856

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Give the radius as user input using the float(input()) function and store it in a variable.
  • Give the angle as user input using the float(input()) function and store it in another variable.
  • Take a variable and initialize its value to 22/7.
  • Check if the given angle is greater than or equal to 360 degrees or not using the if conditional statement.
  • If it is true, then print “Invalid Angle. Please enter the other”.
  • Else, calculate the area of the circular sector using the above given mathematical formula and store it in a variable.
  • Print the area of the circular sector for the given angle.
  • The Exit of the Program.

Below is the implementation:

# Give the radius as user input using the float(input()) function and store it in a variable.
gvn_radiuss = float(input("Enter some Random Number = "))
# Give the angle as user input using the float(input()) function and store it in another variable.
gvn_angl = float(input("Enter some Random Number = "))
# Take a variable and initialize its value to 22/7.
gvn_pi = 22/7
# Check if the given angle is greater than or equal to 360 degrees or not using the
# if conditional statement.
if gvn_angl >= 360:
    # If it is true, then print "Invalid Angle. Please enter the other"
    print("Invalid Angle. Please enter the other")
else:
    # Else, calculate the area of circular sector using the above given mathematical
    # formula and store it in a variable.
    area_of_sectr = (gvn_pi * gvn_radiuss ** 2) * (gvn_angl / 360)
    # Print the area of circular sector for the given angle.
    print("The area of circular sector for the given angle {",
          gvn_angl, "} degrees = ", area_of_sectr)

Output:

Enter some Random Number = 15.5
Enter some Random Number = 45
The area of circular sector for the given angle { 45.0 } degrees = 94.38392857142857

Grab the opportunity and utilize the Python Program Code Examples over here to prepare basic and advanced topics too with ease and clear all your doubts.

Python Program To Find Area of a Circular Sector Read More »