warrior4223 warrior4223 - 1 month ago 7
Python Question

Create string from list of lists then return it with #'s bordering the edges of the string

I'm having trouble writing this function which has to convert a list of lists to a string then surround it with borders. It also has to replace the # on the far right line that has string 'A" with '.' . This is the input and expected output

Input: [['.', '.', '.', 'e'],
['A', 'A', '.', 'e'],
['.', '.', '.', 'e'],
['.', 'X', 'X', 'X'],
['.', '.', '.', '.'],
['.', 'y', 'Z', 'Z']]

Output: ######
#...e#
#AA.e.
#...e#
#.XXX#
#....#
#.yZZ#
######


As you can see the line with the A's has a period at the end instead of '#' as this is one of the conditions of the function. Somehow it has to recognize which list has 1 or multiple A's and then replace the # on the end with a period. This is the code I have so far thanks for any help

def border_around(lst):
new_value = ''.join(str(r) for v in lst for r in v)
maxlen = max(len(s) for s in new_value)
colwidth = maxlen + 2
return '#' + '.'*colwidth

Answer
def border_around(lst):
    ncols = max(len(row) for row in lst)+2
    first = '#' * ncols + '\n'
    last = '\n' + '#' * ncols
    return first + '\n'.join('#'+''.join(row)+'#' for row in lst) + last