Siyah Siyah - 22 days ago 5
Python Question

How to get to spit out a method multiple times in Python?

This would be a very easy fix for the professionals, I guess, but I want to know why I am doing it wrong and what I am missing right now.

What do I want to do? I want to have a palindrome in the shape of a pyramid. I can get the bottom layer of the pyramid with my code, but I don't know how to shape a for loop that will spit out x amount of lines with a palindrome in the shape of a pyramid...

Example:

a
aba
abcba
abcdcba
abcdedcba


and so on...

My code:

end_letter = 0 # is this correct?

def test_palindrome(end_letter):
print call_palindrome(end_letter) + call_palindrome_second_part(end_letter)

def call_palindrome(end_letter):

letters_from_a_to_y = ""

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

return(letters_a_to_y)

def call_palindrome_second_part(end_letter):

letters_y_to_a = ""

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

return(letters_y_to_a)

test_palindrome(end_letter)


How can I get this code working? What am I doing wrong and what am I missing?

I'd appreciate if someone can help me and explain me what I should do and why.

Answer

The following is the corrected program:

def palindromeGen(end_letter):
    print(call_palindrome(end_letter) + call_palindrome_second_part(end_letter))

def call_palindrome(end_letter):

    letters_a_to_y = ""           

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

    return(letters_a_to_y)

def call_palindrome_second_part(end_letter): 

    letters_y_to_a = ""

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

    return(letters_y_to_a)

def test_palindrome(ch):
    for i in range(ord('a'), ord(ch)+1):
        palindromeGen(i)

test_palindrome('e')

Explanation:

  • Bug in call_palindrome(): letters_from_a_to_y --> letters_a_to_y
  • end_letter is an argument, you supplied it as a variable either you give it the value (like ord('e')) or assign the same.
  • Once you are able to produce one line, you could iterate it over multiple lines. I've converted your test_palindrome() to palindromeGen() and coded a new one for this process.