Python Program to check whether a given number is an Armstrong Number or not using lambda and list
Program
num = int(input("Enter a number:\t"))
a = list(map(int,str(num)))
b = list(map(lambda x : x ** 3, a))
if sum(b) == num:
print(num, "is an armstrong number")
else:
print(num, "is not an arsmtrong number")
Python Program to Check Whether a Given Number is an Armstrong Number Using Lambda and List
What is an Armstrong Number
An Armstrong number is a number that is equal to the sum of its own digits, each raised to the power of the number of digits.
For a three-digit number, it follows this formula:
abc = a³ + b³ + c³
Examples
- 153 = 1³ + 5³ + 3³ = 153 (Armstrong Number)
- 9474 = 9⁴ + 4⁴ + 7⁴ + 4⁴ = 9474 (Armstrong Number)
- 123 = 1³ + 2³ + 3³ = 36 (Not an Armstrong Number)
-
Take user input
num = int(input("Enter a number:\t"))
- The user enters a number, which is stored in
num
.
-
Convert number to a list of digits
a = list(map(int, str(num)))
- The number is first converted to a string, then each digit is mapped to an integer, creating a list of digits.
-
Use lambda to compute cubes of digits
b = list(map(lambda x: x ** 3, a))
- The lambda function takes each digit and raises it to the power of three.
-
Check Armstrong condition
if sum(b) == num:
- If the sum of cubes is equal to the original number, it is an Armstrong number.
-
Print the result
- If the condition is met, the program prints that the number is an Armstrong number; otherwise, it prints that it is not.
Key Takeaways
- The program efficiently converts the number into a list of digits using
map
andstr()
. - The lambda function is used to compute the cubes of each digit in a compact way.
- The program checks if the sum of cubes matches the original number to determine if it is an Armstrong number.
Output 1
Enter a number: 89
89 is not an arsmtrong number
Output 2
Enter a number: 407
407 is an armstrong number