I am wondering where it has gone wrong. Suppose I want to obtain:
print(triangle(5))
*
*
* *
* *
* * *
My code:
def triangle(n):
result = ""
for i in range(n):
if (i+1) % 2 == 1:
result = result + "*\n"
if (i+1) % 2 == 0:
result = " " + result
return result
and it gives me only
*
*
( Answer is below, but I'm wondering what went wrong with my own code)
def triangle(n):
if n == 0:
return ''
elif n % 2 != 0:
return triangle(n-1) + ((n-1)//2)*'* ' + '*\n'
else:
return triangle(n-1) + (n//2)*' *' + '\n'