DEV Community

Cover image for Practice Problems
Karthick (k)
Karthick (k)

Posted on

Practice Problems

In this blog, I have done basic conditional statement questions and answer I have practised some important Python number-based programs. These programs helped me understand while loops, functions, conditional statements, digit extraction, mathematical operations, and problem-solving logic.

#1) Palindrome

class Solution:
    def isPalindrome(self, n):
        if n < 0:
            return False

        original = n
        reverse = 0

        while n > 0:
            digit = n % 10
            reverse = (reverse * 10) + digit
            n //= 10

        return original == reverse


print(Solution().isPalindrome(121))
print(Solution().isPalindrome(-121))
print(Solution().isPalindrome(10))
Enter fullscreen mode Exit fullscreen mode
#2) Armstrong Number
import math

Is_Armstong = 370
count = 0
sum = 0
orginal_number = Is_Armstong
temp = Is_Armstong

while temp > 0:
    count += 1
    # Bug 1 fixed: Use / inside math.floor, OR just use // 
    temp = mathfloor(temp / 10)  

while Is_Armstong > 0:
    the_digits = Is_Armstong % 10

    # Bug 2 fixed: Use math.pow() to calculate powers!
    # math.pow returns a decimal (like 27.0), so we wrap it in math. floor to make it a whole number
    . sum = sum + math. floor(math.pow(the_digits, count))  

    Is_Armstong = math.floor(Is_Armstong / 10)

if sum == orginal_number:
    print('It is Armstrong number')
else:
    print('It is not Armstrong number')

Enter fullscreen mode Exit fullscreen mode
#3) Neon Number
import math

Neon_number=9;
sum=0;
temp=Neon_number*Neon_number;
print(temp);

orginal_number=Neon_number;


while temp>0:
    the_digits=temp%10;

    sum=sum+the_digits;

    temp=math.floor(temp//10);

if orginal_number==sum:
    print('It is Neon number');
else:
    print('It is not Neon Number')
Enter fullscreen mode Exit fullscreen mode
#4) Strong Number
import math

Strong_number=145;
orginal_strong=Strong_number;

sum=0;

while Strong_number>0:

    the_digits=Strong_number%10;

    i=1;
    stong_values=1;

    while(i<=the_digits):
        stong_values=stong_values*i;
        i+=1

    sum=sum+stong_values;

    Strong_number=math.floor(Strong_number//10);


if sum==orginal_strong:
    print("It is Strong number");
else:
    print("It is not Strong number");
Enter fullscreen mode Exit fullscreen mode
#5) Addition of first n numbers

numbers=15;
i=0;
fact=0;

while i<=numbers:
    fact=fact+i;
    i+=1;

print(f'sum of frist {numbers} is {fact}')

    #  n * (n + 1) / 2 --- important formula of the frist n sum of numbers.

Enter fullscreen mode Exit fullscreen mode

Top comments (0)