I\'m supposed to write a program that ends up such as this:
* *
* *
* *
*
I have the code written for a regular one, but I\'m not s
Building on @kharazi's answer (because this reminds me of my early GWBasic programming which is what got me excited about programming as a kid):
def triangle(i, leftShape='*', rightShape='*', bottomShape='*', spaceShape=' ', t = 0):
if i <= 0:
print ((t+1)*spaceShape)+bottomShape+((t+1)*spaceShape)
else:
print (spaceShape*(t + 1))+leftShape+(spaceShape*(i*2-1))+rightShape+(spaceShape*(t + 1))
triangle(i-1, leftShape, rightShape, bottomShape, spaceShape, t+1)
if __name__== '__main__':
triangle(3)
triangle(3, '\\', '/')
triangle(3, '\\', '/', '~')
triangle(5, '╚╗', '╔╝', '╚╦╝')
triangle(5, '╚╗', '╔╝', '╚╦╝', '|')
triangle(-2)
Produces the following output:
triangle(3)
* *
* *
* *
*
triangle(3, '\\', '/')
\ /
\ /
\ /
*
triangle(3, '\\', '/', '~')
\ /
\ /
\ /
~
triangle(5, '╚╗', '╔╝', '╚╦╝')
╚╗ ╔╝
╚╗ ╔╝
╚╗ ╔╝
╚╗ ╔╝
╚╗ ╔╝
╚╦╝
triangle(5, '╚╗', '╔╝', '╚╦╝', '|')
|╚╗|||||||||╔╝|
||╚╗|||||||╔╝||
|||╚╗|||||╔╝|||
||||╚╗|||╔╝||||
|||||╚╗|╔╝|||||
||||||╚╦╝||||||
triangle(-2)
*
Let's label some areas in a line:
startSpaces * middleSpaces * endSpaces
For a given line you want startSpaces
+ 1 + middleSpaces
+ 1 + endSpaces
to equal a constant. This constant is 2*(i+t) + 1
line 1 will have t=0
spaces before the *
the final line will have t=i
spaces before the *
(here I'm using the original i
, I know it changes through recursion)
So can you find a pattern for startSpaces
, middleSpaces
and endSpaces
that will give you the proper pattern?
Keep in mind that you will need an additional else if
case for i==1
so that you can handle the row with only one *
This should be enough for you to get a lot closer to solving your problem. I'm assuming it's homework so I won't solve it for you, if you get stuck ask for more clues.
Try:
def triangle(i, t = 0):
if i == 0:
print (t+1) *' '+ '*'
else:
print ' ' * (t + 1)+ '*' + ' ' * (i * 2 - 1) + '*'
triangle(i - 1, t + 1)
triangle(5)
this code print:
* *
* *
* *
* *
* *
*
you should be using a for loop for this, recursion works but it is not the best idea to use it all the time. this is what i did:
def GioTri(i):
foo = i - 1
bar = 0
for i in range(i-1):
print ' ' * bar + "*" + " " * (foo*2 - 1) + "*" + " " * bar
foo = foo - 1
bar = bar + 1
print " " * bar + "*" + " " * bar
the result of this looks like this:
* *
* *
* *
*