Author name: Vikram Chiluka

Program to Repeat String N times with Separator

Python Program to Repeat String N times with Separator

In the previous article, we have discussed Python Program to Find Common Characters between Two Strings
Given a String, the task is to repeat the string n times and add a separator in between.

Examples:

Example1:

Input:

Given string =hello this is BTechgeeks
Given separator='-'
n = 2

Output:

Given string with the above given separator =  hello-this-is-BTechgeeks-hello-this-is-BTechgeeks

Example 2:

Input:

Given string =Good morning this is btechgeeks
Given separator='@'
n = 3

Output:

Given string with the above given separator =  Good@morning@this@is@btechgeeks@Good@morning@this@is@btechgeeks@Good@morning@this@is@btechgeeks

Program to Repeat String N times with Separator

Below are the ways to Repeat String n times with Separator.

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

Approach:

  • Give the string as static input and store it in a variable.
  • Give the number as static input and store it in another variable.
  • Multiply the Given string with the above-given number in order to get a repeated string and store it in another variable.
  • Split the words of the given repeated string to a list of words using the built-in split() function and store it in another variable.
  • Give the separator as static input and store it in another variable.
  • Join the given separator in between the given Splitted String using the built-in join( ) function and store it in another variable.
  • Print the given string with the above-given separator.
  • The Exit of the program.

Note: Give an extra space at the end of the string while giving Static input.

Below is the implementation:

# Give the string as static input and store it in a variable.
gven_strng = " hello this is BTechgeeks "
# Give the number as static input and store it in another variable.
multpr = 2
# Multiply the Given string with the above given number in order to get a repeated string
# and store it in another variable.
repetd_strg = gven_strng*multpr
# Split the words of the given repeated string to a list of words using the built-in split()
# function and store it in another variable.
splitd_strng = repetd_strg.split()
# Give the separator as static input and store it in another variable.
separtr = '-'
# Join the given separator in between the given Splitted String using the built-in join( )
# function and store it in another variable.
reslt = separtr.join(splitd_strng)
# Print the given string with the above given separator.
print('Given string with the above given separator = ', reslt)

Output:

Given string with the above given separator =  hello-this-is-BTechgeeks-hello-this-is-BTechgeeks

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

Approach:

  • Give the string as User input and store it in a variable.
  • Give the number as User input and store it in another variable.
  • Multiply the Given string with the above-given number in order to get a repeated string and store it in another variable.
  • Split the words of the given repeated string to a list of words using the built-in split() function and store it in another variable.
  • Give the separator as User input and store it in another variable.
  • Join the given separator in between the given Splitted String using the built-in join( ) function and store it in another variable.
  • Print the given string with the above-given separator.
  • The Exit of the program.

Note: Give an extra space at the end of the string while giving User input.

Below is the implementation:

# Give the string as User input and store it in a variable.
gven_strng = input('Enter some Random String = ')
# Give the number as User input and store it in another variable.
multpr = int(input('Enter some Random Number ='))
# Multiply the Given string with the above given number in order to get a repeated string
# and store it in another variable.
repetd_strg = gven_strng*multpr
# Split the words of the given repeated string to a list of words using the built-in split()
# function and store it in another variable.
splitd_strng = repetd_strg.split()
# Give the separator as User input and store it in another variable.
separtr = input('Enter some Random Separator = ')
# Join the given separator in between the given Splitted String using the built-in join( )
# function and store it in another variable.
reslt = separtr.join(splitd_strng)
# Print the given string with the above given separator.
print('Given string with the above given separator = ', reslt)

Output:

Enter some Random String = Good morning this is btechgeeks 
Enter some Random Number = 3
Enter some Random Separator = @
Given string with the above given separator = Good@morning@this@is@btechgeeks@Good@morning@this@is@btechgeeks@Good@morning@this@is@btechgeeks

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 Program to Repeat String N times with Separator Read More »

Program to Extract Only Characters from a Given String

Python Program to Extract Only Characters from a Given String

In the previous article, we have discussed Python Program to Add Trailing Zeros to String
Given a string and the task is to extract only characters (alphabets) from a given string.

Examples:

Example1:

Input:

Given String = hello 123 this is Btech Geeks python3 coding platform54231

Output:

The Given String after extracting only characters = hellothisisBtechGeekspythoncodingplatform

Example2:

Input:

Given String=good morning23this is btechgeeks@19python

Output:

The Given String after extracting only characters = goodmorningthisisbtechgeekspython

Program to Extract Only Characters from a Given String

Below are the ways to Extract Only Characters from a given String. Here we used ASCII values to get the result.

Method #1: Using ASCII Values (Static Input)

Approach:

  • Give the string as static input and store it in the variable.
  • Take a new empty string to store only characters from the above-Given String.
  • Traverse in this given string using the For loop.
  • Inside the for loop, Check each letter of the above-given string is only a character or not by using the ord( ) method.
  • Ord( ) method gives the ASCII values of the character.
  • Check the elements of the given string are Upper case Characters by using if conditional statement and concatenate it to the above declared new string.
  • Else Check for the Lower case Characters by using Elif conditional statement and concatenate it to the above declared new string.
  • Print the above declared new String(has only characters).
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in the variable.
gven_stng = 'hello 123 this is Btech Geeks python3 coding platform54231'
# Take a new empty string to store only characters from the above Given String
only_chrs = ""
# Traverse in this given string using the For loop
for chrs in gven_stng:
    # Inside the for loop, Check each letter of the above given string is only a character
    # or not by using ord( char) method .
    # Ord( ) method gives the ASCII values of the character.
    # Check the elements of the given string are Upper case Characters by using if conditional
    # statement and concat it to the above declared new string.
    if ord(chrs) >= 65 and ord(chrs) <= 90:
        only_chrs += chrs
# Else Check for the Lower case Characters by using Elif conditional statement and
# concat it to the above declared  new string.
    elif ord(chrs) >= 97 and ord(chrs) <= 122:
        only_chrs += chrs
# print the above declared new String(has only characters).
print('The Given String after extracting only characters =',only_chrs)

Output:

The Given String after extracting only characters = hellothisisBtechGeekspythoncodingplatform

Method #2: Using ASCII Values (User Input)

Approach:

  • Give the string as user input using the input() function and store it in the variable.
  • Take a new empty string to store only characters from the above-Given String.
  • Traverse in this given string using the For loop.
  • Inside the for loop, Check each letter of the above-given string is only a character or not by using the ord( ) method.
  • Ord( ) method gives the ASCII values of the character.
  • Check the elements of the given string are Upper case Characters by using if conditional statement and concatenate it to the above declared new string.
  • Else Check for the Lower case Characters by using Elif conditional statement and concatenate it to the above declared new string.
  • Print the above declared new String(has only characters).
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in the variable.
gven_stng = input('Enter some random string = ')
# Take a new empty string to store only characters from the above Given String
only_chrs = ""
# Traverse in this given string using the For loop
for chrs in gven_stng:
    # Inside the for loop, Check each letter of the above given string is only a character
    # or not by using ord( char) method .
    # Ord( ) method gives the ASCII values of the character.
    # Check the elements of the given string are Upper case Characters by using if conditional
    # statement and concat it to the above declared new string.
    if ord(chrs) >= 65 and ord(chrs) <= 90:
        only_chrs += chrs
# Else Check for the Lower case Characters by using Elif conditional statement and
# concat it to the above declared  new string.
    elif ord(chrs) >= 97 and ord(chrs) <= 122:
        only_chrs += chrs
# print the above declared new String(has only characters).
print('The Given String after extracting only characters =', only_chrs)

Output:

Enter some random string = good morning23this is btechgeeks@19python
The Given String after extracting only characters = goodmorningthisisbtechgeekspython

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 Program to Extract Only Characters from a Given String Read More »

Program to Find Common Characters between Two Strings

Python Program to Find Common Characters between Two Strings

In the previous article, we have discussed Python Program to Extract Only Characters from a Given String
Given two strings, the task is to find the common characters between Two Strings.

In this case, we use some of the built-in functions like join(), lower(), sorted() and intersection() methods.

join() :

The string method join()  takes all of the items in an iterable and returns a string after joining them all together. Iterable types include list, tuple, string, dictionary, and set.

lower() :

As the name indicates, It takes a string and converts all uppercase characters to lowercase before returning it.

sorted method() :

The sorted() method is used to orderly sort the elements of a sequence (either ascending or descending).

intersection() method :

The intersection() method is used to find all the elements that are shared by two given sets.

Examples:

Example 1:

Input:

Given First String = Hello Btechgeeks
Given Second String = good morning

Output:

The Common Characters between the above given two Strings =   go

Example 2:

Input:

Given First String = have a nice Day
Given Second String = A special day

Output:

The Common Characters between the above given two Strings = acdeiy

Program to Find Common Characters between Two Strings

Below are the ways to find common characters between two strings.

Method #1: Using intersection Method (Static Input)

Approach:

  • Give the first string as static input, convert the given string into the lower case using the built-in lower() method and store it in a variable.
  • Give the second string as static input, convert the given string into the lower case using the built-in lower() method and store it in another variable.
  • Get the Common characters between both the above-given strings using the built-in intersection() method which is a set method.
  • Sort the above-given string using the built-in sorted() method.
  • Join the above-given string using the built-in join()method.
  • Print all the Common Characters between the above given two Strings.
  • The Exit of the program.

Below is the implementation:

# Give the first string as static input  , convert the given string into lower case
# using built-in lower() method and store it in a variable.
fst_strng = "Hello Btechgeeks".lower()
# Give the  second string as static input , convert the given string into lower case
# using built-in lower() method and store it in another variable.
secnd_strng = "good morning".lower()
# Get the Common characters between both the above given strings using built-in
# intersection() method which is a set method.
# Sort the above given string using  built-in sorted() method.
# Join the the above given string using built-in join()method .
# Print all the Common Characters between the above given two Strings.
print("The Common Characters between the above given two Strings = ",
      ''.join(sorted(set.intersection(set(fst_strng), set(secnd_strng)))))

Output:

The Common Characters between the above given two Strings =   go

Method #2 : Using intersection() Method (User Input)

Approach:

  • Give the first string as User input using the input() function, convert the given string into the lower case using the built-in lower() method and store it in a variable.
  • Give the second string as User input using the input() function, convert the given string into the lower case using the built-in lower() method, and store it in another variable.
  • Get the Common characters between both the above-given strings using the built-in intersection() method which is a set method.
  • Sort the above-given string using the built-in sorted() method.
  • Join the above-given string using the built-in join()method.
  • Print all the Common Characters between the above given two Strings.
  • The Exit of the program.

Below is the implementation:

# Give the first string as User input  using the input() function , convert the given string into lower case
# using built-in lower() method and store it in a variable.
fst_strng = input("Enter some Random String = ").lower()
# Give the  second string as User input  using the input() function, convert the given string into lower case
# using built-in lower() method and store it in another variable.
secnd_strng = input("Enter some Random String = ").lower()
# Get the Common characters between both the above given strings using built-in
# intersection() method which is a set method.
# Sort the above given string using  built-in sorted() method.
# Join the the above given string using built-in join()method .
# Print all the Common Characters between the above given two Strings.
print("The Common Characters between the above given two Strings = ",
      ''.join(sorted(set.intersection(set(fst_strng), set(secnd_strng)))))

Output:

Enter some Random String = have a nice Day
Enter some Random String = A special day
The Common Characters between the above given two Strings = acdeiy

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 Program to Find Common Characters between Two Strings Read More »

Program to Find Sum of Geometric Progression Series

Python Program to Find Sum of Geometric Progression Series

In the previous article, we have discussed Python Program to Repeat String N times with Separator
Geometric progression series

A geometric progression series is one in which any two consecutive terms have the same ratio. As a result, we can find the subsequent term by multiplying the common ratio by the previous term.

This is how the series looks:   a, ar, ar2, ar3, ar4, . . . . .

where common ratio(r)=2nd term/1st term (T2/T1) or (T3/T2)

Standard Formula to find the sum of series in G.P =  a(1 – rn)/(1 – r)

Given First term(a), common ratio(r), Nth term(total number of terms ) in Series, The task is to find Sum of the Geometric Progression Series.

Example: 2,6,18,54,162,486,1458,. . . . . . . .

Here a=2 , r=6/2 =3 , let n=10

Formula to find Nth term = arn1  

= 39366

sum of series = a(1 – rn)/(1 – r) =59048

Examples:

Example1:

Input:

Given Total number of terms=4
Given First Term = 3
Given common ratio = 3

Output:

The sum of the given geometric progression series = 120

Example 2:

Input:

Given Total number of terms=6
Given First Term = 4 
Given common ratio = 5

Output:

The sum of the given geometric progression series = 15624

Program to Find Sum of Geometric Progression Series

Below are the ways to find the Sum of the Geometric Progression Series.

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Import math module using the import keyword.
  • Give the Total number of terms as static input and store it in a variable.
  • Give the first term as static input and store it in another variable.
  • Give the Common Ratio as static input and store it in another variable.
  • Calculate the given Sum of Geometric Progression Series by using the standard mathematical formula a(1 – rn)/(1 – r) and store it in a variable.
  • Print the sum of the Geometric Progression series.
  • The Exit of the program.

Below is the implementation:

# Import math module using import keyword.
import math
# Give the Total number of terms as static input and store it in a variable.
tot_trms = 10
# Give the first term as static input and store it in a variable.
fst_trm = 2
# Give the Common Ratio as static input and store it in a variable.
commn_diff = 3
# Calculate the given Sum of Geometric Progression Series by using standard mathematical formula
# a(1 – r**n)/(1 – r) and store it in a variable.
sum_geoprog = (fst_trm*(1-(commn_diff)**tot_trms))//(1-commn_diff)
# Print the sum of Geometric Progression series .
print("The sum of the given geometric progression series = ", sum_geoprog)

 

Output:

The sum of the given geometric progression series =  59048

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Import math module using the import keyword.
  • Give the Total number of terms as User input using the int(input()) function and store it in a variable.
  • Give the first term as User input using the int(input()) function and store it in another variable.
  • Give the Common Ratio as User input using the int(input()) function and store it in another variable.
  • Calculate the Sum of Geometric Progression Series by using the standard mathematical formula a(1 – rn)/(1 – r) and store it in a variable.
  • Print the sum of the Geometric Progression series.
  • The Exit of the program.

Below is the implementation:

#Import math module using the import keyword.
import math
#Give the Total number of terms as User input using the int(input()) function and store it in a variable.
tot_trms = int(input("Given Total number of terms ="))
#Give the first term as User input using the int(input()) function and store it in another variable.
fst_trm = int(input("Given First Term = "))
#Give the Common Ratio as User input using the int(input()) function  and store it in another variable.
commn_diff = int(input("Given common ratio = "))
#Calculate the Sum of Geometric Progression Series by using standard mathematical formula 
#a(1 – r**n)/(1 – r) and store it in a variable.
sum_geoprog = (fst_trm*(1-(commn_diff)**tot_trms))//(1-commn_diff)
#Print the sum of Geometric Progression series .
print("The sum of the given geometric progression series = ", sum_geoprog)

Output:

Given Total number of terms =6
Given First Term = 4
Given common ratio = 5
The sum of the given geometric progression series = 15624

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 Program to Find Sum of Geometric Progression Series Read More »

Program to Reverse each Word in a Sentence

Python Program to Reverse each Word in a Sentence

In the previous article, we have discussed Python Program to Get the Position of Max Value in a List
Given a Sentence, the task is to Reverse each Word in a Given Sentence.

Split method:

Splitting a string into a list is accomplished by the split() method. It is a built-in Function in python.

join function:

The join() method is a string method that returns a string containing the elements of a sequence that have been joined by a string separator.

Examples:

Example 1:

Input:

Given String = Hello this is btechgeeks

Output:

The Reverse of each word of the above given sentence =  olleH siht si skeeghcetb

Example 2:

Input:

Given String = Good Morning btechGeeks

Output:

The Reverse of each word of the above given sentence = dooG gninroM skeeGhcetb

Program to Reverse each Word in a Sentence

Below are the ways to Reverse each Word in a Sentence.

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

Approach:

  • Give the string as static input and store it in a variable.
  • Split the words of the given string to a list of words using the built-in split() function and store it in another variable.
  • Traverse in the above-Given List of words using For Loop.
  • Inside the Loop, Reverse each word of the list Using the Slicing method and store it in a variable.
  • Join all the reversed words of a given sentence using the built-in join( ) function and store it in another variable.
  • Print the reversed Sentence of each word of a given String.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
strng = "Hello this is btechgeeks"
# Split the words of the given string to a list of words using the built-in split() function and store it in another variable.
splt_wrds = strng.split()
# Traverse in the above Given List of words using For Loop.
# Inside the Loop, Reverse each word of the list Using Slicing method and
# store it in a variable.
rversd_wrds = [wrd[::-1] for wrd in splt_wrds]
# Join all the reversed words of a given sentence using the built-in join( ) function
# and store it in another variable.
finl_sentnce = " ".join(rversd_wrds)
# Print the reversed Sentence of each word of a given String.
print("The Reverse of each word of the above given sentence = ", finl_sentnce)

Output:

The Reverse of each word of the above given sentence =  olleH siht si skeeghcetb

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

Approach:

  • Give the string as User input using input() function and store it in a variable.
  • Split the words of the given string to a list of words using the built-in split() function and store it in another variable.
  • Traverse in the above-Given List of words using For Loop.
  • Inside the Loop, Reverse each word of the list Using the Slicing method and store it in a variable.
  • Join all the reversed words of a given sentence using the built-in join( ) function and store it in another variable.
  • Print the reversed Sentence of each word of a given String.
  • The Exit of the program.

Below is the implementation:

# Give the string as User input using input() function and store it in a variable.
strng = input(" Enter some random String = ")
# Split the words of the given string to a list of words using the built-in split() function and store it in another variable.
splt_wrds = strng.split()
# Traverse in the above Given List of words using For Loop.
# Inside the Loop, Reverse each word of the list Using Slicing method and
# store it in a variable.
rversd_wrds = [wrd[::-1] for wrd in splt_wrds]
# Join all the reversed words of a given sentence using the built-in join( ) function
# and store it in another variable.
finl_sentnce = " ".join(rversd_wrds)
# Print the reversed Sentence of each word of a given String.
print("The Reverse of each word of the above given sentence = ", finl_sentnce)

Output:

Enter some random String = Good Morning btechGeeks
The Reverse of each word of the above given sentence = dooG gninroM skeeGhcetb

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 Program to Reverse each Word in a Sentence Read More »

Program to Get the Position of Max Value in a List

Python Program to Get the Position of Max Value in a List

In the previous article, we have discussed Python Program to Find Vertex, Focus and Directrix of Parabola
max() function :

max() is a built-in function that returns the maximum value in a list.

index() function:

This function searches the lists. It returns the index where the value is found when we pass it as an argument that matches the value in the list. If no value is found, Value Error is returned.

Given a list, the task is to Get the position of Max Value in a List.

Examples:

Example 1 :

Input :

Given List = [1, 5, 9, 2, 7, 3, 8]

Output:

Maximum Value in the above Given list = 9
Position of Maximum value of the above Given List = 3

Example 2 :

Input : 

Given List = [4, 3, 7, 1, 2, 8, 9]

Output:

Maximum Value in the above Given list = 9
Position of Maximum value of the above Given List = 7

Program to Get the Position of Max Value in a List

Below are the ways to Get the Position of Max value in a List.

Method #1: Using Max(),Index() functions  (Static Input)

Approach:

  • Give the List as static input and store it in a variable.
  • Get the maximum value of the given list using the built-in max() function and store it in another variable.
  • Print the maximum value of the above-given List.
  • Get the position of the maximum value of the given List using the built-in index() function and store it in another variable.
  • Print the position of the maximum value of the given List i.e. maximum position+1( since list index starts from zero).
  • The Exit of the program.

Below is the implementation:

# Give the List as static input and store it in a variable.
Gvn_lst = [1, 5, 9, 2, 7, 3, 8]
# Get the maximum value of the given list using the built-in max() function and
# store it in another variable
maxim_vle = max(Gvn_lst)
# Print the maximum value of the above given List.
print("Maximum Value in the above Given list = ", maxim_vle)
# Get the position of the maximum value of the List using the built-in index() function
# and store it in another variable.
maxim_positn = Gvn_lst.index(maxim_vle)
# Print the position of the maximum value of the given List i.e. maximum position+1
# ( since list index starts from zero).
print("Position of Maximum value of the above Given List = ", maxim_positn+1)

Output:

Maximum Value in the above Given list =  9
Position of Maximum value of the above Given List =  3

Method #2: Using Max(),Index() functions  (User Input)

Approach:

  • Give the list as User input using list(),map(),input(),and split() functions and store it in a variable.
  • Get the maximum value of the given list using the built-in max() function and store it in another variable.
  • Print the maximum value of the above-given List.
  • Get the position of the maximum value of the given List using the built-in index() function and store it in another variable.
  • Print the position of the maximum value of the given List i.e. maximum position+1( since list index starts from zero).
  • The Exit of the program.

Below is the implementation:

#Give the list as User input using list(),map(),input(),and split() functions and store it in a variable.
Gvn_lst = list(map(int, input('Enter some random List Elements separated by spaces = ').split()))
# Get the maximum value of the given list using the built-in max() function and
# store it in another variable
maxim_vle = max(Gvn_lst)
# Print the maximum value of the above given List.
print("Maximum Value in the above Given list = ", maxim_vle)
# Get the position of the maximum value of the List using the built-in index() function
# and store it in another variable.
maxim_positn = Gvn_lst.index(maxim_vle)
# Print the position of the maximum value of the given List i.e. maximum position+1
# ( since list index starts from zero).
print("Position of Maximum value of the above Given List = ", maxim_positn+1)

Output:

Enter some random List Elements separated by spaces = 4 3 7 1 2 8 9
Maximum Value in the above Given list = 9
Position of Maximum value of the above Given List = 7

Here we printed the index of the maximum element of the given list.

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 Program to Get the Position of Max Value in a List Read More »

Program to Print nth Iteration of Lucas Sequence

Python Program to Print nth Iteration of Lucas Sequence

In the previous article, we have discussed Python Program to Find Sum of Geometric Progression Series

Definition of Lucas sequence:

We’ve all heard of the Fibonacci sequence. It is a sequence in which each term is the sum of the two preceding terms. The Lucas sequence is the same as the previous one, but with different starting values. A Fibonacci sequence starts with 0 and 1, whereas a Lucas sequence starts with 2 and 1. The other terms in the Lucas sequence are 3, 4, 7, 11, and so on.

Given a number ‘n’ and the task is to print the given nth iteration of Lucas Sequence.

Examples:

Example1:

Input:

n = 6

Output:

The above Given nth iteration of Lucas Sequence =  18

Example 2:

Input:

n = 10

Output:

The above Given nth iteration of Lucas Sequence =  123

Program to Print nth Iteration of Lucas Sequence

Below are the ways to get the given nth Iteration of the Lucas Sequence.

Method #1: Using For Loop  (Static Input)

Approach:

  • Give the First term =2 (since the first term in Lucas Sequence is 2 which is a constant) as static input and store it in a variable.
  • Give the Second term =1 (since the second term in Lucas Sequence is 1 which is a constant) as static input and store it in another variable.
  • Give the number as static input and store it in another variable.
  • Loop from ‘1’ to the above given n+1 value (since doesn’t include the last term) range using For loop.
  • Inside the loop, get the third term which is the sum of the first and the second term, and store it in a variable.
  • Assign the value of the second term to the first term.
  • Assign the value of the third term to the second term and come out of For Loop.
  • Print the Value of the above given nth iteration of Lucas Sequence(i.e. first term).
  • The Exit of the program.

Below is the implementation:

# Give the First term =2 (since the first term in Lucas Sequence is 2 which is a constant)
# as static input and store it in a variable.
fst_trm = 2
# Give the Second term =1 (since the second term in Lucas Sequence is 1 which is a constant)
# as static input and store it in another variable.
secnd_trm = 1
# Give the number as static input and store it in another variable.
gvn_n_vlue = 6
# Loop from '1' to the above given n+1 value (since doesn't include last term) range
# using For loop.
for i in range(1, gvn_n_vlue+1):
 # Inside the loop , get the third term which is the sum of first and the second term
    # and store it in a variable.
    third_trm = fst_trm+secnd_trm
 # Assign the value of second term to the first term.
    fst_trm = secnd_trm
  # Assign the value of the third term to the second term and come out of For Loop.
    secnd_trm = third_trm
# Print the Value of above given nth iteration of Lucas Sequence(i.e. first term).
print("The above Given nth iteration of Lucas Sequence = ", fst_trm)

Output:

The above Given nth iteration of Lucas Sequence =  18

Method #2: Using For Loop  (User Input)

Approach:

  • Give the First term =2 (since the first term in Lucas Sequence is 2 which is a constant) as static input and store it in a variable.
  • Give the Second term =1 (since the second term in Lucas Sequence is 1 which is a constant) as static input and store it in another variable.
  • Give the number as User input and store it in another variable.
  • Loop from ‘1’ to the above given n+1 value (since doesn’t include the last term) range using For loop.
  • Inside the loop, get the third term which is the sum of the first and the second term, and store it in a variable.
  • Assign the value of the second term to the first term.
  • Assign the value of the third term to the second term and come out of For Loop.
  • Print the Value of the above given nth iteration of Lucas Sequence(i.e. first term).
  • The Exit of the program.

Below is the implementation:

# Give the First term =2 (since the first term in Lucas Sequence is 2 which is a constant)
# as static input and store it in a variable.
fst_trm = 2
# Give the Second term =1 (since the second term in Lucas Sequence is 1 which is a constant)
# as static input and store it in another variable.
secnd_trm = 1
# Give the number as User input and store it in another variable.
gvn_n_vlue = int(input("Enter Some Random number = "))
# Loop from '1' to the above given n+1 value (since doesn't include last term) range
# using For loop.
for i in range(1, gvn_n_vlue+1):
 # Inside the loop , get the third term which is the sum of first and the second term
    # and store it in a variable.
    third_trm = fst_trm+secnd_trm
 # Assign the value of second term to the first term.
    fst_trm = secnd_trm
  # Assign the value of the third term to the second term and come out of For Loop.
    secnd_trm = third_trm
# Print the Value of above given nth iteration of Lucas Sequence(i.e. first term).
print("The above Given nth iteration of Lucas Sequence = ", fst_trm)

Output:

Enter Some Random number = 10
The above Given nth iteration of Lucas Sequence = 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.

Python Program to Print nth Iteration of Lucas Sequence Read More »

Program to Find Vertex, Focus and Directrix of Parabola

Python Program to Find Vertex, Focus and Directrix of Parabola

In the previous article, we have discussed Python Program to Print nth Iteration of Lucas Sequence
Parabola:

A parabola is a curve in a 2D plane that is the same distance from a fixed point called focus as a fixed straight line. The directrix is the name given to this line. A parabola’s general equation is y= ax2+bx+c. In this case, a, b, and c can be any real number.

Given a, b, c  values, the task is to determine Vertex, Focus, and Directrix of the above Given Parabola.

Examples:

Example 1 :

Input :

Given first Term = 5
Given second Term = 2
Given Third Term = 3

Output:

The Vertex of the above Given parabola = ( -0.2 ,  2.8 )
The Focus of the above Given parabola = ( -0.2 ,  2.85 )
The Directrix of the above Given parabola = -97

Example 2 :

Input :

Given first Term = 6
Given second Term = 3
Given Third Term = 1

Output:

The Vertex of the above Given parabola = ( -0.25 ,  0.625 )
The Focus of the above Given parabola = ( -0.25 ,  0.6666666666666666 )
The Directrix of the above Given parabola = -239

Program to Find Vertex, Focus and Directrix of Parabola

Below are the ways to find Vertex, Focus, and Directrix of Parabola.

Method #1: Using Mathematical Formula  (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Give the third number as static input and store it in another variable.
  • Print the vertex of the above-given parabola using Standard mathematical formulas.
  • Print the Focus of the above-given parabola using Standard mathematical formulas.
  • Print the Directrix of the above-given parabola using Standard mathematical formulas.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
vertx = 5
# Give the second number as static input and store it in another variable.
focs = 2
# Give the third number as static input and store it in another variable.
dirctx = 3
# Print the vertex of the above given parabola using Standard mathematical formulas.
print("The Vertex of the above Given parabola = (", (-focs / (2 * vertx)),
      ", ", (((4 * vertx * dirctx) - (focs * focs)) / (4 * vertx)), ")")
# Print the Focus of the above given parabola using Standard mathematical formulas.
print("The Focus of the above Given parabola = (", (-focs / (2 * vertx)), ", ",
      (((4 * vertx * dirctx) - (focs * focs) + 1) / (4 * vertx)), ")")
# Print the Directrix of the above given parabola using Standard mathematical formulas.
print("The Directrix of the above Given parabola =", (int)
      (dirctx - ((focs * focs) + 1) * 4 * vertx))

Output:

The Vertex of the above Given parabola = ( -0.2 ,  2.8 )
The Focus of the above Given parabola = ( -0.2 ,  2.85 )
The Directrix of the above Given parabola = -97

Method #2: Using Mathematical Formula  (User Input)

Approach:

  • Give the first number as User input using the input() function and store it in a variable.
  • Give the second number as User input using the input() function and store it in another variable.
  • Give the third number as User input using the input() function and store it in another variable.
  • Print the vertex of the above-given parabola using Standard mathematical formulas.
  • Print the Focus of the above-given parabola using Standard mathematical formulas.
  • Print the Directrix of the above-given parabola using Standard mathematical formulas.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as User input using the input() function  and store it in a variable.
vertx = int(input('Enter some Random Number = '))
# Give the second number as User input using the input() function  and store it in another variable.
focs =  int(input('Enter some Random Number = '))
# Give the third number as User input using the input() function  and store it in another variable.
dirctx =  int(input('Enter some Random Number = '))
# Print the vertex of the above given parabola using Standard mathematical formulas.
print("The Vertex of the above Given parabola = (", (-focs / (2 * vertx)),
      ", ", (((4 * vertx * dirctx) - (focs * focs)) / (4 * vertx)), ")")
# Print the Focus of the above given parabola using Standard mathematical formulas.
print("The Focus of the above Given parabola = (", (-focs / (2 * vertx)), ", ",
      (((4 * vertx * dirctx) - (focs * focs) + 1) / (4 * vertx)), ")")
# Print the Directrix of the above given parabola using Standard mathematical formulas.
print("The Directrix of the above Given parabola =", (int)
      (dirctx - ((focs * focs) + 1) * 4 * vertx))

Output:

Enter some Random Number = 6
Enter some Random Number = 3
Enter some Random Number = 1
The Vertex of the above Given parabola = ( -0.25 , 0.625 )
The Focus of the above Given parabola = ( -0.25 , 0.6666666666666666 )
The Directrix of the above Given parabola = -239

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 Program to Find Vertex, Focus and Directrix of Parabola Read More »

Program to Find the Number of Weeks between two Dates

Python Program to Find the Number of Weeks between two Dates

In the previous article, we have discussed Python Program to Print all Disarium Numbers within Given range
DateTime:

It is a date and time combination with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo.

Date and time are not data types in Python, but a module called DateTime can be imported to work with both the date and the time. There is no need to install the Datetime module externally because it is built into Python.

The Datetime module includes classes for working with dates and times. These classes offer a variety of functions for working with dates, times, and time intervals. In Python, date and DateTime are objects, so when you manipulate them, you are actually manipulating objects rather than strings or timestamps.

Given two dates, and the task is to find the number of weeks between the given two dates.

Examples:

Example1:

Input:

Given First date =2003-11- 10  (YY-MM-DD)
Given second date=2007-4- 12

Output:

The number of weeks between two given dates =  178

Example 2:

Input:

Given First date =1998-5-16 (YY-MM-DD)
Given second date=2001-7- 9

Output:

The number of weeks between two given dates =  164

Program to Find the Number of Weeks between two Dates

Below are the ways to Find the Number of Weeks between two Dates.

Method #1: Using DateTime Module (Static input)

Approach:

  • Import DateTime module using date keyword.
  • Give the First date as static input in the format of YY, MM, DD, and store it in a variable.
  • Give the Second date as static input in the format of YY, MM, DD and store it in another variable.
  • Calculate the absolute difference between the above given two dates using abs(date1-date2) and store it in another variable.
  • Divide the above-got number of days by 7, using the floor division operator, and store it in another variable.
  • Print the number of weeks between the two above given dates.
  • The Exit of the program.

Below is the implementation:

# Import datetime module using date keyword.
from datetime import date
# Give the First date as static input in the format of YY,MM,DD and store it in a variable.
fst_dat_1 = date(2003, 11, 10)
# Give the Second date as static input in the format of YY,MM,DD and store it in another variable.
secnd_dat_2 = date(2007, 4, 12)
# Calculate the absolute difference between the above given two dates using
# abs(date1-date2) and store it in another variable.
no_dayss = abs(fst_dat_1-secnd_dat_2).days
# Divide the above got number of days by 7 ,using floor division operator and
# store it in another variable.
no_weks = no_dayss//7
# Print the number of weeks between  two  above given dates.
print(" The number of weeks between two given dates = ", no_weks)

Output:

The number of weeks between two given dates = 178

Method #2: Using DateTime Module (User input)

Approach:

  • Import DateTime module using date keyword.
  • Give the First date as user input in the format of YY, MM, DD as a string using input(), int(), split() functions function and store it in a variable.
  • Give the Second date as user input in the format of YY, MM, DD as a string using input(), int(), split() functions and store it in another variable.
  • Calculate the absolute difference between the above given two dates using abs(date1-date2) and store it in another variable.
  • Divide the above-got number of days by 7, using the floor division operator, and store it in another variable.
  • Print the number of weeks between the two above given dates.
  • The Exit of the program.

Below is the implementation:

# Import datetime module using date keyword.
from datetime import date
# Give the First date as user input in the format of YY, MM, DD
# as a string using input(),int(),split() functions and store it in a variable.
yy1, mm1, dd1 = map(int, input(
    'Enter year month and date separated by spaces = ').split())
fst_dat_1 = date(yy1, mm1, dd1)
# Give the Second date as user  input using input(),int(),split() functions
# in the format of YY,MM,DD and store it in another variable.
yy2, mm2, dd2 = map(int, input(
    'Enter year month and date separated by spaces = ').split())
secnd_dat_2 = date(yy2, mm2, dd2)
# Calculate the absolute difference between the above given two dates using
# abs(date1-date2) and store it in another variable.
no_dayss = abs(fst_dat_1-secnd_dat_2).days
# Divide the above got number of days by 7 ,using floor division operator and
# store it in another variable.
no_weks = no_dayss//7
# Print the number of weeks between  two  above given dates.
print(" The number of weeks between two given dates = ", no_weks)

Output:

Enter year month and date separated by spaces = 2001 02 11
Enter year month and date separated by spaces = 2001 09 28
The number of weeks between two given dates = 32

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 Program to Find the Number of Weeks between two Dates Read More »

Program to Get Tangent value Using math.tan()

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

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 Program to Get Tangent value Using math.tan() Read More »