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?
CodePudding user response:
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 = ('* ' * (i//2 i%2)) '\n'
return result
CodePudding user response:
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.
CodePudding user response:
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)))))