As others have said the your function
palindrome
does not explain what is does by its name nor by the non existing comments, this can partly be overcome by splitting the function in multiple functions with more descriptive names.Instead of the
append
andinsert
methods of lists it might be clearer to use list concatenations with the + operator.Sometimes a loop for creating lists can be more clearer with a list comprehension.
Keeping those in mind, my rewrite of your code:
# a palindrome in this context is a list of lists of chars which is
# highly symetrical, for instance :
# [['b', 'b', 'b'], ['b', 'a', 'b'], ['b', 'b', 'b']]
def expand_palindrome(palindrome, ch):
n = len(palindrome)
top_and_bottom = [[ch] * (n + 2)]
middle_part = [[ch] + lrow + [ch] for lrow in palindrome]
return top_and_bottom + middle_part + top_and_bottom
def create_number_palindrome(n):
assert(n < 10)
assert(n > 0)
palindrome = [['0']]
for i in range(n):
palindrome = expand_palindrome(palindrome, str(i+1))
return palindrome
def palindrome_string(palindrome):
return '\n'.join(''.join(lrow) for lrow in palindrome)
print(palindrome_string(create_number_palindrome(1)))
print(palindrome_string(create_number_palindrome(7)))