Siyah - 1 year ago 63
Python Question

# How to make this for loop in Python work?

I am stuck and I need your help. I want to spit out a list of palindromes until a certain letter I give....

``````def pyramid_palindrome(last_letter):
for letter in range(97,last_letter):
last_letter = last_letter - (last_letter-1)
print call_first_part_palindrome(last_letter)
print call_second_part_palindrome(last_letter)
``````

What I'd want is, to do this:

``````a
aba
abcba
abcdcba
abcdedcba
abcdefedbca
abcdefgfedcba
abcdefghgfedcba
....
``````

I am thinking like this:

"I will give the last letter as an input, and it will keep iterating the
palindrome until the last letter is being checked."

The problem is that I can't manage to spit out the palindromes one by one, ascending it just like a pyramid. Can someone point me in the right direction?

Am I right when I say I need to use a
`for loop`
in the first
function?

This is my full code:

``````def pyramid_palindrome(last_letter):
for letter in range(97,last_letter):
last_letter = last_letter - (last_letter-1)
print call_first_part_palindrome(last_letter)
print call_second_part_palindrome(last_letter)

def call_first_part_palindrome(last_letter):

letters_a_to_y = ""

for letter in range(97,last_letter):
letters_a_to_y += chr(letter)

return(letters_a_to_y)

def call_second_part_palindrome(last_letter):

letters_y_to_a = ""

for letter in range(last_letter,96,-1):
letters_y_to_a += chr(letter)

return(letters_y_to_a)

pyramid_palindrome(112)
``````

I think I am close, but can't make the finishing touch.

Your problem was when calling your two palindrome functions and on how you were changing the value for `last_letter`-

I tried to modify your code as little as possible:

``````def pyramid_palindrome(last_letter):
for letter in range(97,last_letter):
print(call_first_part_palindrome(letter) + call_second_part_palindrome(letter-2))
``````

And this remains the same:

``````def call_first_part_palindrome(last_letter):

letters_a_to_y = ""

for letter in range(97,last_letter):
letters_a_to_y += chr(letter)

return(letters_a_to_y)

def call_second_part_palindrome(last_letter):

letters_y_to_a = ""

for letter in range(last_letter,96,-1):
letters_y_to_a += chr(letter)

return(letters_y_to_a)

pyramid_palindrome(112)
``````

Which outputs:

``````a
aba
abcba
abcdcba
abcdedcba
abcdefedcba
abcdefgfedcba
abcdefghgfedcba
abcdefghihgfedcba
abcdefghijihgfedcba
abcdefghijkjihgfedcba
abcdefghijklkjihgfedcba
abcdefghijklmlkjihgfedcba
abcdefghijklmnmlkjihgfedcba
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download