-5
k = 0
for z in xrange(x,y,2):  
    k += 1
print (k == 3)

所以我试图找到满足这一点的 x & y 值。我得到 x = 1 和 y =2,因为 1+2=3=k。但是 += 部分让我失望了。谁能解决这个问题?

4

4 回答 4

2

So the question is asking you, what are the first and second values needed in that xrange call so that k, having been incremented by one each time through, will end up with the value 3.

You should look up xrange in the documentation, paying attention to what each of the parameters does (not forgetting the third parameter which is set to 2 here).

于 2012-08-01T15:02:50.613 回答
1

In order to see what += actually does, try the following:

a = 0
a+=1  # (0+1)
print (a) # 1 
a += 3 # (1+3)
print (a) # 4 

Hopefully you can use that knowlege in conjuction with the documentation for the range function to figure out your problem (for this problem, you can view xrange and range as equivalent).

于 2012-08-01T15:01:58.990 回答
1

因此,您实际上要做的是构造一个xrange将准确返回 3 个数字的对象。

前两个参数xrange是起始值(对于您的示例来说可以是任何值)和结束值(实际上是永远不会在范围内的最小值。)给定您选择的任何起始值,您需要选择一个结束值,以便从起始值开始的范围,每次递增 2,将包含 3 个值。

解决方案留给读者。

于 2012-08-01T15:08:32.540 回答
0

解释:xrange(a,b,c); a是开始,b是结束,c是步骤。例如,xrange(0,10,1) 表示从 0 开始,然后按 1 计数,直到达到 10,然后停止

解释:+=; a += b: 是说取值 a 并将 b 添加到它。

x = 1 和 y = 2 对您不起作用,因为您从 1 开始,然后将 2 添加到它,得到 3。这高于 y (2) 所以它停止了。因此,循环只发生一次,所以 k 的值为 1。

于 2012-08-01T15:09:00.790 回答