Indexing error when running this binary search method in python -



Indexing error when running this binary search method in python -

def unique(ip): file = open("/home/user/desktop/ipaddreses.txt",'r') list = file.readlines() list.sort() low = 1 hi = len(list) target = converttostr(ip) if hi > 1: while low <= hi: mid = low + (hi-low)/2 if list[mid] == target: file.close() homecoming false elif list[mid] < target: low = mid+1 else: hi = mid-1 else: if target == list[0]: homecoming false file.close() homecoming true

get error:

if list[mid] == target: indexerror: list index out of range

purpose search through generated ip addresses create sure randomly created ip addresses unique. working before ... got home , error

i don't see how prepare problem code, if want solve problem @ hand, isn't best way it.

sorting , doing binary search worse doing straightforward linear search on array, in general. sorting o(n log n) , in practice requires "looking at" each element of array @ to the lowest degree once, , requires storing @ to the lowest degree 1 re-create of entire file in memory. if iterate on file, @ each element @ once, , utilize constant amount of memory.

you shouldn't implementing binary search anyway (unless you're doing practice), because you've discovered it's easy fiddly bits wrong; utilize the bisect module instead.

it looks there's exit path code don't explicitly close file (the target == list[0] part). why with statements nice; handle you.

you instead:

def unique(ip): ip_str = converttostr(ip) open("/home/user/desktop/ipaddreses.txt", 'r') f: homecoming all(line.rstrip() != ip_str line in f)

if you're going phone call unique on bunch of ip addresses, avoid reading whole file each time, , much faster lookups, using set:

with open("/home/user/desktop/ipaddreses.txt", 'r') f: ip_addresses = set(line.rstrip() line in f) def unique(ip): homecoming converttostr(ip) not in ip_addresses

that said, comparing the source of bisect module, seems differences utilize while low <= hi utilize while lo < hi, , utilize hi = mid - 1 utilize hi = mid. think (though haven't run create sure) if string you're searching largest 1 in list, end low == hi == len(list), set mid = len(list), breaks when list[mid].

python-2.7

Comments

Popular posts from this blog

javascript - mongodb won't find my schema method in nested container -

r - url in CRAN extension manual -

asp.net - .NET Control.ID property inconsistency -