diff --git a/CONTRIBUTERS b/CONTRIBUTERS deleted file mode 100644 index 27f9ec5..0000000 --- a/CONTRIBUTERS +++ /dev/null @@ -1,2 +0,0 @@ -- brennerm -- agumonkey diff --git a/CONTRIBUTORS b/CONTRIBUTORS new file mode 100644 index 0000000..de493f1 --- /dev/null +++ b/CONTRIBUTORS @@ -0,0 +1,16 @@ +- brennerm +- agumonkey +- obeleh +- Prooffreader +- cgopalan (cgopalan.github.io) +- anabalica (ana-balica.github.io) +- dharmit (github.com/dharmit) +- shyboynccu (github.com/shyboynccu) +- illuz +- tutoringsteve +- Kzinglzy +- waveform80 (github.com/waveform80) +- thatneat (github.com/thatneat) +- bruno314 (github.com/bruno314) +- rickhau +- oztalha (github.com/oztalha) diff --git a/README.md b/README.md index 64c68f6..fe0478c 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,14 @@ Creating a knowledge base of unpopular Python built-in features to save a lot of ## Contribute Feel free to use the PyTrickBase.txt as a starting point. -1. Pull request -Send a pull request with your PyTrick, containing example code and a documentation one-liner. Be sure to add yourself to the contributers. +1. Pull request: -2. Issue comment -Add your Python snippet and your documentation as a comment on Issue#1. I will take care of adding your PyTrick and you as a contributer. + Send a pull request with your PyTrick, containing example code and a documentation one-liner. Be sure to add yourself to the contributors. + +2. Issue comment: + + Add your Python snippet and your documentation as a comment on Issue#1. I will take care of adding your PyTrick and you as a contributor. + +## Contact +1. message me at [@__brennerm](https://twitter.com/__brennerm) +2. send an email to xam.rennerb@gmail.com diff --git a/andorassignment.py b/andorassignment.py deleted file mode 100755 index de60714..0000000 --- a/andorassignment.py +++ /dev/null @@ -1,6 +0,0 @@ -#! /usr/bin/env python3 -"""conditional assignment with following structure - and or -""" -a = 1 -print(a < 0 and 'negative' or 'positive') diff --git a/argumentunpacking.py b/argumentunpacking.py index 0039d29..78c86ef 100755 --- a/argumentunpacking.py +++ b/argumentunpacking.py @@ -1,10 +1,10 @@ #! /usr/bin/env python3 """simple tuple and dictionary unpacking""" -def sum(a, b): - return a + b - +def product(a, b): + return a * b + argument_tuple = (1, 1) argument_dict = {'a': 1, 'b': 1} -print(sum(*argument_tuple)) -print(sum(**argument_dict)) \ No newline at end of file +print(product(*argument_tuple)) +print(product(**argument_dict)) diff --git a/cacheproperty.py b/cacheproperty.py new file mode 100644 index 0000000..562fc27 --- /dev/null +++ b/cacheproperty.py @@ -0,0 +1,29 @@ +class PropertyCache: + """ a decorator to cache property + """ + + def __init__(self, func): + self.func = func + + def __get__(self, obj, cls): + if not obj: + return self + value = self.func(obj) + setattr(obj, self.func.__name__, value) + return value + + +class Foo: + def __init__(self): + self._property_to_be_cached = 'result' + + @PropertyCache + def property_to_be_cached(self): + print('compute') + return self._property_to_be_cached + +test = Foo() + +print(test.property_to_be_cached) +print(test.property_to_be_cached) + diff --git a/calculator.py b/calculator.py new file mode 100755 index 0000000..882e2b2 --- /dev/null +++ b/calculator.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +""" +This program lets you create a simple command line calculator without using +the 'if..else' construct. It uses built-in 'operator' module to accomplish the +same + +Created with help of an answer on stackoverflow. Don't have the exact link. +""" + +import operator +ops = { + "+": operator.add, + "-": operator.sub, + "/": operator.truediv, + "*": operator.mul +} + +x = input("Enter an operator [OPTIONS: +, -, *, /]: ") +y = int(input("Enter number: ")) +z = int(input("Enter number: ")) + +print (ops[x](y, z)) diff --git a/concatenatestrings.py b/concatenatestrings.py new file mode 100755 index 0000000..fac8d55 --- /dev/null +++ b/concatenatestrings.py @@ -0,0 +1,7 @@ +#! /usr/bin/env python3 +"""Concatenate long strings elegantly +across line breaks in code""" + +my_long_text = ("We are no longer the knights who say Ni! " + "We are now the knights who say ekki-ekki-" + "ekki-p'tang-zoom-boing-z'nourrwringmm!") diff --git a/conditionalfunctioncall.py b/conditionalfunctioncall.py index 8564fd3..dc8c81f 100755 --- a/conditionalfunctioncall.py +++ b/conditionalfunctioncall.py @@ -1,10 +1,10 @@ #! /usr/bin/env python3 """calling different functions with same arguments based on condition""" -def sum(a, b): - return a + b - +def product(a, b): + return a * b + def subtract(a, b): return a - b - + b = True -print((sum if b else subtract)(1, 1)) \ No newline at end of file +print((product if b else subtract)(1, 1)) diff --git a/controlwhitespaces.py b/controlwhitespaces.py new file mode 100755 index 0000000..9fc9e94 --- /dev/null +++ b/controlwhitespaces.py @@ -0,0 +1,19 @@ +#! /usr/bin/env python3 +"""control the whitespaces in string""" + +s = 'The Little Price' + +# justify string to be at least width wide +# by adding whitespaces +width = 20 +s1 = s.ljust(width) +s2 = s.rjust(width) +s3 = s.center(width) +print(s1) # 'The Little Price ' +print(s2) # ' The Little Price' +print(s3) # ' The Little Price ' + +# strip whitespaces in two sides of string +print(s3.lstrip()) # 'The Little Price ' +print(s3.rstrip()) # ' The Little Price' +print(s3.strip()) # 'The Little Price' diff --git a/copylist.py b/copylist.py new file mode 100755 index 0000000..2328759 --- /dev/null +++ b/copylist.py @@ -0,0 +1,22 @@ +#! /usr/bin/env python3 +"""a fast way to make a shallow copy of a list""" + +a = [1, 2, 3, 4, 5] +print(a[:]) + +"""using the list.copy() method (python3 only)""" + +a = [1, 2, 3, 4, 5] + +print(a.copy()) + + +"""copy nested lists using copy.deepcopy""" + +from copy import deepcopy + +l = [[1, 2], [3, 4]] + +l2 = deepcopy(l) +print(l2) + diff --git a/dictsortbyvalue.py b/dictsortbyvalue.py new file mode 100755 index 0000000..16c5b29 --- /dev/null +++ b/dictsortbyvalue.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +""" Sort a dictionary by its values with the built-in sorted() function and a 'key' argument. """ + +d = {'apple': 10, 'orange': 20, 'banana': 5, 'rotten tomato': 1} +print (sorted(d.items(), key = lambda x: x[1])) + + +""" Sort using operator.itemgetter as the sort key instead of a lambda""" + + +from operator import itemgetter + + +print(sorted(d.items(), key=itemgetter(1))) + + +"""Sort dict keys by value""" + + +print(sorted(d, key=d.get)) diff --git a/dictswapkeysvalues.py b/dictswapkeysvalues.py new file mode 100755 index 0000000..73d2e9d --- /dev/null +++ b/dictswapkeysvalues.py @@ -0,0 +1,7 @@ +#! /usr/bin/env python3 +"""Swaps keys and values in a dict""" + +_dict = {"one": 1, "two": 2} +# make sure all of dict's values are unique +assert len(_dict) == len(set(_dict.values())) +reversed_dict = {v: k for k, v in _dict.items()} \ No newline at end of file diff --git a/listcompnestedfor.py b/listcompnestedfor.py new file mode 100644 index 0000000..4e94b41 --- /dev/null +++ b/listcompnestedfor.py @@ -0,0 +1,16 @@ +#! /usr/bin/env python3 +"""flattening nested lists of depth 2 within a single list comprehension with +multiple for loops""" + +l = [ + [1, 2, 3], + [4, 5, 6], + [7, 8], + [9] + ] + +print([ + j + for i in l + for j in i + ]) diff --git a/loopoverlappingdicts.py b/loopoverlappingdicts.py new file mode 100755 index 0000000..ec9d93c --- /dev/null +++ b/loopoverlappingdicts.py @@ -0,0 +1,8 @@ +#! /usr/bin/env python3 +"""loop over dicts that share (some) keys""" + +dctA = {'a': 1, 'b': 2, 'c': 3} +dctB = {'b': 4, 'c': 5, 'd': 6} + +for ky in set(dctA) & set(dctB): + print(ky) diff --git a/maxsplit.py b/maxsplit.py new file mode 100755 index 0000000..6c60b3b --- /dev/null +++ b/maxsplit.py @@ -0,0 +1,11 @@ +#! /usr/bin/env python3 +"""split a string max times""" +string = "a_b_c" +print(string.split("_", 1)) + + +"""use maxsplit with arbitrary whitespace""" + +s = "foo bar foobar foo" + +print(s.split(None, 2)) diff --git a/namedformatting.py b/namedformatting.py index 7924089..042538a 100755 --- a/namedformatting.py +++ b/namedformatting.py @@ -2,4 +2,14 @@ """easy string formatting using dicts""" d = {'name': 'Jeff', 'age': 24} -print("My name is %(name)s and I'm %(age)i years old." % d) \ No newline at end of file +print("My name is %(name)s and I'm %(age)i years old." % d) + +"""for .format, use this method""" + +d = {'name': 'Jeff', 'age': 24} +print("My name is {name} and I'm {age} years old.".format(**d)) + +"""dict string formatting""" +c = {'email': 'jeff@usr.com', 'phone': '919-123-4567'} +print('My name is {0[name]}, my email is {1[email]} and my phone number is {1[phone]}'.format(d, c)) + diff --git a/removeduplicatefromlist.py b/removeduplicatefromlist.py new file mode 100755 index 0000000..6286854 --- /dev/null +++ b/removeduplicatefromlist.py @@ -0,0 +1,16 @@ +#! /usr/bin/env python3 +"""remove duplicate items from list. note: does not preserve the original list order""" + +items = [2, 2, 3, 3, 1] + +newitems2 = list(set(items)) +print(newitems2) + +"""remove dups and keep order""" + +from collections import OrderedDict + +items = ["foo", "bar", "bar", "foo"] + +print(list(OrderedDict.fromkeys(items).keys())) + diff --git a/reverselist.py b/reverselist.py index 4a0016c..0fedc4e 100755 --- a/reverselist.py +++ b/reverselist.py @@ -2,3 +2,7 @@ """reverting list with special case of slice step param""" a = [5, 4, 3, 2, 1] print(a[::-1]) + +"""iterating over list contents in reverse efficiently.""" +for ele reversed(a): + print(ele) diff --git a/setglobalvariables.py b/setglobalvariables.py new file mode 100755 index 0000000..b80fb14 --- /dev/null +++ b/setglobalvariables.py @@ -0,0 +1,6 @@ +#! /usr/bin/env python3 +"""set global variables from dict""" + +d = {'a': 1, 'b': 'var2', 'c': [1, 2, 3]} +globals().update(d) +print(a, b, c) diff --git a/setoperators.py b/setoperators.py index 80a1431..18825f2 100755 --- a/setoperators.py +++ b/setoperators.py @@ -17,4 +17,27 @@ print(a ^ b) # Union -print(a | b) \ No newline at end of file +print(a | b) + +"""using methods instead of operators which take any iterable as a second arg""" + +a = {'a', 'b', 'c', 'd'} +b = {'c', 'd', 'e', 'f'} +c = {'a', 'c'} + +print(a.intersection(["b"])) + +print(a.difference(["foo"])) + +print(a.symmetric_difference(["a", "b", "e"])) + +print(a.issuperset(["b", "c"])) + +print(a.issubset(["a", "b", "c", "d", "e", "f"])) + +print(a.isdisjoint(["y", 'z'])) + +print(a.union(["foo", "bar"])) + +a.intersection_update(["a", "c", "z"]) +print(a) diff --git a/socketmsghandling.py b/socketmsghandling.py new file mode 100644 index 0000000..151e9ec --- /dev/null +++ b/socketmsghandling.py @@ -0,0 +1,19 @@ +import socket +import functools + +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +conn = s.connect(('localhost', 80)) +msgs = [] + +# normal way +#while True: +# msg = coon.recv(1024) +# if recv: +# msgs.append(msg) +# else: # when no msg come, break +# break + +# hack way with iter and functools.partial +# this circle will auto break when msg is empty '' +for msg in iter(functools.partial(conn.recv, 1024), b''): + msgs.append(msg) \ No newline at end of file diff --git a/switch.py b/switch.py new file mode 100755 index 0000000..babf9be --- /dev/null +++ b/switch.py @@ -0,0 +1,8 @@ +#! /usr/bin/env python3 +"""Analogue of switch statement""" +a = { + True: 1, + False: -1, + None: 0 +} +print(a.get(False, 0)) diff --git a/transpose.py b/transpose.py new file mode 100644 index 0000000..f4d0f82 --- /dev/null +++ b/transpose.py @@ -0,0 +1,6 @@ +#! /usr/bin/env python3 +"""transpose 2d array [[a,b], [c,d], [e,f]] -> [[a,c,e], [b,d,f]]""" + +original = [['a','b'], ['c','d'], ['e','f']] +transposed = zip (*original) +print (list(transposed)) \ No newline at end of file diff --git a/tryelse.py b/tryelse.py new file mode 100644 index 0000000..ea378b0 --- /dev/null +++ b/tryelse.py @@ -0,0 +1,11 @@ +""" You can have an 'else' clause with try/except. + It gets excecuted if no exception is raised. + This allows you to put less happy-path code in the 'try' block so you can be + more sure of where a caught exception came from.""" + +try: + 1 + 1 +except TypeError: + print("Oh no! An exception was raised.") +else: + print("Oh good, no exceptions were raised.") diff --git a/whileelse.py b/whileelse.py new file mode 100755 index 0000000..57812e2 --- /dev/null +++ b/whileelse.py @@ -0,0 +1,12 @@ +""" You can have an else clause with a while. Works like for-else. + When break is encountered, it exits the loop without executing else. """ + +i = 5 + +while i > 1: + print("Whil-ing away!") + i -= 1 + if i == 3: + break +else: + print("Finished up!")