Hello,

I'm very new to python script and I am attempting to understand a part of a program developed at my work place because the have the most computer knowledge here, though still very little and the person who developed the program is no longer accesible. Here's the problem i'm attempting to solve:

I have a .txt file that I believe is converted to an array by a comma delinated string. there is then a tab delinated string of the first four terms as floats. the program is supposed to compare the values in the array to desired values given by the program and find a value closest to the desired value given in the array based on a user inputed allowed percentage deviation. The program is working properly, however, rather than pulling the closest value to the given desired value from the array it is pulling something else that I am assuming is one of three things.

a. it's pulling the first value that it finds in the interval
b. it's pulling all the values in the interval and then averaging the value
c. it's pulling the first in the interval, the last, and finding the midpoint

what i would like it to do is either find the the exact integer in the deviation that is closest to the given, or pull the highest value in the range, either would work, it's just whichever is easiest.

so here's what the code looks like: (I think this is where the program is sorting this list)

i could not find the value for "ideal" anywhere in the program, and perhaps that is the very problem.

D=[abs(ref-read[0][2]),abs(ref-read[1][2]),abs(ref-read[2][2])]
ref is the matrix of ideal values chosen by the user
read=[split_s(current.readline()),split_s(current.readline()),split_s(current.readline())]
dev=the allowed deviation percentage entered in float form by user.

def sort(ideal,D,dev):
	if D[0] > D[1]:
		if D[1] > D[2]:
			if D[2] < ideal*dev:
				return 2
			else:
				return -1
		else:
			if D[1] < ideal*dev:
				return 1
			else:
				return -1
	else:
		if D[0] < D[2]:
			if D[0] < ideal*dev:
				return 0
			else:
				return -1
		else:
			if D[2] < ideal*dev:
				return 2
			else:
				return -1

I greatly appreciate any help that could be provided!
Thank you,
Michael Morris

Edit: code tags added by vegaseat 09/30/05

Dani AI

Generated

A simpler, deterministic approach works better than a deeply nested if/else tree. The nested comparisons are brittle and make it easy to miss the nearer candidate on the low side (which matches s observation). Also be sure your parsed values are real numbers and that the "deviation" value is interpreted consistently (fraction vs percent). was correct to ask for properly formatted code — clean structure makes these bugs obvious.

Try this pattern: build a list of candidates that lie within the allowed deviation, then pick either the one with the smallest absolute difference (closest) or the largest value (highest in range). This avoids complex branching and makes tie-break rules explicit.

def choose_candidate(candidates, target, allowed_fraction, prefer_high=False):
    # allowed_fraction: 0.1 for 10%
    thresh = abs(target) * allowed_fraction
    valid = [(i, v, abs(v - target)) for i, v in enumerate(candidates) if abs(v - target) <= thresh]
    if not valid:
        return None
    if prefer_high:
        return max(valid, key=lambda t: t[1])[0]   # index of highest valid value
    return min(valid, key=lambda t: t[2])[0]       # index of closest valid value

Debug checklist: print a small table of index, value, abs difference and whether it passes the threshold; confirm numeric conversions (use float()); confirm whether user input is percent (divide by 100 if needed). These steps make it easy to reproduce s failing case and verify the fix.

Recommended Answers

All 2 Replies

ok, so I tried assigning a value "ideal=ref", but that didn't fix the problem, though I suppose that it could have been one of the problems anyways. I did a little test I i think i've narrowed down the problem to the program only looking for values close to the ideal value that exceed the ideal value, but not potential values that preceed the ideal.

in short, the program looks for the ideal and if it can't find it then it looks for the next best value past it. this is bad because sometimes the best value is actually the before the ideal.

does that help my case at all? ^_^

Please put your Python code between code tags

Python needs the proper indentation and with the amount of if and else groupings you have, it is almost impossible to figure out what belongs to what!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.