swap variables
The most straightforward solution is to use a third variable to temporarily store one of the old values. e.g.:
tmp = a
a = b
b = tmp
If you've read lots of Python code, you might have seen the following trick to swap two variables in one line:
a, b = b, a
We'll demystify this bit of Python magic later when we talk about tuples.
7---3
相当于7-(-(-3))=4.奇数个-为减,偶数个-变成+math.ceil
math.ceil返回值的上入整数。即a整除b,则返回a/b。若a除以b有余数,则返回a/b+1
Solution: Here's one possible solution:
rows = n // 8 + min(1, n % 8)
cols = min(n, 8)
height = rows * 2
width = cols * 2
Calculating rows is the trickiest part. Here's another way of doing it:
rows = (n + 7) // 8
We haven't shown the math module, but if you're familiar with the ceiling function, you might find this approach more intuitive:
import math
rows = math.ceil(n / 8)
rows = int(rows) # ceil returns a float
同一行赋值
同一行赋值含有相同的存储地址,可能会出现和不在同一行赋值不同的效果
a = b = <expression> is equivalent to...
b = <expression>
a = b
Solution: The one-line syntax results in a and b having the same memory address - i.e. they refer to the same object. This matters if that object is of a mutable type, like list. Consider the following code:
odds = evens = []
for i in range(5):
if (i % 2) == 0:
evens.append(i)
else:
odds.append(i)
print(odds)
print(evens)
We might expect this would print [1, 3], then [0, 2, 4]. But actually, it will print [0, 1, 2, 3, 4] twice in a row. evens and odds refer to the same object, so appending an element to one of them appends it to both of them. This is occasionally the source of hair-pulling debugging sessions. :)
Another consideration is expressions that have side effects. For example, list.pop is a method which removes and returns the final element of a list. If we have L = [1, 2, 3], then a = b = L.pop(), will result in a and b both having a value of 3. But running a = L.pop(), then b = L.pop() will result in a having value 3 and b having value 2.
网友评论