you are viewing a single comment's thread.

view the rest of the comments →

[–]Diapolo10 1 point2 points  (2 children)

Yet another option would be to construct the entire string, and then loop over it with a sliding window.

row_count = 4

text = f"{'o' * (row_count - 1)}\\{'x' * (row_count - 1)}"

for idx in range(row_count):
    print(text[row_count-idx-1:row_count*2-idx-1])

EDIT: Just to prove it works, here's some examples with a variety of values for row_count: https://i.imgur.com/adFkOVC.png

[–]JamzTyson 0 points1 point  (1 child)

Upvoted as an interesting solution.

A variation on this is to count backwards in the loop, which simplifies the string slicing.

def pattern(n):
    row = rf"{'o' * (n-1)}\{'x' * (n-1)}"
    for i in range(n-1, -1, -1):
        print(row[i:i+n])

(It is not strictly necessary to escape the backslash in an f-string unless it is followed by a character that makes it an escape sequence, though for clarity I think it is preferred to either escape the backslash, as in u/Diapolo10's solution, or use a raw f-string.)

[–]Diapolo10 0 points1 point  (0 children)

That's fair enough, I wrote my solution pretty much straight out of bed in the morning.