Home > Enterprise >  Draw a centered triforce surrounded by hyphens using Python
Draw a centered triforce surrounded by hyphens using Python

Time:09-02

I want to draw a triangle of asterisks from a given n which is an odd number and at least equal to 3. So far I did the following:

def main():
    num = 5

    for i in range(num):
        if i == 0:
            print('-' * num   '*' * (i   1)   '-' * num)
        elif i % 2 == 0:
            print('-' * (num-i 1)   '*' * (i   1)   '-' * (num-i 1))
        else:
            continue


if __name__ == "__main__":
    main()

And got this as the result:

-----*-----
----***----
--*****--

But how do I edit the code so the number of hyphens corresponds to the desirable result:

-----*-----
----***----
---*****---
--*-----*--
-***---***-
*****-*****

CodePudding user response:

There's probably a better way but this seems to work:

def triangle(n):
    assert n % 2 != 0  # make sure n is an odd number
    hyphens = n
    output = []
    for stars in range(1, n 1, 2):
        h = '-'*hyphens
        s = '*'*stars
        output.append(h   s   h)
        hyphens -= 1
    pad = n // 2
    mid = n
    for stars in range(1, n 1, 2):
        fix = '-'*pad
        mh = '-'*mid
        s = '*'*stars
        output.append(fix   s   mh   s   fix)
        pad -= 1
        mid -= 2
    print(*output, sep='\n')

triangle(5)

Output:

-----*-----
----***----
---*****---
--*-----*--
-***---***-
*****-*****

CodePudding user response:

Think about what it is you're iterating over and what you're doing with your loop. Currently you're iterating up to the maximum number of hyphens you want, and you seem to be treating this as the number of asterisks to print, but if you look at the edge of your triforce, the number of hyphens is decreasing by 1 each line, from 5 to 0. To me, this would imply you need to print num-i hyphens each iteration, iterating over line number rather than the max number of hyphens/asterisks (these are close in value, but the distinction is important).

I'd recommend trying to make one large solid triangle first, i.e.

-----*-----
----***----
---*****---
--*******--
-*********-
***********

since this is a simpler problem to solve and is just one modification away from what you're trying to do (this is where the distinction between number of asterisks and line number will be important, as your pattern changes dependent on what line you're on).

I'll help get you started; for any odd n, the number of lines you need to print is going to be (n 1). If you modify your range to be over this value, you should be able to figure out how many hyphens and asterisks to print on each line to make a large triangle, and then you can just modify it to cut out the centre.

  • Related