Today I shifted my focus into Python logical programs to sharpen my problem-solving skills. π»β¨
Hereβs what I explored and practiced:
β Armstrong Number (Logic + Function)
An Armstrong number is a number that is equal to the sum of its digits each raised to the power of the number of digits.
Steps I learned:
- Find the count of digits.
- Split the number using
%
(modulus) and//
(floor division). - Raise each digit to the power of count.
- Add them together and check if it matches the original number.
def is_armstrong(num):
count = len(str(num))
temp = num
total = 0
while temp > 0:
digit = temp % 10
total += digit ** count
temp //= 10
return num == total
print(is_armstrong(153)) # True
print(is_armstrong(123)) # False
β Add First N Numbers
n = 10
total = 0
i = 1
while i <= n:
total += i
i += 1
print("Sum =", total) # Sum = 55
β Neon Number
A Neon number is a number where the sum of digits of its square is equal to the number itself.
num = 9
sq = num * num
total = 0
while sq > 0:
total += sq % 10
sq //= 10
print(total == num) # True (Neon number)
β Strong Number
A Strong number is one in which the sum of the factorial of its digits is equal to the number itself.
def factorial(n):
f = 1
while n > 0:
f *= n
n -= 1
return f
num = 145
temp = num
total = 0
while temp > 0:
digit = temp % 10
total += factorial(digit)
temp //= 10
print(total == num) # True
β What is a Function?
- A function is a block of reusable code.
- Helps in writing clean, structured programs.
- Saves time (no repeating same logic everywhere).
π I also learned how to wrap the Armstrong program inside a function for reusability.
π‘ Every day Iβm realizing that these logical exercises are improving my coding confidence, which will definitely help in Data Analytics for writing efficient scripts
Top comments (0)