简体   繁体   English

让 Python 找到两个满足条件的整数

[英]Let Python find two integers satisfying condition

Set-up设置

I'm looking for all the integer pairs (x,y) in 2 closed sets: [822,2000] and [506,1231] such that x/y=1.624 .我正在寻找 2 个封闭集合中的所有整数对(x,y)[822,2000][506,1231]使得x/y=1.624


Code so far到目前为止的代码

I tried,我试过,

a = [[(x,y)] for x in range(822,2001) and y in range(506,1232) if x/y = 1.624]

But this gives a SyntaxError: invalid syntax pointing to the = in the code.但这给出了一个SyntaxError: invalid syntax指向代码中的=

And if I do,如果我这样做,

a = [[(x,y)] for x in range(822,2001) and y in range(506,1232) if x/y <= 1.624]

I get NameError: name 'y' is not defined .我得到NameError: name 'y' is not defined

How do I solve this?我该如何解决这个问题?

Comparing float calculations with == is difficult due to the nature of float arithmetics.由于浮点运算的性质,将浮点计算与 == 进行比较是很困难的。

It is often better to compare like this:像这样比较通常更好:

a = [(x,y) for x in range(822,2001) for y in range(506,1232) if abs(x/y - 1.624) < 0.00001] 
print(set(a)) 

By substracting the wanted value from your result and and comparing its absolute value against something kindof small you get better results.通过从您的结果中减去想要的值,并将其绝对值与某种较小的值进行比较,您会得到更好的结果。

Result (using a set):结果(使用一组):

{(1624, 1000), (1637, 1008), (1015, 625), (1611, 992), (1840, 1133), 
 (1814, 1117), (1827, 1125), (1408, 867), (1218, 750), (1434, 883), 
 (1421, 875)}

Python rounding error with float numbers 浮点数的Python舍入错误

For the first one you are using the assignment operator instead of the equivalent operator so it should be:对于第一个,您使用的是赋值运算符而不是等效运算符,因此它应该是:

a = [[(x,y)] for x in range(822,2001) and y in range(506,1232) if x/y == 1.624]

And for the second you're probably better off using two for loops第二,你最好使用两个 for 循环

a = [[(x,y)] for x in range(822,2001) for y in range(506,1232) if x/y <= 1.624]

The second one would not make sense as you said it because x and y are coming from lists that have an unequal number of elements so you cannot loop over them like that正如你所说的那样,第二个没有意义,因为 x 和 y 来自元素数量不等的列表,所以你不能像那样循环它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM