思路:从左往右遍历原字符串,我们保留每个遍历到的字符(X),但是我们可以选择保留还是舍弃前一个字符(Y),关键看 X 和 Y 的大小,如果 Y > X,显然,舍弃 Y 得到的数会更小,否则保留 Y。如果遍历过程中就删除了 K 个字符,那么遍历结束;如果遍历结束还没删够 K 个,那么删除最后的若干字符。
try: a = bprint(a)exceptSyntaxError:print("<<<< SyntaxError")exceptSystemExit:print("<<<< NameError")except:print("I don't know, but error.")print("He, try/except is so difficult!")# I don't know, but error.# He, try/except is so difficult!
try - except - else
try: a = bprint(a)exceptSyntaxError:print("<<<< SyntaxError")exceptSystemExit:print("<<<< NameError")except:print("I don't know, but error.")else:print("That's good, no error.")print("He, try/except is so difficult!")# I don't know, but error.# He, try/except is so difficult!
可见,有异常时,else block 时不执行的。
try: b =1 a = bprint(a)exceptSyntaxError:print("<<<< SyntaxError")exceptSystemExit:print("<<<< NameError")except:print("I don't know, but error.")else:print("That's good, no error.")print("He, try/except is so difficult!")# 1# That's good, no error.# He, try/except is so difficult!
可见,无异常时 else block 执行。
try - finally
无论 try 语句是否有异常,最后都要执行的代码。
try: b =1 a = bprint(a)exceptSyntaxError:print("<<<< SyntaxError")exceptSystemExit:print("<<<< NameError")except:print("I don't know, but error.")else:print("That's good, no error.")finally:print("I will be here!")print("He, try/except is so difficult!")# 1# That's good, no error.# I will be here!# He, try/except is so difficult!
try: a = bprint(a)exceptSyntaxError:print("<<<< SyntaxError")exceptSystemExit:print("<<<< NameError")except:print("I don't know, but error.")else:print("That's good, no error.")finally:print("I will be here!")print("He, try/except is so difficult!")# I don't know, but error.# I will be here!# He, try/except is so difficult!
很棒的一个回答,详细地介绍了 yield from 的作用,如果只是简单使用,可以把他当作是对于迭代器的展开(yield from iterator == for v in iterator: yield v),但是它不仅仅如此,它在调用者与子生成器之间构建了一个透明的双向联系(establishes a transparent bidirectional connection between the caller and the sub-generator),只不过这个关键词字面意思并没有表现出来罢了。
另外使用 yield from 可以从生成器中读取/向生成器发送数据(双向),而且它自动完成了异常向子生成器的传递。
classSpamException(Exception):passdefwriter():whileTrue:try: w = (yield)except SpamException:print('***')else:print('>> ', w)defwriter_wrapper(coro):yield from corow =writer()wrap =writer_wrapper(w)wrap.send(None)# "prime" the coroutinefor i in [0,1,2,'spam',4]:if i =='spam': wrap.throw(SpamException)else: wrap.send(i)# >> 0# >> 1# >> 2# ***# >> 4