0

I would like to define a function that prints output of a triangle like this, when number of rows = 5.

*
 *
* *
 * *
* * *

currently, my code looks like this:

def triangle(n):
    result = ''
    
    for i in range(1, n+1):
        result += ('*' * i)+'\n'
    return result

however, it's not the way i want it to look. any ideas how I can improve this?

1
  • Try breaking it down into sub-tasks. Start with n=1..10 and note "what is the relationship between n and the number of stars" and "what is the relationship between n and if the line should start with a star or not". When you have that, you have actually answered your own question Commented Sep 27, 2021 at 14:04

3 Answers 3

1

To produce this exact output -

*
 *
* *
 * *
* * *

You can do it this way -

def triangle(n):
    result = ''
    
    for i in range(1, n+1):
        if i % 2 == 0:
            result += ' '
        result += ' '.join('*' * (i//2 + i%2))+'\n'
    return result
Sign up to request clarification or add additional context in comments.

2 Comments

this kinda works but i realised there's a space at the end of the asterisk for each row. is there a way to remove this space? for example if i print triangle(1), it should be 'asterisk\n' only. but now it's 'asterisk \n'
Yes, I updated the answer.
0

This will work for you.

def triangle(n):
result = ''

for i in range(1, n+1):
    line = ('*' * i)+'\n'
    result = result+line+' '+line
return result

The main idea here is you have a result for a corresponding line in line. You need the same line with space prepended to it with the previous result. thus the new code in the loop.

Comments

0

Here are some fun ways to solve this problem, learning a few python tricks in the process

one liner

Here is a one liner solution, it uses multiplication and slicing of the pattern to produce the output and joins the lines:

pat = ' *'
n = 5
print('\n'.join((pat*((i+1)//2))[-i:] for i in range(1, 1+n)))

output:

*
 *
* *
 * *
* * *

using an infinite iterator (and a classical loop):

from itertools import cycle
c = cycle('* ')
result = ''
l = ''
for i in range(5):
    l = next(c)+l
    result+=l+'\n'
print(result)

using itertools.cycle and itertools.accumulate

from itertools import cycle, accumulate
c = cycle('* ')
print('\n'.join(map(lambda x: x[::-1], accumulate(next(c) for i in range(5)))))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.