ProgrammingVery hardAmazon OA · Flipkart coding round
What is printed?
What is printed?
import heapq
def refuel(target, start, stations):
h = []
i = 0
fuel = start
stops = 0
while fuel < target:
while i < len(stations) and stations[i][0] <= fuel:
heapq.heappush(h, -stations[i][1])
i += 1
if not h:
return -1
fuel += -heapq.heappop(h)
stops += 1
return stops
print(refuel(100, 10, [[10, 60], [20, 30], [30, 30], [60, 40]]), refuel(100, 1, [[10, 100]]))- A. 2 -1
- B. 1 -1
- C. 2 0
- D. 3 -1
Correct answer: A. 2 -1
Greedy refuelling takes the largest station passed so far whenever fuel runs short. The first case needs two stops, and in the second the station at 10 can never be reached with fuel 1.
More Python Programming questions
- What is printed? python import heapq def jobs(items): items = sorted(items, key=lambda x: x[0]) h = [] for d, p in items…
- What is printed? python try: print(sorted([3, None, 1])) except TypeError: print('TypeError') print(max(['b', 'a'], key=str.upper)…
- What is printed? python s = 'hello' try: s[0] = 'j' except TypeError: print('immutable') t = s.replace('h', 'j') print(t, s)
- What is printed? python print(1020 / 1019, 1020 // 1019, 264 % 1000, 1020 == 1e20)
- What is printed? python calls = [] def f(x): calls.append(x) return x 2 m = map(f, [1, 2, 3]) print(calls) first = next(m) print(calls…
- In Python, when is the outermost iterable of a generator expression such as (x for x in make()) evaluated?