[note]how a generator works

how a generator works

A Sentence class was discussed in the previous blog.

however, the versions of Sentence haven been created are not pythonic.

Let's see another version.

import re, reprlib

RE_WORD = re.compile("\w+")

class Sentence(object):
    def __init__(self, txt):
        self.words = RE_WORD.findall(txt)

    def __repr__(self):
        return "Sentence({})".format(reprlib.repr(self.words))

    def __iter__(self):
        for ele in self.words:
            yield ele
        return # do not need 
the return above is not needed. the function just fall thought and return automatically.

Either way, a generator function doesn't raise StopIteration Exception: it just exits when it's done producing values.

the __iter__ function above is a generator function, which return a generator and that is also an iterator.

what is a generator function?

any python function that has the yield keyword in its body is a generator function:

a function which, when called, returns a generator object. In other words, a generator function is a generator factory.

for example:
def gen_123():
    yield 1
    yield 2
    yield 3

>>> gen_123  # gen_123 is still a function object
<function gen_123 at 0x...>
>>> gen_123() # that is a generator now.
<generator object gen_123 at 0x...>
>>> for i in gen_123():
        ptint(i)
1
2
3
>>> g = gen_123()
>>> next(g)
1
>>> next(g)
2
>>> next(g)
3

>>> next(g) # when generator is exhausted and applied next function, a StopIteration will be raised.
Traceback (most recent call last):
...
StopIteration

finally, when the function body returns, the enclosing generator object raises StopIteration, in accordance with the Iterator Protocol.

And the yield keyword in generator function suspends the process.

The following case will demonstrate it well.

>>> def gen_AB():
        print("start...")
        yield 'A'
        print("continue")
        yield 'B'
        print("end")
>>> for c in gen_AB():
        print('--->', c)


start...
---> A
continue
---> B
end
>>>
Obviously, the for loop machinery code catches the StopIteration Exception, and the loop terminates clearly.

So, the pythonic Sentence class is created:

class Sentence(object):
    def __init__(self, txt):
        self.txt = txt

    def __repr__(self):
        return "Sentence({})".format(reprlib.repr(self.text))

    def __iter__(self):
        for match in RE_WORD.finditer(self.txt):
            yield match.group()
the finditer method also return an Iterator, that saves more memory.






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
As an AI language model, I cannot generate codes for you, but I can give you an idea of how a basic ultrasound channel data generator works. An ultrasound channel data generator is a program that generates simulated ultrasound images by creating a set of channel data. The channel data represents the raw ultrasound signals that are received by the transducer from different points in the body. Here are the steps involved in generating ultrasound channel data: 1. Define the parameters: The generator needs to define the parameters of the simulation, such as the imaging depth, transducer frequency, and the number of channels. 2. Generate the tissue model: The generator needs to create a model of the tissue being imaged, which includes the density, attenuation, and speed of sound in different tissues. 3. Calculate the transmit beam: The generator needs to calculate the transmit beam, which is the sound wave sent out by the transducer. This is done by modeling the transducer and its characteristics, such as its aperture and focal length. 4. Calculate the receive beam: The generator needs to calculate the receive beam, which is the sound wave that is reflected back to the transducer. This is done by modeling the reflection and scattering of sound waves in the tissue. 5. Generate the channel data: The generator uses the transmit and receive beams to create a set of channel data, which represents the raw ultrasound signals received by each channel of the transducer. 6. Process the channel data: The generator can then process the channel data to create an ultrasound image that can be displayed on a screen. Overall, the ultrasound channel data generator is a complex program that requires a deep understanding of ultrasound physics and signal processing.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值