Roman Suzi
Dec 25, 2024

--

One more way is to calculate both required length and indexes with triangular number formula for the n, which can be found by solving quadratic equation and rounding up the found root. It might be slightly less optimal to calculate triangular number every time, but reveals the core of the mathematical model behind the code challenge. (sorry for broken indents)

import math

def triangular_number(n):

"""Calculate the n-th triangular number."""

return n * (n + 1) // 2

def pyramid(string):

length = len(string)

n = math.ceil((-1 + math.sqrt(1 + 8 * length)) / 2)

required_length = triangular_number(n)

string = string.ljust(required_length, '*')

for row in range(n):

start_index = triangular_number(row)

print(string[start_index:start_index + row + 1])

--

--

No responses yet