Learning_something_new
Learning_something_new

Reputation: 107

palindrome range in python

I am 15 days old to Python Learning and need your guidance for each and every step on the below code. This code checks for largest palindrome made from the product of two 3-digit numbers.

very sorry for the dumbest question.

largest_palindrome = 0
for x in range(999,100,-1):
    for y in range(x,100,-1):
        product = x*y
        check = str(x*y)
        if check ==  check[::-1]:
            if product > largest_palindrome:
                largest_palindrome = product
print(largest_palindrome) ```

 - Need clarification on the below:

for x in range(999,100,-1): #why is -1 introduced here. what is the range it is checking in (999,100,-1)
for y in range(x,100,-1): # why is x introduced in y loop. how much times it will check the range.
product = x*y
check = str(x*y)# why is string introduced here ?

if check ==  check[::-1]: # what does this line mean?
if product > largest_palindrome:
largest_palindrome = product

print(largest_palindrome)

Upvotes: 0

Views: 185

Answers (1)

Gopal Gautam
Gopal Gautam

Reputation: 369

for x in range(999,100,-1): #why is -1 introduced here. what is the range it is checking in (999,100,-1)

Answer: x is iterating from 999 to 100, decreasing by 1 on each loop

for y in range(x,100,-1): # why is x introduced in y loop. how much times it will check the range.

Answer: y is iterating from x (from upper loop) until 100. This loop will be running for each value of x from upper loop

check = str(x*y)# why is string introduced here ?

Answer: converting the product from int to str so that we can reverse the number. Below is possible for string not for int, so it is converted to string

if check == check[::-1]: # what does this line mean?

Answer: check[::-1] is the reverse string of chech. We check here if reversed string and non-reversed string are same (pallindrome if same)

Upvotes: 1

Related Questions