Python

Program to Check a number is Narcissistic Number or Not

Python Program to Check a number is Narcissistic Number or Not

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

Given a number, the task is to check whether the given number is a Narcissistic Number or Not in Python.

Narcissistic Number:

Narcissistic numbers are a type of number that can be generated by adding the sum of its own digits raised to the power of the number of digits.

Example:

370

Number of digits=3

3*(Number of digits)+7*(Number of digits)+0*(Number of digits)

3^(3)+7^(3)+0^3=370

So it is a Narcissistic Number.

Examples:

Example1:

Input:

Given Number =370

Output:

The given Number { 370 } is a Narcissistic Number

Example2:

Input:

Given Number =371

Output:

The given Number { 371 } is a Narcissistic Number

Program to Check a number is Narcissistic Number or Not in Python

Below are the ways to check whether the given number is a Narcissistic Number or Not in Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Convert this number into list of digits using list(),map(),int(),str() functions.
  • Store it in a variable.
  • Calculate the length of the list using the len() function and store it in a variable say listleng.
  • Take a variable tempo and initialize its value to 0.
  • Loop in this digits list using For loop.
  • Calculate the iterator value^listleng where ^ represents the power operator and store it in a variable.
  • Increment the tempo by the above variable.
  • After the end of For loop check if the tempo value is equal to the given number using the If conditional Statement.
  • If it is true then print the given number as a Narcissistic Number.
  • Else it is not a Narcissistic Number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
givennmb = 370
# Convert this number into list of digits using list(),map(),int(),str() functions.
# Store it in a variable.
numbedigis = list(map(int, str(givennmb)))
# Calculate the length of the list using the len() function
# and store it in a variable say listleng.
listleng = len(numbedigis)
# Take a variable tempo and initialize its value to 0.
tempo = 0
# Loop in this digits list using For loop.
for numbrdigit in numbedigis:
        # Calculate the iterator value^listleng where ^ represents
    # the power operator and store it in a variable.
    powevalu = numbrdigit**listleng
    # Increment the tempo by the above variable.
    tempo = tempo+powevalu
# After the end of For loop check if the tempo value is equal
# to the given number using the If conditional Statement.
if(tempo == givennmb):
        # If it is true then print the given number as a Narcissistic Number.
    print('The given Number {', givennmb, '} is a Narcissistic Number')
else:
        # Else it is not a Narcissistic Number.
    print('The given Number {', givennmb, '} is not a Narcissistic Number')

Output:

The given Number { 370 } is a Narcissistic Number

Method #2: Using For Loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Convert this number into list of digits using list(),map(),int(),str() functions.
  • Store it in a variable.
  • Calculate the length of the list using the len() function and store it in a variable say listleng.
  • Take a variable tempo and initialize its value to 0.
  • Loop in this digits list using For loop.
  • Calculate the iterator value^listleng where ^ represents the power operator and store it in a variable.
  • Increment the tempo by the above variable.
  • After the end of For loop check if the tempo value is equal to the given number using the If conditional Statement.
  • If it is true then print the given number as a Narcissistic Number.
  • Else it is not a Narcissistic Number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
givennmb = int(input('Enter some random number = '))
# Convert this number into list of digits using list(),map(),int(),str() functions.
# Store it in a variable.
numbedigis = list(map(int, str(givennmb)))
# Calculate the length of the list using the len() function
# and store it in a variable say listleng.
listleng = len(numbedigis)
# Take a variable tempo and initialize its value to 0.
tempo = 0
# Loop in this digits list using For loop.
for numbrdigit in numbedigis:
        # Calculate the iterator value^listleng where ^ represents
    # the power operator and store it in a variable.
    powevalu = numbrdigit**listleng
    # Increment the tempo by the above variable.
    tempo = tempo+powevalu
# After the end of For loop check if the tempo value is equal
# to the given number using the If conditional Statement.
if(tempo == givennmb):
        # If it is true then print the given number as a Narcissistic Number.
    print('The given Number {', givennmb, '} is a Narcissistic Number')
else:
        # Else it is not a Narcissistic Number.
    print('The given Number {', givennmb, '} is not a Narcissistic Number')

Output:

Enter some random number = 371
The given Number { 371 } is a Narcissistic Number

Related Programs:

Python Program to Check a number is Narcissistic Number or Not Read More »

Program to Check if a Number is Peterson Number

Python Program to Check if a Number is Peterson Number

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

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

Peterson Number:

The Peterson number is the number whose sum of factorials of each digit equals the number itself. Let me give you an example to help you understand:

Examples:

Example1:

Input:

Given number =1

Output:

The given number [ 1 ] is a Peterson number

Example2:

Input:

Given number =145

Output:

The given number [ 145 ] is a Peterson number

Program to Check if a Number is Peterson Number in Python

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

Method #1: Using For Loop (Static Input)

Approach:

  • Import the math module using the import keyword.
  • Give the number as static input and store it in a variable.
  • Take a variable psum and initialize its value to 0.
  • Convert the given number to a string using the str() function.
  • Convert the given number into a list of digits using list(),map(),int,split() functions.
  • Traverse in this list of digits using For loop.
  • Calculate the factorial of the list value using math.factorial() function.
  • Add this factorial value to psum.
  • Check if psum is equal to the given number using the If statement.
  • If it is true then it is a Peterson number.
  • Else it is not Peterson’s number.
  • The Exit of the Program.

Below is the implementation:

# Import the math module using the import keyword.
import math
# Give the number as static input and store it in a variable.4
gvnnumb = 145
# Take a variable psum and initialize its value to 0.
psum = 0
# Convert the given number to a string using the str() function.
strnumbe = str(gvnnumb)
# Convert the given number into a list of
# digits using list(),map(),int,split() functions.
lstdigts = list(map(int, strnumbe))
# Traverse in this list of digits using For loop.
for dgtnumbr in lstdigts:
    # Calculate the factorial of the list value using math.factorial() function.
    numbfact = math.factorial(dgtnumbr)
    # Add this factorial value to psum.
    psum = psum+numbfact
# Check if psum is equal to the given number using the If statement.
if(psum == gvnnumb):
        # If it is true then it is a Peterson number.
    print('The given number [', gvnnumb, '] is a Peterson number')
# Else it is not Peterson's number.
else:
    print('The given number [', gvnnumb, '] is not a Peterson number')

Output:

The given number [ 145 ] is a Peterson number

Method #2: Using For Loop (User Input)

Approach:

  • Import the math module using the import keyword.
  • Give the number as user input using int(input()) and store it in a variable.
  • Take a variable psum and initialize its value to 0.
  • Convert the given number to a string using the str() function.
  • Convert the given number into a list of digits using list(),map(),int,split() functions.
  • Traverse in this list of digits using For loop.
  • Calculate the factorial of the list value using math.factorial() function.
  • Add this factorial value to psum.
  • Check if psum is equal to the given number using the If statement.
  • If it is true then it is a Peterson number.
  • Else it is not Peterson’s number.
  • The Exit of the Program.

Below is the implementation:

# Import the math module using the import keyword.
import math
# Give the number as user input using int(input()) and store it in a variable.
gvnnumb = int(input(
    'Enter some random number to check whether the given number is a Peterson or not = '))
# Take a variable psum and initialize its value to 0.
psum = 0
# Convert the given number to a string using the str() function.
strnumbe = str(gvnnumb)
# Convert the given number into a list of
# digits using list(),map(),int,split() functions.
lstdigts = list(map(int, strnumbe))
# Traverse in this list of digits using For loop.
for dgtnumbr in lstdigts:
    # Calculate the factorial of the list value using math.factorial() function.
    numbfact = math.factorial(dgtnumbr)
    # Add this factorial value to psum.
    psum = psum+numbfact
# Check if psum is equal to the given number using the If statement.
if(psum == gvnnumb):
        # If it is true then it is a Peterson number.
    print('The given number [', gvnnumb, '] is a Peterson number')
# Else it is not Peterson's number.
else:
    print('The given number [', gvnnumb, '] is not a Peterson number')

Output:

Enter some random number to check whether the given number is a Peterson or not = 1
The given number [ 1 ] is a Peterson number

Related Programs:

Python Program to Check if a Number is Peterson Number Read More »

Program for Neon Number

Python Program for Neon Number

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

Given a number, the task is to check whether the given number is a Neon Number or not in Python.

Neon Number:

A Neon Number is a number whose square sum of digits equals the original number.

Ex: 9

Square of 9 =81

Sum of digits of square = 8 +1 =9 ,So it is Neon Number

Examples:

Example1:

Input:

Given Number = 9

Output:

The Given Number [ 9 ] is a neon Number

Example2:

Input:

Given Number =123

Output:

The Given Number [ 123 ] is not a neon Number

Program for Neon Number in Python

Below are the ways to check whether the given number is a Neon Number or Not.

Method #1: Using list() and sum() functions (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Calculate the square of the given number using the ** operator or multiply the given number by itself and store it in a variable.
  • Convert this squared number into a list of digits using list(),int(),map(),str() functions.
  • Store this list in a variable.
  • Calculate the sum of digits of this list using the sum() function.
  • Check if this sum is equal to the given number or not using the If conditional statement.
  • If it is true then the given number is a Neon Number.
  • Else the given number is not a Neon Number.
  • The Exit of the Program.

Below is the implementation:

#Give the number as static input and store it in a variable.
givnumb=9
#Calculate the square of the given number using the ** operator 
#or multiply the given number by itself and store it in a variable.
squarnumb=givnumb**2
#Convert this squared number into a list of digits
#using list(),int(),map(),str() functions.
#Store this list in a variable.
numbedigit=list(map(int,str(givnumb)))
#Calculate the sum of digits of this list using the sum() function.
sumdigi=sum(numbedigit)
#Check if this sum is equal to the given number 
#or not using the If conditional statement.
#If it is true then the given number is a Neon Number.
if(sumdigi==givnumb):
  print('The Given Number [',givnumb,'] is a neon Number')
#Else the given number is not a Neon Number.
else:
    print('The Given Number [',givnumb,'] is not a neon Number')

Output:

The Given Number [ 9 ] is a neon Number

Method #2: Using list() and sum() functions (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Calculate the square of the given number using the ** operator or multiply the given number by itself and store it in a variable.
  • Convert this squared number into a list of digits using list(),int(),map(),str() functions.
  • Store this list in a variable.
  • Calculate the sum of digits of this list using the sum() function.
  • Check if this sum is equal to the given number or not using the If conditional statement.
  • If it is true then the given number is a Neon Number.
  • Else the given number is not a Neon Number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using int(input()) function and store it in a variable
givnumb = int(input('Enter some random number ='))
# Calculate the square of the given number using the ** operator
# or multiply the given number by itself and store it in a variable.
squarnumb = givnumb**2
# Convert this squared number into a list of digits
# using list(),int(),map(),str() functions.
# Store this list in a variable.
numbedigit = list(map(int, str(givnumb)))
# Calculate the sum of digits of this list using the sum() function.
sumdigi = sum(numbedigit)
# Check if this sum is equal to the given number
# or not using the If conditional statement.
# If it is true then the given number is a Neon Number.
if(sumdigi == givnumb):
    print('The Given Number [', givnumb, '] is a neon Number')
# Else the given number is not a Neon Number.
else:
    print('The Given Number [', givnumb, '] is not a neon Number')

Output:

Enter some random number =123
The Given Number [ 123 ] is not a neon Number

Related Programs:

Python Program for Neon Number Read More »

Program to Compute the Value of Euler’s Number ,Using the Formula e = 1 + 11! + 12! + …… 1n!

Python Program to Compute the Value of Euler’s Number ,Using the Formula: e = 1 + 1/1! + 1/2! + …… 1/n!

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Given a number numb, the task is to compute the value of the Euler’s number expansion in Python.

Examples:

Example1:

Input:

given number =3

Output:

Enter some random number = 3
The total sum of euler's value of the series 2.67

Example2:

Input:

given number =5

Output:

The total sum of euler's value of the series  2.72

Program to Compute the Value of Euler’s Number ,Using the Formula: e = 1 + 1/1! + 1/2! + …… 1/n! in Python

There are several ways to calculate the value of the euler’s number some of them are:

Method #1:Using factorial function and for loop(Static Input)

Approach:

  • Give the number as static input.
  • Set the value of the totalsum variable to 1.
  • Find the total of the series using a for loop ranging from 1 to the number.
  • Compute the factorial using math. factorial() function.
  • After rounding to two decimal places, print the totalsum of the series.
  • Exit of program.

Below is the implementation:

import math
# Give the number of terms as static input.
numb = 5
# Set a totalsum variable which calculates the total sum and initialize it to 1.
totalsum = 1
# Find the total of the series using a for loop ranging from 1 to the number.
for val in range(1, numb+1):
  # Compute the factorial using math. factorial() function.
    totalsum = totalsum+(1/math.factorial(val))
# Print the totalsum value of the euler's series, rounded to two decimal places.
print("The total sum of euler's value of the series ", round(totalsum, 2))

Output:

The total sum of euler's value of the series  2.72

Method #2:Using factorial function and for loop(User Input)

Approach:

  • Scan the given number as user input by using int(input()) function.
  • Set the value of the totalsum variable to 1.
  • Find the total of the series using a for loop ranging from 1 to the number.
  • Compute the factorial using math. factorial() function.
  • After rounding to two decimal places, print the totalsum of the series.
  • Exit of program.

Below is the implementation:

import math
#  Scan the number as user input by using int(input()) function
numb = int(input('Enter some random number = '))
# Set a totalsum variable which calculates the total sum and initialize it to 1.
totalsum = 1
# Find the total of the series using a for loop ranging from 1 to the number.
for val in range(1, numb+1):
  # Compute the factorial using math. factorial() function.
    totalsum = totalsum+(1/math.factorial(val))
# Print the totalsum value of the euler's series, rounded to two decimal places.
print("The total sum of euler's value of the series ", round(totalsum, 2))

Output:

Enter some random number = 13
The total sum of euler's value of the series 2.72

Method #3:Using factorial function and while loop(Static Input)

Approach:

  • Give the number as static input.
  • Set a totalsum variable which calculates the total sum and initialize it to 0.
  • Take a variable say value and initialize it to 1.
  • Using while loop calculate the total sum till value greater than given number
  • Compute the factorial using math. factorial() function.
  • Calculate the totalsum by incrementing it value with 1/factorial value.
  • Increment the value by 1.
  • Print the totalsum of the series, rounded to two decimal places.
  • Exit of program.

Below is the implementation:

import math
# Give the number of terms as static input.
numb = 3
# Take a variable say value and initialize it to 1.
value = 1
# Set a totalsum variable which calculates the total sum and initialize it to 1.
totalsum = 1
# Using while loop calculate the total sum till value greater than given number
while(value <= numb):
   # Compute the factorial using math. factorial() function.
    totalsum = totalsum+(1/math.factorial(value))
    # Increment the value by 1.
    value = value+1
# Print the totalsum value of the euler's series, rounded to two decimal places.
print("The total sum of euler's value of the series ", round(totalsum, 2))

Output:

The total sum of euler's value of the series 2.67

Method #4:Using factorial function and while loop(User Input)

Approach:

  • Scan the given number as user input by using int(input()) function.
  • Set a totalsum variable which calculates the total sum and initialize it to 0.
  • Take a variable say value and initialize it to 1.
  • Using while loop calculate the total sum till value greater than given number
  • Compute the factorial using math. factorial() function.
  • Calculate the totalsum by incrementing it value with 1/factorial value.
  • Increment the value by 1.
  • Print the totalsum of the series, rounded to two decimal places.
  • Exit of program.

Below is the implementation:

import math
# Scan the number as user input by using int(input()) function
numb = int(input('Enter some random number = '))
# Take a variable say value and initialize it to 1.
value = 1
# Set a totalsum variable which calculates the total sum and initialize it to 1.
totalsum = 1
# Using while loop calculate the total sum till value greater than given number
while(value <= numb):
   # Compute the factorial using math. factorial() function.
    totalsum = totalsum+(1/math.factorial(value))
    # Increment the value by 1.
    value = value+1
# Print the totalsum value of the euler's series, rounded to two decimal places.
print("The total sum of euler's value of the series ", round(totalsum, 2))

Output:

Enter some random number = 3
The total sum of euler's value of the series 2.67

Related Programs:

Python Program to Compute the Value of Euler’s Number ,Using the Formula: e = 1 + 1/1! + 1/2! + …… 1/n! Read More »

Python Program to Check a Number is Spy number

Python Program to Check a Number is Spy number

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Given a number, the task is to check whether the given number is a spy number or not using Python.

Spy number:

If the sum of a number’s digits equals the product of its digits, it’s called a Spy number. 1124,123,1412,132……

Examples:

Example1:

Input:

Given number=1124

Output:

The given number 1124 is spy number

Example2:

Input:

Given number=123

Output:

The given number 123 is spy number

Program to Check a Number is Spy number in Python

Below are the ways to check the given number is a spy number or not in Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Convert this given number to a string using the function str().
  • Take two variables one to store the sum of digits and another to store the product of digits and initialize the sum of digits to 0 and the product of digits with 1.
  • Convert this given number into a list of digits using list(),map(),int functions.
  • Traverse through the digits of the number(Iterate through the list) using For loop.
  • For each element add the element to the sum of digits.
  • Multiply the element with the product of digits.
  • Check if the sum of digits is equal to the product of digits using the If statement.
  • If it is true then it is a spy number
  • Else it is not a spy number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
numbe = 1124
# Convert this given number to a string using the function str().
strnumbe = str(numbe)
# Take two variables one to store the sum of digits and
# another to store the product of digits and
# initialize the sum of digits to 0 and the product of digits with 1.
sumOfDigit = 0
productOfDigit = 1
# Convert this given number into a list of digits using list(),map(),int functions.
listdigits = list(map(int, strnumbe))
# Traverse through the digits of the number(Iterate through the list) using For loop.
for elemen in listdigits:
    # For each element add the element to the sum of digits.
    # Multiply the element with the product of digits.
    sumOfDigit = sumOfDigit+elemen
    productOfDigit = productOfDigit*elemen
# Check if the sum of digits is equal to the product of digits using the If statement.
# If it is true then it is a spy number
if(sumOfDigit == productOfDigit):
    print('The given number', strnumbe, 'is spy number')
# Else it is not a spy number.
else:
    print('The given number', strnumbe, 'is not spy number')

Output:

The given number 1124 is spy number

Method #2: Using For Loop (User Input)

Approach:

  • Give the number as user input using int(input()) and store it in a variable.
  • Convert this given number to a string using the function str().
  • Take two variables one to store the sum of digits and another to store the product of digits and initialize the sum of digits to 0 and the product of digits with 1.
  • Convert this given number into a list of digits using list(),map(),int functions.
  • Traverse through the digits of the number(Iterate through the list) using For loop.
  • For each element add the element to the sum of digits.
  • Multiply the element with the product of digits.
  • Check if the sum of digits is equal to the product of digits using the If statement.
  • If it is true then it is a spy number
  • Else it is not a spy 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.
numbe = int(input('Enter some random number = '))
# Convert this given number to a string using the function str().
strnumbe = str(numbe)
# Take two variables one to store the sum of digits and
# another to store the product of digits and
# initialize the sum of digits to 0 and the product of digits with 1.
sumOfDigit = 0
productOfDigit = 1
# Convert this given number into a list of digits using list(),map(),int functions.
listdigits = list(map(int, strnumbe))
# Traverse through the digits of the number(Iterate through the list) using For loop.
for elemen in listdigits:
    # For each element add the element to the sum of digits.
    # Multiply the element with the product of digits.
    sumOfDigit = sumOfDigit+elemen
    productOfDigit = productOfDigit*elemen
# Check if the sum of digits is equal to the product of digits using the If statement.
# If it is true then it is a spy number
if(sumOfDigit == productOfDigit):
    print('The given number', strnumbe, 'is spy number')
# Else it is not a spy number.
else:
    print('The given number', strnumbe, 'is not spy number')

Output:

Enter some random number = 123
The given number 123 is spy number

Related Programs:

Python Program to Check a Number is Spy number Read More »

Program to Check If A Number Is A Happy Number

Python Program to Check If A Number Is A Happy Number

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

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

Happy Number :

If the repeating sum of the digits squared equals one, the number is said to be a Happy Number. If we continue this method and get outcome 1, we have a happy number. If the outcome is 4, it enters an infinite loop and is not a happy number. Let’s look at an example to help you grasp it better.

Given Number = 320
Square of the digits  = 32 + 22 + 02 = 13
Square of the digits  = 12 + 32 = 10
Square of the digits  = 12 + 02 = 1

Other Examples of happy numbers  =7, 28, 100 etc.

Examples:

Example1:

Input:

Given number =100

Output:

The given number [ 100 ] is a happy number

Example2:

Input:

Given number = 28

Output:

The given number [ 28 ] is a happy number

Program to Check If A Number Is A Happy Number in Python

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

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Create a function digitSquareSum() that accepts the given number as an argument and returns the sum of squares of digits.
  • Inside the digitSquareSum() function.
  • Convert the given argument to string using the str() function.
  • Convert the given argument into list of digits using list(),map(),int() functions.
  • Store it in a variable.
  • Take a variable sumsquaredigits and initialize its value to 0.
  • Loop in this digits list using For loop.
  • Increment the value of sumsquaredigits by the square of the digit(iterator value).
  • Return the sumsquaredigits value.
  • Take a variable reslt and initialize its value to the given number.
  • Loop till the reslt is not equal to 1 or 4 using while loop.
  • Inside the loop pass the reslt value to digitSquareSum() and store it in the same variable reslt.
  • After the end of the while loop, Check whether reslt value is 1 or not using the If statement.
  • If it is true then the given number is a happy number.
  • Else it is not a happy number.
  • The Exit of the Program.

Below is the implementation:

# Create a function digitSquareSum() that accepts the given number
# as an argument and returns the sum of squares of digits.


def digitSquareSum(resltnumber):
    # Inside the digitSquareSum() function.
    # Convert the given argument to string using the str() function.
    strnumbe = str(resltnumber)
    # Convert the given argument into list of digits using list(),map(),int() functions.
    # Store it in a variable.
    numbrlistdigits = list(map(int, strnumbe))
    # Take a variable sumsquaredigits and initialize its value to 0.
    sumsquaredigits = 0
    # Loop in this digits list using For loop.
    for digitvalu in numbrlistdigits:
        # Increment the value of sumsquaredigits by the square
        # of the digit(iterator value).
        sumsquaredigits = sumsquaredigits+(digitvalu**2)
    # Return the sumsquaredigits value
    return sumsquaredigits


# Give the number as static input and store it in a variable.
numbr = 100
# Take a variable reslt and initialize its value to the given number.
reslt = numbr
# Loop till the reslt is not equal to 1 or 4 using while loop.
while(reslt != 1 and reslt != 4):
    # Inside the loop pass the reslt value to digitSquareSum()
    # and store it in the same variable reslt.
    reslt = digitSquareSum(reslt)
# After the end of the while loop,
# Check whether reslt value is 1 or not using the If statement.
if(reslt == 1):
    # If it is true then the given number is a happy number.
    print('The given number [', numbr, '] is a happy number')
else:
    # Else it is not a happy number.
    print('The given number [', numbr, '] is not a happy number')

Output:

The given number [ 100 ] is a happy number

Method #2: Using For Loop (User Input)

Approach:

  • Give the number as user input using int(input()) and store it in a variable.
  • Create a function digitSquareSum() that accepts the given number as an argument and returns the sum of squares of digits.
  • Inside the digitSquareSum() function.
  • Convert the given argument to string using the str() function.
  • Convert the given argument into list of digits using list(),map(),int() functions.
  • Store it in a variable.
  • Take a variable sumsquaredigits and initialize its value to 0.
  • Loop in this digits list using For loop.
  • Increment the value of sumsquaredigits by the square of the digit(iterator value).
  • Return the sumsquaredigits value.
  • Take a variable reslt and initialize its value to the given number.
  • Loop till the reslt is not equal to 1 or 4 using while loop.
  • Inside the loop pass the reslt value to digitSquareSum() and store it in the same variable reslt.
  • After the end of the while loop, Check whether reslt value is 1 or not using the If statement.
  • If it is true then the given number is a happy number.
  • Else it is not a happy number.
  • The Exit of the Program.

Below is the implementation:

# Create a function digitSquareSum() that accepts the given number
# as an argument and returns the sum of squares of digits.


def digitSquareSum(resltnumber):
    # Inside the digitSquareSum() function.
    # Convert the given argument to string using the str() function.
    strnumbe = str(resltnumber)
    # Convert the given argument into list of digits using list(),map(),int() functions.
    # Store it in a variable.
    numbrlistdigits = list(map(int, strnumbe))
    # Take a variable sumsquaredigits and initialize its value to 0.
    sumsquaredigits = 0
    # Loop in this digits list using For loop.
    for digitvalu in numbrlistdigits:
        # Increment the value of sumsquaredigits by the square
        # of the digit(iterator value).
        sumsquaredigits = sumsquaredigits+(digitvalu**2)
    # Return the sumsquaredigits value
    return sumsquaredigits


# Give the number as user input using int(input()) and store it in a variable.
numbr = int(input(
    'Enter some random number to check whether the number is happy number or not = '))
# Take a variable reslt and initialize its value to the given number.
reslt = numbr
# Loop till the reslt is not equal to 1 or 4 using while loop.
while(reslt != 1 and reslt != 4):
    # Inside the loop pass the reslt value to digitSquareSum()
    # and store it in the same variable reslt.
    reslt = digitSquareSum(reslt)
# After the end of the while loop,
# Check whether reslt value is 1 or not using the If statement.
if(reslt == 1):
    # If it is true then the given number is a happy number.
    print('The given number [', numbr, '] is a happy number')
else:
    # Else it is not a happy number.
    print('The given number [', numbr, '] is not a happy number')

Output:

The given number [ 100 ] is a happy number

Related Programs:

Python Program to Check If A Number Is A Happy Number Read More »

Program to Minimum Operations to make all Elements of the List Equal

Python Program to Minimum Operations to make all Elements of the List Equal

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Given a list, the task is to find the minimum operations needed to make all the elements of the given list equal in Python

Examples:

Example1:

Input:

Given list = [11, 3, 7, 1, 2, 7, 3, 6, 7, 9, 3, 9, 1, 19]

Output:

The minimum operations to make all the elements of the given list [11, 3, 7, 1, 2, 7, 3, 6, 7, 9, 3, 9, 1, 19] equal is:
[ 11 ]

Example2:

Input:

Given list = [9, 9, 8, 9, 5, 8, 3, 1, 4, 7]

Output:

The minimum operations to make all the elements of the given list [9, 9, 8, 9, 5, 8, 3, 1, 4, 7] equal is:
[ 7 ]

Program to Minimum Operation to make all Elements of the List Equal in Python

Below are the ways to find the minimum operations needed to make all the elements of the given list equal in Python

Method #1: Using Counter() (Hashing , Static Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the list as static input and store it in a variable.
  • Calculate the frequency of all the given list elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say freqyValues)
  • Calculate the max value of the freqyValues using values() and max() function and store it in a variable(say mxfrqncyval)
  • Calculate the length of the given list using the len() function and store it in a variable.
  • Subtract the mxfrqncyval from the length of the given list.
  • Print the result.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the list as static input and store it in a variable.
givnlst = [11, 3, 7, 1, 2, 7, 3, 6, 7, 9, 3, 9, 1, 19]
# Calculate the frequency of all the given list
# elements using the Counter() function which returns
# the element and its frequency as key-value pair and
# store this dictionary in a variable(say freqyValues)
freqncyValues = Counter(givnlst)
# Calculate the max value of the freqyValues using values()
# and max() function and store it in a variable(say mxfrqncyval)
mxfrqncyval = max(freqncyValues.values())
# Calculate the length of the given list using the len() function
# and store it in a variable.
lstlengt = len(givnlst)
# Subtract the mxfrqncyval from the length of the given list.
minresul = lstlengt-mxfrqncyval
print('The minimum operations to make all the elements of the given list',
      givnlst, 'equal is:')
print('[', minresul, ']')

Output:

The minimum operations to make all the elements of the given list [11, 3, 7, 1, 2, 7, 3, 6, 7, 9, 3, 9, 1, 19] equal is:
[ 11 ]

Method #2: Using Counter() (Hashing , User Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the frequency of all the given list elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say freqyValues)
  • Calculate the max value of the freqyValues using values() and max() function and store it in a variable(say mxfrqncyval)
  • Calculate the length of the given list using the len() function and store it in a variable.
  • Subtract the mxfrqncyval from the length of the given list.
  • Print the result.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
givnlst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Calculate the frequency of all the given list
# elements using the Counter() function which returns
# the element and its frequency as key-value pair and
# store this dictionary in a variable(say freqyValues)
freqncyValues = Counter(givnlst)
# Calculate the max value of the freqyValues using values()
# and max() function and store it in a variable(say mxfrqncyval)
mxfrqncyval = max(freqncyValues.values())
# Calculate the length of the given list using the len() function
# and store it in a variable.
lstlengt = len(givnlst)
# Subtract the mxfrqncyval from the length of the given list.
minresul = lstlengt-mxfrqncyval
print('The minimum operations to make all the elements of the given list',
      givnlst, 'equal is:')
print('[', minresul, ']')

Output:

Enter some random List Elements separated by spaces = 9 9 8 9 5 8 3 1 4 7
The minimum operations to make all the elements of the given list [9, 9, 8, 9, 5, 8, 3, 1, 4, 7] equal is:
[ 7 ]

Related Programs:

Python Program to Minimum Operations to make all Elements of the List Equal Read More »

Program to Swap the First and Last Value of a List

Python Program to Swap the First and Last Value of a List

Lists in Python:

A list is exactly what it sounds like: a container for various Python objects such as integers, words, values, and so on. In other programming languages, it is equal to an array. It is denoted with square brackets (and this is one of the attributes that differentiates it from tuples, which are separated by parentheses). It is also mutable, which means it can be changed or altered, as opposed to tuples, which are immutable.

Given a list , the task is to swap the first and last value of the given list.

Examples:

String List:

Example1:

Input:

given list = ['hello', 'this', 'is', 'BTechGeeks', 'online', 'platform', 'for', 'btech', 'students']

Output:

printing the given list before swapping the values = 
['hello', 'this', 'is', 'BTechGeeks', 'online', 'platform', 'for', 'btech', 'students']
printing the given list after swapping the values = 
['students', 'this', 'is', 'BTechGeeks', 'online', 'platform', 'for', 'btech', 'hello']

Integer List:

Example2:

Input:

given list = [33, 92, 12, 74, 22, 79, 122, 17, 63, 99, 129]

Output:

printing the given list before swapping the values = 
[33, 92, 12, 74, 22, 79, 122, 17, 63, 99, 129]
printing the given list after swapping the values = 
[129, 92, 12, 74, 22, 79, 122, 17, 63, 99, 33]

Program to Swap the First and Last Value of the Given List in Python

There are several ways to sort the first and last value of the given list in python some of them are:

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Method #1:Using temporary variable

Approach:

  • Give the live input as static.
  • Swap the first and last elements in the given list using a temporary variable.
  • Print the new list after swapping that.
  • The Exit of the Program

i)String list

Below is the implementation:

# given list
given_list = ['hello', 'this', 'is', 'BTechGeeks',
              'online', 'platform', 'for', 'btech', 'students']
# printing the given list before swapping the values
print('printing the given list before swapping the values = ')
print(given_list)
# Swap the first and last elements in the given list using a temporary variable.
tempo = given_list[0]
given_list[0] = given_list[-1]
given_list[-1] = tempo
# printing the given list after swapping the values
print('printing the given list after swapping the values = ')
print(given_list)

Output:

printing the given list before swapping the values = 
['hello', 'this', 'is', 'BTechGeeks', 'online', 'platform', 'for', 'btech', 'students']
printing the given list after swapping the values = 
['students', 'this', 'is', 'BTechGeeks', 'online', 'platform', 'for', 'btech', 'hello']

ii)Integer list

Below is the implementation:

# given list
given_list = [33, 92, 12, 74, 22, 79, 122, 17, 63, 99, 129]
# printing the given list before swapping the values
print('printing the given list before swapping the values = ')
print(given_list)
# Swap the first and last elements in the given list using a temporary variable.
tempo = given_list[0]
given_list[0] = given_list[-1]
given_list[-1] = tempo
# printing the given list after swapping the values
print('printing the given list after swapping the values = ')
print(given_list)

Output:

printing the given list before swapping the values = 
[33, 92, 12, 74, 22, 79, 122, 17, 63, 99, 129]
printing the given list after swapping the values = 
[129, 92, 12, 74, 22, 79, 122, 17, 63, 99, 33]

Method #2: Using comma operator in Python

Approach:

  • Give the live input as static.
  • Swap the first and last elements in the given list using a ‘,’ operator.
  • Print the new list after swapping that.
  • The Exit of the Program

i)String list

Below is the implementation:

# given list
given_list = ['hello', 'this', 'is', 'BTechGeeks',
              'online', 'platform', 'for', 'btech', 'students']
# printing the given list before swapping the values
print('printing the given list before swapping the values = ')
print(given_list)
# Swap the first and last elements in the given list using a , operator
given_list[0], given_list[-1] = given_list[-1], given_list[0]
# printing the given list after swapping the values
print('printing the given list after swapping the values = ')
print(given_list)

Output:

printing the given list before swapping the values = 
['hello', 'this', 'is', 'BTechGeeks', 'online', 'platform', 'for', 'btech', 'students']
printing the given list after swapping the values = 
['students', 'this', 'is', 'BTechGeeks', 'online', 'platform', 'for', 'btech', 'hello']

ii)Integer list

Below is the implementation:

# given list
given_list = [33, 92, 12, 74, 22, 79, 122, 17, 63, 99, 129]
# printing the given list before swapping the values
print('printing the given list before swapping the values = ')
print(given_list)
# Swap the first and last elements in the given list using a , operator
given_list[0], given_list[-1] = given_list[-1], given_list[0]
# printing the given list after swapping the values
print('printing the given list after swapping the values = ')
print(given_list)

Output:

printing the given list before swapping the values = 
[33, 92, 12, 74, 22, 79, 122, 17, 63, 99, 129]
printing the given list after swapping the values = 
[129, 92, 12, 74, 22, 79, 122, 17, 63, 99, 33]

Related Programs:

Python Program to Swap the First and Last Value of a List Read More »

Program to Count Pair in an Array or List whose Product is Divisible by K

Python Program to Count Pair in an Array or List whose Product is Divisible by K

Given a list, the task is to count the number of pairs in the given list whose product is divisible by k in Python.

Examples:

Example1:

Input:

Given list = [1, 15, 19, 2, 9, 6, 10, 12]
Given k=3

Output:

The total number of pairs are =  9

Example2:

Input:

Given list = 1 9 21 7 34 29 91 3 8 5
Given k=5

Output:

The total number of pairs are = 11

Python Program to Count Pair in an Array or List whose Product is Divisible by K

Below are the ways to count the number of pairs in the given list whose product is divisible by k in Python.

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Method #1: Using Nested For Loops (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the value of k as static input and store it in another variable.
  • We will tackle this problem using two nested loops.
  • Take a variable count which stores the count and initialize its value to 0.
  • Calculate the length of the given list using the len() function.
  • Iterate from 0 to the number of elements of the given list using For loop.
  • Loop from m+1 to the number of elements of the given list using another For loop(Inner For loop) where m is the iterator value of the parent For loop.
  • Check If (givenlist[m]*givenlist[m] %k == 0) using If conditional Statement where m is the iterator value of the parent For loop and n is the inner loop iterator value.
  • If it is true then increment the count by 1.
  • Print the count.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
givenlst = [1, 15, 19, 2, 9, 6, 10, 12]
# Give the value of k as static input and store it in another variable.
k = 3
# Take a variable count which stores the count and initialize its value to 0.
paircont = 0
# Calculate the length of the given list using the len() function.
listleng = len(givenlst)
# We will use two nested loops.
# Iterate from 0 to the number of elements of the given list using For loop.
for m in range(0, listleng):
    # Loop from m+1 to the number of elements of the given list
    # using another For loop(Inner For loop)
    # where m is the iterator value of the parent For loop.
    for n in range(m+1, listleng):
        # Check If (givenlist[m]*givenlist[m] %k == 0) using If conditional Statement
        # where m is the iterator value of the parent For loop
        # and n is the inner loop iterator value.
        if((givenlst[m]+givenlst[n]) % k == 0):
            # If it is true then increment the count by 1.
            paircont = paircont+1
# Print the count.
print('The total number of pairs are = ', paircont)

Output:

The total number of pairs are =  9

Method #2: Using Nested For Loops (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the value of k as user input using int(input()) and store it in another variable.
  • We will tackle this problem using two nested loops.
  • Take a variable count which stores the count and initialize its value to 0.
  • Calculate the length of the given list using the len() function.
  • Iterate from 0 to the number of elements of the given list using For loop.
  • Loop from m+1 to the number of elements of the given list using another For loop(Inner For loop) where m is the iterator value of the parent For loop.
  • Check If (givenlist[m]*givenlist[m] %k == 0) using If conditional Statement where m is the iterator value of the parent For loop and n is the inner loop iterator value.
  • If it is true then increment the count by 1.
  • Print the count.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
givenlst = list(
    map(int, input('Enter some random List Elements separated by spaces = ').split()))
# Give the value of k as user input using int(input()) and store it in another variable.
k = int(input('Enter some random value of k = '))
# Take a variable count which stores the count and initialize its value to 0.
paircont = 0
# Calculate the length of the given list using the len() function.
listleng = len(givenlst)
# We will use two nested loops.
# Iterate from 0 to the number of elements of the given list using For loop.
for m in range(0, listleng):
    # Loop from m+1 to the number of elements of the given list
    # using another For loop(Inner For loop)
    # where m is the iterator value of the parent For loop.
    for n in range(m+1, listleng):
        # Check If (givenlist[m]*givenlist[m] %k == 0) using If conditional Statement
        # where m is the iterator value of the parent For loop
        # and n is the inner loop iterator value.
        if((givenlst[m]+givenlst[n]) % k == 0):
            # If it is true then increment the count by 1.
            paircont = paircont+1
# Print the count.
print('The total number of pairs are = ', paircont)

Output:

Enter some random List Elements separated by spaces = 1 9 21 7 34 29 91 3 8 5
Enter some random value of k = 5
The total number of pairs are = 11

Related Programs:

Python Program to Count Pair in an Array or List whose Product is Divisible by K Read More »

Python Program to Find a Fixed Point in a given Array or List

Python Program to Find a Fixed Point in a given Array or List

An array is a type of variable that can hold several values at once.

One element in a fixed point array is given as if its value is the same as its index. If a value is present, the code will return it; otherwise, it will return -1. We have an array of x unique numbers sorted in ascending order in this. In the following code, we create a function that returns a fixed point integer and returns -1 if there is no fixed point integer. The fixed point index is defined as an index I such that array[i] equals i.

Given a list, the task is to find a fixed point in the given list in Python if the fixed point is present in the given list then print -1.

Examples:

Example1:

Input:

Given List = [19, 24, 25, 3, 81, 144, 600, 900, 225, 4, 9, 1, 16, 49, 23, 49, 25, 10, 25]

Output:

The Fixed point present in the given list is [ 3 ]

Example2:

Input:

Given list = [7 , 8, 45, 19, 21, 23, 6 ,7, 5,]

Output:

The Fixed point present in the given list is [ 6 ]

Program to Find a Fixed Point in a given Array or List Python

Below are the ways to find a Fixed Point in the given list in Python.

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Create a function findFixed() which accepts the given list as an argument and returns -1 if the list does not contain a fixed point else print the fixed point.
  • Pass the given list as an argument to the findFixed() function.
  • Inside the findFixed() function calculate the length of the given list.
  • Loop till length of the given list using For loop.
  • Check if the element is equal to the index(iterator value of the For loop).
  • If it is true then return index.
  • Return -1 after the end of the For loop.
  • Print the Fixed-point Index
  • The Exit of the Program.

Below is the implementation:

# Create a function findFixed() which accepts the given list
# as an argument and returns -1
# if the list does not contain a fixed point else print the fixed point.


def findFixed(gvnlst):
    # Inside the findFixed() function calculate the length of the given list.
    lstleng = len(gvnlst)
    # Loop till length of the given list using For loop.
    for m in range(lstleng):
      # Check if the element is equal to the index(iterator value of the For loop).
        if gvnlst[m] is m:
            # If it is true then return index.
            return m
    # Return -1 after the end of the For loop.
    return -1


# Give the list as static input and store it in a variable.
gvnlst = [19, 24, 25, 3, 81, 144, 600, 900,
          225, 4, 9, 1, 16, 49, 23, 49, 25, 10, 25]
# Pass the given list as an argument to the findFixed() function.
fxdpoint = findFixed(gvnlst)
print('The Fixed point present in the given list is [', fxdpoint, ']')

Output:

The Fixed point present in the given list is [ 3 ]

Method #2: Using For Loop (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Create a function findFixed() which accepts the given list as an argument and returns -1 if the list does not contain a fixed point else print the fixed point.
  • Pass the given list as an argument to the findFixed() function.
  • Inside the findFixed() function calculate the length of the given list.
  • Loop till the length of the given list using For loop.
  • Check if the element is equal to the index(iterator value of the For loop).
  • If it is true then return index.
  • Return -1 after the end of the For loop.
  • Print the Fixed-point Index
  • The Exit of the Program.

Below is the implementation:

# Create a function findFixed() which accepts the given list
# as an argument and returns -1
# if the list does not contain a fixed point else print the fixed point.


def findFixed(gvnlst):
    # Inside the findFixed() function calculate the length of the given list.
    lstleng = len(gvnlst)
    # Loop till length of the given list using For loop.
    for m in range(lstleng):
      # Check if the element is equal to the index(iterator value of the For loop).
        if gvnlst[m] is m:
            # If it is true then return index.
            return m
    # Return -1 after the end of the For loop.
    return -1


# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvnlst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Pass the given list as an argument to the findFixed() function.
fxdpoint = findFixed(gvnlst)
print('The Fixed point present in the given list is [', fxdpoint, ']')

Output:

Enter some random List Elements separated by spaces = 7 8 45 19 21 23 6 7 5
The Fixed point present in the given list is [ 6 ]

Related Programs:

Python Program to Find a Fixed Point in a given Array or List Read More »