Python

Program to Generate Strong Numbers in an Interval

Python Program to Generate Strong Numbers in an Interval

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

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

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

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

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

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

Examples:

Example 1:

Input:

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

Output:

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

Example 2:

Input:

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

Output:

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

Program to Generate Strong Numbers in an Interval

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

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

Approach:

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

Below is the implementation:

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

Output:

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

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

Approach:

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

Below is the implementation:

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

Output:

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

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

Python Program to Generate Strong Numbers in an Interval Read More »

Program to Get Sum of all the Factors of a Number

Python 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 Get Sum of all the Factors of a Number Read More »

Program to Find Strong Numbers in a List

Python Program to Find Strong Numbers in a List

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

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

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

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

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

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

Examples:

Example1:

Input:

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

Output:

The Strong Numbers in a given List are :
1 145

Example2:

Input:

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

Output:

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

Program to Find Strong Numbers in a List

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

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

Approach:

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

Below is the implementation:

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

Output:

The Strong Numbers in a given List are :
1 145

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

Approach:

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

Below is the implementation:

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

Output:

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

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

Python Program to Find Strong Numbers in a List Read More »

Program to Get n Random Items from a List

Python Program to Get n Random Items from a List

In the previous article, we have discussed Python Program Divide all Elements of a List by a Number
Random Module in python :

As this Random module is one of Python’s predefined modules, its methods return random values.

It selects integers uniformly from a range. For sequences, it has a function to generate a random permutation of a list in-place, as well as a function to generate a random sampling without replacement. Let’s take a look at how to import the Random Module.

The random module in Python is made up of various built-in Methods.

choice():  choice() is used to select an item at random from a list, tuple, or other collection.

Because the choice() method returns a single element, we will be using it in looping statements.
sample(): To meet our needs, we’ll use sample() to select multiple values.

Examples:

Example1:

Input:

Given no of random numbers to be generated = 5
Given list =[1, 2, 3, 2, 2, 1, 4, 5, 6, 8, 9]

Output:

The given 5 Random numbers are :
2
3
8
6
9

Example 2:

Input:

Given no of random numbers to be generated = 3
Given list = [2, 1, 6, 1, 4, 5, 6, 8]

Output:

The given 3 Random numbers are :
6
5
1

Program to Get n Random Items from a List

Below are the ways to Get n Random Items from a Given List.

Method #1: Using random.choice() Method (Static input)

Approach:

  • Import random module using the import keyword.
  • Give the number as static input and store it in a variable.
  • Give the list as static input and store it in another variable.
  • Loop in the given list above given ‘n’ number of times using For loop.
  • Inside the loop, apply random.choice() method for the above-given list and store it in a variable.
  • Print the given number of random numbers to be generated.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number as static input and store it in a variable.
randm_numbrs = 3
# Give the list as static input and store it in another variable.
gvn_lst = [1, 2, 3, 2, 2, 1, 4, 5, 6, 8, 9]
print("The given", randm_numbrs, "Random numbers are :")
# Loop above given 'n' number of times using For loop.
for itr in range(randm_numbrs):
  # Inside the loop, apply random.choice() method for the above given list and
  # store it in a variable.
    reslt = random.choice(gvn_lst)
   # Print the given numbers of random numbers to be generated.
    print(reslt)

Output:

The given 3 Random numbers are :
5
3
4

Method #2: Using random.choice() Method (User input)

Approach:

  • Import random module using the import keyword.
  • Give the number as user input using int(input()) and store it in a variable.
  • Give the list as user input and using list(),map(), int(),input(),and split() functions store it in another variable
  • The loop above given ‘n’ number of times using For loop.
  • Inside the loop, apply random.choice() method for the above-given list and store it in a variable.
  • Print the given number of random numbers to be generated.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number as user input using int(input()) and store it in a variable.
randm_numbrs = int(input("Enter some random number = "))
#Give the list as user input and using list(),map(), int(),input(),and split() functions 
#store it in another variable
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
print("The given", randm_numbrs, "Random numbers are :")
# Loop above given 'n' number of times using For loop.
for itr in range(randm_numbrs):
 # Inside the loop, apply random.choice() method for the above given list and
 # store it in a variable.
    reslt = random.choice(gvn_lst)
 # Print the given numbers of random numbers to be generated.
    print(reslt)

Output:

Enter some random number = 4
Enter some random List Elements separated by spaces = 1 2 3 4 5 6 7 8 9 
The given 4 Random numbers are :
2
2
4
8

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 n Random Items from a List Read More »

Program to Select a Random Element from a Tuple

Python Program to Select a Random Element from a Tuple

In the previous article, we have discussed Python Program to Get n Random Items from a List
Random Module in python :

As this Random module is one of Python’s predefined modules, its methods return random values.

It selects integers uniformly from a range. For sequences, it has a function to generate a random permutation of a list in-place, as well as a function to generate a random sampling without replacement. Let’s take a look at how to import the Random Module.

The random module in Python is made up of various built-in Methods.

choice():  choice() is used to select an item at random from a list, tuple, or other collection.

Because the choice() method returns a single element, we will be using  it in looping statements.
sample(): To meet our needs, we’ll use sample() to select multiple values.

Examples:

Example1:

Input:

Given no of random numbers to be generated = 3
Given tuple = ("btechgeeks", 321, "good morning", [7, 8, 5, 33], 35.8)

Output:

Example 2:

Input:

Given no of random numbers to be generated = 4
Given tuple = (255, "hello", "btechgeeks", 150,"good morning", [1, 2, 3, 4], 100, 98)

Output:

The given 4 Random numbers are :
[1, 2, 3, 4]
255
255
98

Program to Select a Random Element from a Tuple

Below are the ways to select a random element from a given Tuple.

Method #1: Using random.choice() Method (Only one element)

Approach:

  • Import random module using the import keyword.
  • Give the tuple as static input and store it in a variable.
  • Apply random. choice() method for the above-given tuple and store it in another variable.
  • Print the random element from the above-given tuple
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the tuple as static input and store it in a variable.
gvn_tupl = (255, "hello", "btechgeeks", 150,
            "good morning", [1, 2, 3, 4], 100, 98)
# Apply random.choice() method for the above given tuple and store it in another variable.
reslt = random.choice(gvn_tupl)
# Print the random element from the above given tuple
print("The random element from the above given tuple = ", reslt)

Output:

The random element from the above given tuple =  btechgeeks

Method #2: Using For Loop (N elements)

Approach:

  • Import random module using the import keyword.
  • Give the number as static input and store it in a variable.
  • Give the tuple as static input and store it in another variable.
  • Loop in the given tuple above given ‘n’ number of times using For loop.
  • Inside the loop, apply random.choice() method for the above-given tuple and store it in a variable.
  • Print the given number of random elements to be generated from the given tuple.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number as static input and store it in a variable.
randm_numbrs = 3
# Give the tuple as static input and store it in another variable.
gvn_tupl = ("btechgeeks", 321, "good morning", [7, 8, 5, 33], 35.8)
print("The given", randm_numbrs, "Random numbers are :")
# Loop in the given tuple above given 'n' number of times using For loop.
for itr in range(randm_numbrs):
  # Inside the loop, apply random.choice() method for the above given tuple and
  # store it in a variable.
    reslt = random.choice(gvn_tupl)
   # Print the given numbers of random elements to be generated.
    print(reslt)

Output:

The given 3 Random numbers are :
btechgeeks
[7, 8, 5, 33]
321

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 Select a Random Element from a Tuple Read More »

Program to Check if a String is a keyword or Not

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

Program to Find Product of Values of elements in a Dictionary

Python 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 Find Product of Values of elements in a Dictionary Read More »

Python Itertools.product()

Python Itertools.product()

itertools:

itertools is a Python package that provides several functions that work on iterators to generate complicated iterators. This module functions as a fast, memory-efficient tool that can be used alone or in combination to construct iterator algebra.

The key feature of itertools is that its functions are utilized to generate memory-efficient and exact code.

In this article, we will look at itertools. product(), which is a combinatorics generator. This tool is used to calculate the Cartesian Product of two sets and to identify all possible pairs in the form of a tuple (x,y), where x belongs to one set and y belongs to another. Cartesian products can also be achieved with a for loop, although they are less efficient and more difficult to code than itertools.

Examples:

Example1:

Input:

Given First List =[4, 19, 11, 5]
Given Second List=[10, 9, 8, 6, 5, 3]

Output:

The Cartesian Product of the two lists : 
[(4, 10), (4, 9), (4, 8), (4, 6), (4, 5), (4, 3), (19, 10), (19, 9), (19, 8), (19, 6), (19, 5), (19, 3), (11, 10), (11, 9), (11, 8), (11, 6), 
(11, 5), (11, 3), (5, 10), (5, 9), (5, 8), (5, 6), (5, 5), (5, 3)]

Example2:

Input:

Given First List=['hello', 'this', 'is', 'btechgeeks']
Given Second List =['sky', 'is', 'blue']

Output:

The Cartesian Product of the two lists : 
[('hello', 'sky'), ('hello', 'is'), ('hello', 'blue'), ('this', 'sky'), ('this', 'is'), ('this', 'blue'), ('is', 'sky'), ('is', 'is'), ('is', 'blue'), 
('btechgeeks', 'sky'), ('btechgeeks', 'is'), ('btechgeeks', 'blue')]

Itertools.product() in Python

Below are the ways to implement Itertools. product() in Python.

Method #1: Using Itertools.product() (Static Input)

I)Number lists

Approach:

  • Import product from itertools using the import keyword.
  • Give the first list as static input and store it in a variable.
  • Give the second list as static input and store it in another variable.
  • We use the product function to create a list, which we then print.
  • Print the Product of the two lists.
  • The Exit of the Program.

Below is the implementation:

# Import product from itertools using the import keyword.
from itertools import product
# Give the first list as static input and store it in a variable.
lstt1 = [4, 19, 11, 5]
# Give the second list as static input and store it in another variable.
lstt2 = [10, 9, 8, 6, 5, 3]
# We use the product function to create a list, which we then print.
productlists = list(product(lstt1, lstt2))
# Print the Product of the two lists.
print('The Cartesian Product of the two lists : ')
print(productlists)

Output:

The Cartesian Product of the two lists : 
[(4, 10), (4, 9), (4, 8), (4, 6), (4, 5), (4, 3), (19, 10), (19, 9), (19, 8), (19, 6), (19, 5), (19, 3), (11, 10), (11, 9), (11, 8), (11, 6), 
(11, 5), (11, 3), (5, 10), (5, 9), (5, 8), (5, 6), (5, 5), (5, 3)]

II)String lists

Approach:

  • Import product from itertools using the import keyword.
  • Give the first list(string list) as static input and store it in a variable.
  • Give the second list(string list) as static input and store it in another variable.
  • We use the product function to create a list, which we then print.
  • Print the Product of the two lists.
  • The Exit of the Program.

Below is the implementation:

# Import product from itertools using the import keyword.
from itertools import product
# Give the first list(string list) as static input and store it in a variable.
lstt1 = ['hello', 'this', 'is', 'btechgeeks']
# Give the second list(string list) as static input and store it in another variable.
lstt2 = ['sky', 'is', 'blue']
# We use the product function to create a list, which we then print.
productlists = list(product(lstt1, lstt2))
# Print the Product of the two lists.
print('The Cartesian Product of the two lists : ')
print(productlists)

Output:

The Cartesian Product of the two lists : 
[('hello', 'sky'), ('hello', 'is'), ('hello', 'blue'), ('this', 'sky'), ('this', 'is'), ('this', 'blue'), ('is', 'sky'), ('is', 'is'), ('is', 'blue'), 
('btechgeeks', 'sky'), ('btechgeeks', 'is'), ('btechgeeks', 'blue')]

Method #2: Using Itertools.product() (User Input)

I)Number lists

Approach:

  • Import product from itertools using the import keyword.
  • Give the first list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the second list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • We use the product function to create a list, which we then print.
  • Print the Product of the two lists.
  • The Exit of the Program.

Below is the implementation:

# Import product from itertools using the import keyword.
from itertools import product
# Give the first list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
lstt1 = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Give the second list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
lstt2 = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# We use the product function to create a list, which we then print.
productlists = list(product(lstt1, lstt2))
# Print the Product of the two lists.
print('The Cartesian Product of the two lists : ')
print(productlists)

Output:

Enter some random List Elements separated by spaces = 6 8 7 2 9
Enter some random List Elements separated by spaces = 11 12
The Cartesian Product of the two lists : 
[(6, 11), (6, 12), (8, 11), (8, 12), (7, 11), (7, 12), (2, 11), (2, 12), (9, 11), (9, 12)]

II)String lists

Approach:

  • Import product from itertools using the import keyword.
  • Give the first list as user input using list(),input(),and split() functions.
  • Store it in a variable.
  • Give the second list as user input using list(),input(),and split() functions.
  • Store it in a variable.
  • We use the product function to create a list, which we then print.
  • Print the Product of the two lists.
  • The Exit of the Program.

Below is the implementation:

# Import product from itertools using the import keyword.
from itertools import product
# Give the first list as user input using list(),input(),and split() functions.
# Store it in a variable.
lstt1 = list(input(
    'Enter some random List Elements separated by spaces = ').split())
# Give the second list as user input using list(),input(),and split() functions.
# Store it in a variable.
lstt2 = list(input(
    'Enter some random List Elements separated by spaces = ').split())
# We use the product function to create a list, which we then print.
productlists = list(product(lstt1, lstt2))
# Print the Product of the two lists.
print('The Cartesian Product of the two lists : ')
print(productlists)

Output:

Enter some random List Elements separated by spaces = good morning this is btechgeeks
Enter some random List Elements separated by spaces = how are you
The Cartesian Product of the two lists : 
[('good', 'how'), ('good', 'are'), ('good', 'you'), ('morning', 'how'), ('morning', 'are'), ('morning', 'you'), ('this', 'how'), 
('this', 'are'), ('this', 'you'), ('is', 'how'), ('is', 'are'), ('is', 'you'), ('btechgeeks', 'how'), ('btechgeeks', 'are'),
 ('btechgeeks', 'you')]

Related Programs:

Python Itertools.product() Read More »

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

Stack Tutorial: an Implementation Beginner’s Guide

Prerequisites

In order to understand this stack tutorial, you’ll need to learn the Stack data structure which requires the following:

  1. Python 3
  2. Basic data structure concepts like List (Click here to refresh List concepts)
  3. OOP concepts

What is a Stack?

Howdy! If you are reading this article, you are about to learn one of the very basic and most useful data structure concepts. If you know other languages like C or C++, implementation of stack might be tricky (since you will have to keep track of pointers!) but not with Python. Python is so amazing that you can use lists to easily implement them but you will also learn how to implement using pointers to adopt a language agnostic way. But first, let’s understand what they are. If you are already familiar with this, you can skip to the implementation section.

When you hear the word Stack, the first thing that comes to your mind may be a stack of books, and we can use this analogy to explain stacks easily! Some of the commonalities include:

  1. There is a book at the top of the stack (if there is only one book in the stack, then that will be considered the topmost book).
  2. Only when you remove the topmost book can you get access to the bottom ones. No Jenga games here! (Also assume that you can only lift one book at a time).
  3. Once you remove all the books from the top one by one, there will be none left and hence you cannot remove any more books.

Check out this fun game called Towers of Hanoi which beautifully demonstrates how a Stack works. Read the instructions carefully and turn off the music (it is awfully loud!).

What is a Stack

To describe the above points programmatically:

  1. Keep track of the topmost element as this will give you the information about the number of elements in the stack and whether the stack is empty/full (if the stack is empty then top will be set to 0 or a negative number)
  2. The last element to enter the stack will always be the first to leave (Last In First Out – LIFO)
  3. If all the elements are removed, then the stack is empty and if you try to remove elements from an empty stack, a warning or an error message is thrown.
  4. If the stack has reached its maximum limit and you try to add more elements, a warning or error message is thrown.

Things to remember:

  1. The entry and exit of elements happens only from one end of the stack (top)
  2. Push – Adding an element to the Stack
  3. Pop – Removing an element from the Stack
  4. Random access is not allowed – you cannot add or remove an element from the middle.

Note: Always keep track of the Top. This tells us the status of the stack.

How to implement Stack?

Now that you know what a Stack is, let’s get started with the implementation!

Stack implementation using List

Here we are going to define a class Stack and add methods to perform the below operations:

  1. Push elements into a Stack
  2. Pop elements from a Stack and issue a warning if it’s empty
  3. Get the size of the Stack
  4. Print all the elements of the Stack
class Stack:

    #Constructor creates a list
    def __init__(self):
        self.stack = list()

    #Adding elements to stack
    def push(self,data):
        #Checking to avoid duplicate entries
        if data not in self.stack:
            self.stack.append(data)
            return True
        return False

    #Removing last element from the stack
    def pop(self):
        if len(self.stack)<=0:
            return ("Stack Empty!")
        return self.stack.pop()
        
    #Getting the size of the stack
    def size(self):
        return len(self.stack)

myStack = Stack()
print(myStack.push(5)) #prints True
print(myStack.push(6)) #prints True
print(myStack.push(9)) #prints True
print(myStack.push(5)) #prints False since 5 is there
print(myStack.push(3)) #prints True
print(myStack.size())  #prints 4 
print(myStack.pop())   #prints 3
print(myStack.pop())   #prints 9
print(myStack.pop())   #prints 6
print(myStack.pop())   #prints 5
print(myStack.size())  #prints 0
print(myStack.pop())   #prints Stack Empty!

NOTE: We are not worried about the size of the stack since it is represented by a list which can dynamically change its size.

Stack implementation using Array

Python Lists have made it so easy to implement Stack. However, if you want to implement Stack language agnostically, you have to assume that lists are like arrays (fixed in size) and use a Top pointer to keep a tab on the status of the stack. Check this animation to understand how it works.

Algorithm

  1. Declare a list and an integer MaxSize, denoting the maximum size of the Stack
  2. Top is initially set to 0
  3. Push operation:
    1. Check if Top is less than the MaxSize of the Stack
      1. If yes, append data to stack and increment top by 1
      2. If no, print stack full message
  4. Pop operation:
    1. Check if Top is greater than 0:
      1. If yes, pop the last element from the list and decrement top by 1
      2. If no, print stack empty message
  5. Size operation:
    1. The value of the Top pointer is the size of the Stack

Program

class Stack:
    
    #Constructor 
    def __init__(self):
        self.stack = list()
        self.maxSize = 8
        self.top = 0
    
    #Adds element to the Stack
    def push(self,data):
        if self.top>=self.maxSize:
            return ("Stack Full!")
        self.stack.append(data)
        self.top += 1
        return True
        
    #Removes element from the stack
    def pop(self):
        if self.top<=0:
            return ("Stack Empty!")
        item = self.stack.pop()
        self.top -= 1
        return item
        
    #Size of the stack
    def size(self):
        return self.top

s = Stack()
print(s.push(1))#prints True
print(s.push(2))#prints True
print(s.push(3))#prints True
print(s.push(4))#prints True
print(s.push(5))#prints True
print(s.push(6))#prints True
print(s.push(7))#prints True
print(s.push(8))#prints True
print(s.push(9))#prints Stack Full!
print(s.size())#prints 8        
print(s.pop())#prints 8
print(s.pop())#prints 7
print(s.pop())#prints 6
print(s.pop())#prints 5
print(s.pop())#prints 4
print(s.pop())#prints 3
print(s.pop())#prints 2
print(s.pop())#prints 1
print(s.pop())#prints Stack Empty!

Note: Element 9 was not added and hence size remains 8.

Apart from the methods described above, you can add methods to return the top element, check if the stack is empty etc.

Conclusion

One of the main application of Stacks is in recursion. Be sure to check this tutorial to know what recursion is.  Once you are familiar with this concept, try to solve these puzzles using recursion – sentence reversal and balancing brackets. Happy Pythoning!

Stack Tutorial: an Implementation Beginner’s Guide Read More »