Problem 3: Scale (100pts)
Problem
Implement the generator function
scale(it, multiplier), which yields elements of the given iterableit, scaled bymultiplier.As an extra challenge, try writing this function using
yield fromstatement andmap!
实现生成器函数 scale(it, multiplier),它产出给定可迭代对象 it 的元素,并将其按 multiplier 进行缩放(相乘)。
作为一个额外的挑战,尝试使用 yield from 语句和 map 来编写此函数!
def scale(it, multiplier):
"""Yield elements of the iterable it scaled by a number multiplier.
>>> m = scale(iter([1, 5, 2]), 5)
>>> type(m)
<class 'generator'>
>>> list(m)
[5, 25, 10]
>>> # generators allow us to represent infinite sequences!!!
>>> def naturals():
... i = 0
... while True:
... yield i
... i += 1
>>> m = scale(naturals(), 2)
>>> [next(m) for _ in range(5)]
[0, 2, 4, 6, 8]
"""
"*** YOUR CODE HERE ***"
Hints
Solutions
使用 map:
def scale(it, multiplier):
yield from map(lambda x: x * multiplier, it)