Python Program to Find the Number of Weeks between two Dates

Program to Find the Number of Weeks between two Dates

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

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

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

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

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

Examples:

Example1:

Input:

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

Output:

The number of weeks between two given dates =  178

Example 2:

Input:

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

Output:

The number of weeks between two given dates =  164

Program to Find the Number of Weeks between two Dates

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

Method #1: Using DateTime Module (Static input)

Approach:

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

Below is the implementation:

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

Output:

The number of weeks between two given dates = 178

Method #2: Using DateTime Module (User input)

Approach:

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

Below is the implementation:

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

Output:

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

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Sort Palindrome Words in a Sentence

Program to Sort Palindrome Words in a Sentence

In the previous article, we have discussed Python Program to Find the Sum of Digits of a Number at Even and Odd places
Given a string and the task is to sort all the palindrome words in a given sentence.

Palindrome:

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

Example :

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

Output :

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

Examples:

Example1:

Input:

Given string/sentence ='sos how are you madam pip instal'

Output:

The given string before sorting all the palindromic words is =  sos how are you madam pip instal
The final string after sorting all the palindromic words is =  madam how are you pip sos instal

Example2:

Input:

Given string/sentence = 'the good is madam aba dad mom din cac'

Output:

The given string before sorting all the palindromic words is = the good is madam aba dad mom din cac
The final string after sorting all the palindromic words is = the good is aba cac dad madam din mom

Program to Sort Palindrome Words in a Sentence in Python

Below are the ways to sort all the palindromic words in a given sentence:

Method #1: Using Sort() function (Static input)

Approach:

  • Give the sentence/string as static input and store it in a variable.
  • Convert the given sentence to a list of words using list() and split() functions and store it another variable.
  • Take an empty list to say palindromicwordslist that stores all the palindromic words in the given string and initialize it to null/empty using the list() function or [].
  • Traverse the given list of words using a for loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then append this word to the palindromicwordslist using the append() function.
  • Sort the palindromicwordslist using the sort() function.
  • Take a variable say tempo and initialize its value to 0(Here it acts as a pointer to palindromicwordslist ).
  • Traverse the list of words of the given sentence using the For loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then modify the word with the palindromicwordslist[tempo] word.
  • Increment the tempo value by 1.
  • Convert this list of words of the given sentence to the string using the join() function.
  • Print the final string after sorting the palindromic words.
  • The Exit of the Program.

Below is the implementation:

# Give the sentence/string as static input and store it in a variable.
gvnstrng = 'sos how are you madam pip instal'
# Convert the given sentence to a list of words using list()
# and split() functions and store it another variable.
strngwrdslst = list(gvnstrng.split())
# Take an empty list to say palindromicwordslist
# that stores all the palindromic words in the given string
# and initialize it to null/empty using the list() function or [].
palindromicwordslist = []
# Traverse the given list of words using a for loop.
for wrd in strngwrdslst:
        # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(wrd == wrd[::-1]):
        # If it is true then append this word to the palindromicwordslist
        # using the append() function.
        palindromicwordslist.append(wrd)

# Sort the palindromicwordslist using the sort() function.
palindromicwordslist.sort()
# Take a variable say tempo and initialize its value to 0
# (Here it acts as a pointer to palindromicwordslist ).
tempo = 0
# Traverse the list of words of the given sentence using the For loop.
for wrditr in range(len(strngwrdslst)):
  # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(strngwrdslst[wrditr] == strngwrdslst[wrditr][::-1]):
        # If it is true then modify the word with the palindromicwordslist[tempo] word.
        strngwrdslst[wrditr] = palindromicwordslist[tempo]
        tempo = tempo+1
        # Increment the tempo value by 1.


# Convert this list of words of the given sentence
# to the string using the join() function.
finalstrng = ' '.join(strngwrdslst)
print('The given string before sorting all the palindromic words is = ', gvnstrng)
# Print the final string after sorting the palindromic words.
print('The final string after sorting all the palindromic words is = ', finalstrng)

Output:

The given string before sorting all the palindromic words is =  sos how are you madam pip instal
The final string after sorting all the palindromic words is =  madam how are you pip sos instal

Method #2:Using Sort() function (User input)

Approach:

  • Give the sentence/string as user input using the input() function and store it in a variable.
  • Convert the given sentence to a list of words using list() and split() functions and store it another variable.
  • Take an empty list to say palindromicwordslist that stores all the palindromic words in the given string and initialize it to null/empty using the list() function or [].
  • Traverse the given list of words using a for loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then append this word to the palindromicwordslist using the append() function.
  • Sort the palindromicwordslist using the sort() function.
  • Take a variable say tempo and initialize its value to 0(Here it acts as a pointer to palindromicwordslist ).
  • Traverse the list of words of the given sentence using the For loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then modify the word with the palindromicwordslist[tempo] word.
  • Increment the tempo value by 1.
  • Convert this list of words of the given sentence to the string using the join() function.
  • Print the final string after sorting the palindromic words.
  • The Exit of the Program.

Below is the implementation:

# Give the sentence/string as user input using input() function
# and store it in a variable.
gvnstrng = input('Enter some random string = ')
# Convert the given sentence to a list of words using list()
# and split() functions and store it another variable.
strngwrdslst = list(gvnstrng.split())
# Take an empty list to say palindromicwordslist
# that stores all the palindromic words in the given string
# and initialize it to null/empty using the list() function or [].
palindromicwordslist = []
# Traverse the given list of words using a for loop.
for wrd in strngwrdslst:
        # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(wrd == wrd[::-1]):
        # If it is true then append this word to the palindromicwordslist
        # using the append() function.
        palindromicwordslist.append(wrd)

# Sort the palindromicwordslist using the sort() function.
palindromicwordslist.sort()
# Take a variable say tempo and initialize its value to 0
# (Here it acts as a pointer to palindromicwordslist ).
tempo = 0
# Traverse the list of words of the given sentence using the For loop.
for wrditr in range(len(strngwrdslst)):
  # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(strngwrdslst[wrditr] == strngwrdslst[wrditr][::-1]):
        # If it is true then modify the word with the palindromicwordslist[tempo] word.
        strngwrdslst[wrditr] = palindromicwordslist[tempo]
        tempo = tempo+1
        # Increment the tempo value by 1.


# Convert this list of words of the given sentence
# to the string using the join() function.
finalstrng = ' '.join(strngwrdslst)
print('The given string before sorting all the palindromic words is = ', gvnstrng)
# Print the final string after sorting the palindromic words.
print('The final string after sorting all the palindromic words is = ', finalstrng)

Output:

Enter some random string = the good is madam aba dad mom din cac
The given string before sorting all the palindromic words is = the good is madam aba dad mom din cac
The final string after sorting all the palindromic words is = the good is aba cac dad madam din mom

 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 Check if a given Word contains Consecutive Letters using Functions

Python Program to Check if a given Word contains Consecutive Letters using Functions

Functions in Python:

In Python, a function is a grouping of connected statements that performs a computational, logical, or evaluative activity. The idea is to combine some often or repeatedly performed tasks into a function, so that instead of writing the same code for different inputs again and over, we may call the function and reuse the code contained within it.

Built-in and user-defined functions are both possible. It aids the program’s ability to be concise, non-repetitive, and well-organized.

Given a word the task is to check if the given word contains Consecutive letters using Functions.

Examples:

Example1:

Input:

Given string = btechGeeks

Output:

The given string { btechGeeks } does not contains consecutive letters

Example2:

Input:

Given string = Abtechgeeks

Output:

The given string { Abtechgeeks } contains consecutive letters

Python Program to Check if a given Word contains Consecutive Letters using Functions

Below are the ways to check if the given word contains Consecutive letters using Functions.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Create a function checkConsecutive() that accepts the given string as an argument and returns true if the given word contains consecutive letters else returns false.
  • Pass the given string as an argument to checkConsecutive() function.
  • Convert all of the word’s characters to the upper case because when we use ASCII values to check for consecutive letters, we want all of the characters to be in the same case.
  • Traverse the given string using For loop.
  • Using Python’s ord() function, convert the character at the index equivalent to the loop counter to its equivalent ASCII value.
  • Check whether the ASCII value is one less than the ASCII value of the character at the index comparable to the loop counter + 1.
  • If the condition given in the earlier point is met, the function returns true otherwise, the function returns False.
  • Print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkConsecutive() that accepts
# the given string as an argument and returns true if the given word
# contains consecutive letters else returns false.


def checkConsecutive(givenstring):
  # Convert all of the word's characters to the upper case
  # because when we use ASCII values to check for
  # consecutive letters, we want all of the characters to be in the same case.
    givenstring = givenstring.upper()
    # Traverse the given string using For loop.
    # Using Python's ord() function, convert the character at the index equivalent
    # to the loop counter to its equivalent ASCII value.
    for m in range(len(givenstring)-1):
      # Check whether the ASCII value is one less than the ASCII value of the character
      # at the index comparable to the loop counter + 1.
        if (ord(givenstring[m]) + 1) == ord(givenstring[m+1]):
          # If the condition given in the earlier point is met,
          # the function returns true otherwise,
          # the function returns False
            return True
    return False


# Give the string as static input and store it in a variable.
givenstring = "btechGeeks"
# Pass the given string as an argument to checkConsecutive() function.
if(checkConsecutive(givenstring)):
    print('The given string {', givenstring, '} contains consecutive letters')
else:
    print('The given string {', givenstring,
          '} does not contains consecutive letters')

Output:

The given string { btechGeeks } does not contains consecutive letters

Method #2: Using For Loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Create a function checkConsecutive() that accepts the given string as an argument and returns true if the given word contains consecutive letters else returns false.
  • Pass the given string as an argument to checkConsecutive() function.
  • Convert all of the word’s characters to the upper case because when we use ASCII values to check for consecutive letters, we want all of the characters to be in the same case.
  • Traverse the given string using For loop.
  • Using Python’s ord() function, convert the character at the index equivalent to the loop counter to its equivalent ASCII value.
  • Check whether the ASCII value is one less than the ASCII value of the character at the index comparable to the loop counter + 1 using ord() function.
  • If the condition given in the earlier point is met, the function returns true otherwise, the function returns False.
  • Print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkConsecutive() that accepts
# the given string as an argument and returns true if the given word
# contains consecutive letters else returns false.


def checkConsecutive(givenstring):
  # Convert all of the word's characters to the upper case
  # because when we use ASCII values to check for
  # consecutive letters, we want all of the characters to be in the same case.
    givenstring = givenstring.upper()
    # Traverse the given string using For loop.
    # Using Python's ord() function, convert the character at the index equivalent
    # to the loop counter to its equivalent ASCII value.
    for m in range(len(givenstring)-1):
      # Check whether the ASCII value is one less than the ASCII value of the character
      # at the index comparable to the loop counter + 1.
        if (ord(givenstring[m]) + 1) == ord(givenstring[m+1]):
          # If the condition given in the earlier point is met,
          # the function returns true otherwise,
          # the function returns False
            return True
    return False


# Give the string as user input using the input() function and store it in a variable.
givenstring = input('Enter some random string = ')
# Pass the given string as an argument to checkConsecutive() function.
if(checkConsecutive(givenstring)):
    print('The given string {', givenstring, '} contains consecutive letters')
else:
    print('The given string {', givenstring,
          '} does not contains consecutive letters')

Output:

Enter some random string = Abtechgeeks
The given string { Abtechgeeks } contains consecutive letters

Related Programs:

Python Program to Subtract two Complex Numbers

Program to Subtract two Complex Numbers

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

Complex numbers in python:

A complex number is formed by combining two real numbers. Python complex numbers can be generated using two methods: the complex() function and a direct assignment statement. Complex numbers are most commonly used when two real numbers are used to define something.

Given two complex numbers, and the task is to subtract given two complex numbers and get the result.

Example:

given complex no = complex(2, 3)   # result  = 2+3j

Examples:

Example1:

Input:

Given first complex number = 2+3j
Given second complex number = 1+5j

Output:

The Subtraction of  (2+3j) - (1+5j) = (1-2j)

Example2:

Input:

Given first complex number = 6+1j
Given second complex number = 5+2j

Output:

The Subtraction of  (6+1j) - (5+2j) = (1-1j)

Program to Subtract two Complex Numbers

Below are the ways to Subtract given two Complex Numbers.

Method #1: Using complex() function  (Static input)

Approach:

  • Give the first complex number as static input and store it in a variable.
  • Give the second complex number as static input and store it in another variable.
  • Subtract the given two complex numbers and store it in another variable.
  • Print the Subtraction of the given two complex numbers
  • The Exit of the program.

Below is the implementation:

# Give the first complex number as static input and store it in a variable.
fst_complx_no = 2 + 3j
# Give the second complex number as static input and store it in another variable.
scnd_complx_no = 1 + 5j
# Subtract the given two complex numbers and store it in another variable.
subtrctn_res = fst_complx_no - scnd_complx_no
# Print the Subtraction of the given two complex numbers
print(" The Subtraction of ", fst_complx_no,
      "-", scnd_complx_no, "=", subtrctn_res)

Output:

The Subtraction of  (2+3j) - (1+5j) = (1-2j)

Method #2: Using complex() function  (User input)

Approach:

  • Give the real part and imaginary part of the first complex number as user input using map(), int(), split().
  • Store it in two variables.
  • Using a complex() function convert those two variables into a complex number and store it in a variable.
  • Give the real part and imaginary part of the second complex number as user input using map(), int(), split().
  • Store it in two variables.
  • Using a complex() function convert those two variables into a complex number and store it in another variable.
  • Subtract the given two complex numbers and store it in another variable.
  • Print the Subtraction of the given two complex numbers
  • The Exit of the program.

Below is the implementation:

#Give the real part and imaginary part of the first complex number as user input using map(), int(), split().
#Store it in two variables.
realpart_1, imaginarypart_1 = map(int, input(
    'Enter real part and complex part of the complex number = ').split())
#Using a complex() function convert those two variables into a complex number and store it in a variable.   
fst_complexnumbr = complex(realpart_1, imaginarypart_1)
#Give the real part and imaginary part of the second complex number as user input using map(), int(), split().
#Store it in two variables.
realpart_2, imaginarypart_2 = map(int, input(
    'Enter real part and complex part of the complex number = ').split())
#Using a complex() function convert those two variables into a complex number and store it in another variable.
scnd_complexnumbr = complex(realpart_2, imaginarypart_2)
# Subtract the given two complex numbers and store it in another variable.
subtrctn_res = fst_complexnumbr - scnd_complexnumbr
# Print the Subtraction of the given two complex numbers
print(" The Subtraction of ", fst_complexnumbr,
      "-", scnd_complexnumbr, "=", subtrctn_res)

Output:

Enter real part and complex part of the complex number = 3 7
Enter real part and complex part of the complex number = 1 14
The Subtraction of (3+7j) - (1+14j) = (2-7j)

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

 

Python Program to Find Common Characters between Two Strings

Program to Find Common Characters between Two Strings

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

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

join() :

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

lower() :

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

sorted method() :

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

intersection() method :

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

Examples:

Example 1:

Input:

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

Output:

The Common Characters between the above given two Strings =   go

Example 2:

Input:

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

Output:

The Common Characters between the above given two Strings = acdeiy

Program to Find Common Characters between Two Strings

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

Method #1: Using intersection Method (Static Input)

Approach:

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

Below is the implementation:

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

Output:

The Common Characters between the above given two Strings =   go

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

Approach:

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

Below is the implementation:

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

Output:

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

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Get Sum of all the Factors of a Number

Program to Get Sum of all the Factors of a Number

In the previous article, we have discussed Python Program to Find Product of Values of elements in a Dictionary
Given a number, and the task is to get the sum of all the factors of a given number.

Factors are numbers or algebraic expressions that divide another number by themselves and leave no remainder.

Example: let the given number = 24

# The factors of 24 are : 1, 2, 3, 4, 6, 8, 12, 24

The sum of all the factors of 24 = 1+2+ 3+4+6+ 8+12+24 = 60

Examples:

Example1:

Input:

Given Number = 24

Output:

The Sum of all the factors of { 24 } is =  60

Example 2:

Input:

Given Number = 140

Output:

The Sum of all the factors of { 140 } is =  336

Program to Get Sum of all the Factors of a Number

Below are the ways to get the sum of all the factors of a given number.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take a list and initialize it with ‘1’ and store it in another variable.
  • Loop from ‘2’  to the above-given number range using For loop.
  • Check whether the given number modulus iterator value is equal to ‘0’ or not using if conditional statement.
  • If the statement is True, append the iterator value to the above-declared list.
  • Get the sum of all the factors of the above-given list using the built-in sum() function and store it in another variable.
  • Print the sum of all the factors of a given number.
  • The Exit of the program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 24
# Take a list and initialize it with '1' and store it in another variable.
all_factors = [1]
# Loop from '2' to above given number range using For loop.
for itr in range(2, gvn_numb+1):
    # Check whether the given number modulus iterator value is equal to '0' or not
    # using if conditional statement.
    if gvn_numb % itr == 0:
      # If the statement is True ,append the iterator value to the above declared list .
        all_factors.append(itr)
  # Get the sum of all the factors of above got list using built-in sum() function
  # and store it in another variable.
reslt = sum(all_factors)
# Print the sum of all the factors of a given number.
print("The Sum of all the factors of {", gvn_numb, "} is = ", reslt)

Output:

The Sum of all the factors of { 24 } is =  60

Method #2: Using For Loop (User Input)

Approach:

  • Give the number as user input using int(input()) and store it in a variable.
  • Take a list and initialize it with ‘1’ and store it in another variable.
  • Loop from ‘2’  to the above-given number range using For loop.
  • Check whether the given number modulus iterator value is equal to ‘0’ or not using if conditional statement.
  • If the statement is True, append the iterator value to the above-declared list.
  • Get the sum of all the factors of the above-given list using the built-in sum() function and store it in another variable.
  • Print the sum of all the factors of a given number.
  • The Exit of the program.

Below is the implementation:

# Give the number as user input using int(input()) and store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Take a list and initialize it with '1' and store it in another variable.
all_factors = [1]
# Loop from '2' to above given number range using For loop.
for itr in range(2, gvn_numb+1):
    # Check whether the given number modulus iterator value is equal to '0' or not
    # using if conditional statement.
    if gvn_numb % itr == 0:
      # If the statement is True ,append the iterator value to the above declared list .
        all_factors.append(itr)
  # Get the sum of all the factors of above got list using built-in sum() function
  # and store it in another variable.
reslt = sum(all_factors)
# Print the sum of all the factors of a given number.
print("The Sum of all the factors of {", gvn_numb, "} is = ", reslt)

Output:

Enter some random number = 140
The Sum of all the factors of { 140 } is = 336

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 Check if a String is a keyword or Not

Program to Check if a String is a keyword or Not

In the previous article, we have discussed Python Program to Remove Elements from a Tuple
Definition of Keyword:–

A keyword is a reserved word in programming languages that has its own unique meaning. It conveys their unique meaning to the interpreter while executing. And, when using variables in code, we never use the keyword as the variable name.

Some of the keywords in Python are :

True, False, finally, not, or, and, if, else, elif, None, lambda, nonlocal, not, except, as, pass, try, def, in, with, while, import, continue, from, raise, return, global, class, break, from, assert, for, in, with, is, yield, del, and so on.

kwlist method:

To accomplish this, we must import a built-in Python module called “keyword,” and within the keyword module, there is a method called “kwlist” that stores all of the keywords found in the Python language in a list. And if the given string appears in the list, it is considered a keyword; otherwise, it is not a keyword.

Examples:

Example1:

Input:

Given First String = btechgeeks
Given Second String = for

Output:

The given string{ btechgeeks } is not a keyword
The given string{ for } is a keyword

Example 2:

Input:

Given First String = while
Given Second String = for

Output:

The given string{ while } is a keyword
The given string{ for } is a keyword

Program to Check if a String is a keyword or Not

Below are the ways to check if a String is a keyword or Not.

Method #1: Using kwlist Method (Static Input)

Approach:

  • Import keyword module using the import keyword.
  • Get all the keywords in python using keyword.kwlist method and store it in a variable.
  • Give the first string as static input and store it in another variable.
  • Give the second string as static input and store it in another variable.
  • Check whether the given first string is present in the above keyword list or not using the if conditional statement.
  • If the given condition is True, print “keyword”.
  • If the given condition is False, print ” Not keyword” using else conditional statement.
  • Similarly, Check whether the given second string is present in the above keyword or not list using if conditional statement.
  • If the given condition is True, print “keyword”.
  • If the given condition is False, print ” Not keyword” using else conditional statement.
  • The Exit of the Program.

Below is the implementation:

# Import keyword module using import keyword.
import keyword
# Get all the keywords in python using keyword.kwlist method and store it in a variable.
keywrds_lst = keyword.kwlist
# Give the first string as static input and store it in another variable.
fst_str = "btechgeeks"
# Give the second string as static input and store it in another variable.
secnd_str = "for"
# Check whether the given first string is present in the above keyword list or not
# using if conditional statement.
if fst_str in keywrds_lst:
  # If the given condition is True , print "keyword".
    print("The given string{", fst_str, "} is a keyword")
else:
  # If the given condition is False , print " Not keyword" using else conditional statement.
    print("The given string{", fst_str, "} is not a keyword")
# Check whether the given second string is present in the above keyword or not list
# using if conditional statement.
if secnd_str in keywrds_lst:
  # If the given condition is True , print "keyword".
    print("The given string{", secnd_str, "} is a keyword")
else:
  # If the given condition is False , print " Not keyword" using else conditional statement.
    print("The given string{", secnd_str, "} is not a keyword")

Output:

The given string{ btechgeeks } is not a keyword
The given string{ for } is a keyword

Method #2: Using kwlist Method (User Input)

Approach:

  • Import keyword module using the import keyword.
  • Get all the keywords in python using keyword.kwlist method and store it in a variable.
  • Give the first string as user input using the input() function and store it in another variable.
  • Give the second string as user input using the input() function and store it in another variable.
  • Check whether the given first string is present in the above keyword list or not using the if conditional statement.
  • If the given condition is True, print “keyword”.
  • If the given condition is False, print ” Not keyword” using else conditional statement.
  • Similarly, Check whether the given second string is present in the above keyword or not list using if conditional statement.
  • If the given condition is True, print “keyword”.
  • If the given condition is False, print ” Not keyword” using else conditional statement.
  • The Exit of the Program.

Below is the implementation:

# Import keyword module using import keyword.
import keyword
# Get all the keywords in python using keyword.kwlist method and store it in a variable.
keywrds_lst = keyword.kwlist
# Give the first string as user input using the input() function and
# store it in another variable.
fst_str = input("Enter some random string = ")
# Give the second string as user input using the input() function and
# store it another variable.
secnd_str = input("Enter some random string = ")
# Check whether the given first string is present in the above keyword list or not
# using if conditional statement.
if fst_str in keywrds_lst:
  # If the given condition is True , print "keyword".
    print("The given string{", fst_str, "} is a keyword")
else:
  # If the given condition is False , print " Not keyword" using else conditional statement.
    print("The given string{", fst_str, "} is not a keyword")
# Check whether the given second string is present in the above keyword or not list
# using if conditional statement.
if secnd_str in keywrds_lst:
  # If the given condition is True , print "keyword".
    print("The given string{", secnd_str, "} is a keyword")
else:
  # If the given condition is False , print " Not keyword" using else conditional statement.
    print("The given string{", secnd_str, "} is not a keyword")

Output:

Enter some random string = while
Enter some random string = for
The given string{ while } is a keyword
The given string{ for } is a keyword

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 Product of Values of elements in a Dictionary

Program to Find Product of Values of elements in a Dictionary

In the previous article, we have discussed Python Program to Check if a String is a keyword or Not
Dictionary in python :

A dictionary is a set of elements that have key-value pairs. The values in the elements are accessed using the element’s keys.

example:

dict = {‘january’ :1, ‘febrauary’: 2, ‘march’: 3 }

Given a dictionary, and the task is to find the Product of values of elements in a dictionary.

Examples:

Example1:

Input:

Given dictionary = {'jan': 10, 'Feb': 5, 'Mar': 22, 'April': 32, 'May': 6}

Output:

The Product of values in a given dictionary =  211200

Example2:

Input: 

Given dictionary = {'a': 1, 'b': 5, 'c': 2, 'd': 4, 'e': 7, 'f': 2}

Output:

The Product of values in a given dictionary =  560

Program to Find Product of Values of elements in a Dictionary

Below are the ways to Find the Product of Values of elements in a Dictionary.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the dictionary by initializing it with some random values and store it in a variable.
  • Get all the values of the given dictionary using the dictionary.values() method and store it in another variable.
  • Take a variable to say ‘product’ and initialize its value with ‘1’
  • Iterate in the above-given dictionary values using For loop.
  • Inside the loop, Multiply the above-initialized product variable with the iterator and store it in the same variable.
  • Print the product of values for the above-given dictionary.
  • The Exit of the program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict = {'jan': 10, 'Feb': 5, 'Mar': 22, 'April': 32, 'May': 6}
# Get all the values of given dictionary using dictionary.values() method
# and store it in another variable.
dict_vlue = gvn_dict.values()
# Take a variable say 'product' and initialize it's value with '1'
fnl_prod = 1
# Iterate in the above given dictionary values using using For loop.
for itrator in dict_vlue:
  # Inside the loop, Multiply the above initialized product variable with the iterator
  # and store it in a same variable.
    fnl_prod = fnl_prod*itrator
# Print the product of values for the above given dictionary.
print("The Product of values in a given dictionary = ", fnl_prod)

Output:

The Product of values in a given dictionary =  211200

Method #2: Using For Loop (User Input)

Approach:

  • Take a dictionary and initialize it with an empty dictionary using dict() or {}.
  • Give the number of keys as user input using int(input()) and store it in a variable.
  • Loop till the given number of keys using for loop.
  • Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
  • Initialize the key with the value of the dictionary.
  • Get all the values of the given dictionary using the dictionary.values() method and store it in another variable.
  • Take a variable to say ‘product’ and initialize its value with ‘1’
  • Iterate in the above-given dictionary values using For loop.
  • Inside the loop, Multiply the above-initialized product variable with the iterator and store it in the same variable.
  • Print the product of values for the above-given dictionary.
  • The Exit of the program.

Below is the implementation:

# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = {}
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
    input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
        # Inside the for loop scan the key and value as
    # user input using input(),split() functions
    # and store them in two separate variables.
    keyy, valuee =  input(
        'Enter key and value separated by spaces = ').split()
    # Initialize the key with the value of the dictionary.
    gvn_dict[keyy] = valuee

# Get all the values of given dictionary using dictionary.values() method
# and store it in another variable.
dict_vlue = gvn_dict.values()
# Take a variable say 'product' and initialize it's value with '1'
fnl_prod = 1
# Iterate in the above given dictionary values using using For loop.
for itrator in dict_vlue:
  # Inside the loop, Multiply the above initialized product variable with the iterator
  # and store it in a same variable.
    fnl_prod = fnl_prod*int(itrator)
# Print the product of values for the above given dictionary.
print("The Product of values in a given dictionary = ", fnl_prod)

Output:

Enter some random number of keys of the dictionary = 5
Enter key and value separated by spaces = hello 4
Enter key and value separated by spaces = this 9
Enter key and value separated by spaces = is 10
Enter key and value separated by spaces = btechgeeks 12
Enter key and value separated by spaces = python 1
The Product of values in a given dictionary = 4320

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 Generate Perfect Numbers in an Interval

Program to Generate Perfect Numbers in an Interval

In the previous article, we have discussed Python Program to Add Two Numbers Without Using the “+” Operator.
If the sum of a number’s appropriate divisors (excluding the number itself) equals the number, the number is said to be the perfect number.

Consider the following example: appropriate divisors of 6 are 1, 2, 3. Because the sum of these divisors equals 6 (1+2+3=6), 6 is considered a perfect number. When we consider another number, such as 12, the proper divisors of 12 are 1, 2, 3, 4, and 6. Now, because the sum of these divisors does not equal 12, 12 is not a perfect number.

Python programming is simpler and more enjoyable than programming in other languages due to its simplified syntax and superior readability. Now that we understand the concept of a perfect number, let’s construct a Python program to determine whether or not a number is a perfect number. Let’s write some Python code to see if the given user input is a perfect number or not, and have some fun with Python coding.

Examples:

Example1:

Input:

Given lower limit range = 1
Given upper limit range=1000

Output:

The Perfect numbers in the given range 1 and 1000 are:
1 6 28 496

Example 2:

Input:

Given lower limit range = 496
Given upper limit range=8128

Output:

The Perfect numbers in the given range 125 and 8592 are:
496 8128

Program to Generate Perfect Numbers in an Interval

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

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 to say ‘itrnumb‘ and initialize its value to the iterator value.
  • pass the itrnumb as a argument to checkPerfectNumbr() function.
  • Inside the checkPerfectNumbr() function Take a variable to say totalSum and initialize it to 1.
  • Iterator from 2 to number -1 using for loop.
  • Check if the iterator value divides the number using the If conditional statement.
  • If it is true then add the given iterator value to totalSum.
  • Check if the totalSum is equal to the given number using if conditional statement.
  • If it is true then it is a perfect number then return True.
  • Else return False.
  • Inside the main function for the loop check whether the function turns return or False.
  • If it returns true then print the itrnumb.
  • The Exit of the Program.

Below is the implementation:

# function which returns true if the given number is
# perfect number else it will return False


def checkPerfectNumbr(givenNumb):
    # Taking a variable totalSum and initializing it with 1
    totalSum = 1
    # Iterating from 2 to n-1
    for i in range(2, givenNumb):
        # if the iterator value is divides the number then add the given number to totalSum
        if givenNumb % i == 0:
            totalSum += i

    # if the totalSum is equal to the given number
    # then it is perfect number else it is not perfect number

    if(totalSum == givenNumb):
        # if it is true then it is perfect number then return true
        return True
    # if nothing is returned then it is not a perfect number so return False
    return False


# Give the lower limit range as static input and store it in a variable.
lowlimrange = 1
# Give the upper limit range as static input and store it in another variable.
upplimrange = 1000
print('The Perfect numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for itrvalue in range(lowlimrange, upplimrange+1):
        # Inside the for loop pass the iterator value to checkNeonnumb() function.
    if(checkPerfectNumbr(itrvalue)):
        # If it returns true then print the iterator value.
        print(itrvalue, end=' ')

Output:

The Perfect numbers in the given range 1 and 1000 are:
1 6 28 496

Method #2: Using For Loop (User Input)

Approach:

  • Give the lower limit range as user input and store it in a variable.
  • Give the upper limit range as user 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 to say ‘itrnumb‘ and initialize its value to the iterator value.
  • pass the itrnumb as a argument to checkPerfectNumbr() function.
  • Inside the checkPerfectNumbr() function Take a variable to say totalSum and initialize it to 1.
  • Iterator from 2 to number -1 using for loop.
  • Check if the iterator value divides the number using the If conditional statement.
  • If it is true then add the given iterator value to totalSum.
  • Check if the totalSum is equal to the given number using if conditional statement.
  • If it is true then it is a perfect number then return True.
  • Else return False.
  • Inside the main function for the loop check whether the function turns return or False.
  • If it returns true then print the itrnumb.
  • The Exit of the Program.

Below is the implementation:

# function which returns true if the given number is
# perfect number else it will return False


def checkPerfectNumbr(givenNumb):
    # Taking a variable totalSum and initializing it with 1
    totalSum = 1
    # Iterating from 2 to n-1
    for i in range(2, givenNumb):
        # if the iterator value is divides the number then add the given number to totalSum
        if givenNumb % i == 0:
            totalSum += i

    # if the totalSum is equal to the given number
    # then it is perfect number else it is not perfect number

    if(totalSum == givenNumb):
        # if it is true then it is perfect number then return true
        return True
    # if nothing is returned then it is not a perfect number so return False
    return False


# Give the lower limit range and upper limit range as
# user input using map(),int(),split() functions.
# Store them in two separate variables.
lowlimrange, upplimrange = map(int, input(
    'Enter lower limit range and upper limit range separate by spaces = ').split())
print('The Perfect numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for itrvalue in range(lowlimrange, upplimrange+1):
        # Inside the for loop pass the iterator value to checkNeonnumb() function.
    if(checkPerfectNumbr(itrvalue)):
        # If it returns true then print the iterator value.
        print(itrvalue, end=' ')

Output:

Enter lower limit range and upper limit range separate by spaces = 125 8592
The Perfect numbers in the given range 125 and 8592 are:
496 8128

Here we printed all the perfect numbers in the range 125 to 8592

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 Check if Array can be Sorted with One Swap

Program to Check if Array can be Sorted with One Swap

In the previous article, we have discussed Python Program for Maximum Distance between Two Occurrences of Same Element in Array/List
Given a list and the task is to check to see if the given list can be sorted with a single swap.

copy() method:

The list’s shallow copy is returned by the copy() method.

There are no parameters to the copy() method.

It creates a new list. It makes no changes to the original list.

Examples:

Example1:

Input:

Given List = [7, 8, 9]

Output:

The given list [7, 8, 9] can be sorted with a single swap

Explanation:

When we swap 7 and 9 we get [9, 8, 7] which is a sorted list.

Example2:

Input:

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

Output:

The given list [6, 3, 2, 1] cannot be sorted with a single swap

Program to Check if Array can be Sorted with One Swap in Python:

Below are the ways to check to see if the given list can be sorted with a single swap.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Copy the given list in a variable say “new_lst” using the copy() function.
  • Take a variable say ‘c’ and initialize its value with 0.
  • Sort the above obtained “new_lst”.
  • Loop until the length of the “new_lst” using the for loop.
  • Check if the given list element is not equal to the new_lst element using the if conditional statement.
  • If the statement is true then increment the count value of ‘c’ by 1 and store it in the same variable ‘c‘.
  • Check if the value of ‘c’ is equal to 0 or true using the if conditional statement and ‘or ‘ keyword.
  • If the statement is true, print “The given list can be sorted with a single swap”.
  • If it is false, then print “The given list cannot be sorted with a single swap”.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gven_lst = [7, 8, 9]
# Copy the given list in a variable say "new_lst" using the copy() function.
new_lst = gven_lst.copy()
# Take a variable say 'c' and initialize its value with 0.
c = 0
# Sort the above obtained "new_lst".
new_lst.sort()
# Loop until the length of the "new_lst" using the for loop.
for i in range(len(new_lst)):
 # Check if the given list element is not equal to the new_lst element using the
    # if conditional statement.
    if(gven_lst[i] != new_lst[i]):
     # If the statement is true then increment the count value of 'c' by 1 and
        # store it in the same variable 'c'.
        c += 1
# Check if the value of 'c' is equal to 0 or true using the if conditional statement
# and 'or ' keyword.
if(c == 0 or c == 2):
  # If the statement is true, print "The given list can be sorted with a single swap".
    print("The given list", gven_lst, "can be sorted with a single swap")
 # If it is false, then print "The given list cannot be sorted with a single swap".
else:
    print("The given list", gven_lst, "cannot be sorted with a single swap")

Output:

The given list [7, 8, 9] can be sorted with a single swap

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.
  • Copy the given list in a variable say “new_lst” using the copy() function.
  • Take a variable say ‘c’ and initialize its value with 0.
  • Sort the above obtained “new_lst”.
  • Loop until the length of the “new_lst” using the for loop.
  • Check if the given list element is not equal to the new_lst element using the if conditional statement.
  • If the statement is true then increment the count value of ‘c’ by 1 and store it in the same variable ‘c‘.
  • Check if the value of ‘c’ is equal to 0 or true using the if conditional statement and ‘or ‘ keyword.
  • If the statement is true, print “The given list can be sorted with a single swap”.
  • If it is false, then print “The given list cannot be sorted with a single swap”.
  • 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.
gven_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Copy the given list in a variable say "new_lst" using the copy() function.
new_lst = gven_lst.copy()
# Take a variable say 'c' and initialize its value with 0.
c = 0
# Sort the above obtained "new_lst".
new_lst.sort()
# Loop until the length of the "new_lst" using the for loop.
for i in range(len(new_lst)):
 # Check if the given list element is not equal to the new_lst element using the
    # if conditional statement.
    if(gven_lst[i] != new_lst[i]):
     # If the statement is true then increment the count value of 'c' by 1 and
        # store it in the same variable 'c'.
        c += 1
# Check if the value of 'c' is equal to 0 or true using the if conditional statement
# and 'or ' keyword.
if(c == 0 or c == 2):
  # If the statement is true, print "The given list can be sorted with a single swap".
    print("The given list", gven_lst, "can be sorted with a single swap")
 # If it is false, then print "The given list cannot be sorted with a single swap".
else:
    print("The given list", gven_lst, "cannot be sorted with a single swap")

Output:

Enter some random List Elements separated by spaces = 5 6 7 12 15
The given list [5, 6, 7, 12, 15] can be sorted with a single swap

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.