Python:将伪代码转换为代码

时间:2017-11-14 02:19:26

标签: python pseudocode

我尝试编码这些行:

copy the first {ceiling of} n/2 points of P to array Pleft
copy the same {ceiling of} n/2 points from Q to array Qleft
copy the remaining {floor of} n/2 points of P to array Pright
copy the same {floor of} n/2 points from Q to array Qright 
m = P[ ({ceiling of} n/2) - 1].x

我得到了:

mid = len(P) / 2

Pl = P[:mid]
Ql = Q[:mid]
Pr = P[mid:]
Qr = Q[mid:]
m = P[:mid - 1].x

但我不知道如何编码这一行:

copy all the points of array Q for which |x - m| < d into new array S[0..num - 1]

请帮忙。

1 个答案:

答案 0 :(得分:1)

编辑:哎呀!忘了m是一个列表!

这是list comprehensions的用途。由于m是一个列表,因此您还需要使用python的zip函数。新数组的定义是:

S = [x for x, y in zip(Q, m) if abs(x - y) < d]

您必须提供d。另外,为了完整性:

num = len(S)