Python Program to Generate Strong Numbers in an Interval

Program to Generate Strong Numbers in an Interval

In the previous article, we have discussed Python Program to Select a Random Element from a Tuple
Strong number:

A Strong number is a special number in which the total of all digit factorials equals the number itself.

Ex: 145 the sum of factorial of digits = 1 ! + 4 ! +5 ! = 1 + 24 +125

To determine whether a given number is strong or not. We take each digit from the supplied number and calculate its factorial, we will do this for each digit of the number.

We do the sum of factorials once we have the factorial of all digits. If the total equals the supplied number, the given number is strong; otherwise, it is not.

Given a number, the task is to check whether the given number is strong number or not.

Examples:

Example 1:

Input:

Given lower limit range  = 1
Given upper limit  range= 200

Output:

The Strong Numbers in a given range 1 and 200 are :
1 2 145

Example 2:

Input:

Given lower limit range = 100
Given upper limit range= 60000

Output:

The Strong Numbers in a given range 100 and 60000 are :
145 40585

Program to Generate Strong Numbers in an Interval

Below are the ways to generate Strong Numbers in a given interval.

Method #1: Using While loop and factorial() function (Static input)

Approach:

  1. Import math function using import keyword.
  2. Give the lower limit range as static input and store it in a variable.
  3. Give the upper limit range as static input and store it in another variable.
  4. Loop from lower limit range to upper limit range using For loop.
  5. Put the iterator value in a temporary variable called tempNum.
  6. Set a variable, say totalSum to zero. This will save the factorial sum of each of N’s digits.
  7. The number’s final digit must be saved in a variable, such as last_Digit = N % 10.
  8. Calculate the factorial of the last_Digit using math.factorial() function
  9. When the factorial of the last digit is found, it should be added to the totalSum = totalSumfactNum
  10. Following each factorial operation, the number must be reduced in terms of units by dividing it by ten that is  Itr = Itr /10
  11. Steps 5–8 should be repeated until N > 0.
  12. Check if the totalSum is equal to tempNum using the if conditional statement.
  13. If it is true then print the tempNum(which is the iterator value).
  14. The Exit of the program.

Below is the implementation:

# Import the math module using import keyword.
import math
# Give the lower limit range as static input and store it in a variable.
gvn_lower_lmt = 1
# Give the upper limit range as static input and store it in another variable.
gvn_upper_lmt = 200
# Loop from lower limit range to upper limit range using For loop.
print("The Strong Numbers in a given range",
      gvn_lower_lmt, "and", gvn_upper_lmt, "are :")
for itr in range(gvn_lower_lmt, gvn_upper_lmt+1):
   # Taking a variable totalSum and initializing it with 0
    totalSum = 0
    # Put the iterator value in a temporary variable called tempNum.
    tempNum = itr
    # using while to extract digit by digit of the given iterator value
    while(itr):
        s = 1
        factNum = 1
        # Getting the last digit of the iterator value
        remainder = itr % 10
        # calculating the factorial of the digit(extracted by remainder variable)
        # using math.fatorial function
        factNum = math.factorial(remainder)
        # Adding the factorial to the totalSum
        totalSum = totalSum + factNum
        # Dividing the given itertor value by 10
        itr = itr//10
    # checking if the totalSum is equal to the iterator value
    # if it is true then it is strong number then return true
    if(totalSum == tempNum):
        print(tempNum, end=' ')

Output:

The Strong Numbers in a given range 1 and 200 are :
1 2 145

Method #2: Using While loop and factorial() function (User input)

Approach:

  1. Import math function using the import keyword.
  2. Give the lower limit range as user input using int(input()) and store it in a variable.
  3. Give the upper limit range as user input using int(input()) and store it in another variable.
  4. Loop from lower limit range to upper limit range using For loop.
  5. Put the iterator value in a temporary variable called tempNum.
  6. Set a variable, say totalSum to zero. This will save the factorial sum of each of N’s digits.
  7. The number’s final digit must be saved in a variable, such as last_Digit = N % 10.
  8. Calculate the factorial of the last_Digit using math.factorial() function
  9. When the factorial of the last digit is found, it should be added to the totalSum = totalSumfactNum
  10. Following each factorial operation, the number must be reduced in terms of units by dividing it by ten that is  Itr = Itr /10
  11. Steps 5–8 should be repeated until N > 0.
  12. Check if the totalSum is equal to tempNum using the if conditional statement.
  13. If it is true then print the tempNum(which is the iterator value).
  14. The Exit of the program.

Below is the implementation:

# Import the math module using import keyword.
import math
#Give the lower limit range as user input using int(input()) and
#store it in a variable.
gvn_lower_lmt = int(input("Enter some random number = "))
#Give the upper limit range as user input using int(input()) and 
#store it in another variable.
gvn_upper_lmt = int(input("Enter some random number = "))
# Loop from lower limit range to upper limit range using For loop.
print("The Strong Numbers in a given range",
      gvn_lower_lmt, "and", gvn_upper_lmt, "are :")
for itr in range(gvn_lower_lmt, gvn_upper_lmt+1):
   # Taking a variable totalSum and initializing it with 0
    totalSum = 0
    # Put the iterator value in a temporary variable called tempNum.
    tempNum = itr
    # using while to extract digit by digit of the given iterator value
    while(itr):
        s = 1
        factNum = 1
        # Getting the last digit of the iterator value
        remainder = itr % 10
        # calculating the factorial of the digit(extracted by remainder variable)
        # using math.fatorial function
        factNum = math.factorial(remainder)
        # Adding the factorial to the totalSum
        totalSum = totalSum + factNum
        # Dividing the given itertor value by 10
        itr = itr//10
    # checking if the totalSum is equal to the iterator value
    # if it is true then it is strong number then return true
    if(totalSum == tempNum):
        print(tempNum, end=' ')

Output:

Enter some random number = 1
Enter some random number = 5000
The Strong Numbers in a given range 1 and 5000 are :
1 2 145

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 Strong Numbers in a List

Program to Find Strong Numbers in a List

In the previous article, we have discussed Python Program to Generate Strong Numbers in an Interval
Strong number:

A Strong number is a special number in which the total of all digit factorials equals the number itself.

Ex: 145 the sum of factorial of digits = 1 ! + 4 ! +5 ! = 1 + 24 +125

To determine whether a given number is strong or not. We take each digit from the supplied number and calculate its factorial, we will do this for each digit of the number.

We do the sum of factorials once we have the factorial of all digits. If the total equals the supplied number, the given number is strong; otherwise, it is not.

Given a list, and the task is to find all the Strong numbers in a given list.

Examples:

Example1:

Input:

Given List = [4, 1, 4, 145]

Output:

The Strong Numbers in a given List are :
1 145

Example2:

Input:

Given List =[5, 10, 650, 40585, 2, 145, 900]

Output:

The Strong Numbers in a given List are :
40585 2 145

Program to Find Strong Numbers in a List

Below are the ways to find all the Strong numbers in a given list.

Method #1: Using While loop and factorial() function (Static input)

Approach:

  1. Import the math module using the import keyword.
  2. Give the list as static input and store it in a variable.
  3. Loop in the above-given list using For Loop.
  4. Put the iterator value in a temporary variable called tempNum.
  5. Set a variable, say totalSum to zero. This will save the factorial sum of each of N’s digits.
  6. The number’s final digit must be saved in a variable, such as last_Digit = N % 10.
  7. Calculate the factorial of the last_Digit using math.factorial() function
  8. When the factorial of the last digit is found, it should be added to the totalSum = totalSumfactNum
  9. Following each factorial operation, the number must be reduced in terms of units by dividing it by ten that is  Itr = Itr /10
  10. Steps 5–8 should be repeated until N > 0.
  11. Check if the totalSum is equal to tempNum using the if conditional statement.
  12. If it is true then print the tempNum(which is the iterator value).
  13. The Exit of the program.

Below is the implementation:

# Import the math module using import keyword.
import math
# Give the list as static input and store it in a variable.
list1 = [4, 1, 4, 145]
# Loop in the above given list using For Loop.
print("The Strong Numbers in a given List are :")
for i in list1:
   # Taking a variable totalSum and initializing it with 0
    totalSum = 0
    # Put the iterator value in a temporary variable called tempNum.
    tempNum = i
    # using while to extract digit by digit of the given iterator value
    while(i):
        s = 1
        factNum = 1
        # Getting the last digit of the iterator value
        remainder = i % 10
        # calculating the factorial of the digit(extracted by remainder variable)
        # using math.fatorial function
        factNum = math.factorial(remainder)
        # Adding the factorial to the totalSum
        totalSum = totalSum + factNum
        # Dividing the given itertor value by 10
        i = i//10
    # checking if the totalSum is equal to the iterator value
    # if it is true then it is strong number then return true
    if(totalSum == tempNum):
        print(tempNum, end=' ')

Output:

The Strong Numbers in a given List are :
1 145

Method #2: Using While loop and factorial() function (User input)

Approach:

  1. Import the math module using the import keyword.
  2. Give the list as user input using list(),map(),input(),and split() functions and Store it in a variable.
  3. Loop in the above-given list using For Loop.
  4. Put the iterator value in a temporary variable called tempNum.
  5. Set a variable, say totalSum to zero. This will save the factorial sum of each of N’s digits.
  6. The number’s final digit must be saved in a variable, such as last_Digit = N % 10.
  7. Calculate the factorial of the last_Digit using math.factorial() function
  8. When the factorial of the last digit is found, it should be added to the totalSum = totalSumfactNum
  9. Following each factorial operation, the number must be reduced in terms of units by dividing it by ten that is  Itr = Itr /10
  10. Steps 5–8 should be repeated until N > 0.
  11. Check if the totalSum is equal to tempNum using the if conditional statement.
  12. If it is true then print the tempNum(which is the iterator value).
  13. The Exit of the program.

Below is the implementation:

# Import the math module using import keyword.
import math
#Give the list as user input using list(),map(),input(),and split() functions and 
#Store it in a variable
list1 = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Loop in the above given list using For Loop.
print("The Strong Numbers in a given List are :")
for i in list1:
   # Taking a variable totalSum and initializing it with 0
    totalSum = 0
    # Put the iterator value in a temporary variable called tempNum.
    tempNum = i
    # using while to extract digit by digit of the given iterator value
    while(i):
        s = 1
        factNum = 1
        # Getting the last digit of the iterator value
        remainder = i % 10
        # calculating the factorial of the digit(extracted by remainder variable)
        # using math.fatorial function
        factNum = math.factorial(remainder)
        # Adding the factorial to the totalSum
        totalSum = totalSum + factNum
        # Dividing the given itertor value by 10
        i = i//10
    # checking if the totalSum is equal to the iterator value
    # if it is true then it is strong number then return true
    if(totalSum == tempNum):
        print(tempNum, end=' ')

Output:

Enter some random List Elements separated by spaces = 1 145 10 15 2
The Strong Numbers in a given List are :
1 145 2

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 all Disarium Numbers within Given range

Program to Print all Disarium Numbers within Given range

In the previous article, we have discussed Python Program to Get Tangent value Using math.tan()
Disarium Number:

A Disarium number is one in which the sum of each digit raised to the power of its respective position equals the original number.

like 135 , 89, etc.

Here 1^1 + 3^2 + 5^3 = 135 so it is disarium Number

Examples:

Example1:

Input:

Given lower limit range = 7
Given upper limit range = 180

Output:

The disarium numbers in the given range 7 and 180 are: 
7 8 9 89 135 175

Example 2:

Input:

Given lower limit range = 1
Given upper limit range = 250

Output:

The disarium numbers in the given range 1 and 250 are:
1 2 3 4 5 6 7 8 9 89 135 175

Program to Print all Disarium Numbers within Given range

Below are the ways to Print all Disarium Numbers within the given range.

Method #1: Using For Loop (Static input)

Approach:

  • 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.
  • Loop from lower limit range to upper limit range using For loop.
  • Inside the for loop take a variable say ‘num’ and initialize its value to the iterator value.
  • Make a copy of the number so you can verify the outcome later.
  • Make a result variable (with a value of 0) and an iterator ( set to the size of the number)
  • Create a while loop to go digit by digit through the number.
  • On each iteration, multiply the result by a digit raised to the power of the iterator value.
  • On each traversal, increment the iterator.
  • Compare the result value to a copy of the original number.
  • Print if the given number is a disarium number.
  • The Exit of the program.

Below is the implementation:

# Give the lower limit range as static input and store it in a variable.
lowlim_range = 7
# Give the upper limit range as static input and store it in another variable.
upplim_range = 180
print('The disarium numbers in the given range',
      lowlim_range, 'and', upplim_range, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for m in range(lowlim_range, upplim_range+1):

    # given number
    num = m
    # intialize result to zero(ans)
    ans = 0

    # calculating the digits
    digit_s = len(str(num))
    # copy the number in another variable(duplicate)
    dup_numbr = num
    while (dup_numbr != 0):
        # getting the last digit
        remaindr = dup_numbr % 10
        # multiply the result by a digit raised to the power of the iterator value.
        ans = ans + remaindr**digit_s
        digit_s = digit_s - 1
        dup_numbr = dup_numbr//10
    # It is disarium number if it is equal to original number
    if(num == ans):
        print(num, end=' ')

Output:

The disarium numbers in the given range 7 and 180 are:
7 8 9 89 135 175

Method #2: Using For Loop (User input)

Approach:

  • 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.
  • Loop from lower limit range to upper limit range using For loop.
  • Inside the for loop take a variable say ‘num’ and initialize it’s value to  iterator value .
  • Make a copy of the number so you can verify the outcome later.
  • Make a result variable (with a value of 0) and an iterator ( set to the size of the number)
  • Create a while loop to go digit by digit through the number.
  • On each iteration, multiply the result by a digit raised to the power of the iterator value.
  • On each traversal, increment the iterator.
  • Compare the result value to a copy of the original number.
  • Print if the given number is a disarium number.
  • The Exit of the program.

Below is the implementation:

# Give the lower limit range as user input using the int(input()) function and store it in a variable.
lowlim_range = 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.
upplim_range = int(input("Enter some Random number = "))
print('The disarium numbers in the given range',
      lowlim_range, 'and', upplim_range, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for m in range(lowlim_range, upplim_range+1):

    # given number
    num = m
    # intialize result to zero(ans)
    ans = 0

    # calculating the digits
    digit_s = len(str(num))
    # copy the number in another variable(duplicate)
    dup_numbr = num
    while (dup_numbr != 0):
        # getting the last digit
        remaindr = dup_numbr % 10
        # multiply the result by a digit raised to the power of the iterator value.
        ans = ans + remaindr**digit_s
        digit_s = digit_s - 1
        dup_numbr = dup_numbr//10
    # It is disarium number if it is equal to original number
    if(num == ans):
        print(num, end=' ')

Output:

Enter some Random number = 1
Enter some Random number = 250
The disarium numbers in the given range 1 and 250 are:
1 2 3 4 5 6 7 8 9 89 135 175

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 Even Number Pattern

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Given the number of rows, the task is to print Even Number Pattern in C, C++, and Python.

Examples:

Example1:

Input:

Given number of rows = 10

Output:

20 
20 18 
20 18 16 
20 18 16 14 
20 18 16 14 12 
20 18 16 14 12 10 
20 18 16 14 12 10 8 
20 18 16 14 12 10 8 6 
20 18 16 14 12 10 8 6 4 
20 18 16 14 12 10 8 6 4 2

Example2:

Input:

Given number of rows = 6

Output:

12 
12 10 
12 10 8 
12 10 8 6 
12 10 8 6 4 
12 10 8 6 4 2

Program to Print Even Number Pattern in C, C++, and Python

Below are the ways to print Even Number Pattern in C, C++, and Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number of rows as static input and store it in a variable.
  • Take a variable and initialize it with 2*double the number of rows say lastnumb.
  • Take another variable and initialize it with the lastnumb say evennumb.
  • Loop from 1 to the number of rows using For loop.
  • Initialize the evennumb with the lastnumb.
  • Loop from 0 to the iterator value of the parent For loop using another for loop(Nested For loop).
  • Print the evennumb.
  • Reduce the evennumb by 2.
  • Print the Newline character after the end of the inner loop.
  • The Exit of the Program.

1) Python Implementation

Below is the implementation:

# Give the number of rows as static input and store it in a variable.
numberOfRows = 10
# Take a variable and initialize it with 2*double the number of rows say lastnumb.
lastnumb = 2*numberOfRows
# Take another variable and initialize it with the lastnumb say evennumb.
evennumb = lastnumb
# Loop from 1 to the number of rows using For loop.
for m in range(1, numberOfRows+1):
    # Initialize the evennumb with the lastnumb.
    evennumb = lastnumb
    # Loop from 0 to the iterator value of the parent For loop using
    # another for loop(Nested For loop).
    for n in range(0, m):
        # Print the evennumb.
        print(evennumb, end=' ')
        # Reduce the evennumb by 2.
        evennumb = evennumb-2

    # Print the Newline character after the end of the inner loop.
    print()

Output:

20 
20 18 
20 18 16 
20 18 16 14 
20 18 16 14 12 
20 18 16 14 12 10 
20 18 16 14 12 10 8 
20 18 16 14 12 10 8 6 
20 18 16 14 12 10 8 6 4 
20 18 16 14 12 10 8 6 4 2

2) C++ Implementation

Below is the implementation:

#include <iostream>
#include <math.h>
using namespace std;
int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numberOfRows = 8;
    // Take a variable and initialize it with 2*double the
    // number of rows say lastnumb.
    int lastnumb = 2 * numberOfRows;

    // Take another variable and initialize it with the
    // lastnumb say evennumb.
    int evennumb = lastnumb;
    //  Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numberOfRows; m++) {
        // Initialize the evennumb with the lastnumb.
        evennumb = lastnumb;
        // Loop from 0 to the iterator value of the parent
        // For loop using
        // another for loop(Nested For loop).
        for (int n = 0; n < m; n++) {
            // Print the evennumb.
            cout << evennumb << " ";

            // Reduce the evennumb by 2.
            evennumb = evennumb - 2;
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

16 
16 14 
16 14 12 
16 14 12 10 
16 14 12 10 8 
16 14 12 10 8 6 
16 14 12 10 8 6 4 
16 14 12 10 8 6 4 2

3) C Implementation

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numberOfRows = 8;
    // Take a variable and initialize it with 2*double the
    // number of rows say lastnumb.
    int lastnumb = 2 * numberOfRows;

    // Take another variable and initialize it with the
    // lastnumb say evennumb.
    int evennumb = lastnumb;
    //  Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numberOfRows; m++) {
        // Initialize the evennumb with the lastnumb.
        evennumb = lastnumb;
        // Loop from 0 to the iterator value of the parent
        // For loop using
        // another for loop(Nested For loop).
        for (int n = 0; n < m; n++) {
            // Print the evennumb.
            printf("%d ", evennumb);

            // Reduce the evennumb by 2.
            evennumb = evennumb - 2;
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

16 
16 14 
16 14 12 
16 14 12 10 
16 14 12 10 8 
16 14 12 10 8 6 
16 14 12 10 8 6 4 
16 14 12 10 8 6 4 2

Method #2: Using For Loop (User Input)

Approach:

  • Give the number of rows as user input and store it in a variable.
  • Take a variable and initialize it with 2*double the number of rows say lastnumb.
  • Take another variable and initialize it with the lastnumb say evennumb.
  • Loop from 1 to the number of rows using For loop.
  • Initialize the evennumb with the lastnumb.
  • Loop from 0 to the iterator value of the parent For loop using another for loop(Nested For loop).
  • Print the evennumb.
  • Reduce the evennumb by 2.
  • Print the Newline character after the end of the inner loop.
  • The Exit of the Program.

1) Python Implementation

Give the number of rows as user input using int(input()) and store it in a variable.

Below is the implementation:

# Give the number of rows as user input using int(input()) and store it in a variable.
numberOfRows = int(input('Enter some random number of rows = '))
# Take a variable and initialize it with 2*double the number of rows say lastnumb.
lastnumb = 2*numberOfRows
# Take another variable and initialize it with the lastnumb say evennumb.
evennumb = lastnumb
# Loop from 1 to the number of rows using For loop.
for m in range(1, numberOfRows+1):
    # Initialize the evennumb with the lastnumb.
    evennumb = lastnumb
    # Loop from 0 to the iterator value of the parent For loop using
    # another for loop(Nested For loop).
    for n in range(0, m):
        # Print the evennumb.
        print(evennumb, end=' ')
        # Reduce the evennumb by 2.
        evennumb = evennumb-2

    # Print the Newline character after the end of the inner loop.
    print()

Output:

Enter some random number of rows = 10
20 
20 18 
20 18 16 
20 18 16 14 
20 18 16 14 12 
20 18 16 14 12 10 
20 18 16 14 12 10 8 
20 18 16 14 12 10 8 6 
20 18 16 14 12 10 8 6 4 
20 18 16 14 12 10 8 6 4 2

2) C++ Implementation

Give the number of rows as user input using cin and store it in a variable.

Below is the implementation:

#include <iostream>
using namespace std;
int main()
{

    // Give the number of rows as user input using
    // int(input()) and store it in a variable.
    int numberOfRows;
    cin >> numberOfRows;
    // Take a variable and initialize it with 2*double the
    // number of rows say lastnumb.
    int lastnumb = 2 * numberOfRows;

    // Take another variable and initialize it with the
    // lastnumb say evennumb.
    int evennumb = lastnumb;
    //  Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numberOfRows; m++) {
        // Initialize the evennumb with the lastnumb.
        evennumb = lastnumb;
        // Loop from 0 to the iterator value of the parent
        // For loop using
        // another for loop(Nested For loop).
        for (int n = 0; n < m; n++) {
            // Print the evennumb.
            cout << evennumb << " ";

            // Reduce the evennumb by 2.
            evennumb = evennumb - 2;
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

6
12 
12 10 
12 10 8 
12 10 8 6 
12 10 8 6 4 
12 10 8 6 4 2 

3) C Implementation

Give the number of rows as user input using scanf and store it in a variable.

Below is the implementation:

#include <stdio.h>
int main()
{

    // Give the number of rows as user input using scanf and
    // store it in a variable.
    int numberOfRows;
    scanf("%d", &numberOfRows);
    // Take a variable and initialize it with 2*double the
    // number of rows say lastnumb.
    int lastnumb = 2 * numberOfRows;

    // Take another variable and initialize it with the
    // lastnumb say evennumb.
    int evennumb = lastnumb;
    //  Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numberOfRows; m++) {
        // Initialize the evennumb with the lastnumb.
        evennumb = lastnumb;
        // Loop from 0 to the iterator value of the parent
        // For loop using
        // another for loop(Nested For loop).
        for (int n = 0; n < m; n++) {
            // Print the evennumb.
            printf("%d ", evennumb);

            // Reduce the evennumb by 2.
            evennumb = evennumb - 2;
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

6
12 
12 10 
12 10 8 
12 10 8 6 
12 10 8 6 4 
12 10 8 6 4 2

Related Programs:

Python Program to Check Sunny Number

Program to Check Sunny Number

In the previous article, we have discussed Python Program to Find the Missing Term of any Arithmetic Progression
Sunny Number:

A number is said to be a sunny number if the number next to it is a perfect square. In other words, if N+1 is a perfect square, then N is a sunny number.

Example :

Let Given number(N) = 3

Then N+1= 3+1 = 4 # which is a perfect square.

Therefore ,the Given number “3” is a Sunny Number.

some of the examples are 3,8 ,15, 24, 35 ,48 ,63, 80 ,99, 120 etc.

Given a number, the task is to check whether the given number is a Sunny Number or not.

Examples:

Example1:

Input:

Given number = 3

Output:

The given number{ 3 } is Sunny Number

Example2:

Input:

Given number = 122

Output:

The given number{ 122 } is not a Sunny Number

Program to Check Sunny Number

Below are the ways to check whether the given number is a Sunny Number or not.

Method #1: Using math.sqrt() function (Static input)

Approach:

  1. Import the math module using the import keyword.
  2. Give the number as static input and store it in a variable.
  3. Add ‘1’ to the above-given number and store it in another variable say “incremented number”.
  4. Calculate the Square root of the above-obtained number using math.sqrt() built-in function and store it in another variable.
  5. Multiply the above obtained Square root value with itself and store it in another variable say “square_number”.
  6. Check if the value of “square_number ” is equal to the “incremented number” using if conditional statement.
  7. If the statement is True,Print “The given number is Strong Number
  8. Else if the statement is False, print “The given number is Not a Strong Number”.
  9. The Exit of the program.

Below is the implementation:

# Import the math module using import keyword.
import math
# Give the number as static input and store it in a variable.
numb = 3
# Add '1' to the above given number and store it in another variable say
# "incremented number".
incremnt_num = numb + 1
# Calculate the Square root of the above obtained number using math.sqrt()
# built-in function and store it in another variable.
sqrt_numb = math.sqrt(incremnt_num)
# Multiply the above obtained Square root value with itself and
# store it in another variable say "square_number".
square_number = sqrt_numb * sqrt_numb
# Check if the value of "square_number " is equal the "incremented number"
# using if conditional statement.
if(square_number == incremnt_num):
  # If the statement is True ,Print "The given number is Strong Number"
    print("The given number{", numb, "} is Sunny Number")
else:
  # Else if the statement is False, print "The given number is Not a Strong Number" .
    print("The given number{", numb, "} is not a Sunny Number")

Output:

The given number{ 3 } is Sunny Number

Method #2: Using math.sqrt() function (User input)

Approach:

  1. Import the math module using the import keyword.
  2. Give the number as user input using the int(input()) function and store it in a variable.
  3. Add ‘1’ to the above-given number and store it in another variable say “incremented number”.
  4. Calculate the Square root of the above-obtained number using math.sqrt() built-in function and store it in another variable.
  5. Multiply the above obtained Square root value with itself and store it in another variable say “square_number”.
  6. Check if the value of “square_number ” is equal to the “incremented number” using if conditional statement.
  7. If the statement is True, Print “The given number is Strong Number”
  8. Else if the statement is False, print “The given number is Not a Strong Number”.
  9. The Exit of the program.

Below is the implementation:

# Import the math module using import keyword.
import math
# Give the number as user input using int(input()) and store it in a variable.
numb = int(input("Enter some random number = "))
# Add '1' to the above given number and store it in another variable say
# "incremented number".
incremnt_num = numb + 1
# Calculate the Square root of the above obtained number using math.sqrt()
# built-in function and store it in another variable.
sqrt_numb = math.sqrt(incremnt_num)
# Multiply the above obtained Square root value with itself and
# store it in another variable say "square_number".
square_number = sqrt_numb * sqrt_numb
# Check if the value of "square_number " is equal the "incremented number"
# using if conditional statement.
if(square_number == incremnt_num):
  # If the statement is True ,Print "The given number is Strong Number"
    print("The given number{", numb, "} is Sunny Number")
else:
  # Else if the statement is False, print "The given number is Not a Strong Number" .
    print("The given number{", numb, "} is not a Sunny Number")

Output:

Enter some random number = 30
The given number{ 30 } is not a Sunny Number

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.

 

Pandas: Create Dataframe from List of Dictionaries

Methods of creating a dataframe from a list of dictionaries

In this article, we discuss different methods by which we can create a dataframe from a list of dictionaries. Before going to the actual article let us done some observations that help to understand the concept easily. Suppose we have a list of dictionary:-

list_of_dict = [
{'Name': 'Mayank' , 'Age': 25, 'Marks': 91},
{'Name': 'Raj', 'Age': 21, 'Marks': 97},
{'Name': 'Rahul', 'Age': 23, 'Marks': 79},
{'Name': 'Manish' , 'Age': 23},
]

Here we know that dictionaries consist of key-value pairs. So we can analyze that if we make the key as our column name and values as the column value then a dataframe is easily created. And we have a list of dictionaries so a dataframe with multiple rows also.

pandas.DataFrame

This methods helps us to create dataframe in python

syntax: pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

Let us see different methods to create dataframe from a list of dictionaries

  • Method 1-Create Dataframe from list of dictionaries with default indexes

As we see in in pandas.Datframe() method there is parameter name data.We have to simply pass our list of dictionaries in this method and it will return the dataframe.Let see this with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Age': 23,  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23,  'Marks': 86},
]
#create dataframe
df=pd.DataFrame(list_of_dict)
print(df)

Output

   Age  Marks    Name
0   25     91  Mayank
1   21     97     Raj
2   23     79   Rahul
3   23     86  Manish

Here we see that dataframe is created with default indexes 0,1,2,3….

Now a question may arise if from any dictionary key-value pair is less than other dictionaries.So in this case what happened.Let understand it with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23},
]
#create dataframe
df=pd.DataFrame(list_of_dict)
print(df)

Output

    Age  Marks    Name
0  25.0   91.0  Mayank
1  21.0   97.0     Raj
2   NaN   79.0   Rahul
3  23.0    NaN  Manish

Here we see in case of missing key value pair NaN value is there in the output.

  • Method 2- Create Dataframe from list of dictionary with custom indexes

Unlike the previous method where we have default indexes we can also give custom indexes by passes list of indexes in index parameter of pandas.DataFrame() function.Let see this with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23},
]
#create dataframe
df=pd.DataFrame(list_of_dict,index=['a','b','c','d'])
print(df)

Output

    Age  Marks    Name
a  25.0   91.0  Mayank
b  21.0   97.0     Raj
c   NaN   79.0   Rahul
d  23.0    NaN  Manish

Here we see that instead of default index 1,2,3….. we have now indes a,b,c,d.

  • Method 3-Create Dataframe from list of dictionaries with changed order of columns

With the help of pandas.DataFrame() method we can easily arrange order of column by simply passes list ozf columns in columns parameter in the order in which we want to display it in our dataframe.Let see this with the help of example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Age': 23,  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23,  'Marks': 86},
]
#create dataframe
df=pd.DataFrame(list_of_dict,columns=['Name', 'Marks', 'Age'])
print(df)

Output

     Name  Marks  Age
0  Mayank     91   25
1     Raj     97   21
2   Rahul     79   23
3  Manish     86   23

Here also a question may arise if we pass less column in columns parameter or we pass more column in parameter then what happened.Let see this with the help of an example.

Case 1: Less column in column parameter

In this case the column which we don’t pass will be drop from the dataframe.Let see this with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Age': 23,  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23,  'Marks': 86},
]
#create dataframe
df=pd.DataFrame(list_of_dict,columns=['Name', 'Marks'])
print(df)

Output

     Name  Marks
0  Mayank     91
1     Raj     97
2   Rahul     79
3  Manish     86

Here we see that we didn’t pass Age column that’s why Age clumn is also not in our dataframe.

Case 2: More column in column parameter

In this case a new column will be added in dataframe but its all the value will be NaN.Let see this with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Age': 23,  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23,  'Marks': 86},
]
#create dataframe
df=pd.DataFrame(list_of_dict,columns=['Name', 'Marks', 'Age','city'])
print(df)

Output

     Name  Marks  Age  city
0  Mayank     91   25   NaN
1     Raj     97   21   NaN
2   Rahul     79   23   NaN
3  Manish     86   23   NaN

So these are the methods to create dataframe from list of dictionary in pandas.

Create Numpy Array of different shapes & initialize with identical values using numpy.full() in Python

Creating Numpy Array of different shapes & initialize with identical values using numpy.full()

In this article we will see how we can create a numpy array of different shapes but initialized with identical values. So, let’s start the explore the concept to understand it well.

numpy.full() :

Numpy module provides a function numpy.full() to create a numpy array of given shape and initialized with a given value.

Syntax : numpy.full(shape, given_value, dtype=None, order='C')

Where,

  • shape : Represents shape of the array.
  • given_value : Represents initialization value.
  • dtype : Represents the datatype of elements(Optional).

But to use Numpy we have to include the following module i.e.

import numpy as np
Let’s see the below example to understand the concept.

Example-1 : Create a 1D Numpy Array of length 8 and all elements initialized with value 2

Here array length is 8 and array elements are to be initialized with 2.

Let’s see the below the program.

import numpy as np
# 1D Numpy Array created of length 8 & all elements initialized with value 2
sample_arr = np.full(8,2)
print(sample_arr)
Output :
[2 2 2 2 2 2 2 2]

Example-2 : Create a 2D Numpy Array of 3 rows | 4 columns and all elements initialized with value 5

Here 2D array of row 3 and column 4 and array elements to be initialized with 5.

Let’s see the below the program.

import numpy as np
#Create a 2D Numpy Array of 3 rows & 4 columns. All intialized with value 5
sample_arr = np.full((3,4), 5)
print(sample_arr)
Output :
[[5 5 5 5]
[5 5 5 5]
[5 5 5 5]]

Example-3 : Create a 3D Numpy Array of shape (3,3,4) & all elements initialized with value 1

Here initialized value is 1.

Let’s see the below the program.

import numpy as np
# Create a 3D Numpy array & all elements initialized with value 1
sample_arr = np.full((3,3,4), 1)
print(sample_arr)
Output :

[[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]

[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]

[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]]

Example-4 : Create initialized Numpy array of specified data type

Here, array length is 8 and value is 4 and data type is float.

import numpy as np
# 1D Numpy array craeted & all float elements initialized with value 4
sample_arr = np.full(8, 4, dtype=float)
print(sample_arr)
Output :
[4. 4. 4. 4. 4. 4. 4. 4.]
Read Also:

Python Program to Take in the Marks of 5 Subjects and Display the Grade

Program to Take in the Marks of 5 Subjects and Display the Grade

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

Given the marks of 5 subjects of the student, the task is to display the grade of the student based on the marks in Python.

Read Also: Python Program for Swapping Three Variables Without Using any Temporary Variable.

Examples:

Example1:

Input:

Enter first subject marks as integer = 75
Enter second subject marks as integer = 79
Enter third subject marks as integer = 65
Enter fourth subject marks as integer = 82
Enter fifth subject marks as integer = 63

Output:

Average of 5 marks = 72.8 Grade =C

Example2:

Input:

Enter first subject marks as integer = 63
Enter second subject marks as integer = 19
Enter third subject marks as integer = 99
Enter fourth subject marks as integer = 85
Enter fifth subject marks as integer = 73

Output:

Average of 5 marks = 67.8 Grade =D

Program to Take in the Marks of 5 Subjects and Display the Grade in Python

There are several ways to calculate the grade of the student based on the marks of 5 subjects in Python some of them are:

Method #1:Using IF..elif..else Statements(Static Input)

Approach:

  • Give the 5 subject marks as static input and store them in 5 variables.
  • Calculate the sum of the 5 subject marks and store it in a variable.
  • Divide the sum by 5 to get the average of all the given marks.
  • To determine the grade based on the average of the marks, use an if…Elif..else conditions.
  • Print the grade.
  • The Exit of the Program.

Below is the implementation:

# Give the 5 subject marks as static input and store them in 5 variables.
marks1 = 95
marks2 = 85
marks3 = 89
marks4 = 93
marks5 = 87
# Calculate the sum of the 5 subject marks and store it in a variable.
summarks = marks1+marks2+marks3+marks4+marks5
# Divide the sum of marks by 5 to get the average of all the given marks.
avgmark = summarks/5
# To determine the grade based on the average of the marks, use an if...Elif..else conditions.
if(avgmark >= 90):
    print("Average of 5 marks =", avgmark, 'Grade =A')
elif(avgmark >= 80 and avgmark < 90):
    print("Average of 5 marks =", avgmark, 'Grade =B')
elif(avgmark >= 70 and avgmark < 80):
    print("Average of 5 marks =", avgmark, 'Grade =C')
elif(avgmark >= 60 and avgmark < 70):
    print("Average of 5 marks =", avgmark, 'Grade =D')
else:
    print("Average of 5 marks =", avgmark, 'Grade =E')

Output:

Average of 5 marks = 89.8 Grade =B

Explanation:

  • The user must enter 5 different values as static input and store them in different variables.
  • Then add together all five marks and divide by five to get the average.
  • If the average is more than 90, the grade is displayed as “A.”
  • If the average is between 80 and 90, the letter “B” is printed.
  • If the average is between 70 and 80, the letter “C” is printed.
  • If the average is between 60 and 70, the letter “D” is printed.
  • If the average falls below 60, the letter “F” is printed.

Method #2:Using IF..elif..else Statements (User Input separated by newline)

Approach:

  • Give the 5 subject marks as user input using int(input()) which converts the string to an integer.
  • Store them in 5 separate variables.
  • Calculate the sum of the 5 subject marks and store it in a variable.
  • Divide the sum by 5 to get the average of all the given marks.
  • To determine the grade based on the average of the marks, use an if…Elif..else conditions.
  • Print the grade.
  • The Exit of the Program.

Below is the implementation:

# Give the 5 subject marks as user input using int(input()) which converts the string to an integer.
# Store them in 5 separate variables.
marks1 = int(input('Enter first subject marks as integer = '))
marks2 = int(input('Enter second subject marks as integer = '))
marks3 = int(input('Enter third subject marks as integer = '))
marks4 = int(input('Enter fourth subject marks as integer = '))
marks5 = int(input('Enter fifth subject marks as integer = '))
# Calculate the sum of the 5 subject marks and store it in a variable.
summarks = marks1+marks2+marks3+marks4+marks5
# Divide the sum of marks by 5 to get the average of all the given marks.
avgmark = summarks/5
# To determine the grade based on the average of the marks, use an if...Elif..else conditions.
if(avgmark >= 90):
    print("Average of 5 marks =", avgmark, 'Grade =A')
elif(avgmark >= 80 and avgmark < 90):
    print("Average of 5 marks =", avgmark, 'Grade =B')
elif(avgmark >= 70 and avgmark < 80):
    print("Average of 5 marks =", avgmark, 'Grade =C')
elif(avgmark >= 60 and avgmark < 70):
    print("Average of 5 marks =", avgmark, 'Grade =D')
else:
    print("Average of 5 marks =", avgmark, 'Grade =E')

Output:

Enter first subject marks as integer = 75
Enter second subject marks as integer = 79
Enter third subject marks as integer = 65
Enter fourth subject marks as integer = 82
Enter fifth subject marks as integer = 63
Average of 5 marks = 72.8 Grade =C

Method #3:Using IF..elif..else Statements and map(),split() functions (User Input separated by spaces)

Approach:

  • Give the 5 subject marks as user input separated by spaces using map(), split() functions.
  • Store them in 5 separate variables.
  • Calculate the sum of the 5 subject marks and store it in a variable.
  • Divide the sum by 5 to get the average of all the given marks.
  • To determine the grade based on the average of the marks, use an if…Elif..else conditions.
  • Print the grade.
  • The Exit of the Program.

Below is the implementation:

# Give the 5 subject marks as user input separated by spaces using map(), split() functions.
# Store them in 5 separate variables.
marks1, marks2, marks3, marks4, marks5 = map(int, input(
    'Enter 5 subject marks separated by spaces = ').split())
# Calculate the sum of the 5 subject marks and store it in a variable.
summarks = marks1+marks2+marks3+marks4+marks5
# Divide the sum of marks by 5 to get the average of all the given marks.
avgmark = summarks/5
# To determine the grade based on the average of the marks, use an if...Elif..else conditions.
if(avgmark >= 90):
    print("Average of 5 marks =", avgmark, 'Grade =A')
elif(avgmark >= 80 and avgmark < 90):
    print("Average of 5 marks =", avgmark, 'Grade =B')
elif(avgmark >= 70 and avgmark < 80):
    print("Average of 5 marks =", avgmark, 'Grade =C')
elif(avgmark >= 60 and avgmark < 70):
    print("Average of 5 marks =", avgmark, 'Grade =D')
else:
    print("Average of 5 marks =", avgmark, 'Grade =E')

Output:

Enter 5 subject marks separated by spaces = 45 96 78 99 92
Average of 5 marks = 82.0 Grade =B

Read Also:

  1. Python program to create grade calculator?
  2. Python program to find grade of a student using if else?
  3. Student mark list program in python using for loop?
  4. Python program to find average and grade for given marks?
  5. Write a program to take in the marks of 5 subjects and display the grade in c?
  6. Python program to calculate total marks percentage and grade of a student?
  7. Student mark list program in python using function?
  8. Student mark list program in python using class?
  9. Write a program to enter marks of 5 subjects and calculate percentage and division?
  10. Write a program to display student name and marks in python?
  11. Python program to create grade calculator?
  12. Python program to take in the marks of 5 subjects and display the grade?
  13. Write a python program to take in the marks of 5 subjects and display the grade?

Related Programs:

Add column to csv python – Python: Add a Column to an Existing CSV File

Python Add a Column to an Existing CSV File

Methods to add a column to an existing CSV File

Add column to csv python: In this article, we will discuss how to add a column to an existing CSV file using csv.reader and csv.DictWriter  classes. Apart from appending the columns, we will also discuss how to insert columns in between other columns of the existing CSV file.

We also include these for beginners:

  • Add a list as a column to an existing csv file python
  • Add column from one csv to another python
  • Add column to existing csv
  • Add two columns in csv python
  • Add column to csv powershell
  • Python csv write to specific row and column
  • Add column to existing csv
  • Add two columns in csv python
  • Add column to csv powershell
  • Add a list as a column to an existing csv file python
  • Add column from one csv to another python
  • Python add a column to an existing csv file
  • Python add a new column to csv
  • Python add csv column to list
  • Python pandas append column to csv
  • Add a line to a csv file python

Original CSV file content

total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
  • Method 1-Add a column with the same values to an existing CSV file

Python add column to csv: In this, we see how we make one column and add it to our CSV file but all the values in this column are the same.

Steps will be to append a column in CSV file are,

  1. Open ‘input.csv’ file in read mode and create csv.reader object for this CSV file
  2. Open ‘output.csv’ file in write mode and create csv.writer object for this CSV file
  3. Using reader object, read the ‘input.csv’ file line by line
  4. For each row (read like a list ), append default text in the list.
  5. Write this updated list / row in the ‘output.csv’ using csv.writer object for this file.
  6. Close both input.csv and output.csv file.

Let see this with the help of an example

from csv import writer
from csv import reader
default_text = 'New column'
# Open the input_file in read mode and output_file in write mode
with open('example1.csv', 'r') as read_obj, \
        open('output_1.csv', 'w', newline='') as write_obj:
    # Create a csv.reader object from the input file object
    csv_reader = reader(read_obj)
    # Create a csv.writer object from the output file object
    csv_writer = writer(write_obj)
    # Read each row of the input csv file as list
    for row in csv_reader:
        # Append the default text in the row / list
        row.append(default_text)
        # Add the updated row / list to the output file
        csv_writer.writerow(row)
output_data=pd.read_csv('output_1.csv')
output_data.head()

Output

total_bill tip sex smoker day time size New column
0 16.99 1.01 Female No Sun Dinner 2 New column
1 10.34 1.66 Male No Sun Dinner 3 New column
2 21.01 3.50 Male No Sun Dinner 3 New column
3 23.68 3.31 Male No Sun Dinner 2 New column
4 24.59 3.61 Female No Sun Dinner 4 New column

Here we see that new column is added but all value in this column is same.

Now we see how we can add different values in the column.

  •  Method 2-Add a column to an existing CSV file, based on values from other columns

How to add a new column to a csv file using python: In this method how we can make a new column but in this column the value we add will be a combination of two or more columns. As we know there is no direct function to achieve so we have to write our own function to achieve this task. Let see the code for this.

from csv import writer
from csv import reader
def add_column_in_csv(input_file, output_file, transform_row):
    """ Append a column in existing csv using csv.reader / csv.writer classes"""
    # Open the input_file in read mode and output_file in write mode
    with open(input_file, 'r') as read_obj, \
            open(output_file, 'w', newline='') as write_obj:
        # Create a csv.reader object from the input file object
        csv_reader = reader(read_obj)
        # Create a csv.writer object from the output file object
        csv_writer = writer(write_obj)
        # Read each row of the input csv file as list
        for row in csv_reader:
            # Pass the list / row in the transform function to add column text for this row
            transform_row(row, csv_reader.line_num)
            # Write the updated row / list to the output file
            csv_writer.writerow(row)
add_column_in_csv('example1.csv', 'output_2.csv', lambda row, line_num: row.append(row[0] + '__' + row[1]))
output_data=pd.read_csv('output_2.csv')
output_data.head()

Output

total_bill tip sex smoker day time size total_bill__tip
0 16.99 1.01 Female No Sun Dinner 2 16.99__1.01
1 10.34 1.66 Male No Sun Dinner 3 10.34__1.66
2 21.01 3.50 Male No Sun Dinner 3 21.01__3.5
3 23.68 3.31 Male No Sun Dinner 2 23.68__3.31
4 24.59 3.61 Female No Sun Dinner 4 24.59__3.61

Here we see the new column is formed as the combination of the values of the 1st and 2nd column.

Explanation:

In the Lambda function, we received each row as a list and the line number. It then added a value in the list and the value is a merger of the first and second value of the list. It appended the column in the contents of example1.csv by merging values of the first and second columns and then saved the changes as output_2.csv files.

  • Method 3-Add a list as a column to an existing csv file

Python csv write column: In this method, we will add our own value in the column by making a list of our values and pass this into the function that we will make. Let see the code for this.

from csv import writer
from csv import reader
def add_column_in_csv(input_file, output_file, transform_row):
    """ Append a column in existing csv using csv.reader / csv.writer classes"""
    # Open the input_file in read mode and output_file in write mode
    with open(input_file, 'r') as read_obj, \
            open(output_file, 'w', newline='') as write_obj:
        # Create a csv.reader object from the input file object
        csv_reader = reader(read_obj)
        # Create a csv.writer object from the output file object
        csv_writer = writer(write_obj)
        # Read each row of the input csv file as list
        for row in csv_reader:
            # Pass the list / row in the transform function to add column text for this row
            transform_row(row, csv_reader.line_num)
            # Write the updated row / list to the output file
            csv_writer.writerow(row)
l=[]
l.append("New Column")
rows = len(data.axes[0])
for i in range(rows):
    val=i+1
    l.append(val)
add_column_in_csv('example1.csv', 'output_3.csv', lambda row, line_num: row.append(l[line_num - 1]))
output_data=pd.read_csv('output_3.csv')
output_data.head()

Output

total_bill tip sex smoker day time size New Column
0 16.99 1.01 Female No Sun Dinner 2 1
1 10.34 1.66 Male No Sun Dinner 3 2
2 21.01 3.50 Male No Sun Dinner 3 3
3 23.68 3.31 Male No Sun Dinner 2 4
4 24.59 3.61 Female No Sun Dinner 4 5

Explanation

In the Lambda function, we received each row as a list and the line number. It then added a value in the list and the value is an entry from our list l at index  line_num – 1.Thus all the entries in the list l are added as a column in the CSV.

So these are some of the methods to add new column in csv.

Test yourself:

  1. Write to a specific column in csv python pandas?
  2. Write to specific column csv python?
  3. How do i add a column to an existing csv file in python?
  4. How to add column in existing csv file using python?

 

Python pythagorean triples – 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

Python pythagorean triples: 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. Some things you have to notice while reading.

  • Program to check pythagorean triples in c
  • Pythagorean triples list
  • Pythagorean triples program in java
  • Pythagorean triples in python assignment expert
  • Pythagorean triples leetcode
  • Pythagorean triples hackerrank solution

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

Pythagorean triples c program: 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

Answer yourself:

  1. Write a program to print all pythagorean triplets between 1 to 100?
  2. Find all pythagorean triples below the given limit?
  3. Program to determine all pythagorean triplets in the range in c++ and python?

Related Programs: