Advertisement

Perimeter of squares in a rectangle from Codewars

Perimeter of squares in a rectangle from Codewars Perimeter of squares in a rectangle from Codewars


The drawing shows 6 squares the sides of which have a length of 1, 1, 2, 3, 5, 8. It's easy to see that the sum of the perimeters of these squares is : 4 * (1 + 1 + 2 + 3 + 5 + 8) = 4 * 20 = 80

Could you give the sum of the perimeters of all the squares in a rectangle when there are n + 1 squares disposed in the same manner as in the drawing:

#Hint: See Fibonacci sequence #Ref:

The function perimeter has for parameter n where n + 1 is the number of squares (they are numbered from 0 to n) and returns the total perimeter of all the squares.

perimeter(5) should return 80
perimeter(7) should return 216

Source Code:

First Attempt:

def recur_fibo(n):
if n lessthan= 1:
return 1
else:
return recur_fibo(n - 1) + recur_fibo(n - 2)

def perimeter(n):
return sum([recur_fibo(i) for i in range(n + 1)]) * 4

Second Attempt:

def perimeter(n):
n1, n2 = 1, 1
count = 0
sum = 0
while count lessthan n+1:
sum += n1
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
return sum*4

Codewars

Post a Comment

0 Comments