I am a beginner in Python-3. I was solving a level 2 challenge in Google Foobar. Given an initial amount of items (LAMBs) I have to distribute it among individuals, who are ranked according to seniority, while adhering to the following rules:
- The junior most individual gets 1 Lamb
- An immediately senior individual can't get more than twice their juniors lambs, otherwise the junior will rebel
- A senior individual can't get less lambs than the sum of their 2 previous juniors, otherwise the senior will rebel
- In case lambs are leftover and adding a senior does not violate any previous rules, they must be added.
The goal is to find the difference between how many individuals can be paid if we pay the minimum amount to each (stingy) and the maximum amount to each (generous). I noticed that stingy condition resembles a Fibonacci sequence and the generous condition is sum of powers of 2. My code is as follows:
from math import log2 def solution(total_lambs) return (stingy(total_lambs) - generous(total_lambs)) def stingy(total_lambs) if (total_lambs == 1): # from condition 1 at least 1 individual gets paid return 1 elif (total_lambs == 2): # from condition 2 and 4 the most each can is 1 return 2 else: ind, total, x0, x1 = 2, 2, 1, 1 # no. individuals, sum of Fib seq, intial Fib nos. while (total <= total_lambs): x0, x1 = x1, x0 + x1 # advancing the Fib seq total = total + x1 # total is the sum of lambs paid if (total > total_lambs): return ind else: ind = ind + 1 def generous(total_lambs): if (total_lambs == 1): return 1 if (total_lambs == 2): return 2 else: ind = int(log2(capital + 1)) # typecasting to int removes decimals if (total_lambs - 2**n + 1 >= 2**(n - 1) + 2**(n - 2)): # condition 2, 3 and 4 return ind + 1 else: return ind
Please suggest improvements wherever possible.