google kickstart round f. #1 Trash Bins

wonderful world·2021년 9월 19일
0

https://codingcompetitions.withgoogle.com/kickstart/round/0000000000435bae/0000000000887c32

Note

find_idx_by_value: No such built-in function? How about using List.index(v)?
make_nearest_index_list: seems very simple but ugly implementation. refactor me.

def f(n, xs):
    def make_nearest_index_list(xs):
        ret = []
        nearest_trash = find_idx_by_value(xs, value=1, start=0)
        next_trash = find_idx_by_value(xs, value=1, start=nearest_trash+1)
        for i in range(len(xs)):
            if next_trash == None:
                ret += [nearest_trash]
                continue
            
            if abs(i-next_trash) < abs(i-nearest_trash):
                nearest_trash = next_trash
                next_trash = find_idx_by_value(xs, value=1, start=nearest_trash+1)
                
            ret += [nearest_trash]
        return ret
    # if not found `value`, return None
    def find_idx_by_value(xs, value, start):
        for i in range(start, len(xs)):
            if xs[i] == value:
                return i
        return None
    # 012345    <-- index
    # 100100    <-- xs
    # 003333    <-- make nearest trash bin index list using `xs`
    # 011012    <-- abs diff between `index` and `nearest trash bin`
    # 5         <-- sum of abs diff
    ys = make_nearest_index_list(xs)
    abs_diff = [abs(a-b) for a, b in enumerate(ys)]
    return sum(abs_diff)
    
def ints(ss):
    return [int(s) for s in ss]
    
if __name__ == '__main__':
    T = int(input())
    for i in range(T):
        n = int(input())
        xs = ints(input())
        print (f'Case #{i+1}: {f(n, xs)}')
profile
hello wirld

0개의 댓글