Having trouble concatenating strings from lists

Viewed 97

When I run the following code:

size = 5

alph = 'zyxwvutsrqponmlkjihgfedcba'
lis_t = [n for n in alph]
lis = lis_t[(26-size):]

for i in range(2*size):
    if i<size:
        print("".join([n+'-' for n in lis[:i]] + lis[i] + ['-'+n for n in lis[:i]]).center(size, '-'))
    if i > size:
        print("".join([n+'-' for n in lis[:(9-i)]] + lis[i] + ['-'+n for n in lis[9-i]]).center(size, '-'))

I get the error:

TypeError: can only concatenate list (not "str") to list

I don't know what's wrong with my print statements. It should do something like this:

--------e-------
------e-d-e------
----e-d-c-d-e----
--e-d-c-b-c-d-e--
e-d-c-b-a-b-c-d-e
--e-d-c-b-c-d-e--
----e-d-c-d-e----
------e-d-e------
--------e--------
2 Answers

Try this variation:

size = 5
alph = 'zyxwvutsrqponmlkjihgfedcba'

for n in list(range(size))+list(range(size-1))[::-1]:
    print('-'.join('-'*(size-n-1)+alph[-size:-size+n]+alph[-size+n:-size-1:-1]+'-'*(size-n-1)))

Output:

--------e--------
------e-d-e------
----e-d-c-d-e----
--e-d-c-b-c-d-e--
e-d-c-b-a-b-c-d-e
--e-d-c-b-c-d-e--
----e-d-c-d-e----
------e-d-e------
--------e--------


You can also:

size = 5
alph = 'zyxwvutsrqponmlkjihgfedcba'

for n in list(range(size))+list(range(size-1))[::-1]:
    a,b = alph[n-size:-size-1:-1], '-'*(size-n-1)
    print('-'.join(b+a[1:][::-1]+a+b))

You have two issues with this expression:

 [n + '-' for n in lis[:i]] + lis[i] + ['-'+ n for n in lis[:i]]

First, for size = 5, the length of lis is 5 elements. But, its index i is ranging from 0 to 9 (range(2*size)), so nearly half the values of i will cause an index error on lis.

Second, assuming i is in bounds, we're conatenating three objects:

[n + '-' for n in lis[:i]]  # a list
lis[i]  # a string
['-'+ n for n in lis[:i]]  # a list

To make this work we would need express it as all lists:

[n + '-' for n in lis[:i]] + lis[i:i+1] + ['-'+ n for n in lis[:i]]

I'll leave you to sort out the rest. For me, this seems a potentially recursive problem:

from string import ascii_lowercase as alphabet

def alphagram(size, row=1):
    if row:
        start = size - abs(row)

        letters = alphabet[size-1:start:-1] + alphabet[start:size]

        print('-'.join(letters).center(4*size-3, '-'))

        alphagram(size, row+1 if row != size else 1-row)

alphagram(6)

OUTPUT

> python3 test.py
----------f----------
--------f-e-f--------
------f-e-d-e-f------
----f-e-d-c-d-e-f----
--f-e-d-c-b-c-d-e-f--
f-e-d-c-b-a-b-c-d-e-f
--f-e-d-c-b-c-d-e-f--
----f-e-d-c-d-e-f----
------f-e-d-e-f------
--------f-e-f--------
----------f----------
> 

We can do a compact iterative solution in the manner of @AnnZen but translate it into Python ;-)

from itertools import chain
from string import ascii_lowercase as lower

size = 5

for n in chain(range(1, size+1), range(size-1, 0, -1)):
    print('-'.join(lower[size-1:size-n:-1] + lower[size-n:size]).center(4*size-3, '-'))
Related