Write recursive functions (you are not allowed using for or while loops) to solve the following problems:
-Write a function that prints hello for 500 times
-x in power y ( )
-Geometric progression with common ratio r. For example, the sequence 2, 6, 18, 54, ... is a geometric progression with common ratio 3
def hello500():
"""Print "Hello" for 500 times
"""
def hello(n):
if n == 0:
return
print("Hello")
hello(n-1)
hello(500)
def power(x, y):
"""Calculate x in power y
"""
if y < 0:
return power(x, -y)
if y == 0:
return 1
return power(x, y-1)*x
def geometric(a0, r, n):
"""Print n terms of geometric progression with first term a0
and common ratio r
"""
if n == 1:
print(a0)
else:
print (a0, end=', ')
geometric(a0*r, r, n-1)
def main():
hello500()
print(power(2,10))
geometric(2, 3, 4)
main()
Comments
Leave a comment