True pangram – Python Program to Check if a String is a Pangram or Not

Program to Check if a String is a Pangram or Not

Strings in Python:

True pangram: A Python string is an ordered collection of characters used to express and store text-based data. Strings are saved in an adjacent memory area as individual characters. It is accessible in both directions: forward and backward. Characters are merely symbols. Strings are immutable Data Types in Python, which means they cannot be modified once they are formed. Python check if string is all characters, Python check if string is latin, Python check if a string is all digits, Python check if string is a dictionary, It depends on function too whether pangram program in python without function or if not.

Pangram:

If a sentence or string contains all 26 letters of the English alphabet at least once, it is considered to be a pangram. There are some solutions for pangram (pangram hackerrank solution in python) are also considered.

Examples:

Example1:

Input:

given string ="Helloabcdfegjilknmporqstvuxwzy"

Output:

The given string helloabcdfegjilknmporqstvuxwzy is a pangram

Example2:

Input:

given string ="hellothisisbtechgeeks"

Output:

The given string hellothisisbtechgeeks is not a pangram

Python Program to Check if a String is a Pangram or Not

There are several ways to check if the given string is pangram or not some of them are:

Follow to check pangram python code

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

Method #1:Naive Approach

Approach:

  • Scan the given string or provide static input.
  • Use the lower() method to convert this string to lowercase.
  • The brute force method is to take a string that contains all of the letters of the English alphabet.
  • Traverse through all of the alphabet’s characters string
  • Check to see if this character appears in the given string.
  • If it isn’t present, return False.
  • Return True at the end of the loop (which implies it is pangram)

Below is the implementation:

# Python Program to Check if a String is a Pangram or Not
def checkPangramString(string):

    # creating a new string (alphabet string which stores all the alphabets of the english language
    AlphabetString = 'abcdefghijklmnopqrstuvwxyz'

    # Traverse through the alphabets string
    for char in AlphabetString:
        # Check if this character is present in given string .
        if char not in string.lower():
            # if yes then this character is not available hence return False
            return False
    # After the end of loop return True (which implies it is pangram)
    return True


# given string
string = "Helloabcdfegjilknmporqstvuxwzy"
# converting the given string into lower case
string = string.lower()
# passing this string to checkPangramString function which returns true
# if the given string is pangram else it will return false

if checkPangramString(string):
    print("The given string", string, "is a pangram")
else:
    print("The given string", string, "is not a pangram")

Output:

The given string helloabcdfegjilknmporqstvuxwzy is a pangram

Method #2:Using set() method

The following program can be easily implemented in Python by using the set() method.

Approach:

  • Scan the given string or provide static input.
  • Use the lower() method to convert this string to lowercase.
  • Use the set() function to convert this string to a set.
  • Determine the length of the set.
  • If the length is 26, it is a pangram (since the English language has only 26 alphabets).
  • Otherwise, it is not a pangram.

Below is the implementation:

# Python Program to Check if a String is a Pangram or Not
def checkPangramString(string):

    # converting given string to set using set() function
    setString = set(string)
    # calculate the length of the set
    length = len(setString)
    # If the length is 26, it is a pangram so return true
    if(length == 26):
        return True
    else:
        return False


# given string
string = "Helloabcdfegjilknmporqstvuxwzy"
# converting the given string into lower case
string = string.lower()
# passing this string to checkPangramString function which returns true
# if the given string is pangram else it will return false

if checkPangramString(string):
    print("The given string", string, "is a pangram")
else:
    print("The given string", string, "is not a pangram")

Output:

The given string helloabcdfegjilknmporqstvuxwzy is a pangram

Note:

This method is only applicable if the given string contains alphabets.

Method #3:Using Counter() function (Hashing)

The following program can be easily implemented in Python by using the counter() function

Approach:

  • Scan the given string or provide static input.
  • Use the lower() method to convert this string to lowercase.
  • Calculate the frequency of all characters in the given string using Counter() method
  • Calculate the length of the Counter dictionary.
  • If the length is 26, it is a pangram (since the English language has only 26 alphabets).
  • Otherwise, it is not a pangram.

Below is the implementation:

# Python Program to Check if a String is a Pangram or Not
# importing counter from collections
from collections import Counter


def checkPangramString(string):

    # Calculate the frequency of all characters in the given string
    # using Counter() method
    frequ = Counter(string)
    # calculate the length of the frequency dictionary which is
    # returned from counter() function
    length = len(frequ)
    # If the length is 26, it is a pangram so return true
    if(length == 26):
        return True
    else:
        return False


# given string
string = "Helloabcdfegjilknmporqstvuxwzy"
# converting the given string into lower case
string = string.lower()
# passing this string to checkPangramString function which returns true
# if the given string is pangram else it will return false

if checkPangramString(string):
    print("The given string", string, "is a pangram")
else:
    print("The given string", string, "is not a pangram")

Output:

The given string helloabcdfegjilknmporqstvuxwzy is a pangram

Note:

This method is only applicable if the given string contains alphabets.

Read Also: Python Program to Check a Number is Prime or Not

Test Yourself: 

  1. How to check whether a string is pangram or not in java?
  2. Write a python program to execute a string containing python code?
  3. Check if a string contains all letters of the alphabet python?
  4. How to check whether a string is pangram or not in c?
  5. Pangram hackerrank solution in python?
  6. How to check whether a string is pangram or not in c++?
  7. How to check whether a string is pangram or not in java?
  8. Python program to check if a string is a pangram or not?
  9. Python function to check whether a string is a pangram or not?
  10. How to check whether a string is pangram or not in python?

Related Programs:

Count palindromes java – Python Program to Count Palindrome Words in a Sentence

Program to Count Palindrome Words in a Sentence

Count palindromes java: Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Given a sentence/string the task is to count the number of palindromic words in the given string in Python.

Examples:

Example1:

Input:

Given Sentence =madam how are you

Output:

The total number of palindromic words in the given sentence { madam how are you } are 1

Example2:

Input:

Given Sentence = helleh this issi btechgeeksskeeghcetb pyyp

Output:

The total number of palindromic words in the given sentence { helleh this issi btechgeeksskeeghcetb pyyp } are  4

Program to Count Palindrome Words in a Sentence in Python

Below are the ways to Count Palindrome words in the given sentence in Python

Method #1: Using For Loop (Static Input)

Approach:

  • Give the sentence/string as static input and store it in a variable.
  • Take a variable palcnt which stores the count of palindromic words in the given sentence and initialize its value to 0.
  • Split the given sentence into a list of words using the built-in function split() and store it in a variable.
  • Traverse in this list of words using the For loop.
  • Inside the for loop,Reverse the iterator word using slicing and store it in a variable.
  • Check if this reverse word is equal to the iterator word(Palindrome Condition) using the If conditional statement.
  • If it is true then increment the value of palcnt by 1.
  • Print the palcnt value.
  • The Exit of the Program.

Below is the implementation:

# Give the sentence/string as static input and store it in a variable.
gvnsentence ="helleh this issi btechgeeksskeeghcetb pyyp"
# Take a variable palcnt which stores the count of palindromic words
# in the given sentence and initialize its value to 0.
palcnt = 0
# Split the given sentence into a list of words using
# the built-in function split() and store it in a variable.
sentcewords = gvnsentence.split()
# Traverse in this list of words using the For loop.
for itrword in sentcewords:
    # Inside the for loop,Reverse the iterator word
    # using slicing and store it in a variable.
    reveword = itrword[::-1]
    # Check if this reverse word is equal to the
    # iterator word(Palindrome Condition) using the If conditional statement.
    if(reveword == itrword):
        # If it is true then increment the value of palcnt by 1.
        palcnt = palcnt+1


# Print the palcnt value.
print(
    'The total number of palindromic words in the given sentence {', gvnsentence, '} are ', palcnt)

Output:

The total number of palindromic words in the given sentence { helleh this issi btechgeeksskeeghcetb pyyp } are  4

Method #2: Using For Loop (User Input)

Approach:

  • Give the sentence/string as user input using the input() function and store it in a variable.
  • Take a variable palcnt which stores the count of palindromic words in the given sentence and initialize its value to 0.
  • Split the given sentence into a list of words using the built-in function split() and store it in a variable.
  • Traverse in this list of words using the For loop.
  • Inside the for loop,Reverse the iterator word using slicing and store it in a variable.
  • Check if this reverse word is equal to the iterator word(Palindrome Condition) using the If conditional statement.
  • If it is true then increment the value of palcnt by 1.
  • Print the palcnt value.
  • The Exit of the Program.

Below is the implementation:

# Give the sentence/string as user input using the input() function and store it in a variable.
gvnsentence = input('Enter some random sentence =')
# Take a variable palcnt which stores the count of palindromic words
# in the given sentence and initialize its value to 0.
palcnt = 0
# Split the given sentence into a list of words using
# the built-in function split() and store it in a variable.
sentcewords = gvnsentence.split()
# Traverse in this list of words using the For loop.
for itrword in sentcewords:
    # Inside the for loop,Reverse the iterator word
    # using slicing and store it in a variable.
    reveword = itrword[::-1]
    # Check if this reverse word is equal to the
    # iterator word(Palindrome Condition) using the If conditional statement.
    if(reveword == itrword):
        # If it is true then increment the value of palcnt by 1.
        palcnt = palcnt+1


# Print the palcnt value.
print(
    'The total number of palindromic words in the given sentence {', gvnsentence, '} are ', palcnt)

Output:

Enter some random sentence =madam how are you
The total number of palindromic words in the given sentence { madam how are you } are 1

Answer these:

  1. Count palindrome words in a sentence python?
  2. Count palindrome words in a sentence in java?
  3. Write a function to find all the words in a string which are palindrome in c#?
  4. Given a sentence write a program to count the number of palindrome words in it in c?
  5. Write a function to find all the words in a string which are palindrome in python?
  6. Write a function to find all the words in a string which are palindrome java?
  7. Write a function to find all the words in a string which are palindrome in c?
  8. Python program to count words in a sentence?
  9. Python program to count number of words in a paragraph?
  10. Python program to count words in a string?
  11. Python program to count number of words in a sentence?
  12. Palindrome count program in python?

Related Programs:

Python Program to Compute a Polynomial Equation given that the Coefficients of the Polynomial are stored in a List

Program to Compute a Polynomial Equation given that the Coefficients of the Polynomial are stored in a List

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

Given Coefficients of the polynomial and x which are stored in the list, the task is to compute the value of the polynomial equation with given x from the given Coefficients in Python.

Examples:

Example1:

Input:

given coefficient list = [7, 1, 3, 2]

Output:

The total value of the given polynomial 7 x^3 +1 x^2 +3 x +2 with the given value of x=5 is 917

Example2:

Input:

 given coefficient list = [3, 9, 1, 2]

Output:

The total value of the given polynomial 3 x^3 +9 x^2 +1 x +2 with the given value of x 6 = 980

Program to Compute a Polynomial Equation given that the Coefficients of the Polynomial are stored in a List

There are several ways to compute the value of the polynomial equation with given x from the given Coefficients in Python some of them are:

Method #1:Using for and while loop(User Input)

Approach:

  • Import the math module.
  • Take a empty list.
  • Loop from 1 to 4 using for loop as there are 4 coefficients terms in the equation.
  • Scan the coefficient as user input using int(input()) function.
  • Add this to the list using append() function.
  • Scan the value of x as user input using int(input()) function.
  • To compute the value of the polynomial expression for the first three terms, use a for loop and a while loop and store it in a sum variable.
  • To the total variable, add the fourth term.
  • The computed value should be printed.
  • Exit of program.

Below is the implementation:

import math
# Take a empty list.
coefflist = []
# Loop from 1 to 4 using for loop as there are 4 coefficients terms in the equation.
for t in range(4):
    # Scan the coefficient as user input using int(input()) function.
    elemen = int(input('Enter some random coefficient ='))
    # Add this to the list using append() function.
    coefflist.append(elemen)
# Scan the value of x as user input using int(input()) function.
x = int(input('Enter some random value of x ='))
# Taking a variable which stores totalValue and initialize it with 0
totalValue = 0
temp = 3
for k in range(0, 3):
    while(temp > 0):
        totalValue = totalValue+(coefflist[k]*(x**temp))
        # breaking the while looop
        break
    temp = temp-1
# To the total variable, add the fourth term.
totalValue = totalValue+coefflist[3]
print("The total value of the given polynomial " +
      str(coefflist[0])+' x^3 +'+str(coefflist[1])+' x^2 +'+str(coefflist[2])+' x +' +
      str(coefflist[3]), 'with the given value of x=', x, 'is', totalValue)

Output:

Enter some random coefficient =1
Enter some random coefficient =9
Enter some random coefficient =3
Enter some random coefficient =5
Enter some random value of x =8
The total value of the given polynomial 1 x^3 +9 x^2 +3 x +5 with the given value of x= 8 is 1117

Explanation:

  • The math module has been imported.
  • The user must enter the polynomial coefficients, which are saved in a list.
  • In addition, the user must input the value of x.
  • The for loop, which is used to retrieve the coefficients in the list, changes the value of I from 0 to 2.
  • The power for the value of x is determined by the value of j, which varies from 3 to 1.
  • This method is used to compute the values of the first three terms.
  • The final term is added to the total.
  • The final calculated value is printed.

Method #2: Using for and while loop(Static Input)

Approach:

  • Import the math module.
  • Take in the polynomial equation coefficients as static input in given list.
  • Give the value of x as static input.
  • To compute the value of the polynomial expression for the first three terms, use a for loop and a while loop and store it in a sum variable.
  • To the total variable, add the fourth term.
  • The computed value should be printed.
  • Exit of program.

Below is the implementation:

import math
# Take in the polynomial equation coefficients as static input in given list.
coefflist = [7, 1, 3, 2]
# Give the value of x as static input.
x = 5
# Taking a variable which stores totalValue and initialize it with 0
totalValue = 0
temp = 3
for k in range(0, 3):
    while(temp > 0):
        totalValue = totalValue+(coefflist[k]*(x**temp))
        # breaking the while looop
        break
    temp = temp-1
# To the total variable, add the fourth term.
totalValue = totalValue+coefflist[3]
print("The total value of the given polynomial " +
      str(coefflist[0])+' x^3 +'+str(coefflist[1])+' x^2 +'+str(coefflist[2])+' x +' +
      str(coefflist[3]), 'with the given value of x=', x, 'is', totalValue)

Output:

The total value of the given polynomial 7 x^3 +1 x^2 +3 x +2 with the given value of x=5 is 917

Explanation:

  • The for loop, which is used to retrieve the coefficients in the list, changes the value of I from 0 to 2.
  • The power for the value of x is determined by the value of j, which varies from 3 to 1.
  • This method is used to compute the values of the first three terms.
  • The final term is added to the total.
  • The final calculated value is printed.

Answer these:

  1. Python program to print polynomial equation?
  2. Solve polynomial equation in python?
  3. Polynomial program in python assignment expert?
  4. Polynomial python code?
  5. Roots of a polynomial python without numpy?
  6. Write a python code to generate a polynomial function and then plot the same?
  7. Given polynomial write a program that prints polynomial in cixpi ci 1xpi 1 c1x co format?
  8. Solve polynomial equation in python?
  9. Write a python code to generate a polynomial function and then plot the same?
  10. Generate polynomial python?

Related Programs:

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:

Age in days – Python Program to Calculate Age in Days from Date of Birth

Program to Calculate Age in Days from Date of Birth

Age in days: In the previous article, we have discussed Python Program to Check Strontio Number or Not.
Given the Date of Birth and task is to calculate the corresponding age in days. Python code to show age in years, months days, Python age in days, Python code for date of birth, Python age calculator date time, If you carefully observe in the content you will get it.

datetime module:

Your age in days: The datetime module contains numerous classes that can be used to manipulate date and time in both simple and complex ways.

In this, the date is formatted as the year month date (YY, MM, DD).

datetime.today() :The current date/system date is returned by datetime.today().

To calculate age from date of birth, subtract the date of birth from the current date.

timedelta() function in Python:

The Python timedelta() function is part of the datetime library and is commonly used for calculating date differences. It can also be used for date manipulation in Python. It is one of the simplest methods for manipulating dates.

Examples:

Example1:

Input:

Given Date of Birth = (2000, 3, 14)

Output:

The age in days and time for the Given DOB =  7823 days, 14:16:13.409557

Example2:

Input:

Given Date of Birth = (1999, 5, 16)

Output:

The age in days and time for the Given DOB = 8126 days, 14:14:30.074853

Program to Calculate Age in Days from Date of Birth

Below are the ways to calculate age in days from the given Date of Birth.

Method #1: Using the datetime Module (Static Input)

Approach:

  • Import datetime(), timedelta() functions from datetime module using import keyword.
  • Give the date of birth as static input in the format (YY, MM, DD) using datetime() function and store it in a variable.
  • Get the current/today date using datetime.today() function and store it in another variable.
  • Subtract the given date of birth from the current date to get the age in days and store it in another variable.
  • Print the age in days and time from the given date of birth.
  • The Exit of the Program.

Note: If we include the timedelta() function we get age in time including microseconds.

If you want age only in days then remove the timedelta() function import only datetime() function.

Below is the implementation:

# Import datetime(), timedelta() functions from datetime module using import keyword.
from datetime import datetime, timedelta
# Give the date of birth as static input in the format (YY, MM, DD) using datetime() function
# and store it in a variable.
gvn_DOB = datetime(1999, 5, 16)
# Get the current/today date using datetime.today() function and store it in
# another variable.
current_date = datetime.today()
# Subtract the given date of birth from the current date to get the age in days
# and store it in another variable.
age_in_days = current_date - gvn_DOB
# Print the age in days and time from the given date of birth.
print("The age in days and time for the Given DOB = ", age_in_days)

Output:

The age in days and time for the Given DOB =  8126 days, 14:14:30.074853

Method #2: Using the datetime Module (User Input)

Approach:

  • Import datetime(), timedelta() functions from datetime module using import keyword.
  • Give the year, month, day as user input using map (), int(), split() functions and store them separately in three different variables.
  • Convert the year, month, day to date of birth using datetime() module and store it in another variable.
  • Get the current/today date using datetime.today() function and store it in another variable.
  • Subtract the given date of birth from the current date to get the age in days and store it in another variable.
  • Print the age in days and time from the given date of birth.
  • The Exit of the Program.

Below is the implementation:

# Import datetime(), timedelta() functions from datetime module using import keyword.
from datetime import datetime, timedelta
# Give the year, month, day as user input using map (), int(), split() functions 
#and store them separately in three different variables.
yr,mont,dy= map(int,input("Enter year ,month ,day separated by spaces = ").split())
#Convert the year, month, day to date of birth using datetime() module and store it in another variable.
gvn_DOB=datetime(yr, mont, dy)
# Get the current/today date using datetime.today() function and store it in
# another variable.
current_date = datetime.today()
# Subtract the given date of birth from the current date to get the age in days
# and store it in another variable.
age_in_days = current_date - gvn_DOB
# Print the age in days and time from the given date of birth.
print("The age in days and time for the Given DOB = ", age_in_days)

Output:

Enter year ,month ,day separated by spaces = 2003 7 19
The age in days and time for the Given DOB = 6601 days, 14:47:41.427259

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.

Test Yourself:

  1. Write a python program to calculate your age in days between today and date of birth?
  2. Python program to calculate age in years?
  3. Python calculate age between two dates?
  4. Calculate age in months python?
  5. Calcualte age from date of birth python pandas?
  6. Python calculate age between two dates?
  7. Calculate age in months python?
  8. Python program to calculate age in days?
  9. How to calculate age in days in python
  10. Python calculate age from date of birth?
  11. Python program to calculate age from date of birth?
  12. Python program to calculate age in years months and days?
  13. Python calculate age from date of birth?

Related Posts On:

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 Program to Print the Equilateral Triangle Pattern of Star

Python Program to Print the Equilateral Triangle Pattern of Star

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. They have tried to include all details like, python program to print equilateral triangle, print star pattern in python using for loop, python star pattern programs, python pattern programs, triangle pattern in python, star pattern in python using while loop, inverted equilateral triangle in python, python star pattern programs, python pattern programs, triangle pattern in python, python program to print the equilateral triangle pattern of star.

Given the number of rows, the task is to Print Equilateral triangle Pattern of Star in C, C++, and Python

Examples:

Example1:

Input:

Given number of rows = 8

Output:

              * 
             * * 
            * * * 
           * * * * 
          * * * * * 
         * * * * * * 
        * * * * * * * 
       * * * * * * * *

Example2:

Input:

Given number of rows = 10
Given Character to print ='$'

Output

                  $ 
                 $ $ 
                $ $ $ 
               $ $ $ $ 
              $ $ $ $ $ 
             $ $ $ $ $ $ 
            $ $ $ $ $ $ $ 
           $ $ $ $ $ $ $ $ 
          $ $ $ $ $ $ $ $ $ 
         $ $ $ $ $ $ $ $ $ $

Program to Print the Equilateral triangle Pattern of Star in C, C++, and Python

Below are the ways to Print the Equilateral triangle Pattern of Star in C, C++, and Python.

Method #1: Using For Loop (Star Character)

Approach:

  • Give the number of rows as static input and store it in a variable.
  • Take a variable to say g and initialize its value with (2*number of rows)-2.
  • Loop from 0 to the number of rows using For loop.
  • Loop from 0 to g using another For Loop(Inner For loop).
  • Print the space character in the inner For Loop.
  • Decrement the value of g by 1 after the end of the inner For loop.
  • Loop from 0 to m+1 using another For loop(Nested For loop) where m is the iterator value of the parent For loop.
  • Print the star character with space.
  • Print the Newline character after the end of the Two inner For loops.
  • 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 = 8
# Take a variable to say g and initialize its value with (2*number of rows)-2.
g = (2*numberOfRows)-2
# Loop from 0 to the number of rows using For loop.
for m in range(0, numberOfRows):
    # Loop from 0 to g using another For Loop(Inner For loop).
    for n in range(0, g):
      # Print the space character in the inner For Loop.
        print(end=" ")
    # Decrement the value of g by 1 after the end of the inner For loop.
    g = g-1
    # Loop from 0 to m+1 using another For loop(Nested For loop)
    # where m is the iterator value of the parent For loop.
    for n in range(0, m+1):
      # Print the star character with space.
        print('*', end=" ")
    # Print the Newline character after the end of the Two inner For loops.
    print()

Output:

              * 
             * * 
            * * * 
           * * * * 
          * * * * * 
         * * * * * * 
        * * * * * * * 
       * * * * * * * *

2) C++ Implementation

Below is the implementation:

#include <iostream>
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 to say g and initialize its value
    // with (2*number of rows)-2.
    int g = (2 * numberOfRows) - 2;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < numberOfRows; m++) {
        // Loop from 0 to g using another For Loop(Inner For
        // loop).
        for (int n = 0; n < g; n++) {
            // Print the space character in the inner For
            // Loop.
            cout << " ";
        }
        // Decrement the value of g by 1 after the end of
        // the inner For loop.
        g = g - 1;
        // Loop from 0 to m+1 using another For loop(Nested
        // For loop) where m is the iterator value of the
        // parent For loop.
        for (int n = 0; n < m + 1; n++) {
            // Print the star character with space.
            cout << "* ";
        }
        // Print the Newline character after the end of the
        // Two inner For loops.
        cout << endl;
    }
    return 0;
}

Output:

              * 
             * * 
            * * * 
           * * * * 
          * * * * * 
         * * * * * * 
        * * * * * * * 
       * * * * * * * *

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 = 13;

    // Take a variable to say g and initialize its value
    // with (2*number of rows)-2.
    int g = (2 * numberOfRows) - 2;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < numberOfRows; m++) {
        // Loop from 0 to g using another For Loop(Inner For
        // loop).
        for (int n = 0; n < g; n++) {
            // Print the space character in the inner For
            // Loop.
            printf(" ");
        }
        // Decrement the value of g by 1 after the end of
        // the inner For loop.
        g = g - 1;
        // Loop from 0 to m+1 using another For loop(Nested
        // For loop) where m is the iterator value of the
        // parent For loop.
        for (int n = 0; n < m + 1; n++) {
            // Print the star character with space.
            printf("* ");
        }
        // Print the Newline character after the end of the
        // Two inner For loops.
        printf("\n");
    }
    return 0;
}

Output:

                        * 
                       * * 
                      * * * 
                     * * * * 
                    * * * * * 
                   * * * * * * 
                  * * * * * * * 
                 * * * * * * * * 
                * * * * * * * * * 
               * * * * * * * * * * 
              * * * * * * * * * * * 
             * * * * * * * * * * * * 
            * * * * * * * * * * * * *

Method #2: Using For Loop (User Input)

Approach:

  • Give the number of rows as static input and store it in a variable.
  • Scan the character to print as user input and store it in a variable.
  • Take a variable to say g and initialize its value with (2*number of rows)-2.
  • Loop from 0 to the number of rows using For loop.
  • Loop from 0 to g using another For Loop(Inner For loop).
  • Print the space character in the inner For Loop.
  • Decrement the value of g by 1 after the end of the inner For loop.
  • Loop from 0 to m+1 using another For loop(Nested For loop) where m is the iterator value of the parent For loop.
  • Print the star character with space.
  • Print the Newline character after the end of the Two inner For loops.
  • 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.
  • Give the Character as user input using input() and store it in another 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 = '))
# Give the character to print as user input using int(input()) and store it in another variable.
characte = input('Enter some random character to print = ')
# Take a variable to say g and initialize its value with (2*number of rows)-2.
g = (2*numberOfRows)-2
# Loop from 0 to the number of rows using For loop.
for m in range(0, numberOfRows):
    # Loop from 0 to g using another For Loop(Inner For loop).
    for n in range(0, g):
      # Print the space character in the inner For Loop.
        print(end=" ")
    # Decrement the value of g by 1 after the end of the inner For loop.
    g = g-1
    # Loop from 0 to m+1 using another For loop(Nested For loop)
    # where m is the iterator value of the parent For loop.
    for n in range(0, m+1):
      # Print the given character with space.
        print(characte, end=" ")
    # Print the Newline character after the end of the Two inner For loops.
    print()

Output

Enter some random number of rows = 10
Enter some random character to print = $
                  $ 
                 $ $ 
                $ $ $ 
               $ $ $ $ 
              $ $ $ $ $ 
             $ $ $ $ $ $ 
            $ $ $ $ $ $ $ 
           $ $ $ $ $ $ $ $ 
          $ $ $ $ $ $ $ $ $ 
         $ $ $ $ $ $ $ $ $ $

2) C++ Implementation

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

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows as user input using
    // cin and store it in a variable.
    int numberOfRows;
    cin >> numberOfRows;
    // Create a character variable.
    char characte;
    // Give the character as user input using cin and store
    // it in another variable.
    cout << "Enter some random character to print = "
         << endl;
    cin >> characte;
    cout << endl;
    int g = (2 * numberOfRows) - 2;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < numberOfRows; m++) {
        // Loop from 0 to g using another For Loop(Inner For
        // loop).
        for (int n = 0; n < g; n++) {
            // Print the space character in the inner For
            // Loop.
            cout << " ";
        }
        // Decrement the value of g by 1 after the end of
        // the inner For loop.
        g = g - 1;
        // Loop from 0 to m+1 using another For loop(Nested
        // For loop) where m is the iterator value of the
        // parent For loop.
        for (int n = 0; n < m + 1; n++) {
            // Print the given character with space.
            cout << characte << " ";
        }
        // Print the Newline character after the end of the
        // Two inner For loops.
        cout << endl;
    }
    return 0;
}

Output

10
Enter some random character to print = $
                  $ 
                 $ $ 
                $ $ $ 
               $ $ $ $ 
              $ $ $ $ $ 
             $ $ $ $ $ $ 
            $ $ $ $ $ $ $ 
           $ $ $ $ $ $ $ $ 
          $ $ $ $ $ $ $ $ $ 
         $ $ $ $ $ $ $ $ $ $

3) C Implementation

  • Give the number of rows as user input using scanf and store it in a variable.
  • Give the Character as user input using scanf and store it in another 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);
    // Create a character variable.
    // Give the character as user input using scanf and
    // store it in another variable.
    char characte;
    scanf("%c", &characte);
    printf("\n");
    // Take a variable to say g and initialize its value
    // with (2*number of rows)-2.
    int g = (2 * numberOfRows) - 2;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < numberOfRows; m++) {
        // Loop from 0 to g using another For Loop(Inner For
        // loop).
        for (int n = 0; n < g; n++) {
            // Print the space character in the inner For
            // Loop.
            printf(" ");
        }
        // Decrement the value of g by 1 after the end of
        // the inner For loop.
        g = g - 1;
        // Loop from 0 to m+1 using another For loop(Nested
        // For loop) where m is the iterator value of the
        // parent For loop.
        for (int n = 0; n < m + 1; n++) {
            // Print the given character with space.
            printf("%c ",characte);
        }
        // Print the Newline character after the end of the
        // Two inner For loops.
        printf("\n");
    }
    return 0;
}

Output

10$
                  $ 
                 $ $ 
                $ $ $ 
               $ $ $ $ 
              $ $ $ $ $ 
             $ $ $ $ $ $ 
            $ $ $ $ $ $ $ 
           $ $ $ $ $ $ $ $ 
          $ $ $ $ $ $ $ $ $ 
         $ $ $ $ $ $ $ $ $ $

Related Programs:

Python make list of odd numbers – Python Program to Find Sum of Odd Numbers Using Recursion in a List/Array

Program to Find Sum of Odd Numbers Using Recursion in a ListArray

Python make list of odd numbers: In the previous article, we have discussed Python Program to Check Armstrong Number using Recursion

Given a list and the task is to find the sum of odd numbers using recursion in a given list in python.

Recursion:

Recursion is the process by which a function calls itself directly or indirectly, and the associated function is known as a recursive function. Certain issues can be addressed fairly easily using a recursive approach. Towers of Hanoi (TOH), Inorder /Preorder/Postorder Tree Traversals, DFS of Graph, and other analogous issues are examples.

Some of them are:

  • Sum of array using recursion in python
  • Sum of array elements using recursion in c
  • Sum of array using recursion coding ninjas
  • Sum of array elements using recursion javascript

Examples:

Example1:

Input:

Given List = [6, 12, 4, 2, 3, 9, 1, 5]

Output:

The Sum of Odd Elements in a given list [6, 12, 4, 2, 3, 9, 1, 5] = 18

Example2:

Input:

Given List = [4, 3, 1, 5, 11]

Output:

The Sum of Odd Elements in a given list [4, 3, 1, 5, 11] = 20

Program to Find Sum of Odd Numbers Using Recursion in a List/Array in Python

Below are the ways to find the sum of odd numbers using recursion in a given list in python:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Calculate the length of the given list and store it in another variable.
  • Take a variable say rslt_sum and initialize its value to 0.
  • Pass the given list and length of the given list as the arguments to the oddelemt_sum function.
  • Create a recursive function to say oddelemt_sum which takes the given list and length of the given list as the arguments and returns the sum of odd numbers in a given list using recursion.
  • Make the rslt_sum a global declaration.
  • Check if the length of the given list is greater than 0 using the if conditional statement.
  • If the statement is true, then subtract 1 from the length of the given list and store it in a variable k.
  • Check if the element present at the index k of the given list is odd using the modulus operator and if conditional statement.
  • If the statement is true, add the element present at the index k of the given list to the above-initialized rslt_sum.
  • Store it in the same variable.
  • Pass the given list and k value as the arguments to the oddelemt_sum function.{Recursive Logic}
  • Return rslt_sum.
  • Print the sum of odd numbers in the above-given list.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say oddelemt_sum which takes the given list and length
# of the given list as the arguments and returns the sum of odd numbers in a given list
# using recursion.


def oddelemt_sum(gven_lst, len_lst):
    # Make the rslt_sum a global declaration.
    global rslt_sum
    # Check if the length of the given list is greater than 0 using the if conditional
    # statement.
    if(len_lst > 0):
        # If the statement is true, then subtract 1 from the length of the given list and
        # store it in a variable k.
        k = len_lst-1
   # Check if the element present at the index k of the given list is odd using modulus
   # operator and if conditional statement.
        if(gven_lst[k] % 2 != 0):
            # If the statement is true, add the element present at the index k of the
            # given list to the above-initialized rslt_sum.
            # Store it in the same variable.
            rslt_sum = rslt_sum+gven_lst[k]
           # Pass the given list and k value as the arguments to the oddelemt_sum function
           # {Recursive Logic}.
        oddelemt_sum(gven_lst, k)
       # Return rslt_sum.
    return rslt_sum


# Give the list as static input and store it in a variable.
gven_lst = [6, 12, 4, 2, 3, 9, 1, 5]
# Calculate the length of the given list and store it in another variable.
len_lst = len(gven_lst)
# Take a variable say rslt_sum and initialize its value to 0.
rslt_sum = 0
# Pass the given list and length of the given list as the arguments to the oddelemt_sum
# function.
# Print the sum of odd numbers in the above-given list.
print("The Sum of Odd Elements in a given list",
      gven_lst, "=", oddelemt_sum(gven_lst, len_lst))

Output:

The Sum of Odd Elements in a given list [6, 12, 4, 2, 3, 9, 1, 5] = 18

Method #2: Using Recursion (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the length of the given list and store it in another variable.
  • Take a variable say rslt_sum and initialize its value to 0.
  • Pass the given list and length of the given list as the arguments to the oddelemt_sum function.
  • Create a recursive function to say oddelemt_sum which takes the given list and length of the given list as the arguments and returns the sum of odd numbers in a given list using recursion.
  • Make the rslt_sum a global declaration.
  • Check if the length of the given list is greater than 0 using the if conditional statement.
  • If the statement is true, then subtract 1 from the length of the given list and store it in a variable k.
  • Check if the element present at the index k of the given list is odd using the modulus operator and if conditional statement.
  • If the statement is true, add the element present at the index k of the given list to the above-initialized rslt_sum.
  • Store it in the same variable.
  • Pass the given list and k value as the arguments to the oddelemt_sum function.{Recursive Logic}
  • Return rslt_sum.
  • Print the sum of odd numbers in the above-given list.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say oddelemt_sum which takes the given list and length
# of the given list as the arguments and returns the sum of odd numbers in a given list
# using recursion.


def oddelemt_sum(gven_lst, len_lst):
    # Make the rslt_sum a global declaration.
    global rslt_sum
    # Check if the length of the given list is greater than 0 using the if conditional
    # statement.
    if(len_lst > 0):
        # If the statement is true, then subtract 1 from the length of the given list and
        # store it in a variable k.
        k = len_lst-1
   # Check if the element present at the index k of the given list is odd using modulus
   # operator and if conditional statement.
        if(gven_lst[k] % 2 != 0):
            # If the statement is true, add the element present at the index k of the
            # given list to the above-initialized rslt_sum.
            # Store it in the same variable.
            rslt_sum = rslt_sum+gven_lst[k]
           # Pass the given list and k value as the arguments to the oddelemt_sum function
           # {Recursive Logic}.
        oddelemt_sum(gven_lst, k)
       # Return rslt_sum.
    return rslt_sum


# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gven_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Calculate the length of the given list and store it in another variable.
len_lst = len(gven_lst)
# Take a variable say rslt_sum and initialize its value to 0.
rslt_sum = 0
# Pass the given list and length of the given list as the arguments to the oddelemt_sum
# function.
# Print the sum of odd numbers in the above-given list.
print("The Sum of Odd Elements in a given list",
      gven_lst, "=", oddelemt_sum(gven_lst, len_lst))

Output:

Enter some random List Elements separated by spaces = 4 3 1 5 11
The Sum of Odd Elements in a given list [4, 3, 1, 5, 11] = 20

Find the best practical and ready-to-use Python Programming Examples that you can simply run on a variety of platforms and never stop learning.

Test Yourself:

  1. Write a python program to calculate the sum of a list of numbers using recursion?
  2. Check number in array using recursion in python?
  3. Check number in array using recursion in java?
  4. Write a python program to calculate the sum of a list of numbers using recursion?
  5. Python program to find sum of odd numbers using recursion in a list/array?

Related Posts On:

Python Program to Count Non Palindrome words in a Sentence

Program to Count Non Palindrome words in a Sentence

In the previous article, we have discussed Python Program to Find Leaders in an Array/List
Given a string and the task is to count all the Non-palindromic words in a given sentence.

Palindrome:

If the reverse of a string is the same as the string, it is said to be a palindrome.

Example :

Given string = “sos asked to bring the madam “.

Output :

Explanation: In this “madam”, “sos” are the palindromic words. By sorting them we get {“madam”,”sos”}

Examples:

Example1:

Input:

Given String = "dad and mom both ordered to bring sos in malayalam"

Output:

The count of all the Non-palindromic words in a given sentence = 6

Example2:

Input:

Given String = "My mom and dad treats me in equal level"

Output:

The count of all the Non-palindromic words in a given sentence = 6

Program to Count Non-Palindrome words in a Sentence

Below are the ways to count all the Non-palindromic words in a given sentence.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take an empty list say “lst” and store it in another variable.
  • Split the given string using the split() function and store it in another variable.
  • Loop in the above-obtained split list of words using the for loop.
  • Check if the iterator value is not equal to the reverse of the iterator value using the if conditional statement.
  • If the statement is true, then append the respective iterator value to the above initialized empty list using the append() method.
  • Calculate the length above initialized list “lst” using the len() function and store it in a variable.
  • Print the count of all the Non-palindromic words in a given sentence.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "dad and mom both ordered to bring sos in malayalam"
# Take an empty list and store it in another variable.
lst = []
# Split the given string using the split() function and store it in another variable.
splt_str = gvn_str.split()
# Loop in the above-obtained split list of words using the for loop.
for wrd in splt_str:
    # Check if the iterator value is not equal to the reverse of the iterator value using
    # the if conditional statement.
    if wrd != wrd[::-1]:
     # If the statement is true, then append the respective iterator value to the
        # above initialized empty list using the append() method.
        lst.append(wrd)
# Calculate the length above initialized list "lst" using the len() function
# and store it in a variable.
# Print the count of all the Non-palindromic words in a given sentence.
count = len(lst)
# Print the count of all the Non-palindromic words in a given sentence.
print("The count of all the Non-palindromic words in a given sentence =", count)

Output:

The count of all the Non-palindromic words in a given sentence = 6

Method #2: Using For loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take an empty list say “lst” and store it in another variable.
  • Split the given string using the split() function and store it in another variable.
  • Loop in the above-obtained split list of words using the for loop.
  • Check if the iterator value is not equal to the reverse of the iterator value using the if conditional statement.
  • If the statement is true, then append the respective iterator value to the above initialized empty list using the append() method.
  • Calculate the length above initialized list “lst” using the len() function and store it in a variable.
  • Print the count of all the Non-palindromic words in a given sentence.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Take an empty list and store it in another variable.
lst = []
# Split the given string using the split() function and store it in another variable.
splt_str = gvn_str.split()
# Loop in the above-obtained split list of words using the for loop.
for wrd in splt_str:
    # Check if the iterator value is notequal to the reverse of the iterator value using
    # the if conditional statement.
    if wrd != wrd[::-1]:
     # If the statement is true, then append the respective iterator value to the
        # above initialized empty list using the append() method.
        lst.append(wrd)
# Calculate the length above initialized list "lst" using the len() function
# and store it in a variable.
# Print the count of all the Non-palindromic words in a given sentence.
count = len(lst)
# Print the count of all the Non-palindromic words in a given sentence.
print("The count of all the Non-palindromic words in a given sentence =", count)

Output:

Enter some random string = My mom and dad treats me in equal level
The count of all the Non-palindromic words in a given sentence = 6

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.

Test Yourself:

  1. Exclude palindrome words in python
  2. Qrite a function to find all the words in a string which are palindrome in python
  3. Python program to count no of words in a string
  4. Python program to count number of words in a sentence
  5. Python program to count words in a sentence
  6. Python program to count number of words in a paragraph
  7. Count palindrome words in a sentence python
  8. Palindrome count program in python
  9. Java program to print palindrome words in a string?
  10. Count palindrome words in a sentence in c
  11. Count palindrome words in a sentence python
  12. Palindrome program in python using function?

Related Posts:

Python Program to Find Leaders in an Array/List

Program to Find Leaders in an ArrayList

In the previous article, we have discussed Python Program to Check Automorphic Number or Not
Leader:

If an element is greater than all of the elements on its right side, it is the leader. And the last element is always a leader.

Examples:

Example1:

Input:

Given list =[23, 11, 1, 7, 8, 6, 3]

Output:

The leaders of the given list [23, 11, 1, 7, 8, 6, 3] are :
23
11
8
6
3

Example2:

Input:

Given List =  [1, 2, 3, 7, 8, 6]

Output:

The leaders of the given list [1, 2, 3, 7, 8, 6] are :
8
6

Given a list, the task is to find all the leaders of the given list in python.

Program to Find Leaders in an Array/List in Python

Below are the ways to find all the leaders of the given list in python some of them are:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Calculate the length of the list and store it in another variable.
  • Loop from 0 to the length of the list using the For loop.
  • Loop from parent loop iterator value to the length of the list using another Nested for loop(Inner For loop)
  • Check if the element at the index of the parent loop iterator value is less than or equal to the element at the index of the inner loop iterator value.(gvnlist [ m ] <= gvnlist [ n ] ) using the if conditional statement.
  • If it is true then break the inner loop using the break keyword.
  • After the end of the inner For loop check if the inner loop iterator value is equal to the length of the given list -1 using the if conditional statement.
  • If it is true then it is the leader so print it.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvnlstt = [23, 11, 1, 7, 8, 6, 3]
# Calculate the length of the list and store it in another variable.
lstleng = len(gvnlstt)
print('The leaders of the given list', gvnlstt, 'are :')
# Loop from 0 to the length of the list using the For loop.
for m in range(lstleng):
    # Loop from parent loop iterator value to the length of the list
    # using another Nested for loop(Inner For loop)
    for n in range(m+1, lstleng):
            # Check if the element at the index of the parent loop iterator value
        # is less than or equal to the element at the index of the inner loop iterator value.
        # (gvnlist[m] <= gvnlist[n]) using the if conditional statement.
        if (gvnlstt[m] <= gvnlstt[n]):
            # If it is true then break the inner loop using the break keyword.
            break

            # After the end of the inner For loop check if the inner loop iterator value
        # is equal to the length of the given list - 1 using the if conditional statement.
    if(n == lstleng-1):
        # If it is true then it is the leader so print it.
        print(gvnlstt[m])

Output:

The leaders of the given list [23, 11, 1, 7, 8, 6, 3] are :
23
11
8
6
3

Method #2: Using For loop (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the length of the list and store it in another variable.
  • Loop from 0 to the length of the list using the For loop.
  • Loop from parent loop iterator value to the length of the list using another Nested for loop(Inner For loop)
  • Check if the element at the index of the parent loop iterator value is less than or equal to the element at the index of the inner loop iterator value.(gvnlist [ m ] <= gvnlist [ n ] ) using the if conditional statement.
  • If it is true then break the inner loop using the break keyword.
  • After the end of the inner For loop check if the inner loop iterator value is equal to the length of the given list -1 using the if conditional statement.
  • If it is true then it is the leader so print it.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvnlstt = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Calculate the length of the list and store it in another variable.
lstleng = len(gvnlstt)
print('The leaders of the given list', gvnlstt, 'are :')
# Loop from 0 to the length of the list using the For loop.
for m in range(lstleng):
    # Loop from parent loop iterator value to the length of the list
    # using another Nested for loop(Inner For loop)
    for n in range(m+1, lstleng):
            # Check if the element at the index of the parent loop iterator value
        # is less than or equal to the element at the index of the inner loop iterator value.
        # (gvnlist[m] <= gvnlist[n]) using the if conditional statement.
        if (gvnlstt[m] <= gvnlstt[n]):
            # If it is true then break the inner loop using the break keyword.
            break

            # After the end of the inner For loop check if the inner loop iterator value
        # is equal to the length of the given list - 1 using the if conditional statement.
    if(n == lstleng-1):
        # If it is true then it is the leader so print it.
        print(gvnlstt[m])

Output:

Enter some random List Elements separated by spaces = 1 2 3 7 8 6
The leaders of the given list [1, 2, 3, 7, 8, 6] are :
8
6

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.

Answer these:

  1. Write a program to print all the leaders in the array in python?
  2. Leaders in array coding ninjas?
  3. Write a program to print all the leaders in the array in c?
  4. Leaders in an array java program?
  5. Leaders in array coding ninjas github?
  6. Sum of leaders in an array?
  7. Leaders in an array gfg practice?
  8. Leaders in an array leetcode?
  9. Leaders in array coding ninjas?
  10. Leaders in an array java program?
  11. Leaders in array coding ninjas github?
  12. Lum of leaders in an array?
  13. Leaders in an array gfg practice?
  14. Leaders in an array leetcode?
  15. Find leaders in array?
  16. How to find leaders in an array?
  17. Find leaders in an array leetcode?
  18. Python program to find an element in a list?
  19. Python program to find adjacent elements in a list?

Related Posts On