python - Index out of Range while counting inversions -
i trying count number of inversions in .txt file given argument in command line input. when ever gets line checks if there inversion index out of range error. have tried writing down place , value in , j each loop can't figure out how stop going out of range. here error
file "./counting_inversions.py", line 31, in sortandcountsplit if (l[i] <= r[j]): indexerror: list index out of range
does 1 else know solution?
import argparse def readfile(): arg_parser = argparse.argumentparser(description='print given input file.') arg_parser.add_argument('filename', help='path file') args = arg_parser.parse_args() open(args.filename, 'r') in_file: n = int(in_file.readline()) vals = [int(val) val in in_file.readlines()] return([n, vals]) def sortandcount(invlist): if (len(invlist) == 1): return (invlist, 0) else: midpoint = int(len(invlist) / 2) left, lc = sortandcount(invlist[:midpoint]) right, rc = sortandcount(invlist[midpoint:]) arr, sc = sortandcountsplit(left, right) return (arr, (lc + rc + sc)) def sortandcountsplit(l, r): s = [] = j = inversions = 0 k in range((len(l) + len(r))): if ((i < len(l)) , (l[i] <= r[j]) or j >= len(r)): s.append(l[i]) += 1 else: s.append(r[j]) j += 1 inversions += len(l) - return (s, inversions) def main(): file = readfile() print(sortandcount(file[1])) main()
Comments
Post a Comment