Author name: Vikram Chiluka

Program to Find the Area of a Rectangle Using Classes

Python Program to Find the Area of a Rectangle Using Classes

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Object-Oriented Programming(OOPS):

Object-oriented programming (OOP) is a form of program structure that involves grouping related characteristics and activities into separate objects.

Objects are conceptually similar to system components. Consider a program to be a sort of factory assembly line. A system component processes some material at each step of the assembly line, eventually changing raw material into a finished product.

An object comprises data, such as the raw or preprocessed materials at each step of an assembly line, as well as behavior, such as the action performed by each assembly line component.

Given length and breadth, the task is to calculate the area of the rectangle with the given length and breadth using classes.

Examples:

Example1:

Input:

given length of rectangle = 15
given breadth of rectangle = 11

Output:

The area of the rectangle with the given sides 15 , 11 = 165

Example2:

Input:

given length of rectangle = 31
given breadth of rectangle = 19

Output:

The area of the rectangle with the given sides 31 , 19 = 589

Program to Find the Area of a Rectangle Using Classes in Python

Below is the full approach to calculate the area of the rectangle with the given length and breadth using classes in Python.

1)Using Classes(Static Input)

Approach:

  • Give the length and breadth as static input and store it in two variables.
  • Create a class and use a parameterized constructor to initialize its values (length and breadth of the rectangle).
  • Create a method called areaofRect that returns the area with the given length and breadth of the rectangle.
  • Create an object to represent the class.
  • Call the method areaofRect() on the object with the length and breadth as the parameters taken from the user as static input.
  • Print the area of the rectangle.
  • The exit of the program.

Below is the implementation:

# creating a class
class rectangle():
  # parameterized constructor with breadth and length as arguments
  # parameterized constructor is used to initialize its values (length and breadth of the rectangle).
    def __init__(self, rectbreadth, rectlength):
        self.rectbreadth = rectbreadth
        self.rectlength = rectlength
    # Creating a method called areaofRect that returns the area with the given length and breadth of the rectangle

    def areaofRect(self):
        return self.rectbreadth*self.rectlength


# Give the length and breadth as static input and store it in two variables.
rectlength = 31
rectbreadth = 19
# Creating an object to represent the class.
# Call the method areaofRect() on the object with the length and breadth as the parameters taken from the user as static input.
rectObj = rectangle(rectlength, rectbreadth)
print("The area of the rectangle with the given sides",
      rectlength, ',', rectbreadth, '=', rectObj.areaofRect())

Output:

The area of the rectangle with the given sides 31 , 19 = 589

2)Using Classes(User Input separated by spaces)

Approach:

  • Scan the given length and breadth as user input using a map, int, and split() functions and store them in two variables.
  • Create a class and use a parameterized constructor to initialize its values (length and breadth of the rectangle).
  • Create a method called areaofRect that returns the area with the given length and breadth of the rectangle.
  • Create an object to represent the class.
  • Call the method areaofRect() on the object with the length and breadth as the parameters taken from the user as static input.
  • Print the area of the rectangle.
  • The exit of the program.

Below is the implementation:

# creating a class
class rectangle():
  # parameterized constructor with breadth and length as arguments
  # parameterized constructor is used to initialize its values (length and breadth of the rectangle).
    def __init__(self, rectbreadth, rectlength):
        self.rectbreadth = rectbreadth
        self.rectlength = rectlength
    # Creating a method called areaofRect that returns the area with the given length and breadth of the rectangle

    def areaofRect(self):
        return self.rectbreadth*self.rectlength


# Scan the given length and breadth as user input using a map, int, 
#and split() functions and store them in two variables.
rectlength, rectbreadth = map(int, input('Enter the length and breadth of the rectangle separated by spaces = ').split())
# Creating an object to represent the class.
# Call the method areaofRect() on the object with the length and breadth as the parameters taken from the user as static input.
rectObj=rectangle(rectlength, rectbreadth)
print("The area of the rectangle with the given sides",
      rectlength, ',', rectbreadth, '=', rectObj.areaofRect())

Output:

Enter the length and breadth of the rectangle separated by spaces = 7 9
The area of the rectangle with the given sides 7 , 9 = 63

Explanation:

  • The user must provide the length and breadth values.
  • A rectangle class is created, and the __init__() method is used to initialize the class’s values.
  • The area method returns self. length*self. breadth, which is the class’s area.
  • The class’s object is created.
  • Using the object, the method area() is invoked with the length and breadth as the parameters given by the user.
  • The area has been printed.

3)Using Classes(User Input separated by newline)

Approach:

  • Scan the rectangle’s length as user input using the int(input()) function and store it in a  variable.
  • Scan the rectangle’s breadth as user input using the int(input()) function and store it in another variable.
  • Here int() is used to convert the given number to integer datatype.
  • Create a class and use a parameterized constructor to initialize its values (length and breadth of the rectangle).
  • Create a method called areaofRect that returns the area with the given length and breadth of the rectangle.
  • Create an object to represent the class.
  • Call the method areaofRect() on the object with the length and breadth as the parameters taken from the user as static input.
  • Print the area of the rectangle.
  • The exit of the program.

Below is the implementation:

# creating a class
class rectangle():
  # parameterized constructor with breadth and length as arguments
  # parameterized constructor is used to initialize its values (length and breadth of the rectangle).
    def __init__(self, rectbreadth, rectlength):
        self.rectbreadth = rectbreadth
        self.rectlength = rectlength
    # Creating a method called areaofRect that returns the area with the given length and breadth of the rectangle

    def areaofRect(self):
        return self.rectbreadth*self.rectlength


# Scan the rectangle's length as user input using the int(input()) function and store it in a  variable.
rectlength = int(input('Enter some random length of the rectangle = '))
# Scan the rectangle's breadth as user input using the int(input()) function and store it in another variable.
# Here int() is used to convert the given number to integer datatype.
rectbreadth = int(input('Enter some random breadth of the rectangle = '))
# Creating an object to represent the class.
# Call the method areaofRect() on the object with the length and breadth as the parameters taken from the user as static input.
rectObj = rectangle(rectlength, rectbreadth)
print("The area of the rectangle with the given sides",
      rectlength, ',', rectbreadth, '=', rectObj.areaofRect())

Output:

Enter some random length of the rectangle = 15
Enter some random breadth of the rectangle = 11
The area of the rectangle with the given sides 15 , 11 = 165

Explanation:

  • The user must provide the length and breadth values.
  • A rectangle class is created, and the __init__() method is used to initialize the class’s values.
  • The area method returns self. length*self. breadth, which is the class’s area.
  • The class’s object is created.
  • Using the object, the method area() is invoked with the length and breadth as the parameters given by the user.
  • The area has been printed.

Related Programs:

Python Program to Find the Area of a Rectangle Using Classes Read More »

Python Program to Print All Permutations of a String in Lexicographic Order without Recursion

Python Program to Print All Permutations of a String in Lexicographic Order without Recursion

Strings in Python:

Strings are simple text in programming, which might be individual letters, words, phrases, or whole sentences. Python strings have powerful text-processing capabilities, such as searching and replacing characters, cutting characters, and changing case. Empty strings are written as two quotations separated by a space. Single or double quotation marks may be used. Three quote characters can be used to easily build multi-line strings.

Given a string ,the task is to print all the permutations of the given string in lexicographic order without using recursion in Python.

Examples:

Example1:

Input:

given string ='hug'

Output:

printing all [ hug ] permutations :
hug
ugh
uhg
ghu
guh
hgu

Example2:

Input:

given string ='tork'

Output:

printing all [ tork ] permutations :
tork
trko
trok
kort
kotr
krot
krto
ktor
ktro
okrt
oktr
orkt
ortk
otkr
otrk
rkot
rkto
rokt
rotk
rtko
rtok
tkor
tkro
tokr

Program to Print All Permutations of a String in Lexicographic Order without Recursion

Below are the ways to Print All string permutations without recursion in lexicographic order:

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

1)Using for and while Loops(Static Input)

Approach:

  • Give the string as static input.
  • The algorithm works by first generating a loop that will run n! times, where n is the length of the string.
  • Each loop iteration produces the string and looks for its next variant to print in the following iteration.
  • The following is the next higher permutation.
  • If we call our sequence seq, we identify the least index p such that all entries in seq[p…end] are in decreasing order.
  • If seq[p…end] represents the whole sequence, i.e. p == 0, then seq is the highest permutation. So we simply reverse the entire string to find the shortest permutation, which we regard to be the next permutation.
  • If p > 0, we reverse seq[p…end].

Below is the implementation:

from math import factorial


def printPermutationsLexico(string):
    # In lexicographic sequence, print all permutations of string s.
    stringseq = list(string)

    # There will be n! permutations where n = len (seq).
    for t in range(factorial(len(stringseq))):
        # print permutation by joining all the characters using join() function
        print(''.join(stringseq))

        # Find p such that seq[per:] is the longest sequence with lexicographic
        # elements in decreasing order.
        per = len(stringseq) - 1
        while per > 0 and stringseq[per - 1] > stringseq[per]:
            per -= 1

        # reverse the stringsequence from per to end using reversed function
        stringseq[per:] = reversed(stringseq[per:])

        if per > 0:
            # Find q such that seq[q] is the smallest element in seq[per:] and seq[q] is greater
            # than seq[p - 1].Find q such that seq[q] is the smallest
            # element in seq[per:] and seq[q] is greater than seq[per - 1].
            q = per
            while stringseq[per - 1] > stringseq[q]:
                q += 1

            # swapping seq[per - 1] and seq[q]
            stringseq[per - 1], stringseq[q] = stringseq[q], stringseq[per - 1]


# given string as static input
given_string = 'hug'
# printing  all the perumutations
print('printing all [', given_string, '] permutations :')
# passing given string to printPermutationsLexico function
printPermutationsLexico(given_string)

Output:

printing all [ hug ] permutations :
hug
ugh
uhg
ghu
guh
hgu

Explanation:

  • User must give string input as static .
  • On the string, the method printPermutationsLexico is called.
  • The function then prints the string’s permutations in lexicographic order.

2)Using for and while Loops(User Input)

Approach:

  • Enter some random string as user input using int(input()) function.
  • The algorithm works by first generating a loop that will run n! times, where n is the length of the string.
  • Each loop iteration produces the string and looks for its next variant to print in the following iteration.
  • The following is the next higher permutation.
  • If we call our sequence seq, we identify the least index p such that all entries in seq[p…end] are in decreasing order.
  • If seq[p…end] represents the whole sequence, i.e. p == 0, then seq is the highest permutation. So we simply reverse the entire string to find the shortest permutation, which we regard to be the next permutation.
  • If p > 0, we reverse seq[p…end].

Below is the implementation:

from math import factorial


def printPermutationsLexico(string):
    # In lexicographic sequence, print all permutations of string s.
    stringseq = list(string)

    # There will be n! permutations where n = len (seq).
    for t in range(factorial(len(stringseq))):
        # print permutation by joining all the characters using join() function
        print(''.join(stringseq))

        # Find p such that seq[per:] is the longest sequence with lexicographic
        # elements in decreasing order.
        per = len(stringseq) - 1
        while per > 0 and stringseq[per - 1] > stringseq[per]:
            per -= 1

        # reverse the stringsequence from per to end using reversed function
        stringseq[per:] = reversed(stringseq[per:])

        if per > 0:
            # Find q such that seq[q] is the smallest element in seq[per:] and seq[q] is greater
            # than seq[p - 1].Find q such that seq[q] is the smallest
            # element in seq[per:] and seq[q] is greater than seq[per - 1].
            q = per
            while stringseq[per - 1] > stringseq[q]:
                q += 1

            # swapping seq[per - 1] and seq[q]
            stringseq[per - 1], stringseq[q] = stringseq[q], stringseq[per - 1]


# Enter some random string as user input using int(input()) function.
given_string =input('Enter some random string = ')
# printing  all the perumutations
print('printing all [', given_string, '] permutations :')
# passing given string to printPermutationsLexico function
printPermutationsLexico(given_string)

Output:

Enter some random string = epic
printing all [ epic ] permutations :
epic
icep
icpe
iecp
iepc
ipce
ipec
pcei
pcie
peci
peic
pice
piec
ceip
cepi
ciep
cipe
cpei
cpie
ecip
ecpi
eicp
eipc
epci

Related Programs:

Python Program to Print All Permutations of a String in Lexicographic Order without Recursion Read More »

Program to Iterate Through Two Lists in Parallel

Python Program to Iterate Through Two Lists in Parallel

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.

List:

A list in Python is a collection of zero or more elements. A list element can be any type of data. It can be a string, a number, or a mixture of the two. In Python, a list is equivalent to an array in C or Java. Lists are mutable, which means you may change their content, and they contain a variety of helpful specialized methods.

When working with Python lists, we may encounter an issue in which we must iterate over two list entries. Iterating one after the other is an option, but it is more time consuming, and a one-two liner is always preferred. Let’s go over several different approaches to doing this assignment.

Given two lists, the task is to iterate two lists simultaneously.

Examples:

Printing list one after other:

Example1:

Input:

samplelistone = ["hello", "this", "is", "BTechGeeks", "Python"]
samplelisttwo = [38, 23, 10, 20]

Output:

printing the samplelistone  hello this is BTechGeeks Python
printing the samplelisttwo  38 23 10 20
printing the two lists elements simultaneously 
hello this is BTechGeeks Python 38 23 10 20

Example2:

Input:

samplelistone = [27823, 9792, "hello", "this", True, 7.6]
samplelisttwo = ['sky', 'is', 'blue', 122, 5.3214, False, 'hello']

Output:

printing the samplelistone  27823 9792 hello this True 7.6
printing the samplelisttwo  sky is blue 122 5.3214 False hello
printing the two lists elements simultaneously 
27823 9792 hello this True 7.6 sky is blue 122 5.3214 False hello

Printing list in parallel:

Example1:

Input:

samplelistone = ["hello", "this", "is", "BTechGeeks", "Python"]
samplelisttwo = [38, 23, 10, 20, 31]

Output:

printing the samplelistone  hello this is BTechGeeks Python
printing the samplelisttwo  38 23 10 20 31
printing the two lists elements simultaneously 
hello 38
this 23
is 10
BTechGeeks 20
Python 31

Example2:

Input:

samplelistone = [27823, 9792, "hello", "this", True, 7.6]
samplelisttwo = ['sky', 'is', 'blue', 122, 5.3214, False, 'hello']

Output:

printing the samplelistone  27823 9792 hello this True 7.6
printing the samplelisttwo  sky is blue 122 5.3214 False hello
printing the two lists elements simultaneously 
27823 sky
9792 is
hello blue
this 122
True 5.3214
7.6 False

Program to Iterate Through Two Lists in Parallel in Python

Below are the ways to iterate through two lists in parallel in python:

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 for loop and “+” operator

The combination of the above functionalities may make our job easier. The disadvantage here is that we may have to concatenate the list, which would require more RAM than desired.

Below is the implementation:

# initializing lists
samplelistone = ["hello", "this", "is", "BTechGeeks", "Python"]
samplelisttwo = [38, 23, 10, 20]
# printing the two original lists
print("printing the samplelistone ", *samplelistone)
print("printing the samplelisttwo ", *samplelisttwo)
# traversing the two lists simulatenously
print("printing the two lists elements simultaneously ")
for value in samplelistone + samplelisttwo:
    print(value, end=" ")

Output:

printing the samplelistone  hello this is BTechGeeks Python
printing the samplelisttwo  38 23 10 20
printing the two lists elements simultaneously 
hello this is BTechGeeks Python 38 23 10 20

Method #2: Using chain() function

This approach is identical to the one before, but it is somewhat more memory efficient because chain() is used to execute the work and internally builds an iterator.

Chain function will be available in itertools.

Below is the implementation:

from itertools import chain
# initializing lists
samplelistone = [27823, 9792, "hello", "this", True, 7.6]
samplelisttwo = ['sky', 'is', 'blue', 122, 5.3214, False, 'hello']
# printing the two original lists
print("printing the samplelistone ", *samplelistone)
print("printing the samplelisttwo ", *samplelisttwo)
# traversing the two lists simulatenously
print("printing the two lists elements simultaneously ")
for value in chain(samplelistone, samplelisttwo):
    print(value, end=" ")

Output:

printing the samplelistone  27823 9792 hello this True 7.6
printing the samplelisttwo  sky is blue 122 5.3214 False hello
printing the two lists elements simultaneously 
27823 9792 hello this True 7.6 sky is blue 122 5.3214 False hello

Method #3:Using zip()

Zip in Python 3 returns an iterator. When any of the lists in the zip() function is exhausted, the function terminates. In other words, it continues until the smallest of all the lists is reached.
The zip method and itertools.izip are implemented below, and itertools.izip iterates over two lists:

Below is the implementation:

import itertools
# initializing lists
samplelistone = [27823, 9792, "hello", "this", True, 7.6]
samplelisttwo = ['sky', 'is', 'blue', 122, 5.3214, False, 'hello']
# printing the two original lists
print("printing the samplelistone ", *samplelistone)
print("printing the samplelisttwo ", *samplelisttwo)
# traversing the two lists simulatenously
print("printing the two lists elements simultaneously ")
for i, j in zip(samplelistone, samplelisttwo):
    print(i, j)

Output:

printing the samplelistone  27823 9792 hello this True 7.6
printing the samplelisttwo  sky is blue 122 5.3214 False hello
printing the two lists elements simultaneously 
27823 sky
9792 is
hello blue
this 122
True 5.3214
7.6 False

Method #4:Using itertools.zip_longest()

When all lists have been exhausted, zip longest comes to a halt. When the shorter iterator(s) have been exhausted, zip longest returns a tuple with the value None.
The itertools implementation is shown below.
zip longest iterates across two lists

Below is the implementation:

import itertools
# initializing lists
samplelistone = [27823, 9792, "hello", "this", True, 7.6]
samplelisttwo = ['sky', 'is', 'blue', 122, 5.3214, False, 'hello']
# printing the two original lists
print("printing the samplelistone ", *samplelistone)
print("printing the samplelisttwo ", *samplelisttwo)
# traversing the two lists simulatenously
print("printing the two lists elements simultaneously ")
for i, j in itertools.zip_longest(samplelistone, samplelisttwo):
    print(i, j)

Output:

printing the samplelistone  27823 9792 hello this True 7.6
printing the samplelisttwo  sky is blue 122 5.3214 False hello
printing the two lists elements simultaneously 
27823 sky
9792 is
hello blue
this 122
True 5.3214
7.6 False
None hello

Related Programs:

Python Program to Iterate Through Two Lists in Parallel Read More »

Program to Find the Gravitational Force Acting Between Two Objects

Python Program to Find the Gravitational Force Acting Between Two Objects

Gravitational Force:

The gravitational force is a force that attracts any two mass-bearing objects. The gravitational force is called attractive because it always strives to pull masses together rather than pushing them apart. In reality, every thing in the cosmos, including you, is tugging on every other item! Newton’s Universal Law of Gravitation is the name for this. You don’t have a significant mass, thus you’re not dragging on those other objects very much. Objects that are extremely far apart do not noticeably pull on each other either. However, the force exists and can be calculated.

Gravitational Force Formula :

Gravitational Force = ( G *  m1 * m2 ) / ( r ** 2 )

Given masses of two objects and the radius , the task is to calculate the Gravitational Force acting between the given two particles in Python.

Examples:

Example1:

Input:

mass1 = 1300012.67
mass2 = 303213455.953
radius = 45.4

Output:

The gravitational force of objects with masses 1300012.67 kg 303213455.953 kg  of radius= 45.4 = 12.761610184592419

Example2:

Input:

Enter the first mass of the object =2491855.892 
Enter the second mass of the object =9000872 
Enter the distance/radius between the objects =50

Output:

The gravitational force of objects with masses 24918552.892 kg 23145689000872.0 kg of radius= 50.0 = 15394799.86164859

Program to Find the Gravitational Force Acting Between Two Objects in Python

We will write the code which calculates the gravitational force acting between the particles and print it

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)Calculating the Gravitational Force  (Static Input)

Approach:

  • Take both the masses and the distance between the masses and store them in different variables  or give input as static
  • One of the variables should be set to the value of the gravitational constant, G.
  • The formula is used to calculate the force between the masses.
  • Print the force value, rounded up to two decimal places.
  • Exit the program.

Below is the implementation:

# given first mass
mass1 = 1300012.67
# given second mass
mass2 = 303213455.953
# enter the radius
radius = 45.4
# Given value of Gravitational Constant Gval
Gval = 6.673*(10**(-11))
# Calculating the value of the gravitational force Gforce
Gforce = (Gval*mass1*mass2)/(radius**2)
# printing the value of gravitational force
print("The gravitational force of objects with masses", str(mass1) +
      " kg "+str(mass2)+" kg ", "of radius=", radius, "=", Gforce)

Output:

The gravitational force of objects with masses 1300012.67 kg 303213455.953 kg  of radius= 45.4 = 12.761610184592419

2)Calculating the Gravitational Force  (User Input)

Approach:

  • Scan the masses and radius as a floating data type and store in different variables
  • One of the variables should be set to the value of the gravitational constant, G.
  • The formula is used to calculate the force between the masses.
  • Print the force value, rounded up to two decimal places.
  • Exit the program.

Below is the implementation:

# scanning  first mass as float
mass1 = float(input("Enter the first mass of the object ="))
# given second mass as float
mass2 = float(input("Enter the second mass of the object ="))
# enter the radius as float
radius = float(input("Enter the distance/radius between the objects ="))
# Given value of Gravitational Constant Gval
Gval = 6.673*(10**(-11))
# Calculating the value of the gravitational force Gforce
Gforce = (Gval*mass1*mass2)/(radius**2)
# printing the value of gravitational force
print("The gravitational force of objects with masses", str(mass1) +
      " kg "+str(mass2)+" kg ", "of radius=", radius, "=", Gforce)

Output:

Enter the first mass of the object =2491855.892
Enter the second mass of the object =9000872
Enter the distance/radius between the objects =50
The gravitational force of objects with masses 24918552.892 kg 23145689000872.0 kg of radius= 50.0 = 15394799.86164859

Related Programs:

Python Program to Find the Gravitational Force Acting Between Two Objects Read More »

Calculate the Area, Semi Perimeter and Perimeter of a Triangle

Python Program to Calculate the Area, Semi Perimeter and Perimeter of a Triangle

Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

With an example, learn how to construct a Python program to find the Area of a Triangle, Perimeter of a Triangle, and Semi-Perimeter of a Triangle. Let’s look at the definitions and mathematics underlying Perimeter and Area of a Triangle before diving into the Python program to find Area of a Triangle.

Area of Triangle:

If we know the lengths of the three sides of a triangle, we can use Heron’s Formula to compute the area of the triangle.

Triangle Area = √((s*(s-a)*(s-b)*(s-c)))

Where

s = (a + b + c )/ 2

(Here s = semi perimeter and a, b, c are the three sides of a given_triangle)

Perimeter of a Triangle = a + b + c

Examples:

Example 1:

Input:

a = 24
b = 12
c = 22

Output:

The semiperimeter of the triangle with the sides 24 12 22 = 29.0
The perimeter of the triangle with the sides 24 12 22 = 58
The area of the triangle with the sides 24 12 22 =131.358

Example 2:

Input:

a = 5.6
b = 2.7
c = 7.9

Output:

The semiperimeter of the triangle with the sides 5.6 2.7 7.9 =8.100
The perimeter of the triangle with the sides 5.6 2.7 7.9 =16.200
The area of the triangle with the sides 5.6 2.7 7.9 =4.677

Program to Calculate the Area, Semi Perimeter and Perimeter of a Triangle

Let us calculate the area, semi perimeter and perimeter of Triangle in Python:

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)Calculating Semi Perimeter of the given triangle

We can calculate semi perimeter using the formula

s=(a+b+c)/2 where a , b ,c are sides of the triangle

Below is the implementation:

# given sides of the triangle
a = 24
b = 12
c = 22

# calculating the semi perimeter of the given triangle by using the formula
semi_perimeter = (a + b + c) / 2
# print semi_perimeter
print("The semiperimeter of the triangle with the sides", a, b, c, "=", semi_perimeter)

Output:

The semiperimeter of the triangle with the sides 24 12 22 = 29.0

2)Calculating Perimeter of the given triangle

We can calculate perimeter using the formula

perimeter=(a+b+c) where a , b ,c are sides of the triangle

Below is the implementation:

# given sides of the triangle
a = 24
b = 12
c = 22

# calculating the  perimeter of the given triangle by using the formula
perimetr = (a + b + c)
# print perimeter
print("The perimeter of the triangle with the sides", a, b, c, "=", perimetr)

Output:

The perimeter of the triangle with the sides 24 12 22 = 58

3)Calculating Area of Triangle

When three sides are specified in this program, the area of the triangle will be determined using Heron’s formula.

If you need to calculate the area of a triangle based on user input, you can utilize the input() function.

Approach:

  • Scan the sides of the given triangle.
  • The semi-perimeter will be calculated using Heron’s formula.
  • To determine the area of the triangle, use Area = (s*(s-a)*(s-b)*(s-c)) ** 0.5.
  • Finally, print the triangle’s area

Below is the implementation:

# given sides of the triangle
a = 24
b = 12
c = 22

# calculating the  semiperimeter of the given triangle by using the formula
s = (a + b + c)/2
# calculating area of triangle with given sides
triangleArea = (s*(s-a)*(s-b)*(s-c)) ** 0.5
# print the area of thee triangle
print("The area of the triangle with the sides",
      a, b, c, "=%0.3f" % triangleArea)

Output:

The area of the triangle with the sides 24 12 22 =131.358

Related Programs:

Python Program to Calculate the Area, Semi Perimeter and Perimeter of a Triangle Read More »

Program to Calculate Area of any Triangle using its Coordinates

Python Program to Calculate Area of any Triangle using its Coordinates

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

GIven three coordinates of a triangle the task is to find the area of the given Triangle in Python.

Examples:

Example1:

Input:

x coordinate of the first point = 6
y coordinate of the first point = 2
x coordinate of the second point = 9
y coordinate of the first point = 11
x coordinate of the third point = 5
y coordinate of the first point = 17

Output:

The Area of the triangle with the given coordinates  (6,2) (9,11) (5,17) = 27.0

Example2:

Input:

x coordinate of the first point = 3
y coordinate of the first point = 7
x coordinate of the second point = 2
y coordinate of the first point = 11
x coordinate of the third point = 9
y coordinate of the first point = 7

Output:

The Area of the triangle with the given cordinates (3,7) (2,11) (9,7) = 12.0

Program to Calculate Area of any Triangle using its Coordinates in

Python

Below are the ways to calculate to find the area of the given Triangle in Python.

Let’s look for the formula before we start coding in Python.

Let the coordinates of a triangle be A(x1, y1), B(x2, y2), and C(x3, y3). Using the Mathematical formula, we can compute the area of triangle ABC.

Area of Triangle = |(1/2)*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2))|

Calculating the Area without considering the modulus may result in a negative value. We only take the magnitude by applying modulus to the expression because Area cannot be negative.

In the program, we utilize the abs() method to get the absolute value or magnitude.

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Give the 3 coordinates as static input and store them in 6 separate variables.
  • Apply the given mathematical formula for the above coordinates.
  • Calculate the absolute value of the area of the triangle using the abs() function.
  • If the value of Area is zero, we can state that the input coordinates cannot be used to build a triangle.
  • Check whether the given area of the triangle is 0 using the If statement.
  • If it is true then the print Triangle cannot be formed using the given coordinates.
  • The Exit of the Program.

Below is the implementation:

# Give the 3 coordinates as static input and store them in 6 separate variables.
xcor1 = 3
ycor1 = 7
xcor2 = 2
ycor2 = 11
xcor3 = 9
ycor3 = 7
# Apply the given mathematical formula for the above coordinates.
# Calculate the absolute value of the area of the triangle using the abs() function.
TriangleArea = abs((0.5)*(xcor1*(ycor2-ycor3)+xcor2 *
                          (ycor3-ycor1)+xcor3*(ycor1-ycor2)))
# Check whether the given area of the triangle is 0 using the If statement.
# If it is true then the print Triangle cannot be formed using the given coordinates.
if (TriangleArea == 0):
    print("Triangle cannot be formed using the given coordinates ")
print('The Area of the triangle with the given coordinates ('+str(xcor1)+','+str(ycor1) +
      ')' + ' ('+str(xcor2)+','+str(ycor2)+')' + ' ('+str(xcor3)+','+str(ycor3)+')', '=', TriangleArea)

Output:

The Area of the triangle with the given cordinates (3,7) (2,11) (9,7) = 12.0

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Give the 3 coordinates as user input using map(),int(),split() functions.
  • Store them in 6 separate variables.
  • Apply the given mathematical formula for the above coordinates.
  • Calculate the absolute value of the area of the triangle using the abs() function.
  • If the value of Area is zero, we can state that the input coordinates cannot be used to build a triangle.
  • Check whether the given area of the triangle is 0 using the If statement.
  • If it is true then the print Triangle cannot be formed using the given coordinates.
  • The Exit of the Program.

Below is the implementation:

# Give the 3 coordinates as user input using map(),int(),split() functions.
# Store them in 6 separate variables.
xcor1 = int(input('Enter some random x coordinate of the first point = '))
ycor1 = int(input('Enter some random y coordinate of the first point = '))
xcor2 = int(input('Enter some random x coordinate of the second point = '))
ycor2 = int(input('Enter some random y coordinate of the first point = '))
xcor3 = int(input('Enter some random x coordinate of the third point = '))
ycor3 = int(input('Enter some random y coordinate of the first point = '))
# Apply the given mathematical formula for the above coordinates.
# Calculate the absolute value of the area of the triangle using the abs() function.
TriangleArea = abs((0.5)*(xcor1*(ycor2-ycor3)+xcor2 *
                          (ycor3-ycor1)+xcor3*(ycor1-ycor2)))
# Check whether the given area of the triangle is 0 using the If statement.
# If it is true then the print Triangle cannot be formed using the given coordinates.
if (TriangleArea == 0):
    print("Triangle cannot be formed using the given coordinates")
print('The Area of the triangle with the given coordinates  ('+str(xcor1)+','+str(ycor1) +
      ')' + ' ('+str(xcor2)+','+str(ycor2)+')' + ' ('+str(xcor3)+','+str(ycor3)+')', '=', TriangleArea)

Output:

Enter some random x coordinate of the first point = 6
Enter some random y coordinate of the first point = 2
Enter some random x coordinate of the second point = 9
Enter some random y coordinate of the first point = 11
Enter some random x coordinate of the third point = 5
Enter some random y coordinate of the first point = 17
The Area of the triangle with the given coordinates  (6,2) (9,11) (5,17) = 27.0

Related Programs:

Python Program to Calculate Area of any Triangle using its Coordinates Read More »

Python Program to Check Whether given Array or List Can Form Arithmetic Progression

Python Program to Check Whether given Array or List Can Form Arithmetic Progression

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

Arithmetic Progression:

Arithmetic Progression (AP) is a numerical series in which the difference between any two consecutive numbers is a constant value. For instance, the natural number sequence: 1, 2, 3, 4, 5, 6,… is an AP with a common difference between two successive terms (say, 1 and 2) equal to 1. (2 -1). Even when dealing with odd and even numbers, we can observe that the common difference between two sequential terms is equal to 2.

Examples:

Example1:

Input:

Given List = [9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69]

Output:

The given list [9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69] is in AP

Example2:

Input:

Given List = [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99, 105]

Output:

The given list [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99, 105] is in AP

Python Program to Check Whether given Array or List Can Form Arithmetic Progression

Below are the ways to Check Whether the given array or list can form the Arithmetic Progression series.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Create a function checkAp() which returns true if the given list is in Arithmetic Progression Else it returns False.
  • Pass the given list as an argument to the checkAp() function.
  • Calculate the length of the given list using the length() function.
  • Inside the Function sort the given list using the built-in sort() function.
  • Now compute the difference between the first two elements of the given list and initialize a new variable commondif with this difference.
  • Traverse the array in reverse order i.e from n-1 to 1 index using For loop.
  • Compare the difference between successive elements.
  • If the difference is not equal to commondif then return False.
  • After the end of For loop return True (This signifies that the given list is in Ap)
  • The Exit of the Program.

Below is the implementation:

# Create a function checkAp() which returns true if the given list
# is in Arithmetic Progression Else it returns False.


def checkAp(gvnlst):
  # Calculate the length of the given list using the length() function.
    lstlen = len(gvnlst)
    # Inside the Function sort the given list using the built-in sort() function.
    gvnlst.sort()
    # Now compute the difference between the first two elements of the given list and
    # initialize a new variable commondif with this difference.
    commondif = gvnlst[1]-gvnlst[0]
    # Traverse the array in reverse order i.e from n-1 to 1 index using For loop.
    for m in range(lstlen-1, 1, -1):
      # Compare the difference between successive elements.

        if(gvnlst[m]-gvnlst[m-1] != commondif):
          # If the difference is not equal to commondif then return False.
            return 0
    # After the end of For loop return True (This signifies that the given list is in Ap)
    return 1


# Give the list as static input and store it in a variable.
givenlist = [9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69]
# Pass the given list as an argument to the checkAp() function.
if(checkAp(givenlist)):
    print('The given list', givenlist, 'is in AP')
else:
    print('The given list', givenlist, 'is not in AP')

Output:

The given list [9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69] is in AP

Method #2: Using For Loop (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Create a function checkAp() which returns true if the given list is in Arithmetic Progression Else it returns False.
  • Pass the given list as an argument to the checkAp() function.
  • Calculate the length of the given list using the length() function.
  • Inside the Function sort the given list using the built-in sort() function.
  • Now compute the difference between the first two elements of the given list and initialize a new variable commondif with this difference.
  • Traverse the array in reverse order i.e from n-1 to 1 index using For loop.
  • Compare the difference between successive elements.
  • If the difference is not equal to commondif then return False.
  • After the end of For loop return True (This signifies that the given list is in Ap)
  • The Exit of the Program.

Below is the implementation:

# Create a function checkAp() which returns true if the given list
# is in Arithmetic Progression Else it returns False.


def checkAp(gvnlst):
  # Calculate the length of the given list using the length() function.
    lstlen = len(gvnlst)
    # Inside the Function sort the given list using the built-in sort() function.
    gvnlst.sort()
    # Now compute the difference between the first two elements of the given list and
    # initialize a new variable commondif with this difference.
    commondif = gvnlst[1]-gvnlst[0]
    # Traverse the array in reverse order i.e from n-1 to 1 index using For loop.
    for m in range(lstlen-1, 1, -1):
      # Compare the difference between successive elements.

        if(gvnlst[m]-gvnlst[m-1] != commondif):
          # If the difference is not equal to commondif then return False.
            return 0
    # After the end of For loop return True (This signifies that the given list is in Ap)
    return 1


# Give the list as user input using list(),map(),input(),and split() functions.
# store it in a variable.
givenlist = list(
    map(int, input('Enter some random List Elements separated by spaces = ').split()))
# Pass the given list as an argument to the checkAp() function.
if(checkAp(givenlist)):
    print('The given list', givenlist, 'is in AP')
else:
    print('The given list', givenlist, 'is not in AP')

Output:

Enter some random List Elements separated by spaces = 3 9 15 21 27 33 39 45 51 57 63 69 75 81 87 93 99 105
The given list [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99, 105] is in AP

Related Programs:

Python Program to Check Whether given Array or List Can Form Arithmetic Progression Read More »

Program to Find the Sum of Sine Series in Python

Python Program to Find the Sum of Sine Series

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Consider the case where we have a value x and we need to determine the sum of the sine(x) series. There are numerous terms in a sine(x) series such that,

sine(x) = x− x^3/fact(3) + x^5/fact(5) −x^7/fact(7).....

To begin solving the specific series-based problem, we will take the degree as input and convert it to radian. To obtain the sum of the entire number of terms in this series, we shall iterate through all of the given terms and obtain the sum by operations.

Given a number x in degrees and number of terms, the task is to print the sum of sine series in  python

Examples:

Example1:

Input:

enter the number of degrees = 55
enter number of terms = 15

Output:

The sum of sine series of 55 degrees of 15 terms = 0.82

Example2:

Input:

enter the number of degrees = 45
enter number of terms = 12

Output:

The sum of sine series of 45 degrees of 12 terms = 0.71

Program to Find the Sum of Sine Series 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)Printing sum of sine series in Python (Static input)

Approach:

  • Give the degree value of x and the number of terms as static and store them in separate variables.
  • As parameters, pass these values to the sine function.
  • Create a sine function and then, using a for loop, convert degrees to radians.
  • Then apply the sine formula expansion to each term and add them to the sum variable.
  • Then print the expansion’s total sum.
  • Exit of program.

Below is the implementation:

# importing math module
import math
# function which returns sum of sine series


def sumsine(degrees, terms):
  # taking a variable which stores sum of sine series
    sumSeries = 0
    for i in range(terms):
      # getting sign
        signofNum = (-1)**i
        # pie value
        pievalue = 22/7
        # degree value of given number
        degval = degrees*(pievalue/180)
        sumSeries = sumSeries + ((degval**(2.0*i+1)) /
                                 math.factorial(2*i+1))*signofNum
     # returning the sum of sine series
    return sumSeries


degrees = 30
terms = 10
print(round(sumsine(degrees, terms), 2))

Output:

The sum of sine series of  30 degrees of 10 terms = 0.5

Explanation:

  • The user must provide the value of x in degrees and the number of terms, which will be saved in separate variables.
  • These values are supplied as arguments to the sine functions.
  • A sine function is built, and a for loop is used to convert degrees to radians and calculate the values of each term using the sine expansion formula.
  • The sum variable is added to each term.
  • This process is repeated until the number of phrases equals the number specified by the user.
  • The total sum of sine series is printed

2)Printing sum of sine series in Python (User input)

Approach:

  • Scan  the degree value of x and the number of terms using int(input())  and store them in separate variables.
  • As parameters, pass these values to the sine function.
  • Create a sine function and then, using a for loop, convert degrees to radians.
  • Then apply the sine formula expansion to each term and add them to the sum variable.
  • Then print the expansion’s total sum.
  • Exit of program.

Below is the implementation:

# importing math module
import math
# function which returns sum of sine series


def sumsine(degrees, terms):
  # taking a variable which stores sum of sine series
    sumSeries = 0
    for i in range(terms):
      # getting sign
        signofNum = (-1)**i
        # pie value
        pievalue = 22/7
        # degree value of given number
        degval = degrees*(pievalue/180)
        sumSeries = sumSeries + ((degval**(2.0*i+1)) /
                                 math.factorial(2*i+1))*signofNum
     # returning the sum of sine series
    return sumSeries


degrees = int(input("enter the number of degrees = "))
terms = int(input("enter number of terms = "))
print("The sum of sine series of ", degrees, "degrees", "of",
      terms, "terms =", round(sumsine(degrees, terms), 2))

Output:

enter the number of degrees = 55
enter number of terms = 15
The sum of sine series of 55 degrees of 15 terms = 0.82

Python Program to Find the Sum of Sine Series Read More »

Python Program to Find the Type of Triangle with Given Sides

Python Program to Find the Type of Triangle with Given Sides

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Given the sides of the triangle, the task is to find the type of triangle with the given sides i.e print the type of triangle acute-angled, obtuse-angled, or right-angled Triangle.

Examples:

Example1:

Input:

Given first side =11
Given second side =6
Given third side =7

Output:

The Triangle with given sides 11 6 7 is Obtuse-angled triangle

Example2:

Input:

Given first side =8
Given second side =6
Given third side =10

Output:

The Triangle with given sides 8 6 10 is Right-angled triangle

Python Program to Find the Type of Triangle with Given Sides

Below are the ways to Find the Type of Triangle with Given Sides in Python.

If c² = a² + b², then the triangle is right-angled.

If c² < a² + b², the triangle is an acute-angle triangle.

If c² > a² + b², the triangle has an obtuse angle.

Method #1:Using If  Else Statement (Static Input)

Approach:

  • Give the three sides of the triangle as static input and store them in three separate variables.
  • Calculate the square of each side of the triangle using the ** operator and store them in three separate variables (squareside1,squareside2,squareside3).
  • Check if squareside1== squareside3+ squareside2, squareside2== squareside1+squareside3,or squareside3== squareside1+squareside2.
  • If it is true then print it as a Right-angled triangle.
  • Print Obtuse-angled triangle if squareside1 > squareside3+ squareside2, squareside2 > squareside1+squareside3, or squareside3 > squareside1+squareside2.
  • Else Print Acute-angled triangle.
  • The Exit of the Program.

Below is the Implementation:

# Give the three sides of the triangle as static input and store them in three separate variables.
side1 = 11
side2 = 6
side3 = 7
# Calculate the square of each side of the triangle using the ** operator and
# store them in three separate variables (squareside1,squareside2,squareside3).
squareside1 = side1**2
squareside2 = side2**2
squareside3 = side3**2
# Check if squareside1== squareside3+ squareside2,
# squareside2== squareside1+squareside3,or squareside3== squareside1+squareside2.
if(squareside1 == (squareside3 + squareside2) or squareside2 == (squareside1+squareside3) or squareside3 == (squareside1+squareside2)):
    # If it is true then print it as a Right-angled triangle.
    print('The Triangle with given sides', side1,
          side2, side3, 'is Right-angled triangle ')
# Print Obtuse-angled triangle if squareside1 > squareside3+ squareside2, squareside2 > squareside1+squareside3, or squareside3 > squareside1+squareside2.
elif(squareside1 > (squareside3 + squareside2) or squareside2 > (squareside1+squareside3) or squareside3 > (squareside1+squareside2)):
    print('The Triangle with given sides', side1,
          side2, side3, 'is Obtuse-angled triangle ')
else:
    # Else Print Acute-angled triangle.
    print('The Triangle with given sides', side1,
          side2, side3, 'is Acute-angled triangle ')

Output:

The Triangle with given sides 11 6 7 is Obtuse-angled triangle

Method #2:Using If  Else Statement (User Input)

Approach:

  • Give the three sides of the triangle as user input using map(),int() and split() functions.
  • Store them in three separate variables.
  • Calculate the square of each side of the triangle using the ** operator and store them in three separate variables (squareside1,squareside2,squareside3).
  • Check if squareside1== squareside3+ squareside2, squareside2== squareside1+squareside3,or squareside3== squareside1+squareside2.
  • If it is true then print it as a Right-angled triangle.
  • Print Obtuse-angled triangle if squareside1 > squareside3+ squareside2, squareside2 > squareside1+squareside3, or squareside3 > squareside1+squareside2.
  • Else Print Acute-angled triangle.
  • The Exit of the Program.

Below is the Implementation:

# Give the three sides of the triangle as user input using map(),int() and split() functions.
side1, side2, side3 = map(int, input(
    'Enter some random three sides of the triangle ').split())
# Calculate the square of each side of the triangle using the ** operator and
# store them in three separate variables (squareside1,squareside2,squareside3).
squareside1 = side1**2
squareside2 = side2**2
squareside3 = side3**2
# Check if squareside1== squareside3+ squareside2,
# squareside2== squareside1+squareside3,or squareside3== squareside1+squareside2.
if(squareside1 == (squareside3 + squareside2) or squareside2 == (squareside1+squareside3) or squareside3 == (squareside1+squareside2)):
    # If it is true then print it as a Right-angled triangle.
    print('The Triangle with given sides', side1,
          side2, side3, 'is Right-angled triangle ')
# Print Obtuse-angled triangle if squareside1 > squareside3+ squareside2, squareside2 > squareside1+squareside3, or squareside3 > squareside1+squareside2.
elif(squareside1 > (squareside3 + squareside2) or squareside2 > (squareside1+squareside3) or squareside3 > (squareside1+squareside2)):
    print('The Triangle with given sides', side1,
          side2, side3, 'is Obtuse-angled triangle ')
else:
    # Else Print Acute-angled triangle.
    print('The Triangle with given sides', side1,
          side2, side3, 'is Acute-angled triangle ')

Output:

Enter some random three sides of the triangle 8 6 10
The Triangle with given sides 8 6 10 is Right-angled triangle

Related Programs:

Python Program to Find the Type of Triangle with Given Sides Read More »

Convert Kilometers to Miles and Vice Versa

Python program to Convert Kilometers to Miles and Vice Versa

Let us begin with the fundamentals, namely understanding the significance of these measuring units. The units of length are the kilometer and the mile.

Examples:

1)km to miles

Input:

distance =6.5 km

Output:

The given distance 6.5 km in miles= 4.038905 miles

2)miles to km 

Input:

distance =6.5 miles

Output:

The given distance 6.5 miles in km= 10.460756071261889 km

Conversion of Kilometers to Miles and Vice Versa

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)Converting kilometers to miles

Formula :

1 kilometer = 0.62137 miles.

As a result, the value 0.62137 can be regarded as the conversion factor or ratio for the conversion to occur.

Algorithm:

  • Define a variable to store the value of the kilo-meter or allow user input.
  • Define and save the value of the conversion factor/ratio in a variable.
  • Create a variable to hold the value of a kilometre converted to a mile. Write the logic for converting kilometres to miles using conversion factor
  • Using the print() function, show the converted value.

Below is the implementation:

# given the distance in km
distkm = 6.5
# conversion ratio
conversion_ratio = 0.62137
# converting the km to miles
distmiles = distkm*conversion_ratio
# print the distance in miles
print("The given distance", distkm, "km", "in miles=", distmiles,"miles")

Output:

The given distance 6.5 km in miles= 4.038905 miles

2)Converting miles to kilometers

Formula :

1 mile= km / 0.62137

As a result, the value 0.62137 can be regarded as the conversion factor or ratio for the conversion to occur.

Algorithm:

  • Define a variable to store the value of the miles or allow user input.
  • Define and save the value of the conversion factor/ratio in a variable.
  • Create a variable to hold the value of a miles converted to a kilometer. Write the logic for converting miles to kilometer using conversion factor
  • Using the print() function, show the converted value.

Below is the implementation:

# given the distance in miles
distmiles = 6.5
# conversion ratio
conversion_ratio = 0.62137
# converting the miles to  km
distkm = distmiles/conversion_ratio
# print the distance in km
print("The given distance", distmiles, "miles", "in km=", distkm, "km")

Output:

The given distance 6.5 miles in km= 10.460756071261889 km

Related Programs:

Python program to Convert Kilometers to Miles and Vice Versa Read More »