Vikram Chiluka

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.

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.

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.

 

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.

 

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.

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 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 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:

Program to Calculate the Length of a String Without Using a Library Function

Python Program to Calculate the Length of a String Without Using a Library Function

Strings in Python:

A string is one of the most frequent data types in any computer language. A string is a collection of characters that can be used to represent usernames, blog posts, tweets, or any other text content in your code. You can make a string and assign it to a variable by doing something like this.

sample_string='BTechGeeks'

Strings are considered immutable in Python, once created, they cannot be modified. You may, however, construct new strings from existing strings using a variety of approaches. This form of programming effort is known as string manipulation.

Examples:

Example1:

Input:

given string = hello this is btechgeeks online

Output:

The length of given string { hello this is btechgeeks online } = 31

Example2:

Input:

given string = for file operations upload files using 23199 -@33hello

Output:

The length of given string { for file operations upload files using 23199 -@33hello } = 54

Program to Calculate the Length of a String Without Using a Library Function in Python

Below is the full approach to calculate the length of the given string without using built-in library len() in Python.

1)Using Count variable(Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a variable to say stringLength that stores the length of the given string.
  • Initialize the stringLength to 0.
  • To traverse the characters in the string, use a For loop.
  • Increment the stringLength (Count Variable) by 1.
  • Print the stringLength.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
given_string = 'HelloThisisBTechGeeks'
# Take a variable to say stringLength that stores the length of the given string.
# Initialize the stringLength to 0.
stringLength = 0
# To traverse the characters in the string, use a For loop.
for charact in given_string:
    # Increment the stringLength (Count Variable) by 1.
    stringLength = stringLength+1
# Print the stringLength.
print('The length of given string {', given_string, '} =', stringLength)

Output:

The length of given string { HelloThisisBTechGeeks } = 21

Explanation:

  • A string must be entered by the user as static input and saved in a variable.
  • The count variable is set to zero.
  • The for loop is used to go over the characters in a string.
  • When a character is encountered, the count is increased.
  • The total number of characters in the string, which is the string’s length, is printed.

2)Using Count variable(User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take a variable to say stringLength that stores the length of the given string.
  • Initialize the stringLength to 0.
  • To traverse the characters in the string, use a For loop.
  • Increment the stringLength (Count Variable) by 1.
  • Print the stringLength.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using input() function and store it in a variable.
given_string = input('Enter some random string = ')
# Take a variable to say stringLength that stores the length of the given string.
# Initialize the stringLength to 0.
stringLength = 0
# To traverse the characters in the string, use a For loop.
for charact in given_string:
    # Increment the stringLength (Count Variable) by 1.
    stringLength = stringLength+1
# Print the stringLength.
print('The length of given string {', given_string, '} =', stringLength)

Output:

Enter some random string = btechgeeksonlineplatformforgeeks and coding platform
The length of given string { btechgeeksonlineplatformforgeeksa nd coding platform } = 52

The total number of characters in the string, which is the string’s length, is printed.
Related Programs:

Program to Convert Gray Code to Binary

Python Program to Convert Gray Code to Binary

Although binary numbers are the most common way to store numbers, they can be challenging to use in many situations, necessitating the usage of a binary number variant. This is where Gray codes come in handy.

Gray code has the property that two consecutive numbers differ in just one bit. Because of this quality, grey code cycles through multiple states with low effort and is used in K-maps, error correction, communication, and so on.

Gray Code is a type of minimum-change coding in which the two subsequent values differ by only one bit. More specifically, it is a binary number system in which only a single bit varies while travelling from one step to the next.

We will learn how to convert gray to binary code in Python in this tutorial. A binary number is a number written in the base-2 numeral system. As a result, a binary number is made up of only 0s and 1s. So, today, we’ll learn how to represent binary and gray code numbers, how to convert a gray number to binary code, and how to use a Python program to convert a gray number to binary code.

Examples:

Example1:

Input:

given gray code =1001000010

Output:

The Binary string of the given gray code= 1001000010 is 1110000011

Example2:

Input:

given gray code =1000111100110

Output:

The Binary string of the given gray code= 1000111100110 is 1111010111011

Program to Convert Gray Code to Binary in Python

Below are the ways to convert the given gray code to binary number in python:

Method #1:Using Right Shift Operator and  While loop( Static Input)

Approach:

  • Give the binary number as static.
  • The grayToBin has been defined.
  • It accepts as an argument the Gray codeword string.
  • It returns the binary number connected with it as a string.
  • If g(i) is the ith bit in the Gray codeword and b(i) is the ith bit in the corresponding binary number, where the 0th bit is the MSB, g(0) = b(0) and b(i) = g(i) XOR b(i – 1) for I > 0.
  • Based on the preceding, b(i) = g(i) XOR g(i – 1) XOR… XOR g (0).
  • Thus, a Gray codeword g can be translated to its corresponding binary number by doing (g XOR (g >> 1) XOR (g >> 2) XOR… XOR (g >> m)), where m is such that g >> (m + 1) equals 0.

Below is the implementation:

# function which accepts the gray code  and returns the binary code  of the gray code
def grayToBin(grayCde):
   # Converting the given gray code to integer
    graynum = int(grayCde, 2)
   # Taking a temporary variable which stores the the gray code integer number
    tempnum = graynum
    # using while loop
    while tempnum != 0:
        tempnum >>= 1
        graynum ^= tempnum

        # bin(n) returns n's binary representation with the prefix '0b' removed
        # the slice operation removes the prefix.
    return bin(graynum)[2:]


# given gray code as static
graycode = "1001000010"
# passing this graycode to grayToBin function
resultbin = grayToBin(graycode)
print('The Binary string of the given gray code=', graycode, 'is', resultbin)

Output:

The Binary string of the given gray code= 1001000010 is 1110000011

Method #2:Using Right Shift Operator and  While loop( User Input)

Approach:

  • Scan the gray code string using input() function.
  • The grayToBin has been defined.
  • It accepts as an argument the Gray codeword string.
  • It returns the binary number connected with it as a string.
  • If g(i) is the ith bit in the Gray codeword and b(i) is the ith bit in the corresponding binary number, where the 0th bit is the MSB, g(0) = b(0) and b(i) = g(i) XOR b(i – 1) for I > 0.
  • Based on the preceding, b(i) = g(i) XOR g(i – 1) XOR… XOR g (0).
  • Thus, a Gray codeword g can be translated to its corresponding binary number by doing (g XOR (g >> 1) XOR (g >> 2) XOR… XOR (g >> m)), where m is such that g >> (m + 1) equals 0.

Below is the implementation:

# function which accepts the gray code  and returns the binary code  of the gray code
def grayToBin(grayCde):
   # Converting the given gray code to integer
    graynum = int(grayCde, 2)
   # Taking a temporary variable which stores the the gray code integer number
    tempnum = graynum
    # using while loop
    while tempnum != 0:
        tempnum >>= 1
        graynum ^= tempnum

        # bin(n) returns n's binary representation with the prefix '0b' removed
        # the slice operation removes the prefix.
    return bin(graynum)[2:]


# given gray code as static
graycode = input("Enter some random gray code string = ")
# passing this graycode to grayToBin function
resultbin = grayToBin(graycode)
print('The Binary string of the given gray code=', graycode, 'is', resultbin)

Output:

Enter some random gray code string = 1000111100110
The Binary string of the given gray code= 1000111100110 is 1111010111011

Related Programs: