Python tan function – Python Program to Get Tangent value Using math.tan()

Program to Get Tangent value Using math.tan()

Python tan function: In the previous article, we have discussed Python Program to Reverse each Word in a Sentence
Math Module :

Python’s math module is a built-in module. By importing this module, we can perform mathematical computations.

Numerous mathematical operations like ceil( ),floor( ),factorial( ),mod( ),value of pi ,…..etc .can be computed with the help of math module.

math.tan() Function in Python:

Using this function, we can quickly find the tangent value for a given angle.

Tan is a trigonometric function that represents the Tangent function.
Its value can be calculated by dividing the length of the opposite side by the length of the adjacent side of a right-angled triangle, as we learned in math.

By importing the math module that contains the definition, we will be able to use the tan() function in Python to obtain the tangent value for any given angle.

Examples:

Example1:

Input:

Given lower limit range =0
Given upper limit range =181
Given step size =30

Output:

The Tangent values in a given range are tan( 0 ) =  0.0
The Tangent values in a given range are tan( 30 ) =  0.5773502691896257
The Tangent values in a given range are tan( 60 ) =  1.7320508075688767
The Tangent values in a given range are tan( 90 ) =  1.633123935319537e+16
The Tangent values in a given range are tan( 120 ) =  -1.7320508075688783
The Tangent values in a given range are tan( 150 ) =  -0.5773502691896257
The Tangent values in a given range are tan( 180 ) =  -1.2246467991473532e-16

Example 2:

Input:

Given lower limit range = 40
Given upper limit range = 300
Given step size = 45

Output:

The Tangent values in a given range are tan( 40 ) =  0.8390996311772799
The Tangent values in a given range are tan( 85 ) =  11.430052302761348
The Tangent values in a given range are tan( 130 ) =  -1.19175359259421
The Tangent values in a given range are tan( 175 ) =  -0.08748866352592402
The Tangent values in a given range are tan( 220 ) =  0.8390996311772799
The Tangent values in a given range are tan( 265 ) =  11.430052302761332

Program to Get Tangent value using math.tan()

Below are the ways to Get Tangent value.

Method #1: Using math Module (Static input)

Approach:

  • Import math module using the import keyword.
  • Give the lower limit range as static input and store it in a variable.
  • Give the upper limit range as static input and store it in another variable.
  • Give the step size as static input and store it in another variable.
  • Loop from lower limit range to upper limit range using For loop.
  • Get the angle value in radians from the given range(converting from degree to radians ) and store it in a variable.
  • Calculate the Tangent value in a given range for the above-obtained radian values using math.tan() function and store it in another variable.
  • print the Tangent Values in the above-given range.
  • The Exit of the program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the lower limit range as static input and store it in a variable.
lwer_lmt = 0
# Give the upper limit range as static input and store it in another variable.
upp_lmt = 181
# Give the step size as static input and store it in another variable.
stp_sze = 30
# Loop from lower limit range to upper limit range using For loop.
for vale in range(lwer_lmt, upp_lmt, stp_sze):
  # Get the angle value in radians from the given range(converting from degree to radians )
  # and store it in a variable.
    radns = math.radians(vale)
    # Calculate the Tangent value in a given range of above obtained radian values using
    # tan()function and store it in another variable.
    tangt = math.tan(radns)
    # print the Tangent Values in the above given range.
    print("The Tangent values in a given range are tan(", vale, ') = ', tangt)

Output:

The Tangent values in a given range are tan( 0 ) =  0.0
The Tangent values in a given range are tan( 30 ) =  0.5773502691896257
The Tangent values in a given range are tan( 60 ) =  1.7320508075688767
The Tangent values in a given range are tan( 90 ) =  1.633123935319537e+16
The Tangent values in a given range are tan( 120 ) =  -1.7320508075688783
The Tangent values in a given range are tan( 150 ) =  -0.5773502691896257
The Tangent values in a given range are tan( 180 ) =  -1.2246467991473532e-16

Method #2: Using math Module (User input)

Approach:

  • Import math module using the import keyword.
  • Give the lower limit range as User input using the int(input(()) function and store it in a variable.
  • Give the upper limit range as User input using the int(input(()) function and store it in another variable.
  • Give the step size as User input and store it in another variable.
  • Loop from lower limit range to upper limit range using For loop.
  • Get the angle value in radians from the given range(converting from degree to radians ) and store it in a variable.
  • Calculate the Tangent value in a given range of the above-obtained radian values using the tan()function and store it in another variable.
  • print the Tangent Values in the above-given range.
  • The Exit of the program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the lower limit range as User input using the int(input(()) function and store it in a variable.
lwer_lmt = int(input('Enter some Random number ='))
# Give the upper limit range as User input using the int(input(()) function and store it in another variable.
upp_lmt = int(input('Enter some Random number ='))
# Give the step size as User input and store it in another variable.
stp_sze = int(input('Enter some Random number ='))
# Loop from lower limit range to upper limit range using For loop.
for vale in range(lwer_lmt, upp_lmt, stp_sze):
  # Get the angle value in radians from the given range(converting from degree to radians )
  # and store it in a variable.
    radns = math.radians(vale)
    # Calculate the Tangent value in a given range of above obtained radian values using
    # tan()function and store it in another variable.
    tangt = math.tan(radns)
    # print the Tangent Values in the above given range.
    print("The Tangent values in a given range are tan(", vale, ') = ', tangt)

Output:

Enter some Random number = 40
Enter some Random number = 300
Enter some Random number = 45
The Tangent values in a given range are tan( 40 ) = 0.8390996311772799
The Tangent values in a given range are tan( 85 ) = 11.430052302761348
The Tangent values in a given range are tan( 130 ) = -1.19175359259421
The Tangent values in a given range are tan( 175 ) = -0.08748866352592402
The Tangent values in a given range are tan( 220 ) = 0.8390996311772799
The Tangent values in a given range are tan( 265 ) = 11.430052302761332

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.

 

Python pick random element from list – Python Program to Select a Random Element from a Tuple

Program to Select a Random Element from a Tuple

Python pick random element from list: In the previous article, we have discussed Python Program to Get n Random Items from a List
Random Module in python :

Get random element from list python: As this Random module is one of Python’s predefined modules, its methods return random values.

It selects integers uniformly from a range. For sequences, it has a function to generate a random permutation of a list in-place, as well as a function to generate a random sampling without replacement. Let’s take a look at how to import the Random Module.

The random module in Python is made up of various built-in Methods.

choice():  choice() is used to select an item at random from a list, tuple, or other collection.

Because the choice() method returns a single element, we will be using  it in looping statements.
sample(): To meet our needs, we’ll use sample() to select multiple values.

Examples:

Example1:

Input:

Given no of random numbers to be generated = 3
Given tuple = ("btechgeeks", 321, "good morning", [7, 8, 5, 33], 35.8)

Output:

Example 2:

Input:

Given no of random numbers to be generated = 4
Given tuple = (255, "hello", "btechgeeks", 150,"good morning", [1, 2, 3, 4], 100, 98)

Output:

The given 4 Random numbers are :
[1, 2, 3, 4]
255
255
98

Program to Select a Random Element from a Tuple

Python select random element from list: Below are the ways to select a random element from a given Tuple.

Method #1: Using random.choice() Method (Only one element)

Approach:

  • Import random module using the import keyword.
  • Give the tuple as static input and store it in a variable.
  • Apply random. choice() method for the above-given tuple and store it in another variable.
  • Print the random element from the above-given tuple
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the tuple as static input and store it in a variable.
gvn_tupl = (255, "hello", "btechgeeks", 150,
            "good morning", [1, 2, 3, 4], 100, 98)
# Apply random.choice() method for the above given tuple and store it in another variable.
reslt = random.choice(gvn_tupl)
# Print the random element from the above given tuple
print("The random element from the above given tuple = ", reslt)

Output:

The random element from the above given tuple =  btechgeeks

Method #2: Using For Loop (N elements)

Approach:

  • Import random module using the import keyword.
  • Give the number as static input and store it in a variable.
  • Give the tuple as static input and store it in another variable.
  • Loop in the given tuple above given ‘n’ number of times using For loop.
  • Inside the loop, apply random.choice() method for the above-given tuple and store it in a variable.
  • Print the given number of random elements to be generated from the given tuple.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number as static input and store it in a variable.
randm_numbrs = 3
# Give the tuple as static input and store it in another variable.
gvn_tupl = ("btechgeeks", 321, "good morning", [7, 8, 5, 33], 35.8)
print("The given", randm_numbrs, "Random numbers are :")
# Loop in the given tuple above given 'n' number of times using For loop.
for itr in range(randm_numbrs):
  # Inside the loop, apply random.choice() method for the above given tuple and
  # store it in a variable.
    reslt = random.choice(gvn_tupl)
   # Print the given numbers of random elements to be generated.
    print(reslt)

Output:

The given 3 Random numbers are :
btechgeeks
[7, 8, 5, 33]
321

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.

 

Union of sets python – Python Program to Union of Set of Tuples

Python Program to Union of Set of Tuples

Union of sets python: In this tutorial, we will learn how to calculate the union of sets of tuples in Python. Let us begin by defining the union in set theory.
The set of every element in the collection of sets is the set of the union of sets. In the case of duplicate elements in different sets, the final union will only contain the specific element once. The letter ‘U’ represents the union.
This problem is centered on finding the union of sets of tuples, which indicates that the set is made up of tuple elements.

Examples:

Example1:

Input:

first = {('hello', 5), ('this', 100)}
second = {('this', 100), ('is', 200)}
third = {('hello', 5), ('btechgeeks', 461), ('python', 234)}

Output:

first Union Second =  {('is', 200), ('this', 100), ('hello', 5)}
Second Union third =  {('python', 234), ('is', 200), ('this', 100), ('hello', 5), ('btechgeeks', 461)}
first Union Second Union third =  {('python', 234), ('is', 200), ('this', 100), ('hello', 5), ('btechgeeks', 461)}

Program to Union of Set of Tuples in Python

Below are the ways to find the union of the set of tuples in Python.

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Method #1: Using  or( | ) operator

Approach:

  • Give the set of tuples as static input and store them in Separate Variables.
  • In Python, we may retrieve the union of a set of tuples by using the OR operator (|). In order to acquire the union of two variables, use the OR operator directly between them.
  • Calculate the union using | operator and store it in a variable.
  • Print the union.
  • The Exit of the Program.

Below is the implementation:

# Give the set of tuples as static input and store them in Separate Variables.
first = {('hello', 5), ('this', 100)}
second = {('this', 100), ('is', 200)}
third = {('hello', 5), ('btechgeeks', 461), ('python', 234)}

# In Python, we may retrieve the union of a set of tuples
# by using the OR operator (|). In order to acquire the union of two variables,
# use the OR operator directly between them.
# Calculate the union using | operator and store it in a variable.

reslt1 = second | third
reslt2 = first | second
reslt3 = first | second | third
# Print the union of first and second
print("first Union Second = ", reslt2)
# print the union of second and third
print("Second Union third = ", reslt1)
# print the union of first second and third.
print("first Union Second Union third = ", reslt3)

Output:

first Union Second =  {('this', 100), ('is', 200), ('hello', 5)}
Second Union third =  {('this', 100), ('hello', 5), ('btechgeeks', 461), ('python', 234), ('is', 200)}
first Union Second Union third =  {('this', 100), ('hello', 5), ('btechgeeks', 461), ('python', 234), ('is', 200)}

Method #2: Using union() method

Approach:

  • Give the set of tuples as static input and store them in Separate Variables.
  • The set union() method returns the union of the set variables supplied as parameters. The first set uses the dot operator (.) to call the union() method, and the other set variables are given as arguments.
  • Calculate the union using the union() method and store it in a variable.
  • Print the union.
  • The Exit of the Program.

Below is the implementation:

# Give the set of tuples as static input and store them in Separate Variables.
first = {('hello', 5), ('this', 100)}
second = {('this', 100), ('is', 200)}
third = {('hello', 5), ('btechgeeks', 461), ('python', 234)}

'''The set union() method returns the union of the set variables supplied as parameters.
The first set uses the dot operator (.) to call the union() method, and 
the other set variables are given as arguments.
Calculate the union using the union() method and store it in a variable.'''
reslt1 = second.union(third)
reslt2 = first.union(second)
reslt3 = first.union(second, third)
# Print the union of first and second
print("first Union Second = ", reslt2)
# print the union of second and third
print("Second Union third = ", reslt1)
# print the union of first second and third.
print("first Union Second Union third = ", reslt3)

Output:

first Union Second =  {('is', 200), ('this', 100), ('hello', 5)}
Second Union third =  {('python', 234), ('is', 200), ('this', 100), ('hello', 5), ('btechgeeks', 461)}
first Union Second Union third =  {('python', 234), ('is', 200), ('this', 100), ('hello', 5), ('btechgeeks', 461)}

Related Programs:

Python string to tuple – Python Program for Comma-separated String to Tuple

Program for Comma-separated String to Tuple

Python string to tuple: In the previous article, we have discussed Python Program to Shuffle Elements of a Tuple
Tuple in Python:

A tuple is an immutable list of objects. That means the elements of a tuple cannot be modified or changed while the program is running.

split() function:

Syntax: input string.split(seperator=None, maxsplit=-1)

Python split tuple: It delimits the string with the separator and returns a list of words from it. The maxsplit parameter specifies the maximum number of splits that can be performed. If it is -1 or not specified, all possible splits are performed.

Example:  Given string =  ‘hello btechgeeks goodmorning’.split()

Output : [‘hello’, ‘btechgeeks’, ‘goodmorning’ ]

Given a string and the task is to find a tuple with a comma-separated string.

Examples:

Example 1:

Input: 

Given String = 'good, morning, btechgeeks'     (static input)

Output:

Given input String =  good, morning, btechgeeks
A tuple with comma-separated string is :  ('good', ' morning', ' btechgeeks')

Example 2:

Input:

Given String = hello, btechgeeks, 123        (user input)

Output:

A tuple with comma-separated string is : ('hello', ' btechgeeks', ' 123')

Program for Comma-separated String to Tuple

Split a tuple python: Below are the ways to find a tuple with a comma-separated string.

Method #1: Using split() Method (Static input)

Approach:

  • Give the string as static input and store it in a variable.
  • Print the above-given input string.
  • Split the given input string separated by commas using the split() function and convert it into a tuple.
  • Store it in another variable.
  • Print the tuple with a comma-separated string.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'good, morning, btechgeeks'
# Print the above-given input string.
print("Given input String = ", gvn_str)
# Split the given input string separated by commas using the split() function
# and convert it into a tuple.
# Store it in another variable.
tupl = tuple(gvn_str.split(","))
# Print the tuple with a comma-separated string.
print("A tuple with comma-separated string is : ", tupl)

Output:

Given input String =  good, morning, btechgeeks
A tuple with comma-separated string is :  ('good', ' morning', ' btechgeeks')

Method #2: Using split() Method (User input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Print the above-given input string.
  • Split the given input string separated by commas using the split() function and convert it into a tuple.
  • Store it in another variable.
  • Print the tuple with a comma-separated string.
  • The Exit of the program.

Below is the implementation:

#Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Print the above-given input string.
print("Given input String = ", gvn_str)
# Split the given input string separated by commas using the split() function
# and convert it into a tuple.
# Store it in another variable.
tupl = tuple(gvn_str.split(","))
# Print the tuple with a comma-separated string.
print("A tuple with comma-separated string is : ", tupl)

Output:

Enter some random string = hello, btechgeeks, 123
Given input String = hello, btechgeeks, 123
A tuple with comma-separated string is : ('hello', ' btechgeeks', ' 123')

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.

Clear a bit in c – Program to Clear the Rightmost Set Bit of a Number in C++ and Python

Program to Clear the Rightmost Set Bit of a Number in C++ and Python


Clear a bit in c:
In the previous article, we have discussed about C++ Program to Check if it is Sparse Matrix or Not. Let us learn Program to Clear the Rightmost Set Bit of a Number in C++ Program and Python.

Binary Representation of a Number:

Binary is a base-2 number system in which a number is represented by two states: 0 and 1. We can also refer to it as a true and false state. A binary number is constructed in the same way that a decimal number is constructed.

Examples:

Examples1:

Input:

given number=19

Output:

The given number before removing right most set bit : 
19
The given number after removing right most set bit : 
18

Examples2:

Input:

given number =18

Output:

The given number before removing right most set bit : 
18
The given number after removing right most set bit : 
16

Examples3:

Input:

given number=512

Output:

The given number before removing right most set bit : 
512
The given number after removing right most set bit : 
0

Program to Clear the Rightmost Set Bit of a Number in C++ and Python

There are several ways to clear the rightmost set Bit of a Number 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 Bitwise Operators in C++

Approach:

  • There is a function called clear rightmost set bit that is defined.
  • It accepts n as an argument and returns n with its rightmost set bit cleared.
  • This is accomplished by computing n & (n – 1) and returning the result.
  • (n – 1) equals n when all the rightmost successive 0s are flipped and the initial rightmost 1 is flipped.
  • As a result, n & (n – 1) equals n with the rightmost 1 cleared.

Below is the implementation of above approach:

#include <bits/stdc++.h>
using namespace std;
// function which removes the right most set bit in the
// given number
int clearRight(int numb)
{
    // clearing the right most set bit from
    // the given number and store it in the result
    int reslt = (numb) & (numb - 1);
    // returing the calculated result
    return reslt;
}

// main function
int main()
{
    // given number
    int numb = 19;

    cout << "The given number before removing right most "
            "set bit : "
         << numb << endl;
    // passing the given number to clearRight function
    // to remove the clear the rightmost setbit
    cout << "The given number after removing right most "
            "set bit : "
         << clearRight(numb) << endl;
    return 0;
}

Output:

The given number before removing right most set bit : 19
The given number after removing right most set bit : 18

Method #2: Using Bitwise Operators in Python

Approach:

  • There is a function called clear rightmost set bit that is defined.
  • It accepts n as an argument and returns n with its rightmost set bit cleared.
  • This is accomplished by computing n & (n – 1) and returning the result.
  • (n – 1) equals n when all the rightmost successive 0s are flipped and the initial rightmost 1 is flipped.
  • As a result, n & (n – 1) equals n with the rightmost 1 cleared.
  • We will implement the same function in python

Below is the implementation:

# function which removes the right most set bit in the
# given number


def clearRight(numb):
    # clearing the right most set bit from
    # the given number and store it in the result
    reslt = (numb) & (numb - 1)
    # returing the calculated result
    return reslt
# Driver Code


# given number
numb = 19

print("The given number before removing right most "
      "set bit : ")
print(numb)
# passing the given number to clearRight function
# to remove the clear the rightmost setbit
print("The given number after removing right most set bit : ")
print(clearRight(numb))

Output:

The given number before removing right most set bit : 
19
The given number after removing right most set bit : 
18

Related Programs:

Angle between two vectors python – Python Program To Calculate the Angle Between Two Vectors

Program To Calculate the Angle Between Two Vectors

Angle between two vectors python: In the previous article, we have discussed Python Program to Find the Sine Series for the Given range
Mathematical Way :

Python angle between two vectors: The angle between two vectors can be calculated using the formula, which states that the angle cos of two vectors is equal to the dot product of two vectors divided by the dot product of the mod of two vectors.

cosθ = X.Y/|X|.|Y|  =>θ =  cos^-1 X.Y/|X|.|Y|

Example:

Let  X={5,6} and y={4,3} are two vectors.

The angle between given two vectors = X.Y=  5*4+6*3 = 38

|X| = √ 5^2 +6^2 = 7.8102

|Y| = √ 4^2 +3^2 = 5

cosθ = 38/7.8102*5 = 0.973

θ= 13.324°

In this, we use the ‘math’ module to perform some complex calculations for us, such as square root, cos inverse, and degree, by calling the functions sqrt(), acos(), and degrees ().

Given two vectors, and the task is to calculate the angle between the given two vectors.

Examples:

Example1:

Input: 

Given x1, y1, x2, y2 = 5, 6, 4, 3

Output:

The Cos angle between given two vectors = 0.9730802874900094
The angle in degree between given two vectors =  13.324531261890783

Example 2:

Input:

Given x1, y1, x2, y2  =  7, 3, 2, 1

Output:

The Cos angle between given two vectors = 0.9982743731749958
The angle in degree between given two vectors = 3.36646066342994

Program To Calculate the Angle Between Two Vectors

Python angle between two vectors: Below are the ways to Calculate the Angle Between Two Vectors.

Method #1: Using Mathematical Formula (Static input)

Approach:

  • Import math module using the import keyword.
  • Give four variables as static input and store them in four different variables.
  • Calculate the dot product of the given two vectors using the above mathematical formula and store them in another variable.
  • Calculate the Mod of given two vectors using the above mathematical formula and store them in another variable.
  • Find the cosine angle between the given two vectors using the above mathematical formula and store them in another variable.
  • Print the cosine angle between the given two vectors.
  • Calculate the angle in degrees using built-in math.degrees(), math.acos() functions and store it in a variable .
  • Print the angle ‘θ’ between the given two vectors.
  • The Exit of the program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give four variables as static input and store them in four different variables.
x1, y1, x2, y2 = 5, 6, 4, 3


def angle_between_Gvnvectors(x1, y1, x2, y2):
    # Calculate the dot product of given two vectors using above mathematical formula
    # and store them in another variable.

    dot_Prodct = x1*x2 + y1*y2
 # Calculate the Mod of given two vectors using above mathematical formula and
# store them in another variable
    mod_Of_Vectr1 = math.sqrt(x1*x1 + y1*y1)*math.sqrt(x2*x2 + y2*y2)
 # Find the cosine angle between given two vectors  using above mathematical formula
# and store them in another variable.
    cosine_angle = dot_Prodct/mod_Of_Vectr1
 # Print the cosine angle between given two vectors.
    print(" The Cos angle between given two vectors =", cosine_angle)
# Calculate the angle in degrees using built-in math.degrees(), math.acos() functions
# and store it in a variable .
    angl_in_Degres = math.degrees(math.acos(cosine_angle))
# Print the angle 'θ' between given two vectors.
    print("The angle in degree between given two vectors = ", angl_in_Degres)


angle_between_Gvnvectors(x1, y1, x2, y2)

Output:

The Cos angle between given two vectors = 0.9730802874900094
The angle in degree between given two vectors =  13.324531261890783

Method #2: Using Mathematical Formula (User input)

Approach:

  • Import math module using the import keyword.
  • Give four variables as user input using map(),split() , int(input()) functions and store them in four different variables.
  • Calculate the dot product of the given two vectors using the above mathematical formula and store them in another variable.
  • Calculate the Mod of given two vectors using the above mathematical formula and store them in another variable.
  • Find the cosine angle between the given two vectors using the above mathematical formula and store them in another variable.
  • Print the cosine angle between the given two vectors.
  • Calculate the angle in degrees using built-in math.degrees(), math.acos() functions and store it in a variable .
  • Print the angle ‘θ’ between the given two vectors.
  • The Exit of the program.

Below is the implementation of the above approach:

# Import math module using the import keyword.
import math
# Give four variables as user input using map(),split() ,int(input())functions and 
#store them in four different variables.
x1, y1, x2, y2 = map(int,input("Enter four random numbers = ").split())
def angle_between_Gvnvectors(x1, y1, x2, y2):
    # Calculate the dot product of given two vectors using above mathematical formula
    # and store them in another variable.

    dot_Prodct = x1*x2 + y1*y2
 # Calculate the Mod of given two vectors using above mathematical formula and
# store them in another variable
    mod_Of_Vectr1 = math.sqrt(x1*x1 + y1*y1)*math.sqrt(x2*x2 + y2*y2)
 # Find the cosine angle between given two vectors  using above mathematical formula
# and store them in another variable.
    cosine_angle = dot_Prodct/mod_Of_Vectr1
 # Print the cosine angle between given two vectors.
    print(" The Cos angle between given two vectors =", cosine_angle)
# Calculate the angle in degrees using built-in math.degrees(), math.acos() functions
# and store it in a variable .
    angl_in_Degres = math.degrees(math.acos(cosine_angle))
# Print the angle 'θ' between given two vectors.
    print("The angle in degree between given two vectors = ", angl_in_Degres)

angle_between_Gvnvectors(x1, y1, x2, y2)

Output:

Enter four random numbers = 7 3 2 1
The Cos angle between given two vectors = 0.9982743731749958
The angle in degree between given two vectors = 3.36646066342994

Here we calculated the angle between the given vectors.

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.

Numpy unique – Python: Find Unique Values in a Numpy Array With Frequency and Indices

Methods to find unique values in a numpy array with frequency and indices

Numpy get unique values: In this article, we will discuss how to find unique values, rows, and columns in a 1D & 2D Numpy array. Before going to the methods first we see numpy.unique() method because this method is going to be used.

numpy.unique() method

Numpy unique: numpy.unique() method help us to get the unique() values from given array.

syntax:numpy.unique(array, return_index=False, return_inverse=False, return_counts=False, axis=None)

Parameters

  1. array-Here we have to pass our array from which we want to get unique value.
  2. return_index- If this parameter is true then it will return the array of the index of the first occurrence of each unique value. By default it is false.
  3. return_counts-If this parameter is true then it will return the array of the count of the occurrence of each unique value. By default it is false.
  4. axis- It is used in the case of nd array, not in 1d array. axis=1 means we have to do operation column-wise and axis=0 means we have to do operation row-wise.

Now we will see different methods to find unique value with their indices and frequencies in a numpy array.

case 1-When our array is 1-D

  • Method 1-Find unique value from the array

Numpy unique values: As we only need unique values and not their frequencies and indices hence we simply pass our numpy array in the unique() method because the default value of other parameters is false so we don’t need to change them. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values=np.unique(arr)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
  • Method 2-Find unique value from the array along with their indices

Numpy frequency count: In this method, as we want to get unique values along with their indices hence we make the return_index parameter true and pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values,index=np.unique(arr,return_index=True)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)
print("First index of unique values are:")
print(index)

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
First index of unique values are:
[0 2 3 4 5 6 7]
  • Method 3-Find unique value from the array along with their frequencies

Numpy count unique: In this method, as we want to get unique values along with their frequencies hence we make the return_counts parameter true and pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values,count=np.unique(arr,return_counts=True)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)
print("Count of unique values are:")
for i in range(0,len(unique_values)):
  print("count of ",unique_values[i]," is ",count[i])

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
Count of unique values are:
count of  1  is  3
count of  2  is  2
count of  3  is  2
count of  4  is  2
count of  5  is  1
count of  6  is  1
count of  7  is  2

Case 2: When our array is 2-D

  • Method 1-Find unique value from the array

Numpy unique: Here we simply pass our array and all the parameter remain the same. Here we don’t make any changes because we want to work on both rows and columns. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique values are
[1 2 3 6]

Method 2-Get unique rows

Numpy unique: As here want to want to work only on rows so here we will make axis=0 and simply pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr,axis=0)
print("Original array is")
print(arr)
print("------------------")
print("Unique rows are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique rows are
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]]

Method 3-Get unique columns

As here want to want to work only on columns so here we will make axis=1 and simply pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr,axis=1)
print("Original array is")
print(arr)
print("------------------")
print("Unique columns are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique columns are
[[1 1 2]
 [1 3 2]
 [1 6 2]
 [1 1 2]]

so these are the methods to find unique values in a numpy array with frequency and indices.

 

Palindrome recursion python – Python Program to Check Whether a String is a Palindrome or not Using Recursion

Program to Check Whether a String is a Palindrome or not Using Recursion

Palindrome recursion python: Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Recursion in Python:

Palindrome recursion python: When a function calls itself and loops until it reaches the intended end state, this is referred to as recursion. It is based on the mathematics idea of recursive definitions, which define elements in a set in terms of other members in the set.

Each recursive implementation contains a base case in which the desired state is reached, and a recursive case in which the desired state is not reached and the function enters another recursive phase.

On each step, the behavior in the recursive situation before the recursive function call, the internal self-call, is repeated. Recursive structures are beneficial when a larger problem (the base case) can be solved by solving repeated subproblems (the recursive case) that incrementally advance the program to the base case.
It behaves similarly to for and while loops, with the exception that recursion moves closer to the desired condition, whereas for loops run a defined number of times and while loops run until the condition is no longer met.

In other words, recursion is declarative because you specify the desired state, whereas for/while loops are iterative because you provide the number of repeats.

Strings in Python:

Recursive palindrome python: A string is typically a piece of text (sequence of characters). To represent a string in Python, we use ” (double quotes) or ‘ (single quotes).

Examples:

Example1:

Input:

given string = "btechgeeksskeeghcetb"

Output:

The given string [ btechgeeksskeeghcetb ] is a palindrome

Example2:

Input:

given string = "aplussulpa"

Output:

The given string [ aplussulpa ] is a palindrome

Program to Check Whether a String is a Palindrome or not Using Recursion

Below are the ways to Check Whether a String is a Palindrome or not using the recursive approach in Python:

1)Using Recursion (Static Input)

Approach:

  • Give some string as static input and store it in a variable.
  • Pass the string to a recursive function checkPalindromeRecursion function as an argument.
  • Calculate the length of the string using the len() function.
  • If the length of the string is less than 1, the function returns True.
  • If the end letter is the same as the initial letter, execute the function recursively with the parameter as the sliced list with the first and last characters deleted, otherwise return False.
  • Use an if statement to determine whether the given string is True or False and then print the result.
  • If the function returns true then the given string is a palindrome.
  • Else the given string is not a palindrome.
  • The exit of the program.

Below is the implementation:

# function which checks the given string is palindrome or not using recursion
# if th given string is palindrome then it is true else the string is false.


def checkPalindromeRecursion(givenstr):
  # Calculate the length of the string using the len() function.
    stringLen = len(givenstr)
    # If the length of the string is less than 1, the function returns True.
    if stringLen < 1:
        return True
    else:
      # If the end letter is the same as the initial letter, execute the function
      # recursively with the parameter as the sliced list
      # with the first and last characters deleted, otherwise return False.
      # Use an if statement to determine whether the given string is
      # True or False and then print the result.
        if givenstr[0] == givenstr[-1]:
            return checkPalindromeRecursion(givenstr[1:-1])
        else:
            return False


# Give some string as static input and store it in a variable.
given_str = 'btechgeeksskeeghcetb'
# Pass the string to a recursive function checkPalindromeRecursion function as an argument.
# If the function returns true then the given string is a palindrome.
if(checkPalindromeRecursion(given_str)):
    print("The given string [", given_str, '] is a palindrome')
# Else the given string is not a palindrome.
else:
    print("The given string", given_str, 'is not a palindrome')

Output:

The given string [ btechgeeksskeeghcetb ] is a palindrome

2)Using Recursion (User Input)

Approach:

  • Give some random string as user input using the input() function and store it in a variable.
  • Pass the string to a recursive function checkPalindromeRecursion function as an argument.
  • Calculate the length of the string using the len() function.
  • If the length of the string is less than 1, the function returns True.
  • If the end letter is the same as the initial letter, execute the function recursively with the parameter as the sliced list with the first and last characters deleted, otherwise return False.
  • Use an if statement to determine whether the given string is True or False and then print the result.
  • If the function returns true then the given string is a palindrome.
  • Else the given string is not a palindrome.
  • The exit of the program.

Below is the implementation:

# function which checks the given string is palindrome or not using recursion
# if th given string is palindrome then it is true else the string is false.


def checkPalindromeRecursion(givenstr):
  # Calculate the length of the string using the len() function.
    stringLen = len(givenstr)
    # If the length of the string is less than 1, the function returns True.
    if stringLen < 1:
        return True
    else:
      # If the end letter is the same as the initial letter, execute the function
      # recursively with the parameter as the sliced list
      # with the first and last characters deleted, otherwise return False.
      # Use an if statement to determine whether the given string is
      # True or False and then print the result.
        if givenstr[0] == givenstr[-1]:
            return checkPalindromeRecursion(givenstr[1:-1])
        else:
            return False


# Give some random string as user input using the input()
# function and store it in a variable.
given_str = input('Enter some random string = ')
# Pass the string to a recursive function checkPalindromeRecursion function as an argument.
# If the function returns true then the given string is a palindrome.
if(checkPalindromeRecursion(given_str)):
    print("The given string [", given_str, '] is a palindrome')
# Else the given string is not a palindrome.
else:
    print("The given string", given_str, 'is not a palindrome')

Output:

Enter some random string = aplussulpa
The given string [ aplussulpa ] is a palindrome

Explanation:

  • A string must be entered by the user.
  • A recursive function gets the string as an argument.
  • If the length of the string is less than one, the function returns True.
  • If the end letter is the same as the initial letter, the function is repeated recursively with the argument as the sliced list with the first and last characters removed, otherwise, false is returned.
  • The if statement is used to determine whether the returned value is True or False, and the result is printed.

Related Programs:

Python Program to Read Height in Centimeters and then Convert the Height to Feet and Inches

Program to Read Height in Centimeters and then Convert the Height to Feet and Inches

179.5cm in feet: Given height in centimeters , the task is to convert the given height to feet and inches in Python.

Examples:

Example1:

Input:

Enter some random height in centimeters = 179.5

Output:

The given height 179.5 cm in inches = 70.72 inches
The given height 179.5 cm in feet = 5.89 feet

Example2:

Input:

Enter some random height in centimeters = 165

Output:

The given height 165.0 cm in inches = 65.01 inches
The given height 165.0 cm in feet = 5.41 feet

Program to Read Height in Centimeters and then Convert the Height to Feet and Inches in Python

179.5cm in feet: There are several ways to read height in centimeters and then convert it to feet and inches in  Python some of them are:

Method #1:Python Static Input

  • Give the height in centimeters as static input.
  • Convert the given height in centimeters to feet by multiplying it with 0.0328 and store it in a variable.
  • Convert the given height in centimeters to inches by multiplying it with 0.0.394 and store it in a variable.
  • Print the height in feet and inches.
  • Exit of Program.

Below is the implementation:

# Give the height in centimeters as static input.
heightcm = 165
# Convert the given height in centimeters to feet by multiplying it with 0.0328
# and store it in a variable.
heightfeet = 0.0328*heightcm
# Convert the given height in centimeters to inches by multiplying it with 0.0.394
# and store it in a variable.
heightinches = 0.394*heightcm
# Print the height in feet and inches.
print("The given height", heightcm, 'cm',
      'in inches = ', round(heightinches, 2), 'inches')
print("The given height", heightcm, 'cm',
      'in feet = ', round(heightfeet, 2), 'feet')

Output:

The given height 165 cm in inches =  65.01 inches
The given height 165 cm in feet =  5.41 feet

Explanation:

  • Given the height in centimeters as static input.
  • The height in centimeters is multiplied by 0.394 and saved in a new variable called height in inches.
  • The height in centimeters is multiplied by 0.0328 and saved in a new variable called height in feet.
  • It is printed the conversion height in inches and feet.

Method #2:Python User Input

Approach:

  • Enter the height in centimeters as user input using float(input()) function .
  • Convert the given height in centimeters to feet by multiplying it with 0.0328 and store it in a variable.
  • Convert the given height in centimeters to inches by multiplying it with 0.0.394 and store it in a variable.
  • Print the height in feet and inches.
  • Exit of Program.

Below is the implementation:

# Enter the height in centimeters as user input using int(input()) function.
heightcm = int(input('Enter some random height in centimeters = '))
# Convert the given height in centimeters to feet by multiplying it with 0.0328
# and store it in a variable.
heightfeet = 0.0328*heightcm
# Convert the given height in centimeters to inches by multiplying it with 0.0.394
# and store it in a variable.
heightinches = 0.394*heightcma
# Print the height in feet and inches.
print("The given height", heightcm, 'cm',
      'in inches = ', round(heightinches, 2), 'inches')
print("The given height", heightcm, 'cm',
      'in feet = ', round(heightfeet, 2), 'feet')

Output:

Enter some random height in centimeters = 169
The given height 169 cm in inches = 66.59 inches
The given height 169 cm in feet = 5.54 feet

Explanation:

  • As the height can be in decimals we take input using  float(input()) function.
  • The height in centimeters is multiplied by 0.394 and saved in a new variable called height in inches.
  • The height in centimeters is multiplied by 0.0328 and saved in a new variable called height in feet.
  • It is printed the conversion height in inches and feet.

Related Programs:

Divide all elements of list python – Python Program Divide all Elements of a List by a Number

Program Divide all Elements of a List by a Number

Divide all elements of list python: In the previous article, we have discussed Python Program to Get Sum of all the Factors of a Number

Given a list, and the task is to divide all the elements of a given List by the given Number in Python

As we know, elements such as int, float, string, and so on can be stored in a List. As we all know, dividing a string by a number is impossible. To divide elements of a list, all elements must be int or float.

Examples:

Example1:

Input:

Given List = [3, 2.5, 42, 24, 15, 32]
Given Number = 2

Output:

The above given list after division all elements of a List by the given Number= [1.5, 1.25, 21.0, 12.0, 7.5, 16.0]

Example 2:

Input:

Given List =  [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
Given Number = 5

Output:

The above given list after division all elements of a List by the given Number= [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]

Program Divide all Elements of a List by a Number

Python divide list by number: 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

Below are the ways to divide all Elements of a List by a Number.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the number as static input and store it in another variable.
  • Take a new empty list and store it in a variable.
  • Iterate in the above-given list using For Loop.
  • Divide the iterator by the above-given number and append the result to the above declared new list.
  • print the above given new list after division all elements of a List by the given Number.
  • The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gven_Lst = [3, 2.5, 42, 24, 15, 32]
# Give the number as static input and store it in another variable.
gvn_numb = 2
# Take a new empty list and store it in a variable.
Lst_aftr_div = []
# Iterate in the above given list using For Loop.
for itr in gven_Lst:
  # Divide the iterator  by  the above given number and append the result to the
  # above declared new list.
    Lst_aftr_div.append(itr/gvn_numb)
# print the above given list after division all elements of a List by the given Number.
print("The above given list after division all elements of a List by the given Number=", Lst_aftr_div)

Output:

The above given list after division all elements of a List by the given Number= [1.5, 1.25, 21.0, 12.0, 7.5, 16.0]

Method #2: Using For Loop (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions and store it in a variable.
  • Give the number as user input using the int(input()) function and store it in another variable.
  • Take a new empty list and store it in a variable.
  • Iterate in the above-given list using the For Loop.
  • Divide the iterator by the above-given number and append the result to the above declared new list.
  • Print the above given new list after division all elements of a List by the given Number.
  • The Exit of the program.

Below is the implementation:

#Give the list as user input using list(),map(),input(),and split() functions.
gven_Lst = list(map(float, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Give the number as user input using int(input()) and store it in another variable.
gvn_numb = int(input("Enter some random number = " ))
#Take a new empty list and store it in a variable.
Lst_aftr_div = []
# Iterate in the above given list using For Loop.
for itr in gven_Lst:
  # Divide the iterator by the above given number and append the result to the
  # above declared new list.
    Lst_aftr_div.append(itr/gvn_numb)
# print the above given list after division all elements of a List by the given Number.
print("The above given list after division all elements of a List by the given Number=", Lst_aftr_div)

Output:

Enter some random List Elements separated by spaces = 4 5 8 9.6 15 63 32 84
Enter some random number = 4
The above given list after division all elements of a List by the given Number= [1.0, 1.25, 2.0, 2.4, 3.75, 15.75, 8.0, 21.0]

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.