0

Trying to minimize iteration

Hello community members i am trying to minimize iteration in my code lazy friends as i am getting time limited exceeded error in 1 test case any help will be appreciated thanks. Problem is:: Several friends live along a straight street. They are friends, thus they enjoy visiting each other. However, they are lazy so none of them wants to visit a friend living more than maxDist meters away from them. Given array houses representing coordinates of points where the friends live (in meters) and an integer maxDist, return an array representing the number of friends each person would be willing to visit. Example For houses = [1, 2, 4, 8, 10] and maxDist = 5, the output should be lazyFriends(houses, maxDist) = [2, 2, 3, 2, 1]. houses: [-5, 0, 5, 10, 15] maxDist: 10 Expected output [2, 3, 4, 3, 2] https://code.sololearn.com/cZSdCA90v1eP/?ref=app

20th Apr 2020, 3:30 PM
कामेश
कामेश - avatar
5 odpowiedzi
+ 5
nice! will think about it.
20th Apr 2020, 3:48 PM
Oma Falk
Oma Falk - avatar
20th Apr 2020, 4:14 PM
Oma Falk
Oma Falk - avatar
0
Thanks Oma Falk
20th Apr 2020, 3:50 PM
कामेश
कामेश - avatar
0
Thanks a lot Oma Falk i am trying to learn lambda function but till now i am unable to grasp it . I understand your answer but i can't able to implement my logic in less lines of code well i will try thanks again for giving me solution
20th Apr 2020, 4:20 PM
कामेश
कामेश - avatar
0
Here's an O(n log n) solution using the bisect module. https://docs.python.org/3/library/bisect.html import bisect def lazyFriends(houses, max_dist): # houses.sort() # In case "houses" isn't sorted. res = [] for house in houses: a = bisect.bisect_left(houses, house-max_dist) b = bisect.bisect_right(houses, house+max_dist) res.append(b - a - 1) return res Here's a brief explanation: Suppose the array "houses" is sorted. For each house "h", we find the index of the leftmost house ("a" in my code") and the index of the rightmost house ("b" in my code) within "max_dist" meters from "h". The number of friends each person is willing to visit is then "b - a - 1".
20th Apr 2020, 4:44 PM
Diego
Diego - avatar