Skip to main content

Posts

Showing posts with the label python

Python — Simplifying Decorators

🐍 Decorators can be complex. But if you study the following, you will understand it in the best form. Step 1: Create Function Input def my_function(): print('Step 1: Create first function') my_function() Output Step 1: Create first function Step 2: Create Decorator Input def my_decorator(func): print('Step 2: Create a decorator. A decorator is a function') func() print('Step 3: Call first function') @my_decorator def my_function(): print('Step 1: Create first function') my_function() Output Step 2: Create a decorator. A decorator is a function Step 1: Create first function Step 3: Call first function Step 3: Add a function and  decorator within the decorator Input import functools def my_decorator(func): @functools.wraps(func) def func_that_runs_func(): print('Step 2: Create a decorator. A decorator is a function') func() print('Step 3: Call first function...

Python - List - Append, Count, Extend, Index, Insert, Pop, Remove, Reverse, Sort

🐍 Advance List List is widely used and it's functionalities are heavily useful. Append Adds one element at the end of the list. Syntax list1.append(value) Input l1 = [1, 2, 3] l1.append(4) l1 Output [1, 2, 3, 4] append can be used to add any datatype in a list. It can even add list inside list. Caution: Append does not return anything. It just appends the list. Count .count(value) counts the number of occurrences of an element in the list. Syntax list1.count(value) Input l1 = [1, 2, 3, 4, 3] l1.count(3) Output 2 It returns 0 if the value is not found in the list. Extend .count(value) counts the number of occurrences of an element in the list. Syntax list1.extend(list) Input l1 = [1, 2, 3] l1.extend([4, 5]) Output [1, 2, 3, 4, 5] If we use append, entire list will be added to the first list like one element. Extend, i nstead of considering a list as one element, it joins the two lists one after other. Append works in the following way. Input l1 = [1, 2, 3] l1.append([4, 5]) Output...

Python - Dictionary - Comprehension, Iteration, Items, Keys, Values

🐍 Advance Dictionaries There is very little one can do with dictionaries. Dictionaries are very useful, but because of their relatively complex state, very few modifications can be done in simple ways. Here are a couple of things you do with dictionaries. Dictionary Comprehension Just like List Comprehensions, Dictionary Data Types also support their own version of comprehension for quick creation. It is not as commonly used as List Comprehensions. Here is an example of Dictionary Comprehension. Input d = {x:x**2 for x in range(10)} d Output {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} Another example where we pick keys from one place and values from another. Input d = {k:v**2 for k,v in zip(['a','b','c','d','e','f','g','h','i','j'],range(10))} d Output {'a': 0, 'b': 1, 'c': 4, 'd': 9, 'e': 16, 'f': 25, 'g': 36, 'h': 49, ...

Python - Set Functions - add, clear, difference, discard, intersection, checks, union, update

🐍 Advanced Sets Let's create a blank set and learn by example. Input s = Set() Add Elements to Set Input s.add(1) s.add(2) s Output {1, 2} This adds new elements to our existing set. Clear Input s.clear() s Output set() This empties the set. It deletes all elements. Copy Input s = {1,2,3} sc = s.copy() print(s,sc) Output {1, 3, 4} {1, 2, 3} This copies elements from one set to another. Difference Syntax set1.difference(set2) Input s.add(4) s.difference(sc) Output {4} This returns elements that are not common in the two sets. Difference Update Syntax set1.difference_update(set2) Input s1 = {1,2,3} s2 = {1,4,5} s1.difference_update(s2) s1 Output {2, 3} This updates set1 to the difference between set1 and set2. Discard Syntax set.discard(element) Input s = {1,2,3,4} s.discard(2) s Output {1, 3, 4} This deletes an element from the set, if that element exists in the set. Intersection Syntax set1.intersection(set2) Input s1 = {1,2,3} s2 = {2,3,4} s1.intersection(s2) Output {2, 3} It ret...

Python - Mathematical Functions - Hexadecimal, Binary, Exponential, Absolute, Round

🐍 Some mathematical functions are in-built in python. Here are some of them. Convert Decimal to Hexadecimal hex(246) Output: '0xf6' hex(512) Output: '0x200' 0x is prefix to all hexadecimal numbers in output. The number after 0x is the hexadecimal value. Convert Decimal to Binary bin(1234) Output: '0b10011010010' bin(246) Output: '0b11110110' bin(512) Output: '0b1000000000' Exponential Function pow() function is similar to num1**num2, but it comes useful when you want to execute (num1**num2)%num3. Passing three arguments to pow(), does this. pow(3,4) Output: 81 This works just like 3**4 pow(3,4,5) Output: 1 But this, works equivalent to (3**4)%5. Either of the two ways can be used. At this point I feel (3**4)%5 is better, as anybody reading the code will understand what is being done immediately. While with pow(2,3,4), the person may have to refer to documentation to understand how this function works. Absolute Value The function abs() is used ...

Python - StringIO - Treat Text Like File

🐍 At times we need a file to run a code. Python allows you to treat a text/string like a file for that purpose. It is not really a file, but it lets you treat it that way. You need a module called StringIO for it. Use Jupyter Notebooks to run the following code. StringIO Let's begin by importing StringIO import io Next, we create a string and store it in a variable. message = 'This is just a normal string.' Let's apply StringIO magic to it and make it look like a file. f = io.StringIO(message) Now, we can do all file operations on it. Like read f.read() Output: 'This is just a normal string.' Like Write f.write(' Second line written to file like object') Output: 40 Like moving cursor to a location in the file f.seek(0) Output: 0 Like read again f.read() Output: 'This is just a normal string. Second line written to file like object' Like closing the file f.close() After closing 'f' cannot carry out the file functions.

Python - Parsing or Regular Expression or Regex or RE (search, split, findall)

🐍  Parsing is way too simple in python. Basic parsing is done using the library re (Regular Expression). TRY ON JUPYTER NOTEBOOK Following should be the first line to start using functionalities of Regular Expressions: import re re.search(pattern, text) import re text = 'This is a string with term1, but it does not have the other term.' pattern = 'term1' print(re.search(pattern, text)) This will search 'term1' in the text and return Details, since it found it in the text. import re text = 'This is a string with term1, but it does not have the other term.' pattern = 'term2' print(re.search(pattern, text)) This will search 'term2' in the text and return 'None', since it didn't find it. re.search(pattern, text).start() It return the position of the first character of the pattern you are searching in the text. import re text = 'This is a string with term1, but it does not have the other term...

Python - .strip(), .capitalize(), .title(), .spit()

🐍 .strip() removes certain characters from both ends of the string. .capitalize() capitalizes the first letter of the string and sets the rest of the string to lower case. .title() capitalizes first letter of every word in the string. Example Run the following code in Jupyter notebook and you will see how each of the above functions work. a = "   john SNOW   " b = "0000CAEsy0james00" print(a.strip().capitalize()+" loves "+b.strip('0').title()) .strip() .strip() removes all spaces from the front and back of a string. Not the spaces in between. .strip() has default argument as space, i.e. ' '. But if you pass another character, it will look for that character in front and back of the string and remove it. For example, if you run print('0000James0Cameron000'.strip('0')) , it will remove all 0s from front and back and print ' James0Cameron '. Note that the 0 in between remains as it is. You can pass a string too. Exa...