Why Python Programmers Should Learn Python
wordaligned.org
wordaligned.org
words = ["zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"]
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
number_to_word = dict(zip(numbers, words))
word_to_number = dict(zip(words, numbers))
The rest, of course, can remain the same. I think adding this would also help to show how Python idioms like zip can help simplify code.That said, I still voted the submission up. I've seen several articles like this which point out how people use new languages in the same braindead way they used their old languages, yet I feel this one featured a very simple example with a paradigm that maps well to Python.
EDIT: Whoops, I got distracted and didn't realize that I didn't finish reading the article. It turns out that the approach is modified later on to do something even better, but I'll leave you to check out the article for that.
words = ["zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"]
number_to_word = dict(zip(range(10), words))
word_to_number = dict(zip(words, range(10)))
The last approach with lots of testing is good. import string
words = "zero one two three four five six seven eight nine".split()
number_to_word = dict(zip(string.digits, words))
word_to_number = dict(zip(words, range(10)))
I'm not sure why string.digits was used in the first zip but not the second. As kirubakaran pointed out, though, the number_to_word dictionary isn't even needed. The best approach, in my opinion, becomes: number_to_word = "zero one two three four five six seven eight nine".split()
word_to_number = dict(zip(number_to_word, range(10))
This would serve to display several cool Python idioms: the simplicity of string splitting, the power of zip, the simplicity of producing a list of numbers, and the use of the accessor on different types of data structures. If memory recalls, none of those operations are that easy to do in Java. from itertools import count
words = "zero one two three four five six seven eight nine".split()
word_to_number = dict(zip(words, count()))
[http://codepad.org/naCDzno7]I think a good later lesson would be to explain how iterators and the standard library works and then revisit this code to make it look like your example, but in the beginning, I think range(10) would be simpler and would better serve the purpose of the lesson. Even in this case, xrange (at least in Python 2.x) is obviously the better choice, but introducing that complexity at this point doesn't gain much, in my opinion.
words = "zero one two three four five six seven eight nine ten".split()
word_to_number = dict((j,i) for i,j in enumerate(words)) (define (zip . lists)
(apply map list lists))