From 3c79961f0f833f5a73df0fd8c87e751c852bdd9b Mon Sep 17 00:00:00 2001 From: brennerm Date: Thu, 19 Mar 2015 11:50:11 +0100 Subject: [PATCH 001/116] Fixed README formatting --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 64c68f6..bb3452f 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,10 @@ 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 contributers. + +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. From 16fe081e8248d31730ce278e1e59a4f049b8f32a Mon Sep 17 00:00:00 2001 From: brennerm Date: Thu, 19 Mar 2015 14:25:45 +0100 Subject: [PATCH 002/116] added contribution of obeleh --- CONTRIBUTERS | 1 + loopoverlappingdicts.py | 8 ++++++++ 2 files changed, 9 insertions(+) create mode 100755 loopoverlappingdicts.py diff --git a/CONTRIBUTERS b/CONTRIBUTERS index 27f9ec5..c1b2648 100644 --- a/CONTRIBUTERS +++ b/CONTRIBUTERS @@ -1,2 +1,3 @@ - brennerm - agumonkey +- obeleh 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) From db1c1d9963654dc3b0e7a0568e3a8467b244f1f2 Mon Sep 17 00:00:00 2001 From: brennerm Date: Thu, 19 Mar 2015 14:57:21 +0100 Subject: [PATCH 003/116] added contribution of obeleh --- copylist.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100755 copylist.py diff --git a/copylist.py b/copylist.py new file mode 100755 index 0000000..031048a --- /dev/null +++ b/copylist.py @@ -0,0 +1,5 @@ +#! /usr/bin/env python3 +"""a fast way to copy a list""" + +a = [1, 2, 3, 4, 5] +print(a[:]) From 358f8b2003a86ca1d8b5bd18d9fa527d15f4e175 Mon Sep 17 00:00:00 2001 From: Serdar Yegulalp Date: Thu, 19 Mar 2015 11:59:17 -0400 Subject: [PATCH 004/116] Update namedformatting.py Suggested implementation for .format --- namedformatting.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/namedformatting.py b/namedformatting.py index 7924089..cc71077 100755 --- a/namedformatting.py +++ b/namedformatting.py @@ -2,4 +2,9 @@ """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)) From 70a41d081cd27aa7456490f44d50a567783962d7 Mon Sep 17 00:00:00 2001 From: David Taylor Date: Fri, 20 Mar 2015 05:53:30 -0400 Subject: [PATCH 005/116] Corrected spelling Changed file name CONTRIBUTERS -> CONTRIBUTORS, corrected spelling of "contributor" in README.md --- CONTRIBUTERS => CONTRIBUTORS | 0 README.md | 4 ++-- 2 files changed, 2 insertions(+), 2 deletions(-) rename CONTRIBUTERS => CONTRIBUTORS (100%) diff --git a/CONTRIBUTERS b/CONTRIBUTORS similarity index 100% rename from CONTRIBUTERS rename to CONTRIBUTORS diff --git a/README.md b/README.md index bb3452f..494012e 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,8 @@ 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. + 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 contributer. + 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. From beb1ba30f7038f63f4a1513a87c7068bb85de613 Mon Sep 17 00:00:00 2001 From: David Taylor Date: Fri, 20 Mar 2015 06:04:49 -0400 Subject: [PATCH 006/116] added concatenatestrings --- CONTRIBUTORS | 1 + concatenatestrings.py | 6 ++++++ 2 files changed, 7 insertions(+) create mode 100644 concatenatestrings.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index c1b2648..bddf46e 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -1,3 +1,4 @@ - brennerm - agumonkey - obeleh +- prooffreader diff --git a/concatenatestrings.py b/concatenatestrings.py new file mode 100644 index 0000000..765bd72 --- /dev/null +++ b/concatenatestrings.py @@ -0,0 +1,6 @@ +#! /usr/bin/env python3 +"""Concatenate strings to elegantly go over 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!") \ No newline at end of file From 735c909f1f3cdf4dae9f048014dd6a6a68d0ddf3 Mon Sep 17 00:00:00 2001 From: David Taylor Date: Fri, 20 Mar 2015 06:06:41 -0400 Subject: [PATCH 007/116] Revert "added concatenatestrings" This reverts commit beb1ba30f7038f63f4a1513a87c7068bb85de613. --- CONTRIBUTORS | 1 - concatenatestrings.py | 6 ------ 2 files changed, 7 deletions(-) delete mode 100644 concatenatestrings.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index bddf46e..c1b2648 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -1,4 +1,3 @@ - brennerm - agumonkey - obeleh -- prooffreader diff --git a/concatenatestrings.py b/concatenatestrings.py deleted file mode 100644 index 765bd72..0000000 --- a/concatenatestrings.py +++ /dev/null @@ -1,6 +0,0 @@ -#! /usr/bin/env python3 -"""Concatenate strings to elegantly go over 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!") \ No newline at end of file From 836ccc4c64567b9d926377a81a70c273136a088b Mon Sep 17 00:00:00 2001 From: David Taylor Date: Fri, 20 Mar 2015 06:10:05 -0400 Subject: [PATCH 008/116] added concatenatestrings.py --- CONTRIBUTORS | 1 + concatenatestrings.py | 7 +++++++ 2 files changed, 8 insertions(+) create mode 100644 concatenatestrings.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index c1b2648..21ef6ae 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -1,3 +1,4 @@ - brennerm - agumonkey - obeleh +- Prooffreader \ No newline at end of file diff --git a/concatenatestrings.py b/concatenatestrings.py new file mode 100644 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!") From e9bf844c7126a8a2ff65f9411b6b5f8e07711c27 Mon Sep 17 00:00:00 2001 From: David Taylor Date: Fri, 20 Mar 2015 06:24:21 -0400 Subject: [PATCH 009/116] added reversedict.py --- reversedict.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 reversedict.py diff --git a/reversedict.py b/reversedict.py new file mode 100644 index 0000000..5d4dfb3 --- /dev/null +++ b/reversedict.py @@ -0,0 +1,7 @@ +#! /usr/bin/env python3 +"""Reverses keys and values in a dict""" + +_dict = {"one": 1, "two": 2} +# make sure dict is reversible +assert len(set(_dict.keys())) == len(set(_dict.values())) +reversed_dict = {v: k for k, v in _dict.items()} \ No newline at end of file From ae679ee20add2192c6c3fa95e00e395313ed8bc2 Mon Sep 17 00:00:00 2001 From: David Taylor Date: Fri, 20 Mar 2015 06:35:20 -0400 Subject: [PATCH 010/116] changed to better name --- reversedict.py => dictswapkeysvalues.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename reversedict.py => dictswapkeysvalues.py (100%) diff --git a/reversedict.py b/dictswapkeysvalues.py similarity index 100% rename from reversedict.py rename to dictswapkeysvalues.py From 924e359dba3f8ac9f3fc038c13b022237fb75ef0 Mon Sep 17 00:00:00 2001 From: David Taylor Date: Fri, 20 Mar 2015 07:35:07 -0400 Subject: [PATCH 011/116] better language and shorter code in dictswapkeysvalues.py --- dictswapkeysvalues.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dictswapkeysvalues.py b/dictswapkeysvalues.py index 5d4dfb3..73d2e9d 100644 --- a/dictswapkeysvalues.py +++ b/dictswapkeysvalues.py @@ -1,7 +1,7 @@ #! /usr/bin/env python3 -"""Reverses keys and values in a dict""" +"""Swaps keys and values in a dict""" _dict = {"one": 1, "two": 2} -# make sure dict is reversible -assert len(set(_dict.keys())) == len(set(_dict.values())) +# 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 From 56a63dfef19d70b6c41ab239878813eee99b3fe3 Mon Sep 17 00:00:00 2001 From: Chandrakant Gopalan Date: Fri, 20 Mar 2015 16:08:22 -0400 Subject: [PATCH 012/116] Initial commit --- whileelse.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 whileelse.py diff --git a/whileelse.py b/whileelse.py new file mode 100644 index 0000000..e0422e2 --- /dev/null +++ b/whileelse.py @@ -0,0 +1,9 @@ +""" You can have an else clause with a while. Works like for-else. """ + +i = 5 + +while i > 1: + print("Whil-ing away!") + i -= 1 +else: + print("Finished up!") From 5a42da0b43ec36b6c9a88d19d0828d0c01376ae7 Mon Sep 17 00:00:00 2001 From: Chandrakant Gopalan Date: Fri, 20 Mar 2015 16:22:18 -0400 Subject: [PATCH 013/116] Added break condition --- whileelse.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/whileelse.py b/whileelse.py index e0422e2..2045b6b 100644 --- a/whileelse.py +++ b/whileelse.py @@ -1,9 +1,12 @@ -""" You can have an else clause with a while. Works like for-else. """ +""" 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 == 3: + break else: print("Finished up!") From 87b40df89f07ff2d3a9f14d7ee3fa63625f0e3f8 Mon Sep 17 00:00:00 2001 From: Chandrakant Gopalan Date: Fri, 20 Mar 2015 16:26:47 -0400 Subject: [PATCH 014/116] Added cgopalan --- CONTRIBUTORS | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 21ef6ae..bb7c991 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -1,4 +1,5 @@ - brennerm - agumonkey - obeleh -- Prooffreader \ No newline at end of file +- Prooffreader +- cgopalan (cgopalan.github.io) From 6aa19765e4b3599560b64619203fdaf06657d5e2 Mon Sep 17 00:00:00 2001 From: ana-balica Date: Sat, 21 Mar 2015 09:28:09 +0530 Subject: [PATCH 015/116] add max split trick --- maxsplit.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 maxsplit.py diff --git a/maxsplit.py b/maxsplit.py new file mode 100644 index 0000000..76bacb3 --- /dev/null +++ b/maxsplit.py @@ -0,0 +1,5 @@ +#! /usr/bin/env python3 +"""split a string max times""" +string = "a_b_c" +print(string.split("_", 1)) + From 205a18bec096a525ebf9af13309018cd1e6cb26c Mon Sep 17 00:00:00 2001 From: ana-balica Date: Sat, 21 Mar 2015 09:39:59 +0530 Subject: [PATCH 016/116] replace sum function with product --- argumentunpacking.py | 10 +++++----- conditionalfunctioncall.py | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) 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/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)) From 7b37daacca49feb1d9d921186c5c47432a409f59 Mon Sep 17 00:00:00 2001 From: Aleksandr Karasev Date: Sat, 21 Mar 2015 08:19:26 +0300 Subject: [PATCH 017/116] Analogue of switch statement --- switch.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 switch.py diff --git a/switch.py b/switch.py new file mode 100644 index 0000000..521dddf --- /dev/null +++ b/switch.py @@ -0,0 +1,9 @@ +#! /usr/bin/env python3 +"""Analogue of switch statement""" +b = False +a = { + True: 1, + False: -1, + None: 0 +}[b] +print(a) From 0cfb7dfb1fd0100b8d23f1d726cc30aec47a841b Mon Sep 17 00:00:00 2001 From: Dharmit Shah Date: Sat, 21 Mar 2015 12:09:30 +0530 Subject: [PATCH 018/116] Added simple calculator program that doesn't use if..else construct --- CONTRIBUTORS | 1 + calculator.py | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 calculator.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index bb7c991..f66e582 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -3,3 +3,4 @@ - obeleh - Prooffreader - cgopalan (cgopalan.github.io) +- dharmit (github.com/dharmit) diff --git a/calculator.py b/calculator.py new file mode 100644 index 0000000..f6ec333 --- /dev/null +++ b/calculator.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 +# 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)) From 4b07f72a5109c2e20ac79eeeed77b18ca80aa8f7 Mon Sep 17 00:00:00 2001 From: illuz Date: Sat, 21 Mar 2015 15:18:53 +0800 Subject: [PATCH 019/116] added setglobalvariables.py --- setglobalvariables.py | 6 ++++++ setglobalvariables.pyc | Bin 0 -> 322 bytes 2 files changed, 6 insertions(+) create mode 100755 setglobalvariables.py create mode 100644 setglobalvariables.pyc 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/setglobalvariables.pyc b/setglobalvariables.pyc new file mode 100644 index 0000000000000000000000000000000000000000..182624017bec489733112f19f1d749ec99009760 GIT binary patch literal 322 zcmYLDF;2rk5S+6eCqartLz4ozpm0S&kt#xTp#sSfO&aU$J)%R79OW)Z)cGf$-~-G$ z5uCKMJGZ;Dlm5)EzUQ;I7MGVXKQY29L4Xb5Q;2~iSO}|(iEISPu_Yg4u`zH7PQXVB zXK*qwF2l-=7&*gW^(+&t%c%W3o_ z18salNbRH{)b{fBTvN@wT2KVSFz XuQ*|6x$EWFxkp_Os+lKu=Gy!MKfpT; literal 0 HcmV?d00001 From 002d15fc93384ed5b51611b60e73eeeae1e0c1e2 Mon Sep 17 00:00:00 2001 From: illuz Date: Sat, 21 Mar 2015 15:19:23 +0800 Subject: [PATCH 020/116] added setglobalvariables.py --- setglobalvariables.pyc | Bin 322 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 setglobalvariables.pyc diff --git a/setglobalvariables.pyc b/setglobalvariables.pyc deleted file mode 100644 index 182624017bec489733112f19f1d749ec99009760..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 322 zcmYLDF;2rk5S+6eCqartLz4ozpm0S&kt#xTp#sSfO&aU$J)%R79OW)Z)cGf$-~-G$ z5uCKMJGZ;Dlm5)EzUQ;I7MGVXKQY29L4Xb5Q;2~iSO}|(iEISPu_Yg4u`zH7PQXVB zXK*qwF2l-=7&*gW^(+&t%c%W3o_ z18salNbRH{)b{fBTvN@wT2KVSFz XuQ*|6x$EWFxkp_Os+lKu=Gy!MKfpT; From 42e00da25ff9e85da733c7ae73b47a83c8c88778 Mon Sep 17 00:00:00 2001 From: illuz Date: Sat, 21 Mar 2015 15:36:29 +0800 Subject: [PATCH 021/116] added removeduplicatefromlist.py --- removeduplicatefromlist.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100755 removeduplicatefromlist.py diff --git a/removeduplicatefromlist.py b/removeduplicatefromlist.py new file mode 100755 index 0000000..97d8f1c --- /dev/null +++ b/removeduplicatefromlist.py @@ -0,0 +1,9 @@ +#! /usr/bin/env python3 +"""remove duplicate items from list""" + +items = [1, 2, 2, 3, 3, 3] + +newitems2 = list(set(items)) +print(newitems2) + + From 92e6e6b5fadbbb98919ec128f48e44371defb384 Mon Sep 17 00:00:00 2001 From: ana-balica Date: Sat, 21 Mar 2015 14:35:21 +0530 Subject: [PATCH 022/116] add myself to contributors --- CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index bb7c991..5cf67fe 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -3,3 +3,4 @@ - obeleh - Prooffreader - cgopalan (cgopalan.github.io) +- anabalica (ana-balica.github.io) From 97cff9696b9cf8baad6bbec26fb59726645bd4b4 Mon Sep 17 00:00:00 2001 From: brennerm Date: Sat, 21 Mar 2015 10:14:33 +0100 Subject: [PATCH 023/116] fixed syntax error in whileelse.py --- whileelse.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/whileelse.py b/whileelse.py index 2045b6b..57812e2 100644 --- a/whileelse.py +++ b/whileelse.py @@ -6,7 +6,7 @@ while i > 1: print("Whil-ing away!") i -= 1 - if == 3: + if i == 3: break else: print("Finished up!") From 61b8d6c9f158b5175471fac7f131a283d2e44717 Mon Sep 17 00:00:00 2001 From: Dharmit Shah Date: Sat, 21 Mar 2015 15:01:45 +0530 Subject: [PATCH 024/116] Added documentation --- calculator.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/calculator.py b/calculator.py index f6ec333..882e2b2 100644 --- a/calculator.py +++ b/calculator.py @@ -1,5 +1,11 @@ #!/usr/bin/env python3 -# Created with help of an answer on stackoverflow. Don't have the exact link. +""" +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 = { From d16d62c2771959beda3fde5896348276a6c37fdc Mon Sep 17 00:00:00 2001 From: matttk Date: Sat, 21 Mar 2015 22:41:57 +0800 Subject: [PATCH 025/116] Sort a dict by element's value --- CONTRIBUTORS | 1 + dictsortbyvalue.py | 5 +++++ 2 files changed, 6 insertions(+) create mode 100644 dictsortbyvalue.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 6052294..2bade2f 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -5,3 +5,4 @@ - cgopalan (cgopalan.github.io) - anabalica (ana-balica.github.io) - dharmit (github.com/dharmit) +- shyboynccu (github.com/shyboynccu) diff --git a/dictsortbyvalue.py b/dictsortbyvalue.py new file mode 100644 index 0000000..1404757 --- /dev/null +++ b/dictsortbyvalue.py @@ -0,0 +1,5 @@ +#!/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])) From 1207ab2024093d4175d372eb326473340884273f Mon Sep 17 00:00:00 2001 From: Max Brenner Date: Sat, 21 Mar 2015 16:26:36 +0100 Subject: [PATCH 026/116] added illuz to CONTRIBUTORS --- CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 2bade2f..f04ca69 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -6,3 +6,4 @@ - anabalica (ana-balica.github.io) - dharmit (github.com/dharmit) - shyboynccu (github.com/shyboynccu) +- illuz From b841f5ccc4f0e26e99a56b2e10d3c187966a6318 Mon Sep 17 00:00:00 2001 From: brennerm Date: Sat, 21 Mar 2015 16:52:18 +0100 Subject: [PATCH 027/116] added contribution of tutoringsteve --- CONTRIBUTORS | 1 + calculator.py | 0 compoundboolstatement.py | 7 +++++++ concatenatestrings.py | 0 dictsortbyvalue.py | 0 dictswapkeysvalues.py | 0 maxsplit.py | 0 switch.py | 0 whileelse.py | 0 9 files changed, 8 insertions(+) mode change 100644 => 100755 calculator.py create mode 100755 compoundboolstatement.py mode change 100644 => 100755 concatenatestrings.py mode change 100644 => 100755 dictsortbyvalue.py mode change 100644 => 100755 dictswapkeysvalues.py mode change 100644 => 100755 maxsplit.py mode change 100644 => 100755 switch.py mode change 100644 => 100755 whileelse.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index f04ca69..7d61819 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -7,3 +7,4 @@ - dharmit (github.com/dharmit) - shyboynccu (github.com/shyboynccu) - illuz +- tutoringsteve diff --git a/calculator.py b/calculator.py old mode 100644 new mode 100755 diff --git a/compoundboolstatement.py b/compoundboolstatement.py new file mode 100755 index 0000000..761e1d9 --- /dev/null +++ b/compoundboolstatement.py @@ -0,0 +1,7 @@ +#! /usr/bin/env python3 +"""readable way of checking existence of elements in list, dict or tuple""" + +l = [1, 2, 3] + +if 1 and 2 and not 4 in l: + print('check!') \ No newline at end of file diff --git a/concatenatestrings.py b/concatenatestrings.py old mode 100644 new mode 100755 diff --git a/dictsortbyvalue.py b/dictsortbyvalue.py old mode 100644 new mode 100755 diff --git a/dictswapkeysvalues.py b/dictswapkeysvalues.py old mode 100644 new mode 100755 diff --git a/maxsplit.py b/maxsplit.py old mode 100644 new mode 100755 diff --git a/switch.py b/switch.py old mode 100644 new mode 100755 diff --git a/whileelse.py b/whileelse.py old mode 100644 new mode 100755 From a5049da12ef58621f7c5753cae572b446d844838 Mon Sep 17 00:00:00 2001 From: illuz Date: Sat, 21 Mar 2015 23:58:29 +0800 Subject: [PATCH 028/116] add controlwhitespaces.py --- controlwhitespaces.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100755 controlwhitespaces.py diff --git a/controlwhitespaces.py b/controlwhitespaces.py new file mode 100755 index 0000000..a646fc4 --- /dev/null +++ b/controlwhitespaces.py @@ -0,0 +1,19 @@ +#! /usr/bin/env python3 +"""control the whitespaces in sing""" + +s = 'The Little Price' + +# justify stirng to be at least width wide +# by adding whitespace +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 whitespace in two sides of sing +print(s3.lstrip()) # 'The Little Price ' +print(s3.rstrip()) # ' The Little Price' +print(s3.strip()) # 'The Little Price' From db69f2a2f9bd93217e94e3e7586d9a46ed5ef940 Mon Sep 17 00:00:00 2001 From: Dave Hughes Date: Sat, 21 Mar 2015 16:00:27 +0000 Subject: [PATCH 029/116] added listecompnestedfor.py Demonstrates nested for loops within a list comprehension --- CONTRIBUTORS | 1 + listcompnestedfor.py | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 listcompnestedfor.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 7d61819..77b54d4 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -8,3 +8,4 @@ - shyboynccu (github.com/shyboynccu) - illuz - tutoringsteve +- waveform80 (github.com/waveform80) diff --git a/listcompnestedfor.py b/listcompnestedfor.py new file mode 100644 index 0000000..7bb487e --- /dev/null +++ b/listcompnestedfor.py @@ -0,0 +1,16 @@ +#! /usr/bin/env python3 +"""flattening nested lists 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 + ]) From 8138a76d0ab8e39b1979c49ef04e4ce49dc6cb5a Mon Sep 17 00:00:00 2001 From: illuz Date: Sun, 22 Mar 2015 00:19:32 +0800 Subject: [PATCH 030/116] fix comment --- controlwhitespaces.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/controlwhitespaces.py b/controlwhitespaces.py index a646fc4..9fc9e94 100755 --- a/controlwhitespaces.py +++ b/controlwhitespaces.py @@ -1,10 +1,10 @@ #! /usr/bin/env python3 -"""control the whitespaces in sing""" +"""control the whitespaces in string""" s = 'The Little Price' -# justify stirng to be at least width wide -# by adding whitespace +# justify string to be at least width wide +# by adding whitespaces width = 20 s1 = s.ljust(width) s2 = s.rjust(width) @@ -13,7 +13,7 @@ print(s2) # ' The Little Price' print(s3) # ' The Little Price ' -# strip whitespace in two sides of sing +# 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' From fde8799150060f3bc5909f863d5a33fc19b51c3a Mon Sep 17 00:00:00 2001 From: brennerm Date: Sat, 21 Mar 2015 17:36:09 +0100 Subject: [PATCH 031/116] added contribution of Kzinglzy --- CONTRIBUTORS | 1 + socketmsghandling.py | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 socketmsghandling.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 7d61819..1090d26 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -8,3 +8,4 @@ - shyboynccu (github.com/shyboynccu) - illuz - tutoringsteve +- Kzinglzy 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 From 15f8b3011afeb96bb5538a79e619ed01ab41d10f Mon Sep 17 00:00:00 2001 From: brennerm Date: Sat, 21 Mar 2015 17:47:16 +0100 Subject: [PATCH 032/116] removed compoundboolstatement.py as it was invalid --- compoundboolstatement.py | 7 ------- 1 file changed, 7 deletions(-) delete mode 100755 compoundboolstatement.py diff --git a/compoundboolstatement.py b/compoundboolstatement.py deleted file mode 100755 index 761e1d9..0000000 --- a/compoundboolstatement.py +++ /dev/null @@ -1,7 +0,0 @@ -#! /usr/bin/env python3 -"""readable way of checking existence of elements in list, dict or tuple""" - -l = [1, 2, 3] - -if 1 and 2 and not 4 in l: - print('check!') \ No newline at end of file From af5fb4aa70f18fab86dafdd6da39da3f8b15e41d Mon Sep 17 00:00:00 2001 From: brennerm Date: Sat, 21 Mar 2015 18:01:08 +0100 Subject: [PATCH 033/116] added default handling in switch.py --- switch.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/switch.py b/switch.py index 521dddf..babf9be 100755 --- a/switch.py +++ b/switch.py @@ -1,9 +1,8 @@ #! /usr/bin/env python3 """Analogue of switch statement""" -b = False a = { True: 1, False: -1, None: 0 -}[b] -print(a) +} +print(a.get(False, 0)) From f478a6e548b6de36de2418dc63c0bfe42f259811 Mon Sep 17 00:00:00 2001 From: brennerm Date: Sat, 21 Mar 2015 18:06:06 +0100 Subject: [PATCH 034/116] removed andorassignment.py due to unexpected behaviour --- andorassignment.py | 6 ------ 1 file changed, 6 deletions(-) delete mode 100755 andorassignment.py 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') From 0cf76018bbef99f688a8ef6c4449eac0dbc470aa Mon Sep 17 00:00:00 2001 From: thatneat Date: Sat, 21 Mar 2015 10:06:14 -0700 Subject: [PATCH 035/116] add try/else trick --- tryelse. | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 tryelse. diff --git a/tryelse. b/tryelse. new file mode 100644 index 0000000..ea378b0 --- /dev/null +++ b/tryelse. @@ -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.") From a0bfb869debe7a2f8c4d6f74a6f5ed4a68e592e9 Mon Sep 17 00:00:00 2001 From: thatneat Date: Sat, 21 Mar 2015 10:06:43 -0700 Subject: [PATCH 036/116] add self to CONTRIBUTORS --- CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 77b54d4..9935bc6 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -9,3 +9,4 @@ - illuz - tutoringsteve - waveform80 (github.com/waveform80) +- thatneat (github.com/thatneat) From 62347931bbce62d41611606dc8a45673c712d78a Mon Sep 17 00:00:00 2001 From: brennerm Date: Sat, 21 Mar 2015 18:10:27 +0100 Subject: [PATCH 037/116] added .py suffix to tryelse, why was it missing? :D --- tryelse. => tryelse.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tryelse. => tryelse.py (100%) diff --git a/tryelse. b/tryelse.py similarity index 100% rename from tryelse. rename to tryelse.py From 9c1850d9a53731b25658852538e786409b95fd90 Mon Sep 17 00:00:00 2001 From: brennerm Date: Sat, 21 Mar 2015 18:23:26 +0100 Subject: [PATCH 038/116] added contribution of Kzinglzy --- cacheproperty.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 cacheproperty.py 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) + From ddf163b985506d37f15711c0a0109f79a115db84 Mon Sep 17 00:00:00 2001 From: Bruno Date: Sat, 21 Mar 2015 21:09:30 +0100 Subject: [PATCH 039/116] transpose.py - elegant way to transpose an 2d array --- transpose.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 transpose.py 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 From fa6976d264fac75fa5f239b114f4720cab61e996 Mon Sep 17 00:00:00 2001 From: Bruno Date: Sat, 21 Mar 2015 21:11:21 +0100 Subject: [PATCH 040/116] transpose.py - elegant way to transpose an 2d array (contributors file modified) --- CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 6426f79..0f2a948 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -11,3 +11,4 @@ - Kzinglzy - waveform80 (github.com/waveform80) - thatneat (github.com/thatneat) +- bruno314 (github.com/bruno314) \ No newline at end of file From e5501d2864ea67b9d00ab4f91d5e8999cb5a6354 Mon Sep 17 00:00:00 2001 From: Rick Date: Sun, 22 Mar 2015 14:01:40 +0800 Subject: [PATCH 041/116] Add one more advanced dictionary to string formatting style Provide another way to format the dictionary to string --- namedformatting.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/namedformatting.py b/namedformatting.py index cc71077..042538a 100755 --- a/namedformatting.py +++ b/namedformatting.py @@ -8,3 +8,8 @@ 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)) + From 1957a4e47d06ad99094e7d082b8509750f488103 Mon Sep 17 00:00:00 2001 From: Rick Date: Sun, 22 Mar 2015 14:13:48 +0800 Subject: [PATCH 042/116] Add one more advanced dictionary to string formatting style Add one more case to namedformatting.py --- CONTRIBUTORS | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 0f2a948..ee3f456 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -11,4 +11,5 @@ - Kzinglzy - waveform80 (github.com/waveform80) - thatneat (github.com/thatneat) -- bruno314 (github.com/bruno314) \ No newline at end of file +- bruno314 (github.com/bruno314) +- rickhau From 7663d00452f7b3820d367500bd86e2667b93deec Mon Sep 17 00:00:00 2001 From: parasimha Date: Sun, 22 Mar 2015 10:19:01 +0000 Subject: [PATCH 043/116] added reversed --- reverselist.py | 4 ++++ 1 file changed, 4 insertions(+) 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) From b101694ad12edcdd40a0dc09a74851df8c245d63 Mon Sep 17 00:00:00 2001 From: parasimha Date: Sun, 22 Mar 2015 10:22:20 +0000 Subject: [PATCH 044/116] keep order when removing dups. --- removeduplicatefromlist.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/removeduplicatefromlist.py b/removeduplicatefromlist.py index 97d8f1c..0bad741 100755 --- a/removeduplicatefromlist.py +++ b/removeduplicatefromlist.py @@ -6,4 +6,11 @@ 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())) From a1063344ea15b167a88d417c378ab0284c3df94c Mon Sep 17 00:00:00 2001 From: parasimha Date: Sun, 22 Mar 2015 10:25:09 +0000 Subject: [PATCH 045/116] added use of None --- maxsplit.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/maxsplit.py b/maxsplit.py index 76bacb3..6c60b3b 100755 --- a/maxsplit.py +++ b/maxsplit.py @@ -3,3 +3,9 @@ string = "a_b_c" print(string.split("_", 1)) + +"""use maxsplit with arbitrary whitespace""" + +s = "foo bar foobar foo" + +print(s.split(None, 2)) From b1b321e203f1cfb0b6a51eabb3d28db9771b6ddd Mon Sep 17 00:00:00 2001 From: parasimha Date: Sun, 22 Mar 2015 10:32:54 +0000 Subject: [PATCH 046/116] added methods --- setoperators.py | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/setoperators.py b/setoperators.py index 80a1431..135b669 100755 --- a/setoperators.py +++ b/setoperators.py @@ -5,7 +5,7 @@ c = set(['a', 'c']) # Intersection -print(a & b) + # Subset print(c < a) @@ -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) From 6bb426309993c7650c6567c1a7bf62d37e99f52e Mon Sep 17 00:00:00 2001 From: parasimha Date: Sun, 22 Mar 2015 10:38:03 +0000 Subject: [PATCH 047/116] Update dictsortbyvalue.py --- dictsortbyvalue.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/dictsortbyvalue.py b/dictsortbyvalue.py index 1404757..16c5b29 100755 --- a/dictsortbyvalue.py +++ b/dictsortbyvalue.py @@ -3,3 +3,18 @@ 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)) From 88222e462f82f01f9956da355a6e48d519f76691 Mon Sep 17 00:00:00 2001 From: Max Brenner Date: Sun, 22 Mar 2015 11:38:04 +0100 Subject: [PATCH 048/116] Added contact info to README --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 494012e..fe0478c 100644 --- a/README.md +++ b/README.md @@ -11,3 +11,7 @@ Feel free to use the PyTrickBase.txt as a starting point. 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 From 325e4636a80341566f7bdc7bb6c37db18314a71f Mon Sep 17 00:00:00 2001 From: Talha Oz Date: Sun, 22 Mar 2015 07:15:08 -0400 Subject: [PATCH 049/116] comment was missing order not preserved info added to the comment --- removeduplicatefromlist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/removeduplicatefromlist.py b/removeduplicatefromlist.py index 97d8f1c..818b8eb 100755 --- a/removeduplicatefromlist.py +++ b/removeduplicatefromlist.py @@ -1,5 +1,5 @@ #! /usr/bin/env python3 -"""remove duplicate items from list""" +"""remove duplicate items from list. note: does not preserve the original list order""" items = [1, 2, 2, 3, 3, 3] From 69696f08e69c55519f1eb286126aac448d46eb85 Mon Sep 17 00:00:00 2001 From: Talha Oz Date: Sun, 22 Mar 2015 07:26:38 -0400 Subject: [PATCH 050/116] comment fixed this does not flatten in case of 2+ nested list. Clarified. --- listcompnestedfor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/listcompnestedfor.py b/listcompnestedfor.py index 7bb487e..4e94b41 100644 --- a/listcompnestedfor.py +++ b/listcompnestedfor.py @@ -1,5 +1,5 @@ #! /usr/bin/env python3 -"""flattening nested lists within a single list comprehension with +"""flattening nested lists of depth 2 within a single list comprehension with multiple for loops""" l = [ From 331bed63b0abae63b31c5fd1c83d47d4fa540305 Mon Sep 17 00:00:00 2001 From: Talha Oz Date: Sun, 22 Mar 2015 07:30:41 -0400 Subject: [PATCH 051/116] items order changed items order changed --- removeduplicatefromlist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/removeduplicatefromlist.py b/removeduplicatefromlist.py index 818b8eb..a67657b 100755 --- a/removeduplicatefromlist.py +++ b/removeduplicatefromlist.py @@ -1,7 +1,7 @@ #! /usr/bin/env python3 """remove duplicate items from list. note: does not preserve the original list order""" -items = [1, 2, 2, 3, 3, 3] +items = [2, 2, 3, 3, 1] newitems2 = list(set(items)) print(newitems2) From 82c17d587fcd6dbc203299ca67510f6bf2eb9a8d Mon Sep 17 00:00:00 2001 From: Talha Oz Date: Sun, 22 Mar 2015 07:34:12 -0400 Subject: [PATCH 052/116] Update CONTRIBUTORS --- CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index ee3f456..de493f1 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -13,3 +13,4 @@ - thatneat (github.com/thatneat) - bruno314 (github.com/bruno314) - rickhau +- oztalha (github.com/oztalha) From cb3ce8023f9a8c9faa1ebd6f484e87e7a375081a Mon Sep 17 00:00:00 2001 From: parasimha Date: Sun, 22 Mar 2015 13:32:50 +0000 Subject: [PATCH 053/116] fixed accidental deletion --- setoperators.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setoperators.py b/setoperators.py index 135b669..18825f2 100755 --- a/setoperators.py +++ b/setoperators.py @@ -5,7 +5,7 @@ c = set(['a', 'c']) # Intersection - +print(a & b) # Subset print(c < a) From 69c6f97143440d8cde63811e22a5d56a6cbca5f9 Mon Sep 17 00:00:00 2001 From: parasimha Date: Sun, 22 Mar 2015 13:47:35 +0000 Subject: [PATCH 054/116] Update copylist.py --- copylist.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/copylist.py b/copylist.py index 031048a..2328759 100755 --- a/copylist.py +++ b/copylist.py @@ -1,5 +1,22 @@ #! /usr/bin/env python3 -"""a fast way to copy a list""" +"""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) + From 0b803f76de0c68d8b67eca13b00bdcc8cb8fb5a8 Mon Sep 17 00:00:00 2001 From: Betezed Date: Mon, 23 Mar 2015 01:29:09 +0100 Subject: [PATCH 055/116] Initial commit --- objgetnamedattribute | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 objgetnamedattribute diff --git a/objgetnamedattribute b/objgetnamedattribute new file mode 100644 index 0000000..178dda6 --- /dev/null +++ b/objgetnamedattribute @@ -0,0 +1,7 @@ +#! /usr/bin/env python3 +""" Return the value of the named attribute of an object """ +class obj(): + attr = 1 + +foo = "attr" +print(getattr(obj, foo)) From b1c7a1beda3947c9dca8fcc9fff976bd9d581987 Mon Sep 17 00:00:00 2001 From: Max Brenner Date: Mon, 23 Mar 2015 10:33:25 +0100 Subject: [PATCH 056/116] Update loopoverlappingdicts.py --- loopoverlappingdicts.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/loopoverlappingdicts.py b/loopoverlappingdicts.py index ec9d93c..20698d3 100755 --- a/loopoverlappingdicts.py +++ b/loopoverlappingdicts.py @@ -1,8 +1,12 @@ #! /usr/bin/env python3 -"""loop over dicts that share (some) keys""" +"""loop over dicts that share (some) keys in Python2""" dctA = {'a': 1, 'b': 2, 'c': 3} dctB = {'b': 4, 'c': 5, 'd': 6} for ky in set(dctA) & set(dctB): print(ky) + +"""loop over dicts that share (some) keys in Python3""" +for ky in dctA.keys() & dctB.keys(): + print(ky) From 16c66614bc485d76ba682008d1ee31eafbb03623 Mon Sep 17 00:00:00 2001 From: Max Brenner Date: Mon, 23 Mar 2015 11:18:04 +0100 Subject: [PATCH 057/116] Update README.md --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index fe0478c..2f90092 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,13 @@ Creating a knowledge base of unpopular Python built-in features to save a lot of unecessary code. ## Contribute +### Requirements +- only use the standard Python library +- compared to the "general approach": + - improve readability + - improve performance + - implement functionality in a shorter way + Feel free to use the PyTrickBase.txt as a starting point. 1. Pull request: From f76d43f312aba52a6dd5fb18ec932db738608652 Mon Sep 17 00:00:00 2001 From: Max Brenner Date: Mon, 23 Mar 2015 11:20:41 +0100 Subject: [PATCH 058/116] Update README.md --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 2f90092..35f1ae6 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,6 @@ Creating a knowledge base of unpopular Python built-in features to save a lot of unecessary code. ## Contribute -### Requirements -- only use the standard Python library -- compared to the "general approach": - - improve readability - - improve performance - - implement functionality in a shorter way - Feel free to use the PyTrickBase.txt as a starting point. 1. Pull request: @@ -18,6 +11,13 @@ Feel free to use the PyTrickBase.txt as a starting point. 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. + +### Requirements +- only use the standard Python library +- compared to the "general approach": + - improve readability + - improve performance + - implement functionality in a shorter way ## Contact 1. message me at [@__brennerm](https://twitter.com/__brennerm) From 868739a3044f32e22dc89483ead66b9b581f8365 Mon Sep 17 00:00:00 2001 From: Nikhil Date: Mon, 23 Mar 2015 16:41:03 +0530 Subject: [PATCH 059/116] Added list to comma separated --- CONTRIBUTORS | 1 + listtocommaseparated.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 listtocommaseparated.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index de493f1..ac77d44 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -14,3 +14,4 @@ - bruno314 (github.com/bruno314) - rickhau - oztalha (github.com/oztalha) +- nikhiln (github.com/nikhiln) diff --git a/listtocommaseparated.py b/listtocommaseparated.py new file mode 100644 index 0000000..f737032 --- /dev/null +++ b/listtocommaseparated.py @@ -0,0 +1,18 @@ +#! /usr/bin/env python3 +"""converts list to comma separated string""" + +items = ['foo', 'bar', 'xyz'] + +print (','.join(items)) + +"""list of numbers to comma separated""" +numbers = [2, 3, 5, 10] + +print (','.join(map(str, numbers))) + +"""list of mix data""" +data = [2, 'hello', 3, 3.4] + +print (','.join(map(str, data))) + + From e0055b5794dbcd8a2a569068497bdaca52f57ad8 Mon Sep 17 00:00:00 2001 From: Betezed Date: Mon, 23 Mar 2015 14:20:37 +0100 Subject: [PATCH 060/116] Rename objgetnamedattribute to objgetnamedattribute.py --- objgetnamedattribute => objgetnamedattribute.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename objgetnamedattribute => objgetnamedattribute.py (100%) diff --git a/objgetnamedattribute b/objgetnamedattribute.py similarity index 100% rename from objgetnamedattribute rename to objgetnamedattribute.py From 34972a49ac7c2eaed1fd3e917807e8828403fe4d Mon Sep 17 00:00:00 2001 From: Betezed Date: Mon, 23 Mar 2015 14:21:04 +0100 Subject: [PATCH 061/116] Update CONTRIBUTORS --- CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index de493f1..f74d41b 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -14,3 +14,4 @@ - bruno314 (github.com/bruno314) - rickhau - oztalha (github.com/oztalha) +- betezed (github.com/betezed) From d87a0f55398523bbad7896114372a3df3093ec13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Cumplido?= Date: Mon, 23 Mar 2015 13:45:56 +0000 Subject: [PATCH 062/116] Add example of ovelapping (key:value) on dicts for Python3 --- CONTRIBUTORS | 1 + loopoverlappingdicts.py | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index ac77d44..119de5b 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -15,3 +15,4 @@ - rickhau - oztalha (github.com/oztalha) - nikhiln (github.com/nikhiln) +- raulcd (github.com/raulcd) diff --git a/loopoverlappingdicts.py b/loopoverlappingdicts.py index 20698d3..19efa75 100755 --- a/loopoverlappingdicts.py +++ b/loopoverlappingdicts.py @@ -2,7 +2,7 @@ """loop over dicts that share (some) keys in Python2""" dctA = {'a': 1, 'b': 2, 'c': 3} -dctB = {'b': 4, 'c': 5, 'd': 6} +dctB = {'b': 4, 'c': 3, 'd': 6} for ky in set(dctA) & set(dctB): print(ky) @@ -10,3 +10,7 @@ """loop over dicts that share (some) keys in Python3""" for ky in dctA.keys() & dctB.keys(): print(ky) + +"""loop over dicts that share (some) keys and values in Python3""" +for item in dctA.items() & dctB.items(): + print(item) From 2eb4092120e4e12ef4bd28b063b7d02e55ec0b7b Mon Sep 17 00:00:00 2001 From: Max Brenner Date: Tue, 24 Mar 2015 08:43:36 +0100 Subject: [PATCH 063/116] Update and rename switch.py to lightweightswitch.py --- lightweightswitch.py | 22 ++++++++++++++++++++++ switch.py | 8 -------- 2 files changed, 22 insertions(+), 8 deletions(-) create mode 100755 lightweightswitch.py delete mode 100755 switch.py diff --git a/lightweightswitch.py b/lightweightswitch.py new file mode 100755 index 0000000..f9329bd --- /dev/null +++ b/lightweightswitch.py @@ -0,0 +1,22 @@ +#! /usr/bin/env python3 +"""lightweight switch statement""" +a = { + True: 1, + False: -1, + None: 0 +} +print(a.get(False, 0)) + +"""works with functions as well""" +def add(a, b): + return a + b + +def subtract(a, b): + return a - b + +b = { + '+': add + '-': subtract +} + +print(b['+'](1, 1)) diff --git a/switch.py b/switch.py deleted file mode 100755 index babf9be..0000000 --- a/switch.py +++ /dev/null @@ -1,8 +0,0 @@ -#! /usr/bin/env python3 -"""Analogue of switch statement""" -a = { - True: 1, - False: -1, - None: 0 -} -print(a.get(False, 0)) From 34a1b1c37575e2554045e30846ea9cc6b0905c63 Mon Sep 17 00:00:00 2001 From: "L. Leon Chen" Date: Wed, 25 Mar 2015 09:16:31 -0400 Subject: [PATCH 064/116] flatten nested lists --- CONTRIBUTORS | 1 + flattenlist.py | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) create mode 100755 flattenlist.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index f41eac8..7d2f4b0 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -17,3 +17,4 @@ - nikhiln (github.com/nikhiln) - raulcd (github.com/raulcd) - betezed (github.com/betezed) +- transcranial (github.com/transcranial) diff --git a/flattenlist.py b/flattenlist.py new file mode 100755 index 0000000..cd3a81f --- /dev/null +++ b/flattenlist.py @@ -0,0 +1,17 @@ +#! /usr/bin/env python3 +""" +Deep flattens a nested list + +Examples: + >>> list(flatten_list([1, 2, [3, 4], [5, 6, [7]]])) + [1, 2, 3, 4, 5, 6, 7] + >>> list(flatten_list(['apple', 'banana', ['orange', 'lemon']])) + ['apple', 'banana', 'orange', 'lemon'] +""" + +def flatten_list(L): + for item in L: + if isinstance(item, list): + yield from flatten_list(item) + else: + yield item From 433677450e941f2874036ce5e68d4e00cd5e7424 Mon Sep 17 00:00:00 2001 From: brennerm Date: Wed, 25 Mar 2015 21:25:54 +0100 Subject: [PATCH 065/116] merged two files --- listcompnestedfor.py | 16 ---------------- 1 file changed, 16 deletions(-) delete mode 100644 listcompnestedfor.py diff --git a/listcompnestedfor.py b/listcompnestedfor.py deleted file mode 100644 index 4e94b41..0000000 --- a/listcompnestedfor.py +++ /dev/null @@ -1,16 +0,0 @@ -#! /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 - ]) From 7604876d4fd27eccdeb8eb98126689d8483bb862 Mon Sep 17 00:00:00 2001 From: Gaurav Kamath Date: Thu, 26 Mar 2015 16:18:12 -0700 Subject: [PATCH 066/116] One-liner for Trees in Python One-liner for Trees in Python --- tree.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 tree.py diff --git a/tree.py b/tree.py new file mode 100644 index 0000000..b7c5221 --- /dev/null +++ b/tree.py @@ -0,0 +1,14 @@ +#! /usr/bin/env python3 +""" +See description here +https://gist.github.com/hrldcpr/2012250 +""" + +from collections import defaultdict + +tree = lambda: defaultdict(tree) + + +users = tree() +users['harold']['username'] = 'chopper' +users['matt']['password'] = 'hunter2' From 18ddf87ee5df7f140a35ea4a196c614f5e4e03b0 Mon Sep 17 00:00:00 2001 From: Gaurav Kamath Date: Thu, 26 Mar 2015 16:24:25 -0700 Subject: [PATCH 067/116] Metatable similar to lua. --- metatable.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 metatable.py diff --git a/metatable.py b/metatable.py new file mode 100644 index 0000000..1ccfc1d --- /dev/null +++ b/metatable.py @@ -0,0 +1,22 @@ +""" +metatable with where the function recieves the dictionary and key. +""" +from collections import defaultdict + +class metatable(defaultdict): + def __missing__(self, key): + if self.default_factory is None: + raise KeyError( key ) + else: + ret = self[key] = self.default_factory(self,key) + return ret + +def fib(d,n): + if n == 0 or n == 1: return n + return d[n - 1] + d[n - 2] + +d = metatable(fib) +print d[1] +print d[3] +print d[10] +print d From a79acade1d3e06cd57086bbbe287f4b46abac222 Mon Sep 17 00:00:00 2001 From: Gaurav Kamath Date: Thu, 26 Mar 2015 16:26:14 -0700 Subject: [PATCH 068/116] Parameterized defaultdict --- keydefaultdict.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 keydefaultdict.py diff --git a/keydefaultdict.py b/keydefaultdict.py new file mode 100644 index 0000000..61ed96a --- /dev/null +++ b/keydefaultdict.py @@ -0,0 +1,21 @@ +""" +keydefaultdict with where the function recieves the dictionary and key. +""" +from collections import defaultdict + +class keydefaultdict(defaultdict): + def __missing__(self, key): + if self.default_factory is None: + raise KeyError( key ) + else: + ret = self[key] = self.default_factory(key) + return ret + +def pow2(n): + return 1 << n + +d = keydefaultdict(pow2) +print d[1] +print d[3] +print d[10] +print d From 88c41a1bec5cd4a7471ae9e095fd8009d2aa4752 Mon Sep 17 00:00:00 2001 From: Gaurav Kamath Date: Thu, 26 Mar 2015 16:27:02 -0700 Subject: [PATCH 069/116] Update keydefaultdict.py --- keydefaultdict.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keydefaultdict.py b/keydefaultdict.py index 61ed96a..269cccd 100644 --- a/keydefaultdict.py +++ b/keydefaultdict.py @@ -1,5 +1,5 @@ """ -keydefaultdict with where the function recieves the dictionary and key. +keydefaultdict with where the function recieves the key. """ from collections import defaultdict From b98d5111ce42076ea0279ee20e32e4972e2c6f19 Mon Sep 17 00:00:00 2001 From: Gaurav Kamath Date: Fri, 27 Mar 2015 10:00:29 -0700 Subject: [PATCH 070/116] converted print statements to print() --- keydefaultdict.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/keydefaultdict.py b/keydefaultdict.py index 269cccd..fd2668d 100644 --- a/keydefaultdict.py +++ b/keydefaultdict.py @@ -15,7 +15,7 @@ def pow2(n): return 1 << n d = keydefaultdict(pow2) -print d[1] -print d[3] -print d[10] -print d +print(d[1]) +print(d[3]) +print(d[10]) +print(d) From f28c20fb999764a93bb2e70cf3da42f560816b98 Mon Sep 17 00:00:00 2001 From: Gaurav Kamath Date: Fri, 27 Mar 2015 10:04:36 -0700 Subject: [PATCH 071/116] converted print statements to print() --- metatable.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/metatable.py b/metatable.py index 1ccfc1d..8f2fdab 100644 --- a/metatable.py +++ b/metatable.py @@ -16,7 +16,7 @@ def fib(d,n): return d[n - 1] + d[n - 2] d = metatable(fib) -print d[1] -print d[3] -print d[10] -print d +print(d[1]) +print(d[3]) +print(d[10]) +print(d) From 94ed4aaa36e87ba780296a325d7874e0f13add2b Mon Sep 17 00:00:00 2001 From: Gaurav Kamath Date: Fri, 27 Mar 2015 10:06:43 -0700 Subject: [PATCH 072/116] Update CONTRIBUTORS --- CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 7d2f4b0..e1078e4 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -18,3 +18,4 @@ - raulcd (github.com/raulcd) - betezed (github.com/betezed) - transcranial (github.com/transcranial) +- st0le (http://st0le.github.io) From f662790defeb3b2030c74cd82369a1f0306e8221 Mon Sep 17 00:00:00 2001 From: kireev165 Date: Mon, 30 Mar 2015 01:39:08 +0300 Subject: [PATCH 073/116] fix syntax error keyword 'in' was missed in for-statement --- reverselist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reverselist.py b/reverselist.py index 0fedc4e..c58de9a 100755 --- a/reverselist.py +++ b/reverselist.py @@ -4,5 +4,5 @@ print(a[::-1]) """iterating over list contents in reverse efficiently.""" -for ele reversed(a): +for ele in reversed(a): print(ele) From c3b0ebb7b3294edda0c9dd8fd60f35d274177219 Mon Sep 17 00:00:00 2001 From: kireev165 Date: Mon, 30 Mar 2015 01:52:55 +0300 Subject: [PATCH 074/116] fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 35f1ae6..9ee9c56 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ ## Intention -Creating a knowledge base of unpopular Python built-in features to save a lot of unecessary code. +Creating a knowledge base of unpopular Python built-in features to save a lot of unnecessary code. ## Contribute Feel free to use the PyTrickBase.txt as a starting point. From 6b1c7269deff9ec5a344006084dbc7b2a9dbf581 Mon Sep 17 00:00:00 2001 From: Gaurav Kamath Date: Mon, 30 Mar 2015 16:31:09 -0700 Subject: [PATCH 075/116] Find Index of Min or Max value --- MinMaxIndex | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 MinMaxIndex diff --git a/MinMaxIndex b/MinMaxIndex new file mode 100644 index 0000000..6df1873 --- /dev/null +++ b/MinMaxIndex @@ -0,0 +1,15 @@ +""" +Find Index of Min/Max Element. +""" + +lst = [40,10,20,30] + +def minIndex(lst): + return min(range(len(lst)), key = lst.__getitem__) #use xrange if < 2.7 + +def maxIndex(lst): + return max(range(len(lst)), key = lst.__getitem__) #use xrange if < 2.7 + +print(minIndex(lst)) +print(maxIndex(lst)) + From f5bbf3f26dc0ca4a151681baba726846282baeaa Mon Sep 17 00:00:00 2001 From: Max Brenner Date: Tue, 31 Mar 2015 19:07:09 +0200 Subject: [PATCH 076/116] Rename MinMaxIndex to MinMaxIndex.py --- MinMaxIndex => MinMaxIndex.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename MinMaxIndex => MinMaxIndex.py (100%) diff --git a/MinMaxIndex b/MinMaxIndex.py similarity index 100% rename from MinMaxIndex rename to MinMaxIndex.py From 32ef8253c2fde193d2d692598257f01ae73e4c4d Mon Sep 17 00:00:00 2001 From: Goutham Pilla Date: Tue, 31 Mar 2015 21:21:33 +0530 Subject: [PATCH 077/116] string of integers to integers list using map --- rawinputintegers.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 rawinputintegers.py diff --git a/rawinputintegers.py b/rawinputintegers.py new file mode 100644 index 0000000..53337ae --- /dev/null +++ b/rawinputintegers.py @@ -0,0 +1,15 @@ +#! /usr/bin/env python3 + +""" +Convert raw string integer inputs to integers +""" + +str_input = "1 2 3 4 5 6" + +print("### Input ###") +print(str_input) + +int_input = map(int, str_input.split()) + +print("### Output ###") +print(int_input) From 78e042760be1ed8b093f946b7b101685b5e9b423 Mon Sep 17 00:00:00 2001 From: Goutham Pilla Date: Wed, 1 Apr 2015 00:41:33 +0530 Subject: [PATCH 078/116] string of integers to integers list using map --- rawinputintegers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rawinputintegers.py b/rawinputintegers.py index 53337ae..7978000 100644 --- a/rawinputintegers.py +++ b/rawinputintegers.py @@ -12,4 +12,4 @@ int_input = map(int, str_input.split()) print("### Output ###") -print(int_input) +print(list(int_input)) From b3a4eae3d2474cb164af414117c9b3f3c2d42c4b Mon Sep 17 00:00:00 2001 From: Goutham Pilla Date: Wed, 1 Apr 2015 00:44:28 +0530 Subject: [PATCH 079/116] - Update contributors --- CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index e1078e4..2406fe1 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -19,3 +19,4 @@ - betezed (github.com/betezed) - transcranial (github.com/transcranial) - st0le (http://st0le.github.io) +- goutham2027 (github.com/goutham2027) From 6477e62b318fa6746bb029a932ba1ae09f78707b Mon Sep 17 00:00:00 2001 From: Dylan Baker Date: Tue, 31 Mar 2015 15:02:40 -0700 Subject: [PATCH 080/116] Adds an example of using python's lazy or for assignments --- conditionalassignment.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/conditionalassignment.py b/conditionalassignment.py index 8b8b304..d6c1aed 100755 --- a/conditionalassignment.py +++ b/conditionalassignment.py @@ -1,4 +1,16 @@ #! /usr/bin/env python3 -"""""" +"""Python has two ways to do conditional assignments + +The first is a fairly standard teranary style; + if else + +The second method takes advantage of the fact that python's or is lazy. When +an assignment is made if the first value is falsy (None is falsy), then it will +automatically return the second value, even if that value is falsy. + +""" b = True print(True if b else False) + +b = None or False +print(b) From f6b41ef2b5006d8114001c93e5585bcf7b1bd98c Mon Sep 17 00:00:00 2001 From: Dylan Baker Date: Wed, 1 Apr 2015 10:41:52 -0700 Subject: [PATCH 081/116] update contributers. --- CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index e1078e4..c4c3547 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -19,3 +19,4 @@ - betezed (github.com/betezed) - transcranial (github.com/transcranial) - st0le (http://st0le.github.io) +- dcbaker From db72f5240d1dcab24b7f56a809fdc31eb5cb7952 Mon Sep 17 00:00:00 2001 From: Gaurav Kamath Date: Wed, 1 Apr 2015 14:08:13 -0700 Subject: [PATCH 082/116] Capitalized filename was sticking out like a sore thumb --- MinMaxIndex.py => minmaxindex.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename MinMaxIndex.py => minmaxindex.py (100%) diff --git a/MinMaxIndex.py b/minmaxindex.py similarity index 100% rename from MinMaxIndex.py rename to minmaxindex.py From eb5817e6626df9c30dbcdcd03db82490afecdee1 Mon Sep 17 00:00:00 2001 From: brennerm Date: Thu, 2 Apr 2015 08:07:47 +0200 Subject: [PATCH 083/116] added isayme's contribution --- CONTRIBUTORS | 1 + nested_functions.py | 12 ++++++++++++ 2 files changed, 13 insertions(+) create mode 100644 nested_functions.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index f60f5f3..0989e10 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -21,3 +21,4 @@ - st0le (http://st0le.github.io) - goutham2027 (github.com/goutham2027) - dcbaker +- isayme diff --git a/nested_functions.py b/nested_functions.py new file mode 100644 index 0000000..be54087 --- /dev/null +++ b/nested_functions.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +"""nested functions""" +def addBy(val): + def func(inc): + return val + inc + return func + +addFive = addBy(5) +print(addFive(4)) + +addThree = addBy(3) +print(addThree(7)) From da806444a1e6dfd394af2ee129b7b019c7e089c9 Mon Sep 17 00:00:00 2001 From: Skycker Date: Sun, 5 Apr 2015 20:11:01 +0300 Subject: [PATCH 084/116] unique by attr sequence of objects --- CONTRIBUTORS | 1 + unique_by_attr.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 unique_by_attr.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 0989e10..1d5c187 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -22,3 +22,4 @@ - goutham2027 (github.com/goutham2027) - dcbaker - isayme +- Skycker (github.com/Skycker) diff --git a/unique_by_attr.py b/unique_by_attr.py new file mode 100644 index 0000000..61a5eb3 --- /dev/null +++ b/unique_by_attr.py @@ -0,0 +1,28 @@ +#! /usr/bin/env python3 +""" + If we have some sequence of objects and want to remove items with the same attribute value + Python creates a dict, where keys are value if attribute (bar in our case), values are object of the sequence. + After that the dict is transformed back to list + + Note: in result we save the last from repeating elements (item2 in our case)! +""" + + +class Foo(): + pass + + +item1 = Foo() +item1.bar = 15 + +item2 = Foo() +item2.bar = 15 + +item3 = Foo() +item3.bar = 5 + +lst = [item1, item2, item3] + +unique_lst = list({getattr(obj, 'bar'): obj for obj in lst}.values()) + +print(unique_lst) # [item2, item3] From fa5cc3ac1498d736802751d8d0e082f5844b801f Mon Sep 17 00:00:00 2001 From: Skycker Date: Sun, 5 Apr 2015 21:22:15 +0300 Subject: [PATCH 085/116] run common method of objects sequence with 1 line of code --- common_seq_method.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 common_seq_method.py diff --git a/common_seq_method.py b/common_seq_method.py new file mode 100644 index 0000000..789d75d --- /dev/null +++ b/common_seq_method.py @@ -0,0 +1,15 @@ +#! /usr/bin/env python3 +"""Run common method of big sequence of objects""" +import operator + + +class Foo(): + def bar(self, *args, **kwargs): + print('method bar works') + + +sequence = [Foo() for i in range(5)] + +# in python3 map returns iterator so we must ask python ro process elements by list() +# in python2 map(operator.methodcaller('bar'), sequence) works perfectly +list(map(operator.methodcaller('bar'), sequence)) From 5f8742048c28bc579145ccdebf3e2641d7492465 Mon Sep 17 00:00:00 2001 From: Goutham Pilla Date: Mon, 6 Apr 2015 10:24:00 +0530 Subject: [PATCH 086/116] - typo in infile documentation --- reverselist.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/reverselist.py b/reverselist.py index c58de9a..33cd91b 100755 --- a/reverselist.py +++ b/reverselist.py @@ -1,5 +1,6 @@ #! /usr/bin/env python3 -"""reverting list with special case of slice step param""" +"""reversing list with special case of slice step param""" + a = [5, 4, 3, 2, 1] print(a[::-1]) From 34a1b5666ec467aaba336a60fb66630e4092250a Mon Sep 17 00:00:00 2001 From: Kirill Kostyukhin Date: Mon, 6 Apr 2015 13:55:35 +0300 Subject: [PATCH 087/116] ro -> to --- common_seq_method.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common_seq_method.py b/common_seq_method.py index 789d75d..b026eb0 100644 --- a/common_seq_method.py +++ b/common_seq_method.py @@ -10,6 +10,6 @@ def bar(self, *args, **kwargs): sequence = [Foo() for i in range(5)] -# in python3 map returns iterator so we must ask python ro process elements by list() +# in python3 map returns iterator so we must ask python to process elements by list() # in python2 map(operator.methodcaller('bar'), sequence) works perfectly list(map(operator.methodcaller('bar'), sequence)) From 0c6626875e6e61547cda665600f3597b2ee0e40e Mon Sep 17 00:00:00 2001 From: Kirill Kostyukhin Date: Mon, 6 Apr 2015 14:22:24 +0300 Subject: [PATCH 088/116] Update unique_by_attr.py --- unique_by_attr.py | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/unique_by_attr.py b/unique_by_attr.py index 61a5eb3..5b581d0 100644 --- a/unique_by_attr.py +++ b/unique_by_attr.py @@ -8,18 +8,13 @@ """ -class Foo(): - pass +class Foo: + def __init__(self, value): + self.bar = value - -item1 = Foo() -item1.bar = 15 - -item2 = Foo() -item2.bar = 15 - -item3 = Foo() -item3.bar = 5 +item1 = Foo(15) +item2 = Foo(15) +item3 = Foo(5) lst = [item1, item2, item3] From 71771db10dbc4781b015e985274a79fcdab0f5a2 Mon Sep 17 00:00:00 2001 From: vvscloud Date: Tue, 7 Apr 2015 10:47:07 +0530 Subject: [PATCH 089/116] Update lightweightswitch.py there is a syntax error in above file in the dictionary 'b'. --- lightweightswitch.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lightweightswitch.py b/lightweightswitch.py index f9329bd..a985220 100755 --- a/lightweightswitch.py +++ b/lightweightswitch.py @@ -15,7 +15,7 @@ def subtract(a, b): return a - b b = { - '+': add + '+': add, '-': subtract } From 83a1b8126e95feee421010020e53fe214dc2699b Mon Sep 17 00:00:00 2001 From: vvscloud Date: Tue, 7 Apr 2015 10:49:46 +0530 Subject: [PATCH 090/116] Update CONTRIBUTORS adding self to contributor list. --- CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 1d5c187..33ef461 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -23,3 +23,4 @@ - dcbaker - isayme - Skycker (github.com/Skycker) +- vvscloud (github.com/vvscloud) From e060482dac413f16f05e2bceb1c84f78ca5b51c5 Mon Sep 17 00:00:00 2001 From: xamvolagis Date: Tue, 7 Apr 2015 03:36:34 -0400 Subject: [PATCH 091/116] Added sortlistkeepindices.py --- CONTRIBUTORS | 1 + sortlistkeepindices.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 sortlistkeepindices.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 1d5c187..7a4d6a8 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -23,3 +23,4 @@ - dcbaker - isayme - Skycker (github.com/Skycker) +- xamvolagis (github.com/xamvolagis) \ No newline at end of file diff --git a/sortlistkeepindices.py b/sortlistkeepindices.py new file mode 100644 index 0000000..cbf1633 --- /dev/null +++ b/sortlistkeepindices.py @@ -0,0 +1,18 @@ +#! /usr/bin/env python3 +"""Sort a list and store previous indices of values""" + +#enumerate is a great but little-known tool for writing nice code + +l = [4,2,3,5,1] +print("original list: ", l) + +values, indices = zip(*sorted(enumerate(l))) + +#now values contains the sorted list and indices contains +#the indices of the corresponding value in the original list + +print("sorted list: ", values) +print("original indices: ", indices) + +#note that this returns tuples, but if necessary they can +#be converted to lists using list() From 3bbe67e0a6b99f64e0166a6b5429bc6b757a10b0 Mon Sep 17 00:00:00 2001 From: xamvolagis Date: Tue, 7 Apr 2015 17:55:25 -0400 Subject: [PATCH 092/116] Fixed sortlistkeepindices.py --- sortlistkeepindices.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sortlistkeepindices.py b/sortlistkeepindices.py index cbf1633..dd39712 100644 --- a/sortlistkeepindices.py +++ b/sortlistkeepindices.py @@ -6,7 +6,7 @@ l = [4,2,3,5,1] print("original list: ", l) -values, indices = zip(*sorted(enumerate(l))) +values, indices = zip(*sorted((a,b) for (b,a) in enumerate(l))) #now values contains the sorted list and indices contains #the indices of the corresponding value in the original list From 7f3e56deec8463e9470907f88857911867677283 Mon Sep 17 00:00:00 2001 From: Richard O'Dwyer Date: Wed, 8 Apr 2015 11:34:06 +0100 Subject: [PATCH 093/116] Adds Python 2 flatten list example --- flattenlist.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/flattenlist.py b/flattenlist.py index cd3a81f..7fc64af 100755 --- a/flattenlist.py +++ b/flattenlist.py @@ -2,7 +2,7 @@ """ Deep flattens a nested list -Examples: +Examples: >>> list(flatten_list([1, 2, [3, 4], [5, 6, [7]]])) [1, 2, 3, 4, 5, 6, 7] >>> list(flatten_list(['apple', 'banana', ['orange', 'lemon']])) @@ -15,3 +15,7 @@ def flatten_list(L): yield from flatten_list(item) else: yield item + +# In Python 2 +from compiler.ast import flatten +flatten(L) From 3591459a62230022db6f6fad459d4ebfb2e6d858 Mon Sep 17 00:00:00 2001 From: Richard O'Dwyer Date: Wed, 8 Apr 2015 14:12:56 +0100 Subject: [PATCH 094/116] Updates CONTRIBUTORS --- CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 2b07e3b..8c7f6ca 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -25,3 +25,4 @@ - Skycker (github.com/Skycker) - vvscloud (github.com/vvscloud) - xamvolagis (github.com/xamvolagis) +- richardasaurus (richard@richard.do) From 82dced680535daa031be4409844dcea0338fccae Mon Sep 17 00:00:00 2001 From: Max Brenner Date: Mon, 13 Apr 2015 21:48:53 +0200 Subject: [PATCH 095/116] Update extendediterableunpacking.py --- extendediterableunpacking.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/extendediterableunpacking.py b/extendediterableunpacking.py index cc424a3..4a4f8f5 100755 --- a/extendediterableunpacking.py +++ b/extendediterableunpacking.py @@ -3,4 +3,9 @@ a placeholder variable""" a, *b, c = range(10) -print(a, b, c) \ No newline at end of file +print(a, b, c) + +"""advanced example""" + +[(c,*d,[*e]),f,*g] = [[1,2,3,4,[5,5,5]],6,7,8] +print(c,d,e,f,g) From 49e20208b959b4f655abf1ac0b3809ee864a271b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Lipi=C5=84ski?= Date: Fri, 17 Apr 2015 17:36:18 +0200 Subject: [PATCH 096/116] Add few ways to flatten list of lists --- listofliststolist.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 listofliststolist.py diff --git a/listofliststolist.py b/listofliststolist.py new file mode 100644 index 0000000..7efeb9f --- /dev/null +++ b/listofliststolist.py @@ -0,0 +1,12 @@ +a = [[1,2], [3,4]] + +# Solutions: + +[x for _list in a for x in _list] + +import itertools +list(itertools.chain(*a)) + +list(itertools.chain.from_iterable(a)) + +sum(a, []) From 8f1517db450f84b908dca4b26b0b14561d09e675 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Lipi=C5=84ski?= Date: Mon, 20 Apr 2015 09:27:34 +0200 Subject: [PATCH 097/116] Move and add another example flatten list of lists --- flattenlist.py | 19 +++++++++++++++++++ listofliststolist.py | 12 ------------ 2 files changed, 19 insertions(+), 12 deletions(-) delete mode 100644 listofliststolist.py diff --git a/flattenlist.py b/flattenlist.py index 7fc64af..a3be006 100755 --- a/flattenlist.py +++ b/flattenlist.py @@ -19,3 +19,22 @@ def flatten_list(L): # In Python 2 from compiler.ast import flatten flatten(L) + + +# Flatten list of lists + +a = [[1, 2], [3, 4]] + +# Solutions: + +[x for _list in a for x in _list] + +import itertools +list(itertools.chain(*a)) + +list(itertools.chain.from_iterable(a)) + +reduce(lambda x, y: x+y, a) + +sum(a, []) + diff --git a/listofliststolist.py b/listofliststolist.py deleted file mode 100644 index 7efeb9f..0000000 --- a/listofliststolist.py +++ /dev/null @@ -1,12 +0,0 @@ -a = [[1,2], [3,4]] - -# Solutions: - -[x for _list in a for x in _list] - -import itertools -list(itertools.chain(*a)) - -list(itertools.chain.from_iterable(a)) - -sum(a, []) From 43e008a3dca8de4a774e55fcc71fc1cd1663ff62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Lipi=C5=84ski?= Date: Tue, 21 Apr 2015 09:21:38 +0200 Subject: [PATCH 098/116] Add prints and info about python 2 --- flattenlist.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/flattenlist.py b/flattenlist.py index a3be006..5843c42 100755 --- a/flattenlist.py +++ b/flattenlist.py @@ -27,14 +27,15 @@ def flatten_list(L): # Solutions: -[x for _list in a for x in _list] +print([x for _list in a for x in _list]) import itertools -list(itertools.chain(*a)) +print(list(itertools.chain(*a))) -list(itertools.chain.from_iterable(a)) +print(list(itertools.chain.from_iterable(a))) -reduce(lambda x, y: x+y, a) +# In Python 2 +print(reduce(lambda x, y: x+y, a)) -sum(a, []) +print(sum(a, [])) From 6ed6e4f8bc480c00a1c4125017d74c5650fb273b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Lipi=C5=84ski?= Date: Tue, 21 Apr 2015 14:50:18 +0200 Subject: [PATCH 099/116] Add myself to contributors --- CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 8c7f6ca..db01a92 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -26,3 +26,4 @@ - vvscloud (github.com/vvscloud) - xamvolagis (github.com/xamvolagis) - richardasaurus (richard@richard.do) +- lipinski (github.com/lipinski) \ No newline at end of file From ff425b14583a827010a50f9e7908773a41b706f2 Mon Sep 17 00:00:00 2001 From: Pahaz Blinov Date: Tue, 28 Apr 2015 19:35:51 +0500 Subject: [PATCH 100/116] style(dictsortbyvalue.py): PEP8 style --- dictsortbyvalue.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dictsortbyvalue.py b/dictsortbyvalue.py index 16c5b29..cf5bdec 100755 --- a/dictsortbyvalue.py +++ b/dictsortbyvalue.py @@ -2,7 +2,7 @@ """ 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])) +print(sorted(d.items(), key=lambda x: x[1])) """ Sort using operator.itemgetter as the sort key instead of a lambda""" From 9a9c0899e29424c8e0bed7f8c13cd997cef8c6e6 Mon Sep 17 00:00:00 2001 From: Pahaz Blinov Date: Tue, 28 Apr 2015 19:39:24 +0500 Subject: [PATCH 101/116] style(extendediterableunpacking): PEP8 style --- extendediterableunpacking.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extendediterableunpacking.py b/extendediterableunpacking.py index 4a4f8f5..bc5d77f 100755 --- a/extendediterableunpacking.py +++ b/extendediterableunpacking.py @@ -7,5 +7,5 @@ """advanced example""" -[(c,*d,[*e]),f,*g] = [[1,2,3,4,[5,5,5]],6,7,8] -print(c,d,e,f,g) +[(c, *d, [*e]), f, *g] = [[1, 2, 3, 4, [5, 5, 5]], 6, 7, 8] +print(c, d, e, f, g) From bad9e5817d9b7a7136f4076d687344624af0b34f Mon Sep 17 00:00:00 2001 From: Pahaz Blinov Date: Tue, 28 Apr 2015 19:41:52 +0500 Subject: [PATCH 102/116] style(flattenlist.py): PEP8 style --- flattenlist.py | 1 + 1 file changed, 1 insertion(+) diff --git a/flattenlist.py b/flattenlist.py index 5843c42..51070d6 100755 --- a/flattenlist.py +++ b/flattenlist.py @@ -9,6 +9,7 @@ ['apple', 'banana', 'orange', 'lemon'] """ + def flatten_list(L): for item in L: if isinstance(item, list): From 171432ea007b3ad179deb8133a08b86c183d9221 Mon Sep 17 00:00:00 2001 From: Pahaz Blinov Date: Tue, 28 Apr 2015 19:44:35 +0500 Subject: [PATCH 103/116] style(keydefaultdict.py): PEP8 style --- keydefaultdict.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/keydefaultdict.py b/keydefaultdict.py index fd2668d..af4fede 100644 --- a/keydefaultdict.py +++ b/keydefaultdict.py @@ -3,16 +3,18 @@ """ from collections import defaultdict + class keydefaultdict(defaultdict): def __missing__(self, key): if self.default_factory is None: - raise KeyError( key ) + raise KeyError(key) else: ret = self[key] = self.default_factory(key) return ret + def pow2(n): - return 1 << n + return 1 << n d = keydefaultdict(pow2) print(d[1]) From 040433ceddfb46b0c5369077351958d0f24d7e4d Mon Sep 17 00:00:00 2001 From: Wenchao Hu Date: Sat, 9 May 2015 20:40:12 +0800 Subject: [PATCH 104/116] Update common_seq_method.py add a new way more understandable --- common_seq_method.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/common_seq_method.py b/common_seq_method.py index b026eb0..c55ebb2 100644 --- a/common_seq_method.py +++ b/common_seq_method.py @@ -13,3 +13,6 @@ def bar(self, *args, **kwargs): # in python3 map returns iterator so we must ask python to process elements by list() # in python2 map(operator.methodcaller('bar'), sequence) works perfectly list(map(operator.methodcaller('bar'), sequence)) + +# there is another way more understandable +[f.bar() for f in sequence] From 299f1f61e53d56ad5c14541c94f9c21ef15eb2f5 Mon Sep 17 00:00:00 2001 From: Hu Wenchao Date: Sun, 10 May 2015 15:37:24 +0800 Subject: [PATCH 105/116] pep8 style --- loopoverlappingdicts.py | 2 +- metatable.py | 14 +++++++++----- minmaxindex.py | 9 +++++---- removeduplicatefromlist.py | 1 - reverselist.py | 2 +- socketmsghandling.py | 6 +++--- sortlistkeepindices.py | 14 +++++++------- transpose.py | 6 +++--- whileelse.py | 12 ++++++------ 9 files changed, 35 insertions(+), 31 deletions(-) diff --git a/loopoverlappingdicts.py b/loopoverlappingdicts.py index 19efa75..e7d5dda 100755 --- a/loopoverlappingdicts.py +++ b/loopoverlappingdicts.py @@ -6,7 +6,7 @@ for ky in set(dctA) & set(dctB): print(ky) - + """loop over dicts that share (some) keys in Python3""" for ky in dctA.keys() & dctB.keys(): print(ky) diff --git a/metatable.py b/metatable.py index 8f2fdab..040079c 100644 --- a/metatable.py +++ b/metatable.py @@ -3,17 +3,21 @@ """ from collections import defaultdict + class metatable(defaultdict): + def __missing__(self, key): if self.default_factory is None: - raise KeyError( key ) + raise KeyError(key) else: - ret = self[key] = self.default_factory(self,key) + ret = self[key] = self.default_factory(self, key) return ret -def fib(d,n): - if n == 0 or n == 1: return n - return d[n - 1] + d[n - 2] + +def fib(d, n): + if n == 0 or n == 1: + return n + return d[n - 1] + d[n - 2] d = metatable(fib) print(d[1]) diff --git a/minmaxindex.py b/minmaxindex.py index 6df1873..ff9e146 100644 --- a/minmaxindex.py +++ b/minmaxindex.py @@ -2,14 +2,15 @@ Find Index of Min/Max Element. """ -lst = [40,10,20,30] +lst = [40, 10, 20, 30] + def minIndex(lst): - return min(range(len(lst)), key = lst.__getitem__) #use xrange if < 2.7 + return min(range(len(lst)), key=lst.__getitem__) # use xrange if < 2.7 + def maxIndex(lst): - return max(range(len(lst)), key = lst.__getitem__) #use xrange if < 2.7 + return max(range(len(lst)), key=lst.__getitem__) # use xrange if < 2.7 print(minIndex(lst)) print(maxIndex(lst)) - diff --git a/removeduplicatefromlist.py b/removeduplicatefromlist.py index 6286854..1544cdc 100755 --- a/removeduplicatefromlist.py +++ b/removeduplicatefromlist.py @@ -13,4 +13,3 @@ items = ["foo", "bar", "bar", "foo"] print(list(OrderedDict.fromkeys(items).keys())) - diff --git a/reverselist.py b/reverselist.py index 33cd91b..aa8e2d0 100755 --- a/reverselist.py +++ b/reverselist.py @@ -6,4 +6,4 @@ """iterating over list contents in reverse efficiently.""" for ele in reversed(a): - print(ele) + print(ele) diff --git a/socketmsghandling.py b/socketmsghandling.py index 151e9ec..c315b4c 100644 --- a/socketmsghandling.py +++ b/socketmsghandling.py @@ -6,14 +6,14 @@ msgs = [] # normal way -#while True: +# while True: # msg = coon.recv(1024) # if recv: # msgs.append(msg) -# else: # when no msg come, break +# 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 + msgs.append(msg) diff --git a/sortlistkeepindices.py b/sortlistkeepindices.py index dd39712..614559d 100644 --- a/sortlistkeepindices.py +++ b/sortlistkeepindices.py @@ -1,18 +1,18 @@ #! /usr/bin/env python3 """Sort a list and store previous indices of values""" -#enumerate is a great but little-known tool for writing nice code +# enumerate is a great but little-known tool for writing nice code -l = [4,2,3,5,1] +l = [4, 2, 3, 5, 1] print("original list: ", l) -values, indices = zip(*sorted((a,b) for (b,a) in enumerate(l))) +values, indices = zip(*sorted((a, b) for (b, a) in enumerate(l))) -#now values contains the sorted list and indices contains -#the indices of the corresponding value in the original list +# now values contains the sorted list and indices contains +# the indices of the corresponding value in the original list print("sorted list: ", values) print("original indices: ", indices) -#note that this returns tuples, but if necessary they can -#be converted to lists using list() +# note that this returns tuples, but if necessary they can +# be converted to lists using list() diff --git a/transpose.py b/transpose.py index f4d0f82..aa9bcae 100644 --- a/transpose.py +++ b/transpose.py @@ -1,6 +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 +original = [['a', 'b'], ['c', 'd'], ['e', 'f']] +transposed = zip(*original) +print(list(transposed)) diff --git a/whileelse.py b/whileelse.py index 57812e2..d659d9e 100755 --- a/whileelse.py +++ b/whileelse.py @@ -1,12 +1,12 @@ -""" You can have an else clause with a while. Works like for-else. +""" 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 + print("Whil-ing away!") + i -= 1 + if i == 3: + break else: - print("Finished up!") + print("Finished up!") From 94b3aa4e8fadcf3c824c59a757cc59eb8afb972f Mon Sep 17 00:00:00 2001 From: felipevolpone Date: Mon, 18 May 2015 20:13:20 -0300 Subject: [PATCH 106/116] An example of how to use dunder method to improve behavior of objects. --- deck_as_list.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 deck_as_list.py diff --git a/deck_as_list.py b/deck_as_list.py new file mode 100644 index 0000000..4ab55fb --- /dev/null +++ b/deck_as_list.py @@ -0,0 +1,35 @@ +#! /usr/bin/env python3 + +""" How to use dunder methods to add behavior to objects. +Here it's an example of how implement a french deck that can be used as a list""" + +import collections + +Card = collections.namedtuple('Card', ['rank', 'suit']) + + +class Deck: + + ranks = [str(n) for n in range(2, 11)] + list('JQKA') + suits = 'spades diamonds clubs hearts'.split() + + def __init__(self): + self._cards = [Card(rank, suit) for suit in self.suits + for rank in self.ranks] + + def __len__(self): + return len(self._cards) + + def __getitem__(self, position): + return self._cards[position] + +card_a = Card('A', 'spades') +print card_a + +deck = Deck() +len(deck) + +print deck[0] +print deck[-1] +for card in deck: + print card From 8a4e23820e7325732ceed22cf8aa0dd3bf1e5bdd Mon Sep 17 00:00:00 2001 From: felipevolpone Date: Mon, 18 May 2015 20:15:16 -0300 Subject: [PATCH 107/116] Adding myself to contributors --- CONTRIBUTORS | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index db01a92..4b61224 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -26,4 +26,5 @@ - vvscloud (github.com/vvscloud) - xamvolagis (github.com/xamvolagis) - richardasaurus (richard@richard.do) -- lipinski (github.com/lipinski) \ No newline at end of file +- lipinski (github.com/lipinski) +- felipevolpone (github.com/felipevolpone) From 54afc3a20cb68d3abfe516d91829ff102b764be4 Mon Sep 17 00:00:00 2001 From: felipevolpone Date: Tue, 19 May 2015 18:54:28 -0300 Subject: [PATCH 108/116] Changing print to print() --- deck_as_list.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/deck_as_list.py b/deck_as_list.py index 4ab55fb..621030c 100644 --- a/deck_as_list.py +++ b/deck_as_list.py @@ -24,12 +24,12 @@ def __getitem__(self, position): return self._cards[position] card_a = Card('A', 'spades') -print card_a +print(card_a) deck = Deck() len(deck) -print deck[0] -print deck[-1] +print(deck[0]) +print(deck[-1]) for card in deck: - print card + print(card) From 9e14a1332a657c3d7c0a2d6939ac104089c080b0 Mon Sep 17 00:00:00 2001 From: Anton Konstantinov Date: Mon, 25 May 2015 10:12:01 +0300 Subject: [PATCH 109/116] Add Code to Function example --- CONTRIBUTORS | 3 ++- codetofunction.py | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 codetofunction.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index db01a92..86e8f1a 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -26,4 +26,5 @@ - vvscloud (github.com/vvscloud) - xamvolagis (github.com/xamvolagis) - richardasaurus (richard@richard.do) -- lipinski (github.com/lipinski) \ No newline at end of file +- lipinski (github.com/lipinski) +- falceeffect (github.com/falceeffect) \ No newline at end of file diff --git a/codetofunction.py b/codetofunction.py new file mode 100644 index 0000000..8dd338c --- /dev/null +++ b/codetofunction.py @@ -0,0 +1,17 @@ +#! /usr/bin/env python3 +''' +A simple way to convert arbitrary Python code into a function +''' + +import math # using sin, cos and sqrt for example + +''' Takes a code string and returns a ready-to-use function ''' +def compile_(s): + code = """def f(x):\n return {}""".format(s) # wrap the string as a function f(x) + scope = {"sin": math.sin, "cos": math.cos, "sqrt": math.sqrt} # define the scope for the code to use + exec(code, scope) # execute code inside the given scope + # f(x) gets defined inside %vis% + return scope["f"] # now we only have to extract it and return + +f = compile_("x**2 + 2*sin(x)") +print(f(10)) \ No newline at end of file From 2d2fecf73ce1f2cb297d9fb7d17a8189bd26cde2 Mon Sep 17 00:00:00 2001 From: Serdar Yegulalp Date: Thu, 28 May 2015 23:44:29 -0400 Subject: [PATCH 110/116] Update namedformatting.py --- namedformatting.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/namedformatting.py b/namedformatting.py index 042538a..3106aa0 100755 --- a/namedformatting.py +++ b/namedformatting.py @@ -9,6 +9,9 @@ d = {'name': 'Jeff', 'age': 24} print("My name is {name} and I'm {age} years old.".format(**d)) +"""alternate .format method""" +print("My name is {} and I'm {} years old.".format('Jeff','24')) + """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)) From 03f0195899c9480f937cc2c50e3d0bfa27b0fcd5 Mon Sep 17 00:00:00 2001 From: awsh Date: Tue, 6 Oct 2015 15:37:17 -0400 Subject: [PATCH 111/116] added context manager examples --- contextmanagers.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 contextmanagers.py diff --git a/contextmanagers.py b/contextmanagers.py new file mode 100644 index 0000000..138c6d9 --- /dev/null +++ b/contextmanagers.py @@ -0,0 +1,40 @@ +#! /usr/bin/env python3 +"""Context managers are useful for automatically releasing resources once you are done with them.""" + +# common context manager that will close +# a file when it has been read +with open('README.md') as f: + contents = f.read() + + +# make your own context manager +import contextlib + +@contextlib.contextmanager +def unlock(resource): + resource = "unlocked" + try: + yield resource + finally: + resource = "locked" + + +# a resource that is locked +resource = "locked" + +# test that it is indeed locked +print(resource) + +# call your 'unlock' context manager with your resource +with unlock(resource) as unlocked: + print(unlocked) # check that it is unlocked + +# ensure it was re-locked when it left the 'unlock' context +print(resource) + + + + + + + From 05b0d1737077b438965cd7cb0a7171b8e98321d9 Mon Sep 17 00:00:00 2001 From: awsh Date: Tue, 6 Oct 2015 15:38:49 -0400 Subject: [PATCH 112/116] updated contributors --- CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 16925d8..7d3b5a6 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -29,3 +29,4 @@ - lipinski (github.com/lipinski) - falceeffect (github.com/falceeffect) - felipevolpone (github.com/felipevolpone) +- awsh (github.com/awsh) From 02c1751bf1e13d8e999e512950271c20d9788d42 Mon Sep 17 00:00:00 2001 From: Nick Date: Fri, 11 Dec 2015 15:51:13 +0000 Subject: [PATCH 113/116] Create reversstring.py - also reverses ints. Very closely related to reverse list. I think explicit versions of these types are probably worth adding - newbies don't always jump from the concept of slicing a list to slicing a string. --- reversestring.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 reversestring.py diff --git a/reversestring.py b/reversestring.py new file mode 100644 index 0000000..ef4bace --- /dev/null +++ b/reversestring.py @@ -0,0 +1,17 @@ +#! /usr/bin/env python3 + +"""reversing string with special case of slice step param""" + +a = 'abcdefghijklmnopqrstuvwxyz' +print(a[::-1]) + + +"""iterating over string contents in reverse efficiently.""" + +for char in reversed(a): + print(ele) + +"""reversing an integer through type conversion and slicing.""" + +num = 123456789 +print(int(str(num)[::-1])) From 344d9eaf34c615efdb3cb33591b710c51c347491 Mon Sep 17 00:00:00 2001 From: Nick Date: Fri, 11 Dec 2015 15:52:25 +0000 Subject: [PATCH 114/116] fixed typo --- reversestring.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reversestring.py b/reversestring.py index ef4bace..7f1b14d 100644 --- a/reversestring.py +++ b/reversestring.py @@ -9,7 +9,7 @@ """iterating over string contents in reverse efficiently.""" for char in reversed(a): - print(ele) + print(char) """reversing an integer through type conversion and slicing.""" From 84c10c007c23dcaaf8bdba471f67313536ce1553 Mon Sep 17 00:00:00 2001 From: Nick Date: Fri, 11 Dec 2015 15:53:58 +0000 Subject: [PATCH 115/116] Fixed typo --- reverselist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reverselist.py b/reverselist.py index 0fedc4e..cd358bb 100755 --- a/reverselist.py +++ b/reverselist.py @@ -1,5 +1,5 @@ #! /usr/bin/env python3 -"""reverting list with special case of slice step param""" +"""reversing list with special case of slice step param""" a = [5, 4, 3, 2, 1] print(a[::-1]) From 197907a44325aa7523f1dd2f60a0c552df5af103 Mon Sep 17 00:00:00 2001 From: Lime Date: Sun, 29 Nov 2015 23:14:40 +0800 Subject: [PATCH 116/116] add dictdefaultvalue.py and boolisslow.py --- CONTRIBUTORS | 1 + boolisslow.py | 42 ++++++++++++++++++++++++++++++++++++++++++ dictdefaultvalue.py | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 boolisslow.py create mode 100644 dictdefaultvalue.py diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 7d3b5a6..73d29e0 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -30,3 +30,4 @@ - falceeffect (github.com/falceeffect) - felipevolpone (github.com/felipevolpone) - awsh (github.com/awsh) +- shiyanhui (github.com/shiyanhui) diff --git a/boolisslow.py b/boolisslow.py new file mode 100644 index 0000000..b2c430d --- /dev/null +++ b/boolisslow.py @@ -0,0 +1,42 @@ +""" +True and False are keywords in python3, but not in Python2. In Python2 +the value of True is 1, and the value of False is 0. True and False can be +regarded as vars and thus they are slow in while loop. + +By the way, True and False can be changed in Python2. + +Note: This leads to a performance improvement only in Python2. +""" + +from timeit import timeit + + +def test_true(): + count = 1000 + while True: # here is True + if count < 0: + break + count -= 1 + + +def test_1(): + count = 1000 + while 1: # here is 1 + if count < 0: + break + count -= 1 + + +# on my macbook pro 15 +# test_true is about 59.3047289848 seconds +# test_1 is about 39.0966179371 seconds +print(timeit(test_true, number=1000000)) +print(timeit(test_1, number=1000000)) + + +# True and False can be changed in python2 +True = 0 +False = 100 + +print(True) +print(False) diff --git a/dictdefaultvalue.py b/dictdefaultvalue.py new file mode 100644 index 0000000..154613a --- /dev/null +++ b/dictdefaultvalue.py @@ -0,0 +1,38 @@ +""" +When update value in a dict based on the old value, we usually check whether +the key is in the dict. But with `dict.setdefault`, `dict.get` and +`collections.defaultdict` the code can be shorter and cleaner. + +Before: + >>> d = {} + >>> if 'a' not in d: # update a list + ... d['a'] = [] + ... + >>> d['a'].append(1) + >>> + >>> if 'b' not in d: # update an integer + ... d['b'] = 0 + ... + >>> d['b'] += 1 + +Now: + >>> d = {} + >>> d.setdefault('a', []).append(1) + >>> d['b'] = d.get('b', 0) + 1 +""" + +""" builtin dict """ +d = {} +d.setdefault('a', []).append(1) +d['b'] = d.get('b', 0) + 1 + +print(d) + + +""" with collections.defaultdict """ +from collections import defaultdict + +d = defaultdict(list) +d['a'].append(1) + +print(d)