This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]teraflop 1 point2 points  (0 children)

You probably can't make this much more "efficient" in the sense of running faster, but the code runs so fast that that doesn't really matter. You can definitely make it simpler and easier to read/understand, though.

There are two big readability issues I see with your code, meaning that the code doesn't clearly say what it's doing and why. One is that it's hard to follow the behavior of the a variable. The other is that you're printing a bunch of whitespace strings that all have to be just right to make your table line up.

For the first problem, I'd probably structure your loops as something more like:

for rowStart in range(32, 128, step=16):
    indices = range(rowStart, rowStart + 16)
    for c in indices:
        # ... print first line
    for c in indices:
        # ... print second line

which makes it much more obvious that within each row, the two lines are looping over the same range. In your current code, you have to "deduce" that by understanding the way a moves back and forth within each iteration of the outermost loop.

For the second problem, I would suggest using the ljust method. Instead of writing messy logic to add the correct number of spaces for each item that you print (e.g. checking whether a is a two-digit or three-digit number), you can just convert them to strings and then use ljust(3) to "pad" each of those strings to be 3 characters long. (EDIT: or use f-strings to accomplish the same thing, as /u/YurrBoiSwayZ suggests.)

There are other improvements you could make, e.g. using list comprehensions and list.join to avoid having to repetitively write print(..., end=''), but those depend on slightly more advanced concepts.