How to Loop to Assign Digits of a Palindrome Check Without Using Arrays?

0
24
Asked By CuriousCoder97 On

I'm working on a project to check if a three-digit number is a palindrome (it reads the same backward as forward). I've written some code, but I'm stuck on how to effectively assign the three digits of the number to separate variables without using arrays. Here's the code I've come up with so far:

```python
Number = int(input('enter 3 digit'))
for a in range(3, 1, -1):
p = number % 10**a
p = num1, num2, num3 ... (line 4)

if:
num3*10**3 + num2*10**2 + num1*10 == number

Print('palindrome')
else:
Print('not a palindrome')
```

Could anyone suggest how I can store the digits individually in variables while avoiding arrays? Just to note, num1 is the hundreds place digit, and num3 is the units digit.

2 Answers

Answered By HelpfulHarry123 On

It's crucial to keep your code formatted correctly, especially in Python where indentation matters a lot. Make sure to use code blocks when sharing your code!

As for the digits, if you need to pull out each digit without an array, consider using division and modulus. For a three-digit number, you can get the digits like this:

```python
num1 = number // 100 # Hundreds place
num2 = (number // 10) % 10 # Tens place
num3 = number % 10 # Units place
```

From here, you can easily check if it’s a palindrome by comparing `number` to `num3 * 100 + num2 * 10 + num1`. Good luck!

CuriousCoder97 -

Thanks for the tip! I'll give that a try and see if I can get it to work.

Answered By CodeWizard88 On

Honestly, if you're still learning, it might be worth considering lists later on as they make it easy to store multiple values. However, if you're stuck on your current method, I think you can shift your algorithm a bit. You can do gradual construction of the reversed number by running through each digit, multiplying it to its correct place and adding it to a 'reversed' variable. Just remember that clarity in your code helps a lot in the long run!

CuriousCoder97 -

I get that, I'll keep lists in mind for future projects! Thanks for your insight!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.