Python

Program to Determine all Pythagorean Triplets in the Range in C++ and Python

Program to Determine all Pythagorean Triplets in the Range in C++ and Python

In the previous article, we have discussed about Program to Print Collatz Conjecture for a Given Number in C++ and Python. Let us learn Program to Determine all Pythagorean Triplets in C++ Program.

A Pythagorean triplet is a collection of three positive numbers, a, b, and c, such that a^2 + b^2 = c^2.

Given a limit, find all Pythagorean Triples with values less than that limit.

Examples:

Example1:

Input:

given upper limit =63

Output:

printing the Pythagorean triplets till the upper limit 63 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61

Example2:

Input:

given upper limit =175

Output:

printing the Pythagorean triplets till the upper limit 175 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61
48 14 50
45 28 53
40 42 58
33 56 65
24 70 74
13 84 85
63 16 65
60 32 68
55 48 73
48 64 80
39 80 89
28 96 100
15 112 113
80 18 82
77 36 85
72 54 90
65 72 97
56 90 106
45 108 117
32 126 130
17 144 145
99 20 101
96 40 104
91 60 109
84 80 116
75 100 125
64 120 136
51 140 149
36 160 164

Find all Pythagorean triplets in the given range in C++ and Python

A simple solution is to use three nested loops to generate these triplets that are less than the provided limit. Check if the Pythagorean condition is true for each triplet; if so, print the triplet. This solution has a time complexity of O(limit3), where ‘limit’ is the stated limit.

An Efficient Solution will print all triplets in O(k) time, where k is the number of triplets to be printed. The solution is to apply the Pythagorean triplet’s square sum connection, i.e., addition of squares a and b equals square of c, and then represent these numbers in terms of m and n.

For every choice of positive integer m and n, the formula of Euclid creates Pythagorean Triplets:

a=m^2 -n^2

b= 2 * m * n

c= m ^2 +n^2

Below is the implementation of efficient solution in C++ and Python:

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

1)Finding all Pythagorean till the given limit in Python

Approach:

  • Scan the upper limit or give static input and save the variable.
  • Calculate the Pythagorean triplets using the formula with a while loop and for loop.
  • If the c value exceeds the upper limit, or if a number equals 0, break from the loop.
  • Print down all Pythagorean triplets’ three numbers.
  • Exit of program.

Below is the implementation:

# enter the upper limit till you find pythagorean triplets
upper_limit = 63
n3 = 0
a = 2
print("printing the pythagorean triplets till the upper limit", upper_limit, ":")
while(n3 < upper_limit):
    for b in range(1, a+1):
        n1 = a*a-b*b
        n2 = 2*a*b
        n3 = a*a+b*b
        if(n3 > upper_limit):
            break
        if(n1 == 0 or n2 == 0 or n3 == 0):
            break
        print(n1, n2, n3)
    a = a+1

Output:

printing the Pythagorean triplets till the upper limit 63 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61

Explanation:

The upper limit / input should be entered by a user as static, and stored in a variable.
The value of Pythagorean triplets using the formula is used during and for loops.
The loop breaks out if the value of a side is greater than the upper boundary, or if one side is 0.
The triplets will then be printed.

2)Finding all Pythagorean till the given limit in C++

Approach:

  • Scan the upper limit using cin or give static input and save the variable.
  • Calculate the Pythagorean triplets using the formula with a while loop and for loop.
  • If the c value exceeds the upper limit, or if a number equals 0, break from the loop.
  • Print down all Pythagorean triplets’ three numbers.
  • Exit of program.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{

    // enter the upper limit till you find pythagorean
    // triplets
    int upper_limit = 175;
    int n3 = 0;
    int a = 2;
    cout << "printing the pythagorean triplets till the "
            "upper limit"
         << upper_limit << ":" << endl;
    while (n3 < upper_limit) {
        for (int b = 1; b <= a; b++) {
            int n1 = a * a - b * b;
            int n2 = 2 * a * b;
            n3 = a * a + b * b;
            if (n3 > upper_limit)
                break;
            if (n1 == 0 or n2 == 0 or n3 == 0)
                break;
            cout << n1 << " " << n2 << " " << n3 << endl;
        }
        a = a + 1;
    }
    return 0;
}

Output:

printing the Pythagorean triplets till the upper limit175:
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61
48 14 50
45 28 53
40 42 58
33 56 65
24 70 74
13 84 85
63 16 65
60 32 68
55 48 73
48 64 80
39 80 89
28 96 100
15 112 113
80 18 82
77 36 85
72 54 90
65 72 97
56 90 106
45 108 117
32 126 130
17 144 145
99 20 101
96 40 104
91 60 109
84 80 116
75 100 125
64 120 136
51 140 149
36 160 164

Related Programs:

Program to Count the Number of Alphabets in a String

Python Program to Count the Number of Alphabets in a String

In the previous article, we have discussed Python Program to Count the Number of Null elements in a List.

Given a string, the task is to count the Number of Alphabets in a given String.

isalpha() Method:

The isalpha() method is a built-in method for string-type objects. If all of the characters are alphabets from a to z, the isalpha() method returns true otherwise, it returns False.

Examples:

Example1:

Input:

Given String = hello btechgeeks

Output:

The Number of Characters in a given string { hello btechgeeks } =  15

Example 2:

Input:

Given String = good morning btechgeeks

Output:

The Number of Characters in a given string { good morning btechgeeks } =  21

Program to Count the Number of Alphabets in a String

Below are the ways to Count the Number of Alphabets in a String.

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

Approach:

  • Give the String as static input and store it in a variable.
  • Take a variable to say ‘count’ and initialize its value with ‘0’
  • Loop from 0 to the length of the above-given String using For Loop.
  • Inside the loop, check whether if the value of the iterator is an alphabet or using the built-in isalpha() method inside the if conditional statement.
  • If the given condition is true, then increment the above-initialized count value by ‘1’.
  • Print the number of Alphabets in a given string by printing the above count value.
  • The Exit of the program.

Below is the implementation:

# Give the String as static input and store it in a variable.
gvn_str = "hello btechgeeks"
# Take a variable say 'count' and initialize it's value with '0'
count_no = 0
# Loop from 0 to the length of the above given String using For Loop.
for itrtor in gvn_str:
    # Inside the loop, check whether  if the value of iterator is alphabet or
    # using built-in isalpha() method inside the if conditional statement.
    if(itrtor.isalpha()):
     # If the given condition is true ,then increment the above initialized count value by '1'.
    	count_no = count_no+1
# Print the number of Alphabets in a given string by printing the above count value.
print(
    "The Number of Characters in a given string {", gvn_str, "} = ", count_no)

Output:

The Number of Characters in a given string { hello btechgeeks } =  15

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

Approach:

  • Give the String as user input using the input() function and store it in the variable.
  • Take a variable to say ‘count’ and initialize its value with ‘0’
  • Loop from 0 to the length of the above-given String using For Loop.
  • Inside the loop, check whether if the value of the iterator is an alphabet or using the built-in isalpha() method inside the if conditional statement.
  • If the given condition is true, then increment the above-initialized count value by ‘1’.
  • Print the number of Alphabets in a given string by printing the above count value.
  • 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.
gvn_str = input("Enter some random String = ")
# Take a variable say 'count' and initialize it's value with '0'
count_no = 0
# Loop from 0 to the length of the above given String using For Loop.
for itrtor in gvn_str:
    # Inside the loop, check whether  if the value of iterator is alphabet or
    # using built-in isalpha() method inside the if conditional statement.
    if(itrtor.isalpha()):
     # If the given condition is true ,then increment the above initialized count value by '1'.
    	count_no = count_no+1
# Print the number of Alphabets in a given string by printing the above count value.
print(
    "The Number of Characters in a given string {", gvn_str, "} = ", count_no)

Output:

Enter some random String = good morning btechgeeks
The Number of Characters in a given string { good morning btechgeeks } = 21

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.

Program to get the Last Word from a String

Python Program to get the Last Word from a String

In the previous article, we have discussed Python Program to Subtract two Complex Numbers

Given a string that contains the words the task is to print the last word in the given string in Python.

Examples:

Example1:

Input:

Given string =hello this is BTechgeeks

Output:

The last word in the given string { hello this is BTechgeeks } is: BTechgeeks

Example2:

Input:

Given string =good morning this is btechgeeks

Output:

The last word in the given string { good morning this is btechgeeks } is: btechgeeks

Program to get the Last Word from a String in Python

Below are the ways to get the last word from the given string in Python.

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.
  • Get the last word from the above list of words using negative indexing and store it in a variable.
  • Print the last word of the given string by printing the above variable.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvnstrng = 'hello this is BTechgeeks'
# Split the words of the given string to a list of words
# using the built-in split() function.
lsttofwrds = gvnstrng.split()
# Get the last word from the above list of words using negative indexing
# and store it in a variable.
lstwrd = lsttofwrds[-1]
# Print the last word of the given string by printing the above variable.
print('The last word in the given string {', gvnstrng, '} is:', lstwrd)

Output:

The last word in the given string { hello this is BTechgeeks } is: BTechgeeks

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

Approach:

  • Give the string as user input using the input() function and store it in the variable.
  • Split the words of the given string to a list of words using the built-in split() function.
  • Get the last word from the above list of words using negative indexing and store it in a variable.
  • Print the last word of the given string by printing the above variable.
  • 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.
gvnstrng = input('Enter some random string = ')
# Split the words of the given string to a list of words
# using the built-in split() function.
lsttofwrds = gvnstrng.split()
# Get the last word from the above list of words using negative indexing
# and store it in a variable.
lstwrd = lsttofwrds[-1]
# Print the last word of the given string by printing the above variable.
print('The last word in the given string {', gvnstrng, '} is:', lstwrd)

Output:

Enter some random string = good morning this is btechgeeks
The last word in the given string { good morning this is btechgeeks } 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.

 

Program to Calculate GST

Python Program to Calculate GST

In the previous article, we have discussed Python Program to Find Median of List
Goods and Services Tax (GST):

GST is an abbreviation for Goods and Services Tax. It is a value-added tax levied on goods and services sold for domestic use or consumption. Customers pay GST to the government when they buy goods and services.

To calculate the GST percentage, first, compute the net GST amount by subtracting the original price from the net price that includes the GST. We will use the GST percent formula after calculating the net GST amount.

Formula:

GST% formula = ((GST Amount * 100)/Original price)

Net price        = Original price + GST amount

GST amount   = Net price – Original price

GST%             = ((GST amount * 100)/Original price)

round() function: round function rounds off to the nearest integer value.

Given the Net price, the original price, and the task is to calculate the GST percentage.

Examples:

Example1:

Input:

Given original price = 520
Given Net price       = 650

Output:

The GST percent for the above given input net and original prices =  25.0%

Example 2:

Input:

Given original price = 354.80
Given Net price       = 582.5

Output:

The GST percent for the above given input net and original prices =  64.17700112739571%

Program to Calculate GST

Below are the ways to Calculate GST.

Method #1: Using Mathematical Formula (Static input)

Approach:

  • Give the original price as static input and store it in a variable.
  • Give the net price as static input and store it in another variable.
  • Calculate the GST amount by using the above-given formula and store it in another variable.
  • Calculate the given GST percentage by using the above-given formula and store it in another variable.
  • Print the given GST value for the above given original and net prices.
  • The Exit of the program.

Below is the implementation:

# Give the original price as static input and store it in a variable.
gvn_Orignl_amt = 520
# Give the net price as static input and store it in another variable.
gvn_Net_amt = 650
# Calculate the GST amount by using the above given formula and store it in
# another variable.
GST_amnt = gvn_Net_amt - gvn_Orignl_amt
# Calculate the given GST percentage by using the above given formula and
# store it in another variable.
gvn_GST_percnt = ((GST_amnt * 100) / gvn_Orignl_amt)
# Print the given GST value for the above given original and net prices.
print("The GST percent for the above given input net and original prices = ",
      gvn_GST_percnt, end='')
print("%")

Output:

The GST percent for the above given input net and original prices =  25.0%

Method #2: Using Mathematical Formula (User input)

Approach:

  • Give the original price as user input using float(input()) and store it in a variable.
  • Give the net price as user input using float(input()) and store it in another variable.
  • Calculate the GST amount by using the above-given formula and store it in another variable.
  • Calculate the given GST percentage by using the above-given formula and store it in another variable.
  • Print the given GST value for the above given original and net prices.
  • The Exit of the program.

Below is the implementation:

# Give the original price as user input using float(input()) and store it in a variable.
gvn_Orignl_amt = float(input("Enter some random number = "))
# Give the net price as user input using float(input()) and store it in another variable.
gvn_Net_amt = float(input("Enter some random number = "))
# Calculate the GST amount by using the above given formula and store it in
# another variable.
GST_amnt = gvn_Net_amt - gvn_Orignl_amt
# Calculate the given GST percentage by using the above given formula and
# store it in another variable.
gvn_GST_percnt = ((GST_amnt * 100) / gvn_Orignl_amt)
# Print the given GST value for the above given original and net prices.
print("The GST percent for the above given input net and original prices = ",
      gvn_GST_percnt, end='')
print("%")

Output:

Enter some random number = 354.80
Enter some random number = 582.5
The GST percent for the above given input net and original prices = 64.17700112739571%

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.

Program to Add Trailing Zeros to String

Python Program to Add Trailing Zeros to String

In the previous article, we have discussed Python Program to Calculate GST
Given a String, and the task is to add the given number of trialing Zeros to the given String.

ljust() method :

We can add trailing zeros to the string using the ljust() method. It has two parameters, x, and y, where x is the length of the string. What will this method accomplish? It will simply go through a string and then to the length of the string that we require, and if both are not the same, it will pad those zeros that they have passed through a string and then store them in another.

Examples:

Example1:

Input:

Given String = hello btechgeeks
no of zeros to be added = 5

Output:

The above given string = hello btechgeeks
The above Given string with added given number of trailing zeros =  hello btechgeeks00000

Example1:

Input:

Given String = good morning btechgeeks
no of zeros to be added = 10

Output:

Enter some Random String = good morning btechgeeks
The above given string = good morning btechgeeks
Enter some Random Number = 10
The above Given string with added given number of trailing zeros = good morning btechgeeks0000000000

Program to Add Trailing Zeros to String

Below are the ways to add trailing Zeros to the given String

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

Approach:

  • Give the string as static input and store it in a variable.
  • Print the above-given string.
  • Give the number of trailing zeros to be added as static input and store it in another variable.
  • Calculate the length of the above-given string using the built-in len() function.
  • Add it with the given number of zeros and store it in another variable.
  • Add the given number of trailing zeros to the above-given String Using the built-in ljust() method and store it in another variable.
  • Print the above-Given string with added given the number of trailing Zeros.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_strng = 'hello btechgeeks'
# Print the above given string .
print("The above given string = " + str(gvn_strng))
# Give the number of trailing zeros to be added as static input and store it in another
# variable.
No_trzers = 5
# Calculate the length of the above given string using built- in len() function .
# Add it with the given number of zeros and store it in another variable.
tot_lenth = No_trzers + len(gvn_strng)
# Add the given number of trailing zeros to the above given String Using built-in ljust()
# method and store it in another variable.
finl_reslt = gvn_strng.ljust(tot_lenth, '0')
# Print the above Given string with added given number of trailing Zeros.
print("The above Given string with added given number of trailing zeros = ", finl_reslt)

Output:

The above given string = hello btechgeeks
The above Given string with added given number of trailing zeros =  hello btechgeeks00000

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

Approach:

  • Give the string as User input using the input() function and store it in a variable.
  • Print the above given string .
  • Give the number of trailing zeros to be added as User input using the int(input()) function and store it in another variable.
  • Calculate the length of the above given string using built- in len() function .
  • Add it with the given number of zeros and store it in another variable.
  • Add the given number of trailing zeros to the above given String Using built-in ljust() method and store it in another variable.
  • Print the above Given string with added given number of trailing Zeros.
  • 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_strng = input("Enter some Random String = ")
# Print the above given string .
print("The above given string = " + str(gvn_strng))
# Give the number of trailing zeros to be added as User input using the int(input()) function and store it in another
# variable.
No_trzers = int(input("Enter some Random Number = "))
# Calculate the length of the above given string using built- in len() function .
# Add it with the given number of zeros and store it in another variable.
tot_lenth = No_trzers + len(gvn_strng)
# Add the given number of trailing zeros to the above given String Using built-in ljust()
# method and store it in another variable.
finl_reslt = gvn_strng.ljust(tot_lenth, '0')
# Print the above Given string with added given number of trailing Zeros.
print("The above Given string with added given number of trailing zeros = ", finl_reslt)

Output:

Enter some Random String = good morning btechgeeks
The above given string = good morning btechgeeks
Enter some Random Number = 10
The above Given string with added given number of trailing zeros = good morning btechgeeks0000000000

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.

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.

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.

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.

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.

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.