python

Python: Create table from string mixed with separators using FOR loops


I need to create a table with given width and height from 6 character string mixed with 2 separators without using import, def, if, else, while, iter, [ or ] etc., only with basic Python functions and FOR loops. Separator can't be at the beginning and at the end of the string.

For example, 3x5 table, string is Python, separators are + and -. The result is:

P+y-t+h-o
n+P-y+t-h
o+n-P+y-t

I have done it like this

# width = int(input("?"))
# height = int(input("?"))
# word = input("?")
# separators = input("?")
width = 13
height = 6
word = "matfyz"
separators = "()"
separator1, separator2 = separators
lenght = width * height
count = (lenght) // len(word) + 1
string = ""

for _ in range(count):
    for letter in word:
        string +=letter

for row in range(0, height):
    temp_separator=''
    for col in range(1, width+1):
        i=1
        print (temp_separator, end = '')
        for letter in string:
            need_this_letter = 1 - ((i != col+(width*row)) * 1)  #TODO: remove logic expression
            print (letter * need_this_letter, end='')
            i += 1
        temp_separator=separator1
        separator1, separator2 = separator2, separator1     
    print('')
    separator1, separator2 = separators

but there is a logic expression in this code (note: #TODO) that I still need to remove in order to comply with the set assignment only to use basic Python functions. Thank you all for any help !


Solution

  • Since the size of the word is always 6 letters and the separators are always 2 letters:

    width = 5
    height = 3
    word = "Python"
    sep1, sep2 = "+-"
    l1,l2,l3,l4,l5,l6 = word
    temp = ""
    
    for _ in range(height):
        print(l1, end='')
        l1,l2,l3,l4,l5,l6 = l2,l3,l4,l5,l6,l1
        for _ in range(width-1):
            print(sep1 + l1, end='')
            sep1,sep2 = sep2,sep1
            l1,l2,l3,l4,l5,l6 = l2,l3,l4,l5,l6,l1
        print()
    

    Output:

    P+y-t+h-o
    n+P-y+t-h
    o+n-P+y-t
    

    If your terminal supports the back space char:

    for _ in range(height):
        for _ in range(width):
            print(l1 + sep1, end='')
            sep1,sep2 = sep2,sep1
            l1,l2,l3,l4,l5,l6 = l2,l3,l4,l5,l6,l1
        sep1,sep2 = sep2,sep1
        print('\b ')