Advertisement
harshtrivedi

Untitled

Jan 16th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.07 KB | None | 0 0
  1. # Resources:
  2. # Minimal Python Datastructures and Algorithms examples: https://github.com/keon/algorithms
  3. #
  4. #
  5.  
  6. "harsh trivedi".capitalize() #=> "Harsh trivedi"
  7. "harsh trivedi".upper() #=> 'HARSH TRIVEDI'
  8. "Harsh Trivedi".lower() #=> 'harsh trivedi'
  9.  
  10. "harsh"[start:end:hop]
  11. "harsh"[start:end:hop]
  12. # hop can be -ve as well, in which case it starts from end
  13.  
  14. some_string[-1]    # last item in the array
  15. some_string[-2:]   # last two items in the array
  16. some_string[:-2]   # everything except the last two items
  17.  
  18.    
  19. some_string[::-1] # To reverse the string
  20.  
  21.  
  22. # Destructive Sort
  23. sorted([4,1,2,3])
  24. # > [1,2,3,4]
  25.  
  26. sorted( [4,1,2,3] , key = lambda x: x, reverse = True)
  27. # > [4,3,2,1]
  28.  
  29. # Inplace Sort
  30. array = [4,1,2,3]
  31. array.sort()
  32.  
  33.  
  34. array = [4,1,2,3]
  35. array.index(2)
  36.  
  37.  
  38. array = [4,1,2,3]
  39. array.pop() #> 3
  40. # array => [4,1,2]
  41.  
  42. array = [0,1,2,3,4,5,6]
  43. array.pop(3) #> 3
  44. # array => [0,1,2,4,5,6]
  45.  
  46. array = [0,1,2,3,4,5,6]
  47. array.pop(-1) #> 6
  48. # array => [0,1,2,4,5]
  49.  
  50.  
  51. range(15)
  52. # [0, 1, 2 ... 14]
  53.  
  54.  
  55. import random
  56. random.random() #> random number in 0-1
  57. random.randint(1,100) # randome integer between 1 to 100
  58.  
  59.  
  60. import re
  61. line = "Cats are smarter than dogs"
  62. match = re.match( r'(.*) are (.*?) .*', line )
  63. print "match.group({})".format( match.group(1) )
  64. # match.group(0)   #=> Cats are smarter than dogs
  65. # match.group(1)   #=> Cats
  66. # match.group(2)   #=> smarter
  67. # match.group(3)   #=> Error !
  68.  
  69.  
  70. math.abs()
  71. math.ceil()
  72. math.floor()
  73.  
  74. map_plus_one = [x+1 for x in range(10)]
  75. map_plus_one = map( lambda x: x+1, range(10))
  76.  
  77.  
  78.  
  79.  
  80.  
  81. # set intersection of list
  82. intersection = set.intersection(set(list1), set(list2))
  83. union = set.union(set(list1), set(list2))
  84. difference = set.difference(set([1,2,3,4]), set([2,3,4,5]))
  85.  
  86.  
  87. # split by constant string
  88. "harsh trivedi".split() #=> ['harsh', 'trivedi']
  89. "harsh trivedi".split(' ') #=> ['harsh', 'trivedi']
  90.  
  91. # split by regex
  92. re.split(" +", "harsh    trivedi")  #=> ['harsh', 'trivedi']
  93.  
  94.  
  95. # replace by constant string
  96. "harshtrivedi".replace("trivedi", '') #=> 'harsh'
  97.  
  98. # replace regex by string
  99. re.sub( ' +', ' ', 'harsh    trivedi') #=> 'harsh trivedi'
  100.  
  101. # replace regex by what was captured
  102. processed = re.sub( '(\w+) + (\w+)', r'\1 \2', 'harsh    trivedi' )
  103. #=> harsh trivedi
  104.  
  105.  
  106. # find all matches of regex match in a list
  107. re.findall( 'har?sh', "harsh trivedi harsh trivedi harsh trivedi trivedi harsh")
  108. # => ['harsh', 'harsh', 'harsh', 'harsh']
  109.  
  110.  
  111. # flatten list
  112. [ element for sub_list in nested_array for element in sub_list]
  113.  
  114. # Deep Flatten List:
  115. def flatten(lol):
  116.     return sum( [flatten(l) for l in lol ], [] ) if isinstance( lol, (tuple,list) ) else [lol]
  117.  
  118. # multi level list comprehension
  119. non_primes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
  120. right_triangle_triples = [(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2 + y**2 == z**2]
  121.  
  122. add_one  = map(lambda x: x+1, [1,2,3,4,5] )
  123. even     = filter(lambda x: x%2==0, [1,2,3,4,5] )
  124. addition = reduce(lambda x,y: x+y, [47,11,42,13])
  125.  
  126. # reduce takes one additional start (optional) parameter:
  127. reduce(lambda x,y: x+y, [1,2,3,4] )    #=> 10
  128. reduce(lambda x,y: x+y, [1,2,3,4], 0 ) #=> 10
  129. reduce(lambda x,y: x+y, [1,2,3,4], 1 ) #=> 11
  130.  
  131. # reduce can be applied to lists as well:
  132. reduce(lambda x,y: x+y, [[1],[2],[3],[4]], [] )  #=> [1, 2, 3, 4]
  133. reduce(lambda x,y: x+y, [ 'har', 'sh', 'tr', 'ivedi'], '' ) #=> harshtrivedi
  134.  
  135. reduce(lambda x,y: x*y, [ 1, 2, 3, 4, 5], 1) #=> 12-
  136.  
  137. # building product lambda from above:
  138. product = lambda l: reduce(lambda x,y: x*y, l, 1)
  139. product([ 1, 2, 3, 4, 5]) #=> 120
  140.  
  141. "harshtrivedi".find('trivedi') #=> 5
  142. "harshtrivedi".find('xyz') #=> -1
  143.  
  144. "harshtrivedi".index('trivedi') #=> 5
  145. "harshtrivedi".index('xyz') #=> Error!
  146.  
  147. # Note that find finds first occurrence from left. There is rfind as well (but index is always from left)
  148. path = 'toto.titi.tata..xls'
  149. path.find('.')  #=> 4
  150. path.rfind('.') #=> 15
  151.  
  152. # enumerate with index [Default it starts from 0 index]
  153. for index, element in enumerate(array):
  154.     print (index, element)
  155.  
  156. # enumerate with some other index k
  157. for index, element in enumerate(array, k):
  158.     print (index, element)
  159.  
  160. # Set X is subset of Set Y
  161. set(X) <= set(Y)
  162.  
  163.  
  164. { "{}".format(i) for i in range(2, 10) }    # => is set
  165. { "{}".format(i):i for i in range(2, 10) }  # => is dict
  166.  
  167. # Using Lambda Functions:
  168. lambda_sum = lambda arg1, arg2: arg1 + arg2;
  169. print lambda_sum( 10, 20 )
  170.  
  171. # btw, sum is present inbuilt
  172. sum([1,2,3,4,5]) #= 15
  173. # you can pass second argument on tell it where to start from
  174. sum([1,2,3,4,5], 10) #= 25
  175. # Interestingly it can sum lists using + operatros as well
  176. sum([ [1], [2,3,4], [5], [6] ], []) #=> [1,2,3,4,5,6]
  177.  
  178. # But this doesn't apply to strings. Use ''.join([ ... ]) instead
  179. sum([ 'one', 'two', 'three', 'four' ], "") #=> ERROR!!!
  180.  
  181.  
  182.  
  183.  
  184. " ".join( ["1", "2", "3"] )     # => '1 2 3'
  185. " ".join( [1, 2, 3] )           # => Error !
  186. " ".join( map(str, [1, 2, 3]) ) # => '1 2 3'
  187.  
  188. # Using map/filter/reduce with instance method is also possible.
  189. map(lambda foo: foo.get_bar(), foos) # get_bar() is an instance method of foo: Usage: foo.get_bar()
  190. map(bar, foos) # bar() is method in main: Usage: bar(foo)
  191.  
  192.  
  193. # Some Useful List Comprehensions
  194. # To split list / string in chunks of size k
  195. [my_string[i:i + k] for i in xrange(0, len(my_string), k)]
  196.  
  197.  
  198. # Note: (for i in range(10))
  199. # returns an generator. So you can do:
  200. iterator = (for i in range(10))
  201. iterator.next() #=> 0
  202. iterator.next() #=> 1
  203. iterator.next() #=> 2
  204.  
  205.  
  206.  
  207. # Read File Lines:
  208. with open("filename", 'r') as f:
  209.     for line in f.readlines():
  210.         line.strip()
  211.         # operate on line here
  212.  
  213. # Write File:
  214. with open("filename", 'w') as f:
  215.     f.write( "\n".join(lines) )
  216.  
  217.  
  218. # Actual Default Dicts:
  219. from collections import defaultdict
  220.  
  221. someddict = defaultdict(int)
  222. someddict[1] #=> 0
  223. someddict[3] += 1
  224. someddict[1] #=> 1
  225.  
  226. someddict = defaultdict(list)
  227. someddict[1] #=> []
  228. someddict[1].append(3)
  229. someddict[1] #=> [3]
  230.  
  231.  
  232. someddict = defaultdict(dict)
  233. someddict[1] #=> {}
  234. someddict[1][3] = "Three"
  235. someddict[1] #=> {3: 'Trhee'}
  236.  
  237.  
  238. # Counting
  239. count_dict = {}
  240. colors = ['blue', 'green', 'red', 'green', 'blue']
  241. for color in colors:
  242.     count_dict[color] = count_dict.get(color, 0) + 1
  243. # count_dict => {'blue': 2, 'green': 2, 'red': 1}
  244.  
  245.  
  246.  
  247.  
  248. # Using Else with For !: Else block will be executed if for didn't break anywhere
  249. for n in range(2, 10):
  250.     for x in range(2, n):
  251.         if n % x == 0:
  252.             print( n, 'equals', x, '*', n/x)
  253.             break
  254.     else:
  255.         # loop fell through without finding a factor
  256.         print(n, 'is a prime number')
  257.  
  258.  
  259. # Append for unique Default
  260. dict_list = {}
  261. colors = ['blue', 'green', 'red', 'green', 'blue']
  262. for color in colors:
  263.     dict_list[color] = dict_list.get(color, []) + [color]
  264. # dict_list => {'blue': ['blue', 'blue'], 'green': ['green', 'green'], 'red': ['red']}
  265.  
  266.  
  267. dictionary = { 1: 'one', 2: 'two', 3: 'three'}
  268. # iterating dicts
  269. for key, val in dictionary.iteritems():
  270.     print '({}, {})'.format(key, val)
  271. dictionary.items() #=> [(1, 'one'), (2, 'two'), (3, 'three')]
  272.  
  273.  
  274.  
  275. # convert dict to list
  276. list_dict = [(1, 'one'), (2, 'two'), (3, 'three')]
  277. dict(list_dict) #=> { 1: 'one', 2: 'two', 3: 'three'}
  278.  
  279. list_dict = [[1, 'one'], [2, 'two'], [3, 'three']]
  280. dict(list_dict) #=> { 1: 'one', 2: 'two', 3: 'three'}
  281.  
  282.  
  283.  
  284. # Set A is Subste of Set B:
  285. set(A) <= set(B)
  286.  
  287. # clear unicode ...
  288. #
  289.  
  290.  
  291. # Dict Comprehensions
  292. list_dict = [(1, 'one'), (2, 'two'), (3, 'three')]
  293. {key: value for (key, value) in list_dict } # {1: 'one', 2: 'two', 3: 'three'}
  294.  
  295. # Set Comprehensions
  296. set_comp = {key for key in iterable}
  297. {key for key in [1,2,3,4,5,6,3,2,4,5,1] } #=> set([1, 2, 3, 4, 5, 6])
  298.  
  299.  
  300. # check if string is substring
  301. "harsh" in "harsh trivedi" #=> True
  302. "xyz" in "harsh trivedi" #=> False
  303.  
  304. # substring count by constant string
  305. "harsh trivedi harsh trivedi harsh".count('harsh')
  306.  
  307. # substring count by regex match
  308. len(re.findall( 'h?r?sh', "harsh trivedi harsh trivedi harsh trivedi trivedi harsh")) #=> 3
  309. # finditer can also be used
  310.  
  311. # Count
  312. List.count(K) # Counts occurrences of K in list L
  313.  
  314.  
  315.  
  316.  
  317. # String Formatters
  318. "%.3f"   % 1      #=> 1.000
  319. "%03d"   % 1      #=> 001
  320. "%03d"   % 1      #=> 001
  321. "%-3d"   % 1      #=> '1  '
  322. "%03d"   % 341    #=> 341
  323.  
  324.  
  325. # Insert element in list at specific index
  326. array = [1,2,4,5]
  327. array.insert(2,3) # Returns None
  328. # array #=> [1, 2, 3, 4, 5]
  329.  
  330. # Bisect the sorted list
  331. import bisect
  332. sorted_array = [1, 2, 3, 4, 5, 6, 7]
  333. appr_index = bisect.bisect( sorted_array, 4.5)
  334. # is equivalent to
  335. sorted_array = [1, 2, 3, 4, 5, 6, 7] ; f = 4.5
  336. appr_index = next( ( i for i, e in enumerate(sorted_array) if e >= f), None )
  337.  
  338.  
  339. # Maintaining sorted array from scratch
  340. sorted_array = []
  341. for _ in range(10):
  342.     k = random.randint(1, 10)
  343.     index = bisect.bisect(sorted_array, k)
  344.     sorted_array.insert(index, k)
  345. # sorted_array #=>? [2, 2, 3, 3, 4, 5,7,8,10]
  346.  
  347.  
  348. # Strange But (might be) Useful
  349. 3 + (2>1) #= 4
  350. 3 + (False) #= 3
  351.  
  352.  
  353. # Dict Construction from key and val lists:
  354. my_dict = dict(zip(keyslist, valslist))
  355.  
  356. my_dict.copy( ) # shallow copy of dict
  357. my_dict1.update(my_dict2) # dict merging
  358.  
  359. my_dict.has_key('eggs') # check membership of eggs
  360.  
  361.  
  362. # Given path. create all sub-directories as required:
  363. if not os.path.exists(directory):
  364.     os.makedirs(directory)
  365.  
  366.  
  367. # Remove by val in list:
  368. some_list = [1,2,3,4,5,2]
  369. some_list.remove(2)
  370. # => some_list = [1,3,4,5,2]
  371. updated_list = filter(lambda e: e != 2, some_list)
  372. # => updated_list = [1,3,4,5]
  373.  
  374.  
  375. # remove element at given index:
  376. some_list = [4,3,1,5,2]
  377. del_index = 3
  378. del some_list[del_index]
  379. #=> some_list = [4,3,1,2]
  380.  
  381. # remove elements by list of indices
  382. some_list = [4,3,1,5,2]
  383. del_indices = [2,1,4]
  384. for del_index in del_indices:
  385.     some_list[del_index] = None
  386. del_list = filter(bool, some_list)
  387.  
  388.  
  389. # iterate through all the files in pattern of path
  390. import glob
  391. for img in glob.glob("some_path/*.jpg"):
  392.     # process img
  393.     pass
  394.  
  395. # Using Collections:
  396.  
  397. import collections
  398. defaultdict
  399.  
  400. ordereddict
  401.  
  402. dequeue
  403.  
  404.  
  405. counter
  406.  
  407.  
  408. Others:
  409.  
  410. glob
  411. shutil
  412.  
  413.  
  414. # Object Oriented Python
  415. # Amazing post here (Covers everything)
  416. # https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/
  417.  
  418.  
  419. class Car(object):
  420.     wheels = 4                      # Class Attribute
  421.     def __init__(self, make, model):
  422.         self.make = make
  423.         self.model = model
  424.  
  425.     def __str__(self):  #
  426.         return "({}):({})".format(self.make, self.model)
  427.  
  428.     @staticmethod
  429.     def make_car_sound():           # Class Method
  430.         print 'VRooooommmm!'
  431.  
  432.     def full_name(self):            # Instance Method
  433.         return "Model: {}  ; Make: {}".format( self.model, self.make)
  434.  
  435. car = Car('Ford', 'Mustang')
  436. print car.wheels  #=> 4
  437. print Car.wheels      #=> 4
  438. Car.wheels = 3
  439. print Car.wheels  #=> 3
  440. Car.make_car_sound()  #= 'VRooooommmm!'
  441. print car             #= '(Ford):(Mustang)'
  442. str(car)              #=> '(Ford):(Mustang)'
  443. car.full_name()       #=> 'Model: Mustang  ; Make: Ford'
  444.  
  445. # ###########################
  446.  
  447. # Pick random element from a list
  448. import random
  449. random.sample(some_list, 1)[0]   #=> random element picked from list
  450. # Pick K random elements from a list
  451. random.sample(some_list, k) #=> list containing k random elements
  452. # shuffle a list (destructively)
  453. some_list = [1, 2, 3, 4, 5]
  454. random.shuffle(some_list)
  455. # some_list #=> [4, 3, 2, 1, 5]
  456.  
  457.  
  458. # Itertools:
  459.  
  460. itertools.groupby( 'AAAABBBCCDAABBB' ) #=> returns generator with following properties
  461. # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
  462. # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
  463.  
  464. # Functional Python Awesomeness:
  465. # http://kachayev.github.io/talks/uapycon2012/#/1
  466.  
  467. # Ruby equivalent of compact
  468. filter(bool, [1,2, "", None, [ ] ]) #=> [1, 2]
  469.  
  470. bool("")   #=> False
  471. bool([])   #=> False
  472. bool(None) #=> False
  473.  
  474. # Todo : https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression
  475. # IterTools: https://docs.python.org/2/library/itertools.html
  476. # BitOperations: http://www.onjava.com/pub/a/python/excerpt/PythonPocketRef/index.html
  477. # Mutation: http://book.pythontips.com/en/latest/mutation.html
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement