Google Foobar: How to find edge cases and identify test cases. Python -
problem
fuel injection perfection
commander lambda has asked refine automatic quantum antimatter fuel injection system lambchop doomsday device. it's great chance closer @ lambchop - , maybe sneak in bit of sabotage while you're @ - took job gladly.
quantum antimatter fuel comes in small pellets, convenient since many moving parts of lambchop each need fed fuel 1 pellet @ time. however, minions dump pellets in bulk fuel intake. need figure out efficient way sort , shift pellets down single pellet @ time.
the fuel control mechanisms have 3 operations:
add 1 fuel pellet remove 1 fuel pellet divide entire group of fuel pellets 2 (due destructive energy released when quantum antimatter pellet cut in half, safety controls allow happen if there number of pellets) write function called answer(n) takes positive integer string , returns minimum number of operations needed transform number of pellets 1. fuel intake control panel can display number 309 digits long, there won't ever more pellets can express in many digits.
for example: answer(4) returns 2: 4 -> 2 -> 1 answer(15) returns 5: 15 -> 16 -> 8 -> 4 -> 2 -> 1
test cases
inputs: (string) n = "4" output: (int) 2
inputs: (string) n = "15" output: (int) 5
here solution:
import math import decimal def answer(n): n = long(n) if n <= 1 or n >= long('9' * 309): return 0 # 1. find closest power of 2 round_threshold_adjust = math.log(3,2)- (1.5) log_n = math.log(n, 2) power = log_n - round_threshold_adjust # round power down if x.50000. if n equally between 2 powers of 2, # choose lower power of 2. e.g. 6, choose, 4 not 8 power2 = long(decimal.decimal(power).quantize(0, decimal.round_half_down)) # 2. calculate difference, add iterations # 3. take log 2 of that, add iteration iters = abs(n - 2**power) + power return(iters)
my solution passes 3 out of 10 test cases. believe other test cases edge cases. may please give me pointers on how can identify code failing? (i not have access test cases)
here of test cases have tried:
assert answer(15) == 5 assert answer(4) == 2 assert answer(3) == 2 assert answer(2) == 1 assert answer(6) == 4 assert answer(7) == 4 assert answer(10) == 5 assert answer(1024) == 10 assert answer(1025) == 11 assert answer(1026) == 12 assert answer(1027) == 13 assert answer(768) == 256 + 9
if understood correctly, given 768 pellets need 256+9 steps transform 1 pellet?
i can in 10 steps:
- divide 768 2
- repeat 7 more times -> end 3 pellets
- subtract 1
- subtract 1
i think first step, adding/subtracting until land @ power of 2, not fastest solution.
i'm not sure how code better solution, maybe points in right direction. intuitively, next step @ binary representation of number, , translate allowed operations representation. might simplify creation of correct algorithm.
Comments
Post a Comment