How many 3-letter codes can you make using the letters J e C K if each code must not repeat a letter
Python’s is a built-in function that allows you to process and transform all the items in an iterable without using an explicit 6 loop, a technique commonly known as mapping. 5 is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable. 5 is one of the tools that support a functional programming style in Python. Show
In this tutorial, you’ll learn:
With this knowledge, you’ll be able to use 5 effectively in your programs or, alternatively, to use list comprehensions or to make your code more Pythonic and readable.For a better understanding of 5, some previous knowledge of how to work with , 6 loops, functions, and 6 functions would be helpful.Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level. Coding With Functional Style in PythonIn functional programming, computations are done by combining functions that take arguments and return a concrete value (or values) as a result. These functions don’t modify their input arguments and don’t change the program’s state. They just provide the result of a given computation. These kinds of functions are commonly known as pure functions. In theory, programs that are built using a functional style will be easier to:
Functional programming typically uses lists, arrays, and other iterables to represent the data along with a set of functions that operate on that data and transform it. When it comes to processing data with a functional style, there are at least three commonly used techniques:
According to Guido van Rossum, Python is more strongly influenced by imperative programming languages than functional languages:
However, back in 1993, the Python community was demanding some functional programming features. They were asking for:
These functional features were added to the language thanks to the contribution of a community member. Nowadays, , , and 9 are fundamental components of the functional programming style in Python.In this tutorial, you’ll cover one of these functional features, the built-in function 5. You’ll also learn how to use list comprehensions and to get the same functionality of 5 in a Pythonic and readable way.Remove adsGetting Started With Python’s >>> str_nums = ["4", "8", "6", "5", "3", "2", "8", "9", "2", "5"] >>> int_nums = map(int, str_nums) >>> int_numsSometimes you might face situations in which you need to perform the same operation on all the items of an input iterable to build a new iterable. The quickest and most common approach to this problem is to use a Python 6 loop. However, you can also tackle this problem without an explicit loop by using 5.In the following three sections, you’ll learn how 5 works and how you can use it to process and transform iterables without a loop.Understanding >>> str_nums = ["4", "8", "6", "5", "3", "2", "8", "9", "2", "5"] >>> int_nums = map(int, str_nums) >>> int_nums 5 loops over the items of an input iterable (or iterables) and returns an iterator that results from applying a transformation function to every item in the original input iterable.According to the , 5 takes a function object and an iterable (or multiple iterables) as arguments and returns an iterator that yields transformed items on demand. The function’s signature is defined as follows:
5 applies 3 to each item in 4 in a loop and returns a new iterator that yields transformed items on demand. 3 can be any Python function that takes a number of arguments equal to the number of iterables you pass to 5.Note: The first argument to 5 is a function object, which means that you need to pass a function without calling it. That is, without using a pair of parentheses.This first argument to 5 is a transformation function. In other words, it’s the function that transforms each original item into a new (transformed) item. Even though the Python documentation calls this argument 3, it can be any Python callable. This includes , classes, methods, 6 functions, and user-defined functions.The operation that 5 performs is commonly known as a mapping because it maps every item in an input iterable to a new item in a resulting iterable. To do that, 5 applies a transformation function to all the items in the input iterable.To better understand 5, suppose you need to take a list of numeric values and transform it into a list containing the square value of every number in the original list. In this case, you can use a 6 loop and code something like this:>>>
When you run this loop on 5, you get a list of square values. The 6 loop iterates over 5 and applies a power operation on each value. Finally, it stores the resulting values in 8.You can achieve the same result without using an explicit loop by using 5. Take a look at the following reimplementation of the above example:>>>
0 is a transformation function that maps a number to its square value. The call to 5 applies 0 to all of the values in 5 and returns an iterator that yields square values. Then you call 4 on 5 to create a list object containing the square values.Since 5 is written in C and is highly optimized, its internal implied loop can be more efficient than a regular Python 6 loop. This is one advantage of using 5.A second advantage of using 5 is related to memory consumption. With a 6 loop, you need to store the whole list in your system’s memory. With 5, you get items on demand, and only one item is in your system’s memory at a given time.Note: In Python 2.x, returns a list. This behavior changed in . Now, 5 returns a map object, which is an iterator that yields items on demand. That’s why you need to call 4 to create the desired list object.For another example, say you need to convert all the items in a list from a string to an integer number. To do that, you can use 5 along with 6 as follows:>>>
5 applies to every value in 9. Since 5 returns an iterator (a map object), you’ll need call 4 so that you can exhaust the iterator and turn it into a list object. Note that the original sequence doesn’t get modified in the process.Remove adsUsing >>> str_nums = ["4", "8", "6", "5", "3", "2", "8", "9", "2", "5"] >>> int_nums = map(int, str_nums) >>> int_numsYou can use any kind of Python callable with 5. The only condition would be that the callable takes an argument and returns a concrete and useful value. For example, you can use classes, instances that implement a special method called , instance methods, class methods, static methods, and functions.There are some built-in functions that you can use with 5. Consider the following examples:>>>
You can use any built-in function with 5, provided that the function takes an argument and returns a value.A common pattern that you’ll see when it comes to using 5 is to use a 6 function as the first argument. 6 functions are handy when you need to pass an expression-based function to 5. For example, you can reimplement the example of square values using a 6 function as follows:>>>
6 functions are quite useful when it comes to using 5. They can play the role of the first argument to 5. You can use 6 functions along with 5 to quickly process and transform your iterables.Processing Multiple Input Iterables With >>> str_nums = ["4", "8", "6", "5", "3", "2", "8", "9", "2", "5"] >>> int_nums = map(int, str_nums) >>> int_numsIf you supply multiple iterables to 5, then the transformation function must take as many arguments as iterables you pass in. Each iteration of 5 will pass one value from each iterable as an argument to 3. The iteration stops at the end of the shortest iterable.Consider the following example that uses : >>>
21 takes two arguments, 23 and 24, and returns 23 to the power of 24. In the first iteration, 23 will be 28, 24 will be 30, and the result will be 28. In the second iteration, 23 will be 33, 24 will be 35, and the result will be 36, and so on. The final iterable is only as long as the shortest iterable, which is 37 in this case.This technique allows you to merge two or more iterables of numeric values using different kinds of math operations. Here are some examples that use 6 functions to perform different math operations on several input iterables:>>>
In the first example, you use a subtraction operation to merge two iterables of three items each. In the second example, you add together the values of three iterables. Transforming Iterables of Strings With Python’s >>> str_nums = ["4", "8", "6", "5", "3", "2", "8", "9", "2", "5"] >>> int_nums = map(int, str_nums) >>> int_numsWhen you’re working with iterables of string objects, you might be interested in transforming all the objects using some kind of transformation function. Python’s 5 can be your ally in these situations. The following sections will walk you through some examples of how to use 5 to transform iterables of string objects.Using the Methods of >>> numbers = [1, 2, 3, 4, 5] >>> squared = [] >>> for num in numbers: ... squared.append(num ** 2) ... >>> squared [1, 4, 9, 16, 25] 42A quite common approach to is to use some of the to transform a given string into a new string. If you’re dealing with iterables of strings and need to apply the same transformation to each string, then you can use 5 along with various string methods:>>>
There are a few transformations that you can perform on every item in 45 using 5 and string methods. Most of the time, you’d use methods that don’t take additional arguments, like , , , , and .You can also use some methods that take additional arguments with default values, such as , which takes an optional argument called 53 that defaults to removing whitespace:>>>
When you use 52 like this, you rely on the default value of 53. In this case, you use 5 to remove all the whitespace in the items of 57.Note: If you need to supply arguments rather than rely on the default value, then you can use a 6 function.Here’s an example that uses 52 to remove dots rather than the default whitespace:>>> 0The 6 function calls 61 on the string object 62 and removes all the leading and trailing dots.This technique can be handy when, for example, you’re processing text files in which lines can have trailing spaces (or other characters) and you need to remove them. If this is the case, then you need to consider that using 52 without a custom 53 will remove the newline character as well.Remove adsRemoving PunctuationWhen it comes to processing text, you sometimes need to remove the punctuation marks that remain after you split the text into words. To deal with this problem, you can create a custom function that removes the punctuation marks from a single word using a regular expression that matches the most common punctuation marks. Here’s a possible implementation of this function using , which is a regular expression function that lives in the module in Python’s standard library: >>> 1Inside 67, you use a regular expression pattern that matches the most common punctuation marks that you’ll find in any text written in English. The call to 68 replaces the matched punctuation marks using an empty string ( 69) and returns a cleaned 70.With your transformation function in place, you can use 5 to run the transformation on every word in your text. Here’s how it works:>>> 2In this piece of text, some words include punctuation marks. For example, you have 72 instead of 73, 74 instead of 75, and so on. The call to 5 applies 67 to every word and removes any punctuation mark. So, in the second 78, you have cleaned words.Note that the apostrophe ( 79) isn’t in your regular expression because you want to keep contractions like 80 as they are.Implementing a Caesar Cipher AlgorithmJulius Caesar, the Roman statesman, used to protect the messages he sent to his generals by encrypting them using a cipher. A Caesar cipher shifts each letter by a number of letters. For example, if you shift the letter 81 by three, then you get the letter 82, and so on.If the shift goes beyond the end of the alphabet, then you just need to rotate back to the beginning of the alphabet. In the case of a rotation by three, 23 would become 81. Here’s how the alphabet would look after the rotation:
The following code implements 87, a function that takes a character and rotates it by three. 87 will return the rotated character. Here’s the code: 3Inside 87, you first check if the character is in the alphabet. If not, then you return the same character. This has the purpose of keeping punctuation marks and other unusual characters. In line 8, you calculate the new rotated position of the character in the alphabet. To do this, you use the built-in function . 90 takes a Unicode character and returns an integer that represents the Unicode code point of the input character. For example, 92 returns 93, and 94 returns 95:>>> 4 90 takes a character as an argument and returns the Unicode code point of the input character.If you add this integer to the target number of 97, then you’ll get the rotated position of the new letter in the alphabet. In this example, 97 is 99. So, the letter 00 rotated by three will become the letter at position 01, which is the letter 02. The letter 03 rotated by three will become the letter at position 04, which is the letter 05, and so on.If the new position of the letter doesn’t go beyond the position of the last letter ( 06), then you return the letter at this new position. To do that, you use the built-in function . 07 is the inverse of 90. It takes an integer representing the Unicode code point of a Unicode character and returns the character at that position. For example, 10 will return 11, and 12 will return 13:>>> 5 07 takes an integer that represents the Unicode code point of a character and returns corresponding character.Finally, if the new rotated position is beyond the position of the last letter ( 06), then you need to rotate back to the beginning of the alphabet. To do that, you need to subtract the length of the alphabet from the rotated position ( 16) and then return the letter at that new position using 07.With 87 as your transformation function, you can use 5 to encrypt any text using the Caesar cipher algorithm. Here’s an example that uses 20 to concatenate the string:>>> 6Strings are also iterables in Python. So, the call to 5 applies 87 to every character in the original input string. In this case, 23 becomes 24, 25 becomes 03, and so on. Finally, the call to 20 concatenates every rotated character in a final encrypted message.Remove adsTransforming Iterables of Numbers With Python’s >>> str_nums = ["4", "8", "6", "5", "3", "2", "8", "9", "2", "5"] >>> int_nums = map(int, str_nums) >>> int_nums 5 also has great potential when it comes to processing and transforming iterables of numeric values. You can perform a wide variety of math and arithmetic operations, convert string values to floating-point numbers or integer numbers, and so on.In the following sections, you’ll cover some examples of how to use 5 to process and transform iterables of numbers.Using Math OperationsA common example of using math operations to transform an iterable of numeric values is to use the . In the following example, you code a transformation function that takes a number and returns the number squared and cubed: >>> 7 32 takes a number 23 and returns its square and cube. Since Python handles , each call to 32 returns a tuple with two values. When you call 5 with 32 as an argument, you get a list of tuples containing the square and the cube of every number in the input iterable.There are a lot of math-related transformations that you can perform with 5. You can add constants to and subtract them from each value. You can also use some functions from the 38 module like 39, , , , and so on. Here’s an example using 40:>>> 8In this case, you transform 5 into a new list containing the factorial of each number in the original list.You can perform a wide spectrum of math transformations on an iterable of numbers using 5. How far you get into this topic will depend on your needs and your imagination. Give it some thought and code your own examples!Converting TemperaturesAnother use case for 5 is to convert between units of measure. Suppose you have a list of temperatures measured in degrees Celsius or Fahrenheit and you need to convert them into the corresponding temperatures in degrees Fahrenheit or Celsius.You can code two transformation functions to accomplish this task: 9 47 takes a temperature measurement in Celsius and makes the conversion to Fahrenheit. Similarly, 48 takes a temperature in Fahrenheit and converts it to Celsius.These functions will be your transformation functions. You can use them with 5 to convert an iterable of temperature measurements to Fahrenheit and to Celsius respectively:>>> 0If you call 5 with 47 and 52, then you get a list of temperature measures in Fahrenheit. If you call 5 with 48 and 55, then you get a list of temperature measures in Celsius.To extend this example and cover any other kind of unit conversion, you just need to code an appropriate transformation function. Remove adsConverting Strings to NumbersWhen working with numeric data, you’ll likely deal with situations in which all your data are string values. To do any further calculation, you’ll need to convert the string values into numeric values. 5 can help with these situations, too.If you’re sure that your data is clean and doesn’t contain wrong values, then you can use or 6 directly according to your needs. Here are some examples:>>> 1In the first example, you use 57 with 5 to convert all the values from string values to values. In the second case, you use 6 to convert from a string to an . Note that if one of the values is not a valid number, then you’ll get a .If you’re not sure that your data is clean, then you can use a more elaborate conversion function like the following: >>> 2Inside 63, you use a that catches a 62 if 57 fails when converting 67. If no error occurs, then your function returns 67 converted to a valid floating-point number. Otherwise, you get a , which is a special 70 value that you can use to represent values that aren’t valid numbers, just like 71 in the above example.You can customize 63 according to your needs. For example, you can replace the statement 73 with the statement 74, and so on.Combining >>> str_nums = ["4", "8", "6", "5", "3", "2", "8", "9", "2", "5"] >>> int_nums = map(int, str_nums) >>> int_numsSo far, you’ve covered how to use 5 to accomplish different tasks involving iterables. However, if you use 5 along with other functional tools like and 9, then you can perform more complex transformations on your iterables. That’s what you’re going to cover in the following two sections.>>> str_nums = ["4", "8", "6", "5", "3", "2", "8", "9", "2", "5"] >>> int_nums = map(int, str_nums) >>> int_numsSometimes you need to process an input iterable and return another iterable that results from filtering out unwanted values in the input iterable. In that case, Python’s 8 can be a good option for you. 8 is a built-in function that takes two positional arguments:
8 yields the items of the input 4 for which 3 returns 85. If you pass 92 to 3, then 8 uses the identity function. This means that 8 will check the truth value of each item in 4 and filter out all of the items that are .To illustrate how you can use 5 along with 8, say you need to calculate the square root of all the values in a list. Since your list can contain negative values, you’ll get an error because the square root isn’t defined for negative numbers:>>> 3With a negative number as an argument, 99 raises a 62. To avoid this issue, you can use 8 to filter out all the negative values and then find the square root of the remaining positive values. Check out the following example:>>> 4 02 is a predicate function that takes a number as an argument and returns 85 if the number is greater than or equal to zero. You can pass 02 to 8 to remove all the negative numbers from 5. So, the call to 5 will process only positive numbers and 99 won’t give you a 62.Remove ads>>> str_nums = ["4", "8", "6", "5", "3", "2", "8", "9", "2", "5"] >>> int_nums = map(int, str_nums) >>> int_numsPython’s 9 is a function that lives in a module called 13 in the Python standard library. 9 is another core functional tool in Python that is useful when you need to apply a function to an iterable and reduce it to a single cumulative value. This kind of operation is commonly known as reduction or folding. 9 takes two required arguments:
9 will apply 3 to all the items in 4 and cumulatively compute a final value.Here’s an example that combines 5 and 9 to calculate the total size of all the files that live in your home directory cumulatively:>>> 5In this example, you call to get the path to your home directory. Then you call on that path to get a list with the paths of all the files that live there. The call to 5 uses to get the size of every file. Finally, you use 9 with to get the cumulative sum of the size of every single file. The final result is the total size of all the files in your home directory in bytes.Note: Some years ago, Google developed and started using a programming model that they called MapReduce. It was a new style of data processing designed to manage big data using parallel and distributed computing on a cluster. This model was inspired by the combination of the map and reduce operations commonly used in functional programming. The MapReduce model had a huge impact on Google’s ability to handle huge amounts of data in a reasonable time. However, by 2014 Google was no longer using MapReduce as their primary processing model. Nowadays, you can find some alternative implementations of MapReduce like Apache Hadoop, which is a collection of open source software utilities that use the MapReduce model. Even though you can use 9 to solve the problem covered in this section, Python offers other tools that can lead to a more Pythonic and efficient solution. For example, you can use the built-in function 30 to compute the total size of the files in your home directory:>>> 6This example is a lot more readable and efficient than the example that you saw before. If you want to dive deeper into how to use 9 and which alternative tools you can use to replace 9 in a Pythonic way, then check out Python’s reduce(): From Functional to Pythonic Style.Processing Tuple-Based Iterables With >>> str_nums = ["4", "8", "6", "5", "3", "2", "8", "9", "2", "5"] >>> int_nums = map(int, str_nums) >>> int_numsPython’s 34 makes an iterator that applies a function to the arguments obtained from an iterable of tuples and yields the results. It’s useful when you’re processing iterables that are already grouped in tuples.The main difference between 5 and 33 is that the latter calls its transformation function using the unpacking operator ( 37) to unpack each tuple of arguments into several positional arguments. So, the transformation function is called as 38 instead of 39.The says that the function is roughly equivalent to the following Python function: 7The 6 loop in this function iterates over the items in 4 and yields transformed items as a result. The call to 38 uses the unpacking operator to unpack the tuples into several positional arguments. Here are some examples of how 33 works:>>> 8In the first example, you use to calculate the power of the first value raised to the second value in each tuple. The tuples will be in the form 46.If every tuple in your iterable has two items, then 3 must take two arguments as well. If the tuples have three items, then 3 must take three arguments, and so on. Otherwise, you’ll get a .If you use 5 instead of 33, then you’ll get a different result because 5 takes one item from each tuple:>>> 9Note that 5 takes two tuples instead of a list of tuples. 5 also takes one value from each tuple in every iteration. To make 5 return the same result as 33, you’d need to swap values:>>> 0In this case, you have two tuples instead of a list of tuples. You’ve also swapped 57 and 30. Now the first tuple provides the bases and the second tuple provides the exponents.Remove adsCoding With Pythonic Style: Replacing >>> str_nums = ["4", "8", "6", "5", "3", "2", "8", "9", "2", "5"] >>> int_nums = map(int, str_nums) >>> int_numsFunctional programming tools like 5, 8, and 9 have been around for a long time. However, list comprehensions and have become a natural replacement for them almost in every use case.For example, the functionality provided by 5 is almost always better expressed using a list comprehension or a generator expression. In the following two sections, you’ll learn how to replace a call to 5 with a list comprehension or a generator expression to make your code more readable and Pythonic.Using List ComprehensionsThere’s a general pattern that you can use to replace a call to 5 with a list comprehension. Here’s how: 1Note that the list comprehension almost always reads more clearly than the call to 5. Since list comprehensions are quite popular among Python developers, it’s common to find them everywhere. So, replacing a call to 5 with a list comprehension will make your code look more familiar to other Python developers.Here’s an example of how to replace 5 with a list comprehension to build a list of square numbers:>>> 2If you compare both solutions, then you might say that the one that uses the list comprehension is more readable because it reads almost like plain English. Additionally, list comprehensions avoid the need to explicitly call 4 on 5 to build the final list.Using Generator Expressions 5 returns a map object, which is an iterator that yields items on demand. So, the natural replacement for 5 is a because generator expressions return generator objects, which are also iterators that yield items on demand.Python iterators are known to be quite efficient in terms of memory consumption. This is the reason why 5 now returns an iterator instead of a 78.There’s a tiny syntactical difference between a list comprehension and a generator expression. The first uses a pair of square brackets ( 75) to delimit the expression. The second uses a pair of parentheses ( 76). So, to turn a list comprehension into a generator expression, you just need to replace the square brackets with parentheses.You can use generator expressions to write code that reads clearer than code that uses 5. Check out the following example:>>> 3This code has a main difference from the code in the previous section: you change the square brackets to a pair of parentheses to turn the list comprehension into a generator expression. Generator expressions are commonly used as arguments in function calls. In this case, you don’t need to use parentheses to create the generator expression because the parentheses that you use to call the function also provide the syntax to build the generator. With this idea, you can get the same result as the above example by calling 4 like this:>>> 4If you use a generator expression as an argument in a function call, then you don’t need an extra pair of parentheses. The parentheses that you use to call the function provide the syntax to build the generator. Generator expressions are as efficient as 5 in terms of memory consumption because both of them return iterators that yield items on demand. However, generator expressions will almost always improve your code’s readability. They also make your code more Pythonic in the eyes of other Python developers.Remove adsConclusionPython’s allows you to perform mapping operations on iterables. A mapping operation consists of applying a transformation function to the items in an iterable to generate a transformed iterable. In general, 5 will allow you to process and transform iterables without using an explicit loop.In this tutorial, you’ve learned how 5 works and how to use it to process iterables. You also learned about some Pythonic tools that you can use to replace 5 in your code.You now know how to:
With this new knowledge, you’ll be able to use 5 in your code and approach your code with a functional programming style. You can also switch to a more Pythonic and modern style by replacing 5 with a list comprehension or a .Mark as Completed Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python's map() Function: Transforming Iterables 🐍 Python Tricks 💌 Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team. Send Me Python Tricks » About Leodanis Pozo Ramos Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites. » More about LeodanisEach tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are: Aldren Bryan Geir Arne Joanna Jacob Master Real-World Python Skills With Unlimited Access to Real Python Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Level Up Your Python Skills » Master Real-World Python Skills Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Level Up Your Python Skills » What Do You Think? Rate this article: Tweet Share Share EmailWhat’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know. Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. and get answers to common questions in our support portal. How many 3There are 15,600 different 3-letter passwords, with no letters repeating, that can be made using the letters a through z.
How many 3Therefore number of possible codes =720. Was this answer helpful?
How many 3If repetition is allowed, we have 4 choices for each letter. Therefore, we can form 4*4*4 = 64 such “words". Good luck!
How many 3 alphabet arrangements are there with at least one repetition of arrangements )?If the letters are distinct and repetition is allowed then 4 * 4 * 4 = 4^3 = 64.
|