Author name: Vikram Chiluka

Program to Calculate LCM of Two numbers

Python Program to Find the LCM of Two Numbers

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

We’ll learn how to find the LCM of two numbers in Python programming in this tutorial.

LCM:

What exactly does LCM stand for? The Least Common Multiple of two numbers is referred to as LCM. The LCM of two numbers a and b, for example, is the lowest positive integer divisible by both.

Given two numbers a and b , the task is to write the program which calculates lcm of a and b in Python.

Examples:

Example1:

Input:

a= 23   b=12

Output:

The LCM of the given two numbers 23 , 12 = 276

Example2:

Input:

a= 18 b=72

Output:

The LCM of the given two numbers 18 , 72 = 72

Example3:

Input:

a= 4 b=8

Output:

The LCM of the given two numbers 4 , 8 = 8

Example4:

Input:

a= 9 b=9

Output:

The LCM of the given two numbers 9 , 9 = 9

Explanation:

 The least common divisor of two numbers is number itself if both the numbers are equal

Program to Calculate LCM of Two numbers in Python

There are several ways to calculate the lcm of two numbers 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 while loop

Algorithm:

  • Scan or give static input for the numbers a and b.
  • Using an If condition, find the bigger value and assign it to the variable ‘max.’
  • Check whether the remainder of (max %a) and (max %b) equals zero or not using an If condition within the while loop.
  •  Print max, which is the LCM of two numbers, if true.
  • If not, use a break statement to skip that value.
  • End of the execution of the program

Below is the implementation:

# given two numbers
# given number a
number1 = 23
# given number b
number2 = 12
# finding bigger number of the given two numbers using if statement
if(number1 > number2):
    maxValue = number1
else:
    maxValue = number2
while(True):
    if(maxValue % number1 == 0 and maxValue % number2 == 0):
        print("The LCM of the given two numbers",
              number1, ",", number2, "=", maxValue)
        break
    maxValue = maxValue + 1

Output:

The LCM of the given two numbers 23 , 12 = 276

Explanation:

  • Both numbers must be entered by the user/static declaration and stored in separate variables.
  • An if statement is used to determine which of the two values is smaller and save the result in a minimum variable.
  • Then, unless break is used, a while loop is employed with a condition that is always true (or 1).
  • Then, within the loop, an if statement is used to determine whether the value in the minimum variable is divisible by both numbers.
  • If it is divisible, the break statement exits the loop.
  • If it is not divisible, the minimum variable’s value is increased.
  • The result(lcm ) will be printed.

Method #2:Using GCD/HCF of the given two numbers

The LCM of two numbers can be determined using the math module’s gcd() function. Consider the following illustration.

Below is the implementation:

# importing math
import math
# given two numbers
# given number a
number1 = 23
# given number b
number2 = 12
# finding lcm of the given two values
lcmValue = (number1*number2)//math.gcd(number1, number2)
print("The LCM of the given two numbers",
      number1, ",", number2, "=", lcmValue)

Output:

The LCM of the given two numbers 23 , 12 = 276

Method #3:Using Numpy lcm function.

We can calculate the lcm of the given two numbers using numpy.

We use numpy lcm function to find the lcm of given two numbers.

First We need to import the numpy to use lcm function as below

import numpy as np

we can find lcm using np.lcm(number1,number2) .

Here number1 and number2 are the parameters of the lcm() function.

Below is the implementation:

# importing numpy
import numpy as np
# given two numbers
# given number a
number1 = 23
# given number b
number2 = 12
# finding lcm of the given two numbers number1 and number2
lcmValue = np.lcm(number1, number2)
# printing the lcm of number1 and number2
print("The LCM of the given two numbers",
      number1, ",", number2, "=", lcmValue)

Output:

The LCM of the given two numbers 23 , 12 = 276

Related Programs:

Python Program to Find the LCM of Two Numbers 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 »