Merging two sorted listWe have two sorted lists, and we want to write a function to merge the two lists into one sorted list:a = 3, 4, 6, 10, 11, 18b = 1, 5, 7, 12, 13, 19, 21Here is our code:a = 3, 4, 6, 10, 11, 18b = 1, 5, 7, 12, 13, 19, 21c = while a and b:if a0. Map, filter, and reduceUsing map, filter, reduce, write a code that create a list of (n).2 for range(10) for even integers:l = x for x in range(10) if x% 2 0print lm = filter(lambda x:x% 2 0, x for x in range(10) )# m = list( filter(lambda x:x% 2 0, x for x in range(10) ) ) # python3print mo = map(lambda x: x.2, m)# o = list( map(lambda x: x.2, m) ) # python3print op = reduce(lambda x,y:x+y, o)# import functools. # python3# p = functools.reduce(lambda x,y:x+y, o) # python3print pOutput:0, 2, 4, 6, 80, 2, 4, 6, 80, 4, 16, 36, 64120. Write a function fQ: We have the following code with unknown function f.
In f, we do not want to use return, instead, we may want to use generator.for x in f(5):print x,The output looks like this:0 1 8 27 64Write a function f so that we can have the output above.We may use the following f to get the same output:def f(n):return x.3 for x in range(5)But we want to use generator not using return.So, the answer should look like this:def f(n):for x in range(n):yield x.3The yield enables a function to comeback where it left off when it is called again. This is the critical difference from a regular function. A regular function cannot comes back where it left off. The yield keyword helps a function to remember its state.A generator function is a way to create an iterator. A new generator object is created and returned each time we call a generator function.
Python coding test problem for interviews closed On the other hand, the problem we use for Java turns out to be pretty trivial in Python (or Ruby, etc) - anyone halfway competent can do it in 15 minutes. So, I'm trying to come up with something better.
A generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately.Another example of using yield:Let's build the primes function so that I fills the n one at a time, and comes back to primes function until n 100.def isPrime(n):if n 1:return Falsefor t in range(2,n):if n% t 0:return Falsereturn Truefor n in primes:print n,The print out from the for-loop should look like this:2 3 5 7 11. 83 89 97Here is the primes function:def primes(n=1):while n.
Build a string with the numbers from 0 to 100, '101112.' The usage of os.path.dirname & os.path.basenameFor example, we have the path like this, /home/k/TEST/PYTHON/p.py:We can get the dir and file using the following:First, we need to import os module: import osThen, we do: os.path.dirname('/home/k/TEST/PYTHON/p.py')'/home/k/TEST/PYTHON' os.path.basename('/home/k/TEST/PYTHON/p.py')'p.py'Or we can get them at once in tuple using os.path.split: os.path.split('/home/k/TEST/PYTHON/p.py')('/home/k/TEST/PYTHON', 'p.py')If we want to combine and make a full path: os.path.join('/home/k/TEST/PYTHON', 'p.py')'/home/k/TEST/PYTHON/p.py'. : Common pathname manipulations: import os print( os.getcwd)C:Python32 curdir = os.curdir print(curdir). scriptsdir = os.path.join(os.curdir, 'ToolsScripts') print(scriptsdir).ToolsScripts diffpy = os.path.join(scriptsdir, 'diff.py') print(diffpy).ToolsScriptsdiff.py os.path.basename(diffpy)' diff.py' os.path.splitext(diffpy)('.ToolsScriptsdiff', '.py')The os.path.join function constructs a pathname out of one or more partial pathnames. Range vs xrange sum(range(1,101))5050 sum(xrange(1,101))5050range returns a list to the sum function containing all the numbers from 1 to 100.But xrange returns an iterator rather than a list, which makes it more lighter in terms of memory use as shown below. range(1,5)1, 2, 3, 4 xrange(1,5)xrange(1, 5)Note: Since the xrange is replaced with range in Python 3.x, we should use range instead for compatibility.
The range in Python 3.x just returns iterator. That means it does not produce the results in memory any more, and if we want to get list from range, we need to force it to do so:list(range(.)). GeneratorsGenerators allow us to declare a function that behaves like an iterator, i.e. It can be used in a for loop. Manipulating functions as first-class objectsFunctions as first-class objects?That means we can pass them around as objects and can manipulate them.
In other words, most of the times, this just means we can pass these first-class citizens as arguments to functions, or return them from functions. Everything in Python is a proper object.
Even things that are 'primitive types' in other languages: dir (100)'abs', 'add', 'and', 'class', 'cmp', 'coerce','delattr', 'div', 'divmod', 'doc', 'float'.' Numerator', 'real'Functions have attributes and can be referenced and assigned to variables.
def one(arg):'I am a function returning arg I received.' 'return arg one(1)1 one One = one One one.doc'I am a function returning arg I received.' Docstrings vs commentsA docstring is the documentation string for a function. We use it as shown below:functionname.docWe can declare it like this:def myfunction:'our docstring 'or:def myfunction:'our docstring 'Everything between the triple quotes (with double quotes, ' or with single quotes,') is the function's docstring, which documents what the function does. A docstring, if it exists, must be the first thing defined in a function.
In other words, it should appear on the next line after the function declaration. We don't technically need to give our function a docstring, but we always should. The docstring will be available at runtime as an attribute of the function.Writing documentation for our program this way makes the code more readable.
We can also use comments for clarification of what the code is doing. In general, docstrings are for documentation, comments are for a code reader. Monkey-patchingThe origin of monkey-patch according to is:'The term monkey patch seems to have come from an earlier term, guerrilla patch, which referred to changing code sneakily at runtime.
The word guerrilla, homophonous with gorilla, became monkey, possibly to make the patch sound less intimidating.' UsingPython supports the creation of anonymous functions (i.e. Functions that are not bound to a name) at runtime, using a construct called lambda. This is not exactly the same as lambda in functional programming languages such as Lisp, but it is a very powerful concept that's well integrated into Python and is often used in conjunction with typical functional concepts like filter, map and reduce.The following code shows the difference between a normal function definition, func and a lambda function, lamb: def func(x): return x. 3 print(func(5))125 lamb = lambda x: x.
3 print(lamb(5))125As we can see, func and lamb do exactly the same and can be used in the same ways. Note that the lambda definition does not include a return statement - it always contains an expression which is returned. Also note that we can put a lambda definition anywhere a function is expected, and we don't have to assign it to a variable at all.The lambda's general form is:lambda arg1, arg2.argN: expression using argumentsFunction objects returned by running lambda expressions work exactly the same as those created and assigned by defs. However, there are a few differences that make lambda useful in specialized roles:. lambda is an expression, not a statement.Because of this, a lambda can appear in places a def is not allowed.
For example, places like inside a list literal, or a function call's arguments. As an expression, lambda returns a value that can optionally be assigned a name. In contrast, the def statement always assigns the new function to the name in the header, instead of returning is as a result. lambda's body is a single expression, not a block of statements.The lambda's body is similar to what we'd put in a def body's return statement. We simply type the result as an expression instead of explicitly returning it.
Because it is limited to an expression, a lambda is less general that a def. We can only squeeze design, to limit program nesting. Lambda is designed for coding simple functions, and def handles larger tasks. def f(x, y, z): return x + y + z f(2, 30, 400)432We can achieve the same effect with lambda expression by explicitly assigning its result to a name through which we can call the function later: f = lambda x, y, z: x + y + z f(2, 30, 400)432Here, the function object the lambda expression creates is assigned to f. This is how def works, too.
But in def, its assignment is an automatic must.For more, please go to. Properties vs Getters/SettersWe have more detailed discussion in.In general, properties are more flexible than attributes. That's because we can define functions that describe what is supposed to happen when we need setting, getting or deleting them. If we don't need this additional flexibility, we may just use attributes since they are easier to declare and faster.However, when we convert an attribute into a property, we just define some getter and setter that we attach to it, that will hook the data access. Then, we don't need to rewrite the rest of our code, the way for accessing the data is the same, whatever our attribute is a property or not.
Classmethod vs staticmethodFrom the on @classmethod: classmethod(function)Return a class method for function.A class method receives the class as implicit first argument,just like an instance method receives the instance.To declare a class method, use this idiom:class C:@classmethoddef f(cls, arg1, arg2.).The @classmethod form is a function decorator.It can be called either on the class (such as C.f) or on an instance (such as C.f).The instance is ignored except for its class. What is map?The syntax of is:map(aFunction, aSequence)The first argument is a function to be executed for all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. def cubic(x):return x.x.x items = x for x in range(11) if x% 2 0 list(map(cubic, items))0, 8, 64, 216, 512, 1000 list(map(lambda x,y: x.y, 1,2,3, 4,5,6))4, 10, 18map is similar to list comprehension but is more limited because it requires a function instead of an arbitrary expression. What is filter and reduce?Just for comparison purpose, in the following example, we will include map as well. integers = x for x in range(11) filter(lambda x: x% 2 0, integers)0, 2, 4, 6, 8, 10 map(lambda x: x.2, integers)0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 reduce(lambda x, y: x + y, integers)55In the above example, we defined a simple list of integer values, then we use the standard functions filter, map and reduce to do various things with that list.
All of the three functions expect two arguments: A function and a list.In the first example, filter calls our lambda function for each element of the list, and returns a new list that contains only those elements for which the function returned 'True'. In this case, we get a list of all even numbers.In the second example, map is used to convert our list. The given function is called for every element in the original list, and a new list is created which contains the return values from our lambda function.
In this case, it computes x^2 for every element.Finally, reduce is somewhat special. The function for this one must accept two arguments (x and y), not just one. The function is called with the first two elements from the list, then with the result of that call and the third element, and so on, until all of the list elements have been handled. This means that our function is called n-1 times if the list contains n elements. The return value of the last call is the result of the reduce construct. In the above example, it simply adds the arguments, so we get the sum of all elements.
Difference between remove, del and pop on listsTo remove a list element, we can use either the del statement if we know exactly which element(s) we are deleting or the remove method if we do not know.list.remove(element), del list(index), list.pop(index)remove removes the first matching value, not a specific index: a = 5,6,7,7,8 a.remove(7) a5, 6, 7, 8Both del and pop work on index: a = 5,6,7,7,8 del a1 a5, 7, 7, 8 a = 5,6,7,7,8 a.pop(1)6 a5, 7, 7, 8 a = 5,6,7,7,8 a.pop(a.index(6)) # get the index for 66 a5, 7, 7, 8.