由于我使用了错误的比较运算符,因此我的查询已完全解决。请不要在这里付出更多的努力。
我正尝试使用不同的比较运算符解决问题,如下所示。第一个比较给出错误的结果,但是第二个比较正常。我的第一个代码中的错误在哪里?
def countApplesAndOranges(s, t, a, b, apples, oranges):
apple_count=0
orange_count=0
print("s: ",s)
print("t: ",t)
for apple in apples:
apple_position=a+apple
if (s>=apple_position<=t):
apple_count+=1
for orange in oranges:
orange_position=b+orange
if (s>=orange_position<=t):
orange_count+=1
print(apple_count,orange_count)
countApplesAndOranges(7, 11, 5, 15, [-2, 2, 1], [5,-6])
Output:
3 0
def countApplesAndOranges(s, t, a, b, apples, oranges):
apple_count=0
orange_count=0
for apple in apples:
apple_position=a+apple
if (apple_position>=s and apple_position<=t):
apple_count+=1
for orange in oranges:
orange_position=b+orange
if (orange_position>=s and orange_position<=t):
orange_count+=1
print(apple_count,orange_count)
countApplesAndOranges(7, 11, 5, 15, [-2, 2, 1], [5,-6])
Output:
1 1
答案 0 :(得分:0)
您混淆了比较:
s >= apple_position <= t
等同于
apple_position <= s and apple_position <= t
不是
apple_position >= s and apple_position <= t
^^
答案 1 :(得分:0)
数学问题! @PeMaCN是正确的。
您是这样写的:
s >= apple_position<=t
不等于:
apple_position>=s and apple_position<=t
您应该写过:
s <= apple_position<=t
(请注意第一个比较更改)