开发者

Trouble iterating in python

开发者 https://www.devze.com 2023-04-05 23:14 出处:网络
Working in Python 2.7. I would like to be able to input a number, and return all the sets of values for x and y that complete the equation win_percentage = observed.

Working in Python 2.7.

I would like to be able to input a number, and return all the sets of values for x and y that complete the equation win_percentage = observed.

def Rlog5(observed):
    z = float(observed)/1000
    for x in range(350, 650, 1):
        y = 1000 - x
        win_percentage = (float(x)-(float(x)*float(y)))/(float(x)+float(y)-(2*(float(x)*float(y))))
        if win_percentage = observed:
           print (z, float(x), float(y))

When I run the function, I get nothing. No errors, but no values either (I've tried with and without the floats for x, but I think it needs them because win_percentage should be a float). The most frustrating part is that I have this code which does basically the same thing, and it works fine:

def solve(numNuggets):
    for numTwenties in range(0, numNuggets/20 + 1):
            for numNines in range(0, (numNuggets - numTwenties*20)/9 + 1):
                numSixes = (numNuggets - numTwenties*20 - numNines*9)/6
                totNuggets = 20*numTwenties + 9*numNines + 6*numSixes
                if totNuggets == numNuggets:
                    print (numSixes, numNines, numTwenties)

I know this kind of a newbie questio开发者_高级运维n, but I'm at my wits end...


As others have noted, you have = where you should have ==, but I assume that's a typo here, since you would get a syntax error. But you are testing floats for equality, and floats are almost never equal because of their imprecision. Generally, you test to see if two floats are within a small difference of each other, traditionally called epsilon.

Try this:

if abs(win_percentage - observed) < 0.000001:
    print etc


= is used for assignment, == is used for comparison.

Change if win_percentage = observed: to if win_percentage == observed:.


Should be

if win_percentage == observed:
0

精彩评论

暂无评论...
验证码 换一张
取 消