![]() For each letter, I return the current value of “output” (which is guaranteed to be a list), plus a new, single-element list. In the above Python code, I iterate over the string ‘abc’, which is a three-element sequence of those three letters. In the above case (and in all of the examples we’ll use here), I’m trying to build an oh-so-useful dictionary in which the keys are the letters a, b, and c, and the values are the ASCII codes for those letters. Let’s try that: reduce(lambda output, current: output +, 'abc', ) So if I can tell “reduce” to emit a list of tuples, I can then pass that list of tuples to “dict”, and get a dictionary back. Perhaps the first and easiest one is not exactly what you might have had in mind, namely passing the “dict” function (which creates a new instance of “dict” - i.e., a new dictionary) a list of two-element tuples. Let’s start with Python: If I want to create a dictionary using “reduce”, I have a few different options. But they will be fun, which is important, no? I should note that some of the things you’re going to see here are not really recommended coding practices, particularly in Python. ![]() ![]() Nevertheless, I find it interesting and instructive to see how we can use “reduce” to create a data structure that we wouldn’t normally associate with this function. I should note that recent versions of Python offer “ dictionary comprehensions,” which are one of my favorite features of the language, and can be used similarly to “reduce” - and probably with less confusion among new programmers. There are times when you might want to build a dictionary step by step, and “reduce” can help you to do that. I tend to use these quite a bit, and I know that I’m not alone hashes are easy to use and work with, have O(1) lookup characteristics, guarantee the uniqueness of their keys, and make the code self-documenting. The jewel in the data-structure crown for these high-level languages is known by many names: Dictionary, hash, hash table, hash map, and mapping. In the last few installments ( first, second, third, and fourth) of this series, we saw how “reduce” can be used to build up a scalar value (such as a number or string), or even a simple collection, such as a list (in Python) or an array (in Ruby). Introduction to machine learning in Python.Introduction to Python (for experienced coders).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |