4 ms·
Peter Norvig's 27 line spell checker https://norvig.com/spell-correct.html https://norvig.com/spell-correct.html
by biorach 4y ago
Peter Norvig's 27 line spell checker
https://norvig.com/spell-correct.html https://norvig.com/spell-correct.html
- DC-3 4y agoThis is nice. One interesting choice is the decision to compute the number of observed words, N, as the default value of an optional argument, thereby ensuring that it is only computed once, while still limiting its scope to the function in which it is needed. Perhaps this is a common pattern but it's one I haven't stumbled across before. The short circuiting `or` chain is also pleasantly virtuosic. Sometimes a little flashiness is tolerable when it works this well!
- version_five 4y ago> One interesting choice is the decision to compute the number of observed words, N, as the default value of an optional argument, thereby ensuring that it is only computed once You're saying python computes an expression that's part of a default value when the code defining the function is run? I guess it makes sense now that i say it, I wouldn't have automatically assumed that. That's an interesting one to remember.
- deleted 4y ago[deleted]
- darkfirefly 4y agoPython's default arguments are evaluated and stored once. This can cause issues, for example the naive "default to []" program: >>> def function(b, a=[]): ... a.append(b) ... print(a) ... ... >>> function(1) [1] >>> function(2) [1, 2] >>> function(3, [4]) [4, 3] >>> function(5) [1, 2, 5] A correct implementation would be: >>> def function2(b, a=None): ... if a is None: a = [] ... a.append(b) ... print(a)
- MisterBiggs 4y agoSurprised to see this works for list() as well. >>> def func(b, a=list()): ... a.append(b) ... print(a) ... >>> func(3) [3] >>> func(3) [3, 3] Honestly surprised this quirk hasn't bit me yet
- thrtythreeforty 4y agoYep and that's also the source of the footgun: def foobar(my_list=[]): my_list.append(42) A cursory glance suggests this function appends a number to an empty list every time it's run. But actually, the default argument is evaluated once when the function is defined, so calling this function repeatedly will continue to append to that same list.
- thatfunkymunki 4y agoyeah, this has consequences for constructors too, you don't want to specify default values in the __init__ function signature because of this.
- maxmcd 4y agoPeter Norvig's python is so elegant: https://github.com/norvig/pytudes#pytudes-index-of-jupyter-ipython-notebooks https://github.com/norvig/pytudes#pytudes-index-of-jupyter-i...
- wunderlust 4y agoYes! I'm working through the Design of Computer Programs on Udacity, which he teaches, and it's so enlightening to hear how he thinks through the conceptual framework of a program and see the code he comes up with to implement it. It's also nice to see that his code isn't always super elegant and that he's willing to write something readable and straightforward if it works well.