Home > database >  Print a pyramid of a specific type
Print a pyramid of a specific type

Time:10-10

For uni we have to print a pyramid of a specific type.

Here is the code:

h = 10
def build_string_pyramid():
    s = ''

    for i in range(1, h   1):
        print('1', end='')
        for j in range(2, i   1):
            print('*', end='')
            print(j, end='')
        print('\r')

    for o in range(h - 1, 0, -1):
        print('1', end='')
        for p in range(2, o   1):
            print('*', end='')
            print(p, end='')
        print('\r')

    return s
print(build_string_pyramid())

The problem is, that we have to submit the resulting Pyramid in the string s. I don't know how to import the printed things to the string s.

CodePudding user response:

Replace every call of the form print(...) with s = .... Keep track of the line endings, so normal print appends a \n, and print(..., end='') is just a simple append. Also, do try to avoid globals:

def build_string_pyramid(h=10):
    s = ''

    for i in range(1, h   1):
        s  = '1'               # print('1', end='')
        for j in range(2, i   1):
            s  = f'*{j}'       # print('*', end=''), print(j, end='')
        s  = '\n'              # print('\r')

    for o in range(h - 1, 0, -1):
        s  = '1'               # print('1', end='')
        for p in range(2, o   1):
            s  = f'*{p}'       # print('*', end=''), print(p, end='')
        s  = '\n'              # print('\r')

    return s

print(build_string_pyramid())

Appending strings like that is not necessarily optimal, since they get reallocated every time. You may want to build up a list first, or even a list of lists per line, and then join them:

def build_string_pyramid(h=10):
    s = []

    for i in range(1, h   1):
        s.append('*'.join(str(j) for j in range(1, i   1)))

    for o in range(h - 1, 0, -1):
        s.append('*'.join(str(p) for p in range(1, o   1)))

    return '\n'.join(s)

print(build_string_pyramid())

Notice how str.join places the delimiters only between the items in a list or generator, so you will get a string with one fewer trailing newline.

As a totally different method, you can go back to your original printing technique, and actually build a string that way too. You can do this by using io.StringIO, which is a file-like object that writes to memory, and allows you to export a string directly:

from io import StringIO

def build_string_pyramid(h=10):
    s = StringIO()

    for i in range(1, h   1):
        print('1', end='', file=s)
        for j in range(2, i   1):
            print(f'*{j}', end='', file=s)
        print(file=s)

    for o in range(h - 1, 0, -1):
        print('1', end='', file=s)
        for p in range(2, o   1):
            print(f'*{p}', end='', file=s)
        print(file=s)

    return s.getvalue()

print(build_string_pyramid())
  • Related