My code is based around the following problem:
It's about making a series of plots of land symmetrical by knocking down fences, but out of context of this problem, the code: Takes a list, makes it symmetrical by adding elements together, and prints / writes the number of changes needed to achieve this.
My main concern is speed: the code works fine but it is taking too long to solve cases with long lists. (up to 100,000 elements, where each element is an integer up to 10,000) Any feedback welcomed!
infile = open("farmin.txt", "r") outfile = open("farmout.txt", "w") n = int(infile.readline()) plots = infile.readline().split() infile.close() plots = [int(i) for i in plots] fencescut = 0 leftpos = 0 rightpos = 0 def mergeplots (direc, n1, n2): global plots if direc == "l": plots[n1] = plots[n1] + plots.pop(n2) else: plots[len(plots) - 1 - n1] = plots[len(plots) - 1 - n1] + plots.pop(len(plots) - 1 - n2) while leftpos <= len(plots)/2 and rightpos <= len(plots)/2: if plots[len(plots) - 1 - rightpos] - plots[leftpos] > 0: # left fence needs to be cut fencescut += 1 mergeplots("l",leftpos, leftpos + 1) elif plots[len(plots) - 1 - rightpos] - plots[leftpos] < 0: #right fence needs to be cut fencescut += 1 mergeplots('r', rightpos, rightpos + 1) else: # no fence needs to be cut leftpos += 1 rightpos += 1 outfile.write(str(fencescut)) outfile.close()