1. Write
a program to check if all the elements of a tuple are in descending order or
not
# function to check if tuple is sorted in descending order
for i in range(1, len(t)):
# return False if the element is greater than the previous element
# check if tuple is sorted
num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Output 1
Enter a number: 663
663 is not an Armstrong number
Output 2
Enter a number: 407
407 is an Armstrong number
Here, we ask the user for a number and check if it is an Armstrong number.
We need to calculate the sum of the cube of each digit. So, we initialize the sum to 0 and obtain each digit number by using the modulus operator %. The remainder of a number when it is divided by 10 is the last digit of that number. We take the cubes using exponent operator.
Finally, we compare the sum with the original number and conclude that it is Armstrong number if they are equal.
Source Code: Check Armstrong number of n digits
num = 1634
order = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
You can change the value of num in the source code and run again to test it.
Did you find this article helpful?
No comments:
Post a Comment