Python

Program to Check Sunny Number

Python Program to Check Sunny Number

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

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

Example :

Let Given number(N) = 3

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

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

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

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

Examples:

Example1:

Input:

Given number = 3

Output:

The given number{ 3 } is Sunny Number

Example2:

Input:

Given number = 122

Output:

The given number{ 122 } is not a Sunny Number

Program to Check Sunny Number

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

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

Approach:

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

Below is the implementation:

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

Output:

The given number{ 3 } is Sunny Number

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

Approach:

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

Below is the implementation:

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

Output:

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

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

 

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.

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

 

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:

Program to Read Height in Centimeters and then Convert the Height to Feet and Inches

Python Program to Read Height in Centimeters and then Convert the Height to Feet and Inches

Given height in centimeters , the task is to convert the given height to feet and inches in Python.

Examples:

Example1:

Input:

Enter some random height in centimeters = 179.5

Output:

The given height 179.5 cm in inches = 70.72 inches
The given height 179.5 cm in feet = 5.89 feet

Example2:

Input:

Enter some random height in centimeters = 165

Output:

The given height 165.0 cm in inches = 65.01 inches
The given height 165.0 cm in feet = 5.41 feet

Program to Read Height in Centimeters and then Convert the Height to Feet and Inches in Python

There are several ways to read height in centimeters and then convert it to feet and inches in  Python some of them are:

Method #1:Python Static Input

  • Give the height in centimeters as static input.
  • Convert the given height in centimeters to feet by multiplying it with 0.0328 and store it in a variable.
  • Convert the given height in centimeters to inches by multiplying it with 0.0.394 and store it in a variable.
  • Print the height in feet and inches.
  • Exit of Program.

Below is the implementation:

# Give the height in centimeters as static input.
heightcm = 165
# Convert the given height in centimeters to feet by multiplying it with 0.0328
# and store it in a variable.
heightfeet = 0.0328*heightcm
# Convert the given height in centimeters to inches by multiplying it with 0.0.394
# and store it in a variable.
heightinches = 0.394*heightcm
# Print the height in feet and inches.
print("The given height", heightcm, 'cm',
      'in inches = ', round(heightinches, 2), 'inches')
print("The given height", heightcm, 'cm',
      'in feet = ', round(heightfeet, 2), 'feet')

Output:

The given height 165 cm in inches =  65.01 inches
The given height 165 cm in feet =  5.41 feet

Explanation:

  • Given the height in centimeters as static input.
  • The height in centimeters is multiplied by 0.394 and saved in a new variable called height in inches.
  • The height in centimeters is multiplied by 0.0328 and saved in a new variable called height in feet.
  • It is printed the conversion height in inches and feet.

Method #2:Python User Input

Approach:

  • Enter the height in centimeters as user input using float(input()) function .
  • Convert the given height in centimeters to feet by multiplying it with 0.0328 and store it in a variable.
  • Convert the given height in centimeters to inches by multiplying it with 0.0.394 and store it in a variable.
  • Print the height in feet and inches.
  • Exit of Program.

Below is the implementation:

# Enter the height in centimeters as user input using int(input()) function.
heightcm = int(input('Enter some random height in centimeters = '))
# Convert the given height in centimeters to feet by multiplying it with 0.0328
# and store it in a variable.
heightfeet = 0.0328*heightcm
# Convert the given height in centimeters to inches by multiplying it with 0.0.394
# and store it in a variable.
heightinches = 0.394*heightcma
# Print the height in feet and inches.
print("The given height", heightcm, 'cm',
      'in inches = ', round(heightinches, 2), 'inches')
print("The given height", heightcm, 'cm',
      'in feet = ', round(heightfeet, 2), 'feet')

Output:

Enter some random height in centimeters = 169
The given height 169 cm in inches = 66.59 inches
The given height 169 cm in feet = 5.54 feet

Explanation:

  • As the height can be in decimals we take input using  float(input()) function.
  • The height in centimeters is multiplied by 0.394 and saved in a new variable called height in inches.
  • The height in centimeters is multiplied by 0.0328 and saved in a new variable called height in feet.
  • It is printed the conversion height in inches and feet.

Related Programs: