Python Forum
How would you (as an python expert) make this code more efficient/simple - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How would you (as an python expert) make this code more efficient/simple (/thread-36444.html)



How would you (as an python expert) make this code more efficient/simple - coder_sw99 - Feb-20-2022

Hi,

my question is quite simple: How would you make this piece of code more simple/efficient?

def draw_pattern_1(p,m):
    print(p, end=' ')
    print(m, end=' ') 
    print(m, end=' ')
    print(m, end=' ')
    print(m, end=' ')
    print(p, end=' ')
    print(m, end=' ')
    print(m, end=' ')
    print(m, end=' ')
    print(m, end=' ')
    print(p)


def draw_pattern_2(l):
    print(l, end='         ')
    print(l, end='         ')
    print(l)
    

    
def draw_grid(f_1,f_2,p,m,l):
    draw_pattern_1(p,m)
    draw_pattern_2(l)
    draw_pattern_2(l)
    draw_pattern_2(l)
    draw_pattern_2(l)
    draw_pattern_1(p,m)
    draw_pattern_2(l)
    draw_pattern_2(l)
    draw_pattern_2(l)
    draw_pattern_2(l)
    draw_pattern_1(p,m)

p=  "+"
m = "-"
l = "|"

draw_grid(draw_pattern_1,draw_pattern_2,p,m,l)
Output:
+ - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - +



RE: How would you (as an python expert) make this code more efficient/simple - Gribouillis - Feb-20-2022

coder_sw99 Wrote:How would you make this piece of code more simple/efficient?
print("""\
+ - - - - + - - - - +
|         |         |
|         |         |
|         |         |
|         |         |
+ - - - - + - - - - +
|         |         |
|         |         |
|         |         |
|         |         |
+ - - - - + - - - - +""")



RE: How would you (as an python expert) make this code more efficient/simple - menator01 - Feb-21-2022

from tabulate import tabulate
data = ([' ', ' '*2])
print(tabulate(data, tablefmt='grid'))
Output:
+--+--+ | | | +--+--+ | | | +--+--+



RE: How would you (as an python expert) make this code more efficient/simple - Gribouillis - Feb-21-2022

A more flexible version with itertools
import itertools as itt

def sandwich(chain, sep):
    yield from sep
    for c in chain:
        yield from c
        yield from sep

def tablerows(r, c):        
    top = ''.join(sandwich((sandwich('-' * n, ' ') for n in c), '+'))
    mid = ''.join(sandwich((' ' * (2 * n + 1) for n in c), '|'))
    return sandwich((itt.repeat(mid, k) for k in r), (top,))

a = (3, 2, 4)
b = (2, 4, 3, 1)

for r in tablerows(a, b):
    print(r)
Output:
+ - - + - - - - + - - - + - + | | | | | | | | | | | | | | | + - - + - - - - + - - - + - + | | | | | | | | | | + - - + - - - - + - - - + - + | | | | | | | | | | | | | | | | | | | | + - - + - - - - + - - - + - +