Problem 1: TakeWhile (100pts)
Problem
Implement
takeWhile, which takes in an iteratortand a predicatep.takeWhileyields the values fromtup to the first element that does not satisfyp.A predicate
pis just a pure function with one argument and returns eitherTrueorFalse.
实现 takeWhile,它接受一个迭代器 t 和一个谓词 p。
takeWhile 产出来自 t 的值,直到第一个不满足 p 的元素。
谓词 p 只是一个接受一个参数并返回 True 或 False 的纯函数。
def takeWhile(t, p):
"""Take elements from t until p is not satisfied.
>>> s = iter([10, 9, 10, 9, 9, 10, 8, 8, 8, 7])
>>> list(takeWhile(s, lambda x: x == 10))
[10]
>>> s2 = iter([1, 1, 2, 3, 5, 8, 13])
>>> list(takeWhile(s2, lambda x: x % 2 == 1))
[1, 1]
>>> s = iter(['a', '', 'b', '', 'c'])
>>> list(takeWhile(s, lambda x: x != ''))
['a']
>>> list(takeWhile(s, lambda x: x != ''))
['b']
>>> next(s)
'c'
"""
"*** YOUR CODE HERE ***"
Hints
- 如果你的程序看起来没有问题,但是 OJ 只有 80/100,可以考虑使用以下结构。原因见 PEP-0479。
try:
"*** YOUR CODE HERE ***"
except StopIteration:
return
Solutions
使用 try:先存储 next(t) 的值,判断是否符合条件再输出
def takeWhile(t, p):
while True:
try:
i = next(t)
if p(i): yield i
else: return
except StopIteration: return
或者使用 for
def takeWhile(t, p):
for i in t:
if p(i): yield i
else: return
one-liner:
使用 next 的 default 参数,递归
def takeWhile(t, p):
if (i := next(t, o := object())) is not o and p(i): yield from [] if (yield i) and False else takeWhile(t, p)