Create a recursive method called triangle that takes one parameter n and then re
ID: 3828605 • Letter: C
Question
Create a recursive method called triangle that takes one parameter n and then returns a string that when printed will print a triangle on the console as shown below.
When it passes, upload you file to this page. Note that triangle(n) will have one asterisk on on first line and n asterisks on the last line. It will put a ' ' characters between every line in the string as shown in the triangle(3) example below
You cannot use loops in you code at all! Your method must meet the definition of a recursive method and call itself have a base case move toward the base case when it calls itself if you need to repeat spaces or a char remember that "*" * i will create a string with i asterisks in it and " " * i will create a string with i spaces
For example "+" * 3 will result in string "+++".
Examples: s = triangle(1)
print(s) outputs: *
s = triangle(2) print(s) outputs: * **
s = triangle(3) # return value is string '* ** ***' print(s) outputs: * ** ***
s = triangle(6) print(s) outputs: * ** *** **** ***** ****** etc.
Explanation / Answer
def triangle(n):
if n == 1:
return '*'
result = triangle(n-1)
result = result + " " + '*'*n
return result
def main_test():
tests = [0, '*', '* **', '* ** ***', '* ** *** ****', '* ** *** **** *****',
'* ** *** **** ***** ******', '* ** *** **** ***** ****** *******',
'* ** *** **** ***** ****** ******* ********',
'* ** *** **** ***** ****** ******* ******** *********',
'* ** *** **** ***** ****** ******* ******** ********* **********']
errors = 0
for n in range(1,len(tests)):
student = triangle(n)
if student[0] == ' ':
student = student[1:] # trim off starting
correct = tests[n]
if student != correct:
print("test n = ", n)
print("-"*20)
print("FAILED triangle({n})")
print("Your triangle is:", repr(student))
print(student)
print()
print("Test was expecting:", repr(correct))
print(correct)
errors += 1
if errors == 0:
print("All Passed")
else:
print("-"*20)
print(" FAILED {errors} TESTS")
if __name__ == '__main__':
main_test()
# code link: https://paste.ee/p/Ee7z2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.