Python Forum
How would you (as an python expert) make this code more efficient/simple
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How would you (as an python expert) make this code more efficient/simple
#4
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:
+ - - + - - - - + - - - + - + | | | | | | | | | | | | | | | + - - + - - - - + - - - + - + | | | | | | | | | | + - - + - - - - + - - - + - + | | | | | | | | | | | | | | | | | | | | + - - + - - - - + - - - + - +
Reply


Messages In This Thread
RE: How would you (as an python expert) make this code more efficient/simple - by Gribouillis - Feb-21-2022, 10:52 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Simple code not working properly tmv 2 476 Feb-28-2025, 09:27 PM
Last Post: deanhystad
  Implementing Efficient Event-Driven Programming in Python JasonGrant 1 530 Jan-31-2025, 04:06 PM
Last Post: deanhystad
  How can I make this code more efficient and process faster? steven_ximen 0 358 Dec-17-2024, 04:27 PM
Last Post: steven_ximen
  [pyparsing] How to make my simple parser fault tolerant medihack 0 832 May-14-2024, 04:52 PM
Last Post: medihack
  Help with simple code JacobSkinner 1 1,296 Mar-18-2024, 08:08 PM
Last Post: deanhystad
  hi need help to make this code work correctly atulkul1985 5 1,868 Nov-20-2023, 04:38 PM
Last Post: deanhystad
  I have a code which is very simple but still I cannot detect what's wrong with it max22 1 1,227 Nov-07-2023, 04:32 PM
Last Post: snippsat
  newbie question - can't make code work tronic72 2 1,487 Oct-22-2023, 09:08 PM
Last Post: tronic72
  A more efficient code titanif 2 1,143 Oct-17-2023, 02:07 PM
Last Post: deanhystad
  Cleaning my code to make it more efficient BSDevo 13 3,552 Sep-27-2023, 10:39 PM
Last Post: BSDevo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020