Python Forum

Full Version: How would you (as an python expert) make this code more efficient/simple
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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:
+ - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - +
coder_sw99 Wrote:How would you make this piece of code more simple/efficient?
print("""\
+ - - - - + - - - - +
|         |         |
|         |         |
|         |         |
|         |         |
+ - - - - + - - - - +
|         |         |
|         |         |
|         |         |
|         |         |
+ - - - - + - - - - +""")
from tabulate import tabulate
data = ([' ', ' '*2])
print(tabulate(data, tablefmt='grid'))
Output:
+--+--+ | | | +--+--+ | | | +--+--+
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:
+ - - + - - - - + - - - + - + | | | | | | | | | | | | | | | + - - + - - - - + - - - + - + | | | | | | | | | | + - - + - - - - + - - - + - + | | | | | | | | | | | | | | | | | | | | + - - + - - - - + - - - + - +