Advertisement
Guest User

Python Tricks

a guest
Oct 21st, 2017
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.92 KB | None | 0 0
  1. # Some neat tricks for programming in Python
  2.  
  3. # sum()
  4.  
  5. # In your program, you're probably going to have something like
  6.  
  7. # set some initial value to 0
  8. sm = 0
  9.  
  10. # begin for loop
  11. for i in range(1, n+1):
  12. # repeatedly add number to initial value
  13. sm += i
  14.  
  15. # That entire block of code can be reduced into a single line using the sum() function
  16.  
  17. sm = sum(range(1, n+1))
  18.  
  19. # There isn't a product() function in Python, sadly, though you can implement your own if you read to the end.
  20.  
  21. # Inline if-else statements
  22.  
  23. # If you have a really simple if-else, like
  24.  
  25. if somethingIsTrue:
  26. return trueVal
  27. else:
  28. return falseVal
  29.  
  30. # that can be simplified into
  31. return trueVal if somethingIsTrue else return falseVal
  32.  
  33. # There must always be an 'else' in these statements, you cannot just have an if.
  34.  
  35. # The syntax is a bit weird compared to the if-else statement (or similar expressions in other programming languages), but it reads just like English: "return this if the statement is true, otherwise return that"
  36.  
  37. # List comprehensions
  38.  
  39. # In mathematics, set-builder notation allows us to easily define sets of things. Python provides a simplified form of the syntax for us to use, in the form of list comprehensions. For example, the list of squares of even numbers less than 16 can be expressed as
  40.  
  41. [ x**2 for x in range(1,16) if x%2 == 0 ]
  42.  
  43. # The first part of a list comprehension is the result, i.e. what you want to fill the list with. The 'for x in list' statements are identical to those you find in for loops, and specify which lists of things we want to take elements from. Finally, the if-statements only add an element to the list comprehension if the predicate returns true.
  44.  
  45. # The above is simply a nicer way of stating:
  46.  
  47. reslist = []
  48. for x in range(1,16):
  49. if(x%2 == 0):
  50. reslist += [x**2]
  51.  
  52. # So, the general form for a list comprehension is:
  53.  
  54. [ modifiedListElement for eachElement in list if predicateIsTrue]
  55.  
  56. # which is equivalent to
  57.  
  58. modifiedList = []
  59. for eachElement in list:
  60. if predicate(eachElement):
  61. modifiedList.append(modifiedListElement)
  62.  
  63. # List comprehensions are tremendously powerful. For example, a list of the first n triangular numbers:
  64.  
  65. [ (x/2) * (x+1) for x in range(1, n+1)]
  66.  
  67. # Because list comprehensions are lists like any other, we can toss them into the sum() function with ease:
  68.  
  69. sum([ (x/2) * (x+1) for x in range(1, n+1)])
  70.  
  71. # List comprehensions can draw from multiple lists if you work with multiple for..in statements, so we can use them to make a list of Pythagorean triples:
  72.  
  73. [ (a,b,c) for c in range(1, n+1) for b in range(1, c) for a in range(1, b) if a**2 + b**2 == c**2 ]
  74.  
  75. # which is equivalent to
  76.  
  77. reslist = []
  78. for c in range(1, n+1):
  79. for b in range(1, c):
  80. for a in range(1, b):
  81. if a**2 + b**2 == c**2:
  82. reslist += [(a,b,c)]
  83.  
  84. # ADVANCED: Lambda functions, map(), filter(), reduce()
  85.  
  86. # Here there be dragons. If you're lost here, I don't blame you. The following functions are redundant if you know how to use list comprehensions, but if you're really curious...
  87.  
  88. # Lambda functions are tiny little nameless functions that only return a single expression.
  89.  
  90. lambda a1, a2: # do something with arguments
  91.  
  92. # They are useful if you need to make a tiny function that you don't want to give an actual name or use elsewhere in your program. Most of the time, you'll need to use lambda functions for the next three functions we'll cover- map(), filter(), and reduce().
  93.  
  94. # map()
  95.  
  96. # map() applies a function of a single argument to each element of a list. In terms of list comprehensions, that looks like the following:
  97.  
  98. map(f, list) = [ f(x) for x in list ]
  99.  
  100. # For example, we can make a lambda function that squares a number:
  101.  
  102. lambda x: x**2
  103.  
  104. # and put that in map()
  105.  
  106. map(lambda x: x**2, list)
  107.  
  108. # Quick note. If you try to look at the result of map() in IDLE, you'll probably get something that looks like
  109.  
  110. # >>> map(lambda x: x**2, range(1,11)) (my input)
  111. # => <map object at 0x7f582d04ce48> (result)
  112.  
  113. # which is something that's really weird and all you need to know is that you can turn it into a readable list using list()
  114.  
  115. # >>> list(map(lambda x: x**2, range(1,11)))
  116. # => [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  117.  
  118. # You won't need to do this if you're going to use it directly (in a for..in loop or in the sum() function) but if you just want to look at the result, keep that in mind.
  119.  
  120. # filter()
  121.  
  122. # filter() creates a new list that only contains elements that satisfy a predicate.
  123.  
  124. filter(pred, list) = [ x for x in list if pred(x) ]
  125.  
  126. # Similarly to map(), we can create a lambda function that returns a boolean value:
  127.  
  128. lambda x: x%2 == 0
  129.  
  130. # and use that with filter()
  131.  
  132. filter(lambda x: x%2 == 0, list)
  133.  
  134. # reduce()
  135.  
  136. # Finally, the scariest function of them all: reduce(). This will be kinda tough for me to explain so bear with me.
  137.  
  138. # So, you can define the sum() function as (roughly) this block of code:
  139.  
  140. def mySum(list):
  141. sm = 0
  142. for i in list:
  143. sm += i
  144. return sm
  145.  
  146. # What if we wanted to make a product() function?
  147.  
  148. def myProduct(list):
  149. prod = 1
  150. for i in list:
  151. prod *= i
  152. return prod
  153.  
  154. # Or find the largest element in a list?
  155.  
  156. def myMaximum(list):
  157. max = list[0] # first element of the list
  158. for i in list:
  159. if i > max:
  160. max = i
  161. return i
  162.  
  163. # If you squint really hard, you can implement map() and filter() like this:
  164.  
  165. def myMap(func, list):
  166. newList = []
  167. for i in list:
  168. newList.append(func(i))
  169. return newList
  170.  
  171. def myFilter(pred, list):
  172. newList = []
  173. for i in list:
  174. if pred(i):
  175. newList.append(i)
  176. return newList
  177.  
  178. # Notice a pattern? We start with an initial value (0, 1, the empty list) and supply a list of things and something to do to those things (add to the initial value, append to the list, compare with the initial value and replace it if it is greater, etc.) We repeatedly apply the function to the initial value and each element from the list, and return the result.
  179.  
  180. # Where we see a pattern in programming, we can abstract it. And we can abstract it with the simple, immensely powerful tool, reduce():
  181.  
  182. reduce(func, list, init)
  183.  
  184. # reduce() is equivalent to the following:
  185.  
  186. def myReduce(func, list, init):
  187. for v in list:
  188. func(init, v)
  189. return init
  190.  
  191. # reduce() takes a two-argument function (where the init is the first argument and the value from the list is the second argument), and applies it to the init value and each element of the list, from left to right. All the above functions listed can be expressed with reduce()
  192.  
  193. def mySum(list):
  194. return reduce(lambda i,v: i+v, list, 0)
  195.  
  196. def myProduct(list):
  197. return reduce(lambda i,v: i*v, list, 1)
  198.  
  199. # if you don't supply an 'init' argument to reduce, it just uses the first element of the list
  200. def myMaximum(list):
  201. return reduce(lambda i,v: i if v > i else v, list)
  202.  
  203. def myMap(func, list):
  204. return reduce(lambda i,v: i.append(func(v)), list, [])
  205.  
  206. def myFilter(p, list):
  207. return reduce(lambda i,v: i.append(v) if p(v) else i, list, [])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement