├── README.md ├── book ├── algorithms │ ├── algorithms_one_liner_01.py │ ├── algorithms_one_liner_02.py │ ├── algorithms_one_liner_03.py │ ├── algorithms_one_liner_04.py │ ├── algorithms_one_liner_05.py │ ├── algorithms_one_liner_06.py │ ├── algorithms_one_liner_07.py │ ├── algorithms_one_liner_08.py │ ├── algorithms_one_liner_09.py │ └── algorithms_one_liner_10.py ├── data_science │ ├── numpy_one_liner_01.py │ ├── numpy_one_liner_02.py │ ├── numpy_one_liner_03.py │ ├── numpy_one_liner_04.py │ ├── numpy_one_liner_05.py │ ├── numpy_one_liner_06.py │ ├── numpy_one_liner_07.py │ ├── numpy_one_liner_08.py │ ├── numpy_one_liner_09.py │ └── numpy_one_liner_10.py ├── machine_learning │ ├── sklearn_one_liner_01.py │ ├── sklearn_one_liner_02.py │ ├── sklearn_one_liner_03.py │ ├── sklearn_one_liner_04.py │ ├── sklearn_one_liner_05.py │ ├── sklearn_one_liner_06.py │ ├── sklearn_one_liner_07.py │ ├── sklearn_one_liner_08.py │ ├── sklearn_one_liner_09.py │ ├── sklearn_one_liner_10.py │ └── sklearn_one_liner_11.py ├── python_tricks │ ├── one_liner_01.py │ ├── one_liner_02.py │ ├── one_liner_03.py │ ├── one_liner_04.py │ ├── one_liner_05.py │ ├── one_liner_06.py │ ├── one_liner_07.py │ ├── one_liner_08.py │ ├── one_liner_09.py │ ├── one_liner_10.py │ └── one_liner_11.py └── regular_expressions │ ├── regex_one_liner_01.py │ ├── regex_one_liner_02.py │ ├── regex_one_liner_03.py │ ├── regex_one_liner_04.py │ ├── regex_one_liner_05.py │ ├── regex_one_liner_06.py │ ├── regex_one_liner_07.py │ ├── regex_one_liner_08.py │ ├── regex_one_liner_09.py │ └── regex_one_liner_10.py └── one_liners.py /README.md: -------------------------------------------------------------------------------- 1 | # Python One Liners 2 | 3 | This repository collects all Python one-liners that are of interest to the Python community. One-Liners are concise snippets of source code (with or without library calls) that accomplish a given task in a concise and compressed manner. 4 | 5 | They are often used to call a Python script from the operating system terminal using the `python -c` command: 6 | 7 | ```python 8 | python -c 'print("hello world")' 9 | ``` 10 | 11 | Here are additional resources for Python one-liners: 12 | 13 | # Free Python One-Liners Learning Resources 14 | 15 | * [Free ''Python One-Liners'' videos & book resources](https://pythononeliners.com/) 16 | * [Collection of ''One-Liners'' with interactive shell](https://blog.finxter.com/10-python-one-liners/) 17 | * [Book ''Python One-Liners''](https://www.amazon.com/gp/product/B07ZY7XMX8) 18 | * [Interesting Quora Thread ''Python One-Liner''](https://www.quora.com/What-are-some-of-the-most-elegant-greatest-Python-one-liners) 19 | * [Python One-Line X - How to accomplish different tasks in a single line](https://blog.finxter.com/python-one-line-x/) 20 | * [Subreddit '''Python One-Liners'''](https://www.reddit.com/r/PythonOneLiners/) 21 | * [Python One-Liners Wiki](https://wiki.python.org/moin/Powerful%20Python%20One-Liners) 22 | 23 | # How to Contribute Your One-Liners 24 | 25 | Feel free to submit your own one-liners in the `one_liners.py` Python file! 26 | 27 | Creating your own one-liners is an excellent way to improve your understanding of the single line of Python code. After all, every complicated Python program consists just of a number of Python one-liners---chained together to a coherent whole! 28 | -------------------------------------------------------------------------------- /book/algorithms/algorithms_one_liner_01.py: -------------------------------------------------------------------------------- 1 | # Finding Anagrams with Lambda Functions and Sorting 2 | 3 | 4 | ## One-Liner 5 | is_anagram = lambda x1, x2: sorted(x1) == sorted(x2) 6 | 7 | ## Results 8 | print(is_anagram("elvis", "lives")) 9 | print(is_anagram("elvise", "livees")) 10 | print(is_anagram("elvis", "dead")) 11 | ''' 12 | True 13 | True 14 | False 15 | ''' 16 | -------------------------------------------------------------------------------- /book/algorithms/algorithms_one_liner_02.py: -------------------------------------------------------------------------------- 1 | # Finding Palindromes with Lambda Functions and Negative Slicing 2 | 3 | 4 | ## One-Liner 5 | is_palindrome = lambda phrase: phrase == phrase[::-1] 6 | 7 | ## Result 8 | print(is_palindrome("anna")) 9 | print(is_palindrome("kdljfasjf")) 10 | print(is_palindrome("rats live on no evil star")) 11 | ''' 12 | True 13 | False 14 | True 15 | ''' 16 | -------------------------------------------------------------------------------- /book/algorithms/algorithms_one_liner_03.py: -------------------------------------------------------------------------------- 1 | # Counting Permutations with Recursive Factorial Functions 2 | 3 | 4 | ## The Data 5 | n = 5 6 | 7 | ## The One-Liner 8 | factorial = lambda n: n * factorial(n-1) if n > 1 else 1 9 | 10 | ## The Result 11 | print(factorial(n)) 12 | ''' 13 | 120 14 | ''' 15 | -------------------------------------------------------------------------------- /book/algorithms/algorithms_one_liner_04.py: -------------------------------------------------------------------------------- 1 | # Finding the Levenshtein Distance 2 | 3 | 4 | ## The Data 5 | a = "cat" 6 | b = "chello" 7 | c = "chess" 8 | 9 | ## The One-Liner 10 | ls = lambda a, b: len(b) if not a else len(a) if not b else min( 11 | ls(a[1:], b[1:])+(a[0] != b[0]), 12 | ls(a[1:], b)+1, 13 | ls(a, b[1:])+1) 14 | 15 | ## The Result 16 | print(ls(a,b)) 17 | print(ls(a,c)) 18 | print(ls(b,c)) 19 | ''' 20 | 5 21 | 4 22 | 3 23 | ''' 24 | -------------------------------------------------------------------------------- /book/algorithms/algorithms_one_liner_05.py: -------------------------------------------------------------------------------- 1 | # Calculating the Powerset by Using Functional Programming 2 | 3 | 4 | # Dependencies 5 | from functools import reduce 6 | 7 | # The Data 8 | s = {1, 2, 3} 9 | 10 | # The One-Liner 11 | ps = lambda s: reduce(lambda P, x: P + [subset | {x} for subset in P], s, [set()]) 12 | 13 | # The Result 14 | print(ps(s)) 15 | ''' 16 | [set(), {1}, {2}, {1, 2}, {3}, {1, 3}, {2, 3}, {1, 2, 3}] 17 | ''' 18 | -------------------------------------------------------------------------------- /book/algorithms/algorithms_one_liner_06.py: -------------------------------------------------------------------------------- 1 | # Caesar’s Cipher Encryption Using Advanced Indexing and List Comprehension 2 | 3 | 4 | ## Data 5 | abc = "abcdefghijklmnopqrstuvwxyz" 6 | s = "xthexrussiansxarexcoming" 7 | 8 | ## One-Liner 9 | rt13 = lambda x: "".join([abc[(abc.find(c) + 13) % 26] for c in x]) 10 | 11 | ## Result 12 | print(rt13(s)) 13 | print(rt13(rt13(s))) 14 | ''' 15 | kgurkehffvnafknerkpbzvat 16 | xthexrussiansxarexcoming 17 | ''' 18 | -------------------------------------------------------------------------------- /book/algorithms/algorithms_one_liner_07.py: -------------------------------------------------------------------------------- 1 | # Finding Prime Numbers with the Sieve of Eratosthenes 2 | 3 | 4 | ## Dependencies 5 | from functools import reduce 6 | 7 | ## The Data 8 | n = 100 9 | 10 | ## The One-Liner 11 | primes = reduce(lambda r, x: r - set(range(x**2, n, x)) if x in r else r, range(2, int(n**0.5) + 1), set(range(2, n))) 12 | 13 | ## The Result 14 | print(primes) 15 | ''' 16 | {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97} 17 | ''' 18 | -------------------------------------------------------------------------------- /book/algorithms/algorithms_one_liner_08.py: -------------------------------------------------------------------------------- 1 | # Calculating the Fibonacci Series with the reduce() Function 2 | 3 | 4 | # Dependencies 5 | from functools import reduce 6 | 7 | # The Data 8 | n = 10 9 | 10 | # The One-Liner 11 | fibs = reduce(lambda x, _: x + [x[-2] + x[-1]], [0] * (n-2), [0, 1]) 12 | 13 | # The Result 14 | print(fibs) 15 | ''' 16 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] 17 | ''' 18 | -------------------------------------------------------------------------------- /book/algorithms/algorithms_one_liner_09.py: -------------------------------------------------------------------------------- 1 | # A Recursive Binary Search Algorithm 2 | 3 | 4 | ## The Data 5 | l = [3, 6, 14, 16, 33, 55, 56, 89] 6 | x = 33 7 | 8 | ## The One-Liner 9 | bs = lambda l, x, lo, hi: -1 if lo>hi else(lo+hi)//2 if l[(lo+hi)//2] == x else bs(l, x, lo, (lo+hi)//2-1) if l[(lo+hi)//2] > x else bs(l, x, (lo+hi)//2+1, hi) 10 | 11 | ## The Results 12 | print(bs(l, x, 0, len(l)-1)) 13 | ''' 14 | 4 15 | ''' 16 | -------------------------------------------------------------------------------- /book/algorithms/algorithms_one_liner_10.py: -------------------------------------------------------------------------------- 1 | # A Recursive Quicksort Algorithm 2 | 3 | 4 | ## The Data 5 | unsorted = [33, 2, 3, 45, 6, 54, 33] 6 | 7 | ## The One-Liner 8 | q = lambda l: q([x for x in l[1:] if x <= l[0]]) + [l[0]] + q([x for x in l if x > l[0]]) if l else [] 9 | 10 | ## The Result 11 | print(q(unsorted)) 12 | ''' 13 | [2, 3, 6, 33, 33, 45, 54] 14 | ''' 15 | -------------------------------------------------------------------------------- /book/data_science/numpy_one_liner_01.py: -------------------------------------------------------------------------------- 1 | # Basic Two-Dimensional Array Arithmetic 2 | 3 | 4 | ## Dependencies 5 | import numpy as np 6 | 7 | ## Data: yearly salary in ($1000) [2017, 2018, 2019] 8 | alice = [99, 101, 103] 9 | bob = [110, 108, 105] 10 | tim = [90, 88, 85] 11 | salaries = np.array([alice, bob, tim]) 12 | taxation = np.array([[0.2, 0.25, 0.22], 13 | [0.4, 0.5, 0.5], 14 | [0.1, 0.2, 0.1]]) 15 | 16 | ## One-liner 17 | max_income = np.max(salaries - salaries * taxation) 18 | 19 | ## Result 20 | print(max_income) 21 | ''' 22 | 81.0 23 | ''' 24 | -------------------------------------------------------------------------------- /book/data_science/numpy_one_liner_02.py: -------------------------------------------------------------------------------- 1 | # Working with NumPy Arrays: Slicing, Broadcasting, and Array Types 2 | 3 | 4 | ## Dependencies 5 | import numpy as np 6 | 7 | ## Data: yearly salary in ($1000) [2025, 2026, 2027] 8 | dataScientist = [130, 132, 137] 9 | productManager = [127, 140, 145] 10 | designer = [118, 118, 127] 11 | softwareEngineer = [129, 131, 137] 12 | employees = np.array([dataScientist, 13 | productManager, 14 | designer, 15 | softwareEngineer]) 16 | 17 | ## One-liner 18 | employees[0,::2] = employees[0,::2] * 1.1 19 | 20 | ## Result 21 | print(employees) 22 | ''' 23 | [[143 132 150] 24 | [127 140 145] 25 | [118 118 127] 26 | [129 131 137]] 27 | ''' 28 | -------------------------------------------------------------------------------- /book/data_science/numpy_one_liner_03.py: -------------------------------------------------------------------------------- 1 | # Conditional Array Search, Filtering, and Broadcasting to Detect Outliers 2 | 3 | 4 | ## Dependencies 5 | import numpy as np 6 | 7 | ## Data: air quality index AQI data (row = city) 8 | X = np.array( 9 | [[ 42, 40, 41, 43, 44, 43 ], # Hong Kong 10 | [ 30, 31, 29, 29, 29, 30 ], # New York 11 | [ 8, 13, 31, 11, 11, 9 ], # Berlin 12 | [ 11, 11, 12, 13, 11, 12 ]]) # Montreal 13 | cities = np.array(["Hong Kong", "New York", "Berlin", "Montreal"]) 14 | 15 | ## One-liner 16 | polluted = set(cities[np.nonzero(X > np.average(X))[0]]) 17 | 18 | ## Result 19 | print(polluted) 20 | ''' 21 | {'Berlin', 'Hong Kong', 'New York'} 22 | ''' 23 | -------------------------------------------------------------------------------- /book/data_science/numpy_one_liner_04.py: -------------------------------------------------------------------------------- 1 | # Boolean Indexing to Filter Two-Dimensional Arrays 2 | 3 | 4 | ## Dependencies 5 | import numpy as np 6 | 7 | ## Data: popular Instagram accounts (millions followers) 8 | inst = np.array([[232, "@instagram"], 9 | [133, "@selenagomez"], 10 | [59, "@victoriassecret"], 11 | [120, "@cristiano"], 12 | [111, "@beyonce"], 13 | [76, "@nike"]]) 14 | 15 | ## One-liner 16 | superstars = inst[inst[:,0].astype(float) > 100, 1] 17 | 18 | ## Results 19 | print(superstars) 20 | ''' 21 | ['@instagram' '@selenagomez' '@cristiano' '@beyonce'] 22 | ''' 23 | -------------------------------------------------------------------------------- /book/data_science/numpy_one_liner_05.py: -------------------------------------------------------------------------------- 1 | # Broadcasting, Slice Assignment, and Reshaping to Clean Every i-th Array Element 2 | 3 | 4 | ## Dependencies 5 | import numpy as np 6 | 7 | ## Sensor data (Mo, Tu, We, Th, Fr, Sa, Su) 8 | tmp = np.array([1, 2, 3, 4, 3, 4, 4, 9 | 5, 3, 3, 4, 3, 4, 6, 10 | 6, 5, 5, 5, 4, 5, 5]) 11 | 12 | ## One-liner 13 | tmp[6::7] = np.average(tmp.reshape((-1,7)), axis=1) 14 | 15 | ## Result 16 | print(tmp) 17 | ''' 18 | [1 2 3 4 3 4 3 5 3 3 4 3 4 4 6 5 5 5 4 5 5] 19 | ''' 20 | -------------------------------------------------------------------------------- /book/data_science/numpy_one_liner_06.py: -------------------------------------------------------------------------------- 1 | # When to Use the sort() Function and When to Use the argsort() Function in NumPy 2 | 3 | 4 | ## Dependencies 5 | import numpy as np 6 | 7 | ## Data: SAT scores for different students 8 | sat_scores = np.array([1100, 1256, 1543, 9 | 1043, 989, 1412, 1343]) 10 | students = np.array(["John", "Bob", "Alice", 11 | "Joe", "Jane", "Frank", "Carl"]) 12 | 13 | ## One-liner 14 | top_3 = students[np.argsort(sat_scores)][:-4:-1] 15 | 16 | ## Result 17 | print(top_3) 18 | ''' 19 | ['Alice' 'Frank' 'Carl'] 20 | ''' 21 | -------------------------------------------------------------------------------- /book/data_science/numpy_one_liner_07.py: -------------------------------------------------------------------------------- 1 | # How to Use Lambda Functions and Boolean Indexing to Filter Arrays 2 | 3 | 4 | ## Dependencies 5 | import numpy as np 6 | 7 | ## Data (row = [title, rating]) 8 | books = np.array([['Coffee Break NumPy', 4.6], 9 | ['Lord of the Rings', 5.0], 10 | ['Harry Potter', 4.3], 11 | ['Winnie-the-Pooh', 3.9], 12 | ['The Clown of God', 2.2], 13 | ['Coffee Break Python', 4.7]]) 14 | 15 | ## One-liner 16 | predict_bestseller = lambda x, y : x[x[:,1].astype(float) > y] 17 | 18 | ## Results 19 | print(predict_bestseller(books, 3.9)) 20 | ''' 21 | [['Coffee Break NumPy' '4.6'] 22 | ['Lord of the Rings' '5.0'] 23 | ['Harry Potter' '4.3'] 24 | ['Coffee Break Python' '4.7']] 25 | ''' 26 | -------------------------------------------------------------------------------- /book/data_science/numpy_one_liner_08.py: -------------------------------------------------------------------------------- 1 | # How to Create Advanced Array Filters with Statistics, Math, and Logic 2 | 3 | 4 | ## Dependencies 5 | import numpy as np 6 | 7 | ## Website analytics data: 8 | ## (row = day), (col = users, bounce, duration) 9 | a = np.array([[815, 70, 115], 10 | [767, 80, 50], 11 | [912, 74, 77], 12 | [554, 88, 70], 13 | [1008, 65, 128]]) 14 | mean, stdev = np.mean(a, axis=0), np.std(a, axis=0) 15 | # [811.2 76.4 88. ], [152.97764543 6.85857128 29.04479299] 16 | 17 | ## One-liner 18 | outliers = ((np.abs(a[:,0] - mean[0]) > stdev[0]) 19 | * (np.abs(a[:,1] - mean[1]) > stdev[1]) 20 | * (np.abs(a[:,2] - mean[2]) > stdev[2])) 21 | 22 | ## Result 23 | print(a[outliers]) 24 | ''' 25 | [[1008 65 128]] 26 | ''' 27 | -------------------------------------------------------------------------------- /book/data_science/numpy_one_liner_09.py: -------------------------------------------------------------------------------- 1 | # Simple Association Analysis: People Who Bought X Also Bought Y 2 | 3 | 4 | ## Dependencies 5 | import numpy as np 6 | 7 | ## Data: row is customer shopping basket 8 | ## row = [course 1, course 2, ebook 1, ebook 2] 9 | ## value 1 indicates that an item was bought. 10 | basket = np.array([[0, 1, 1, 0], 11 | [0, 0, 0, 1], 12 | [1, 1, 0, 0], 13 | [0, 1, 1, 1], 14 | [1, 1, 1, 0], 15 | [0, 1, 1, 0], 16 | [1, 1, 0, 1], 17 | [1, 1, 1, 1]]) 18 | 19 | ## One-liner 20 | copurchases = np.sum(np.all(basket[:,2:], axis = 1)) / basket.shape[0] 21 | 22 | ## Result 23 | print(copurchases) 24 | ''' 25 | 0.25 26 | ''' 27 | -------------------------------------------------------------------------------- /book/data_science/numpy_one_liner_10.py: -------------------------------------------------------------------------------- 1 | # Intermediate Association Analysis to Find Bestseller Bundles 2 | 3 | 4 | ## Dependencies 5 | import numpy as np 6 | 7 | ## Data: row is customer shopping basket 8 | ## row = [course 1, course 2, ebook 1, ebook 2] 9 | ## value 1 indicates that an item was bought. 10 | basket = np.array([[0, 1, 1, 0], 11 | [0, 0, 0, 1], 12 | [1, 1, 0, 0], 13 | [0, 1, 1, 1], 14 | [1, 1, 1, 0], 15 | [0, 1, 1, 0], 16 | [1, 1, 0, 1], 17 | [1, 1, 1, 1]]) 18 | 19 | ## One-liner 20 | copurchases = [(i,j,np.sum(basket[:,i] + basket[:,j] == 2)) for i in range(4) for j in range(i+1,4)] 21 | 22 | ## Result 23 | print(max(copurchases, key=lambda x:x[2])) 24 | ''' 25 | (1, 2, 5) 26 | ''' 27 | -------------------------------------------------------------------------------- /book/machine_learning/sklearn_one_liner_01.py: -------------------------------------------------------------------------------- 1 | # Linear Regression 2 | 3 | 4 | ## Dependencies 5 | from sklearn.linear_model import LinearRegression 6 | import numpy as np 7 | 8 | ## Data (Apple stock prices) 9 | apple = np.array([155, 156, 157]) 10 | n = len(apple) 11 | 12 | ## One-liner 13 | model = LinearRegression().fit(np.arange(n).reshape((n,1)), apple) 14 | 15 | ## Result & puzzle 16 | print(model.predict([[3],[4]])) 17 | ''' 18 | [158. 159.] 19 | ''' 20 | -------------------------------------------------------------------------------- /book/machine_learning/sklearn_one_liner_02.py: -------------------------------------------------------------------------------- 1 | # Logistic Regression in One Line 2 | from sklearn.linear_model import LogisticRegression 3 | import numpy as np 4 | 5 | ## Data (#cigarettes, cancer) 6 | X = np.array([[0, "No"], 7 | [10, "No"], 8 | [60, "Yes"], 9 | [90, "Yes"]]) 10 | 11 | ## One-liner 12 | model = LogisticRegression().fit(X[:,0].reshape(-1,1), X[:,1]) 13 | 14 | ## Result & puzzle 15 | print(model.predict([[2],[12],[13],[40],[90]])) 16 | ''' 17 | ['No' 'No' 'Yes' 'Yes' 'Yes'] 18 | ''' 19 | -------------------------------------------------------------------------------- /book/machine_learning/sklearn_one_liner_03.py: -------------------------------------------------------------------------------- 1 | # K-Means Clustering in One Line 2 | 3 | 4 | ## Dependencies 5 | from sklearn.cluster import KMeans 6 | import numpy as np 7 | 8 | ## Data (Work (h) / Salary ($)) 9 | X = np.array([[35, 7000], [45, 6900], [70, 7100], 10 | [20, 2000], [25, 2200], [15, 1800]]) 11 | 12 | ## One-liner 13 | kmeans = KMeans(n_clusters=2).fit(X) 14 | 15 | ## Result & puzzle 16 | cc = kmeans.cluster_centers_ 17 | print(cc) 18 | ''' 19 | [[ 20. 2000.] 20 | [ 50. 7000.]] 21 | ''' 22 | -------------------------------------------------------------------------------- /book/machine_learning/sklearn_one_liner_04.py: -------------------------------------------------------------------------------- 1 | # K-Nearest Neighbors in One Line 2 | 3 | 4 | ## Dependencies 5 | from sklearn.neighbors import KNeighborsRegressor 6 | import numpy as np 7 | 8 | ## Data (House Size (square meters) / House Price ($)) 9 | X = np.array([[35, 30000], [45, 45000], [40, 50000], 10 | [35, 35000], [25, 32500], [40, 40000]]) 11 | 12 | ## One-liner 13 | KNN = KNeighborsRegressor(n_neighbors=3).fit(X[:,0].reshape(-1,1), X[:,1]) 14 | 15 | ## Result & puzzle 16 | res = KNN.predict([[30]]) 17 | print(res) 18 | ''' 19 | [32500.] 20 | ''' 21 | -------------------------------------------------------------------------------- /book/machine_learning/sklearn_one_liner_05.py: -------------------------------------------------------------------------------- 1 | # Neural Network Analysis in One Line 2 | 3 | 4 | ## Dependencies 5 | from sklearn.neural_network import MLPRegressor 6 | import numpy as np 7 | 8 | ## Questionaire data (WEEK, YEARS, BOOKS, PROJECTS, EARN, RATING) 9 | X = np.array( 10 | [[20, 11, 20, 30, 4000, 3000], 11 | [12, 4, 0, 0, 1000, 1500], 12 | [2, 0, 1, 10, 0, 1400], 13 | [35, 5, 10, 70, 6000, 3800], 14 | [30, 1, 4, 65, 0, 3900], 15 | [35, 1, 0, 0, 0, 100], 16 | [15, 1, 2, 25, 0, 3700], 17 | [40, 3, -1, 60, 1000, 2000], 18 | [40, 1, 2, 95, 0, 1000], 19 | [10, 0, 0, 0, 0, 1400], 20 | [30, 1, 0, 50, 0, 1700], 21 | [1, 0, 0, 45, 0, 1762], 22 | [10, 32, 10, 5, 0, 2400], 23 | [5, 35, 4, 0, 13000, 3900], 24 | [8, 9, 40, 30, 1000, 2625], 25 | [1, 0, 1, 0, 0, 1900], 26 | [1, 30, 10, 0, 1000, 1900], 27 | [7, 16, 5, 0, 0, 3000]]) 28 | 29 | ## One-liner 30 | neural_net = MLPRegressor(max_iter=10000).fit(X[:,:-1], X[:,-1]) 31 | 32 | ## Result 33 | res = neural_net.predict([[0, 0, 0, 0, 0]]) 34 | print(res) 35 | ''' 36 | [1289.34225619] 37 | ''' 38 | -------------------------------------------------------------------------------- /book/machine_learning/sklearn_one_liner_06.py: -------------------------------------------------------------------------------- 1 | # Decision-Tree Learning in One Line 2 | 3 | 4 | ## Dependencies 5 | from sklearn import tree 6 | import numpy as np 7 | 8 | ## Data: student scores in (math, language, creativity) --> study field 9 | X = np.array([[9, 5, 6, "computer science"], 10 | [1, 8, 1, "linguistics"], 11 | [5, 7, 9, "art"]]) 12 | 13 | ## One-liner 14 | Tree = tree.DecisionTreeClassifier().fit(X[:,:-1], X[:,-1]) 15 | 16 | ## Result & puzzle 17 | student_0 = Tree.predict([[8, 6, 5]]) 18 | print(student_0) 19 | 20 | student_1 = Tree.predict([[3, 7, 9]]) 21 | print(student_1) 22 | 23 | ''' 24 | ['computer science'] 25 | ['linguistics'] 26 | ''' 27 | -------------------------------------------------------------------------------- /book/machine_learning/sklearn_one_liner_07.py: -------------------------------------------------------------------------------- 1 | # Get Row with Minimal Variance in One Line 2 | 3 | 4 | ## Dependencies 5 | import numpy as np 6 | 7 | ## Data (rows: stocks / cols: stock prices) 8 | X = np.array([[25,27,29,30], 9 | [1,5,3,2], 10 | [12,11,8,3], 11 | [1,1,2,2], 12 | [2,6,2,2]]) 13 | 14 | ## One-liner: Find the stock with smallest variance 15 | min_row = min([(i,np.var(X[i,:])) for i in range(len(X))], key=lambda x: x[1]) 16 | 17 | ## Result & puzzle 18 | print("Row with minimum variance: " + str(min_row[0])) 19 | print("Variance: " + str(min_row[1])) 20 | ''' 21 | Row with minimum variance: 3 22 | Variance: 0.25 23 | ''' 24 | -------------------------------------------------------------------------------- /book/machine_learning/sklearn_one_liner_08.py: -------------------------------------------------------------------------------- 1 | # Basic Statistics in One Line 2 | 3 | 4 | ## Dependencies 5 | import numpy as np 6 | 7 | ## Stock Price Data: 5 companies 8 | # (row=[price_day_1, price_day_2, ...]) 9 | x = np.array([[8, 9, 11, 12], 10 | [1, 2, 2, 1], 11 | [2, 8, 9, 9], 12 | [9, 6, 6, 3], 13 | [3, 3, 3, 3]]) 14 | 15 | ## One-liner 16 | avg, var, std = np.average(x, axis=1), np.var(x, axis=1), np.std(x, axis=1) 17 | 18 | ## Result & puzzle 19 | print("Averages: " + str(avg)) 20 | print("Variances: " + str(var)) 21 | print("Standard Deviations: " + str(std)) 22 | ''' 23 | Averages: [10. 1.5 7. 6. 3. ] 24 | Variances: [2.5 0.25 8.5 4.5 0. ] 25 | Standard Deviations: [1.58113883 0.5 2.91547595 2.12132034 0. ] 26 | ''' 27 | -------------------------------------------------------------------------------- /book/machine_learning/sklearn_one_liner_09.py: -------------------------------------------------------------------------------- 1 | # Classification with Support-Vector Machines in One Line 2 | 3 | 4 | ## Dependencies 5 | from sklearn import svm 6 | import numpy as np 7 | 8 | ## Data: student scores in (math, language, creativity) --> study field 9 | X = np.array([[9, 5, 6, "computer science"], 10 | [10, 1, 2, "computer science"], 11 | [1, 8, 1, "literature"], 12 | [4, 9, 3, "literature"], 13 | [0, 1, 10, "art"], 14 | [5, 7, 9, "art"]]) 15 | 16 | ## One-liner 17 | svm = svm.SVC().fit(X[:,:-1], X[:,-1]) 18 | 19 | ## Result & puzzle 20 | student_0 = svm.predict([[3, 3, 6]]) 21 | print(student_0) 22 | 23 | student_1 = svm.predict([[8, 1, 1]]) 24 | print(student_1) 25 | 26 | ''' 27 | ['art'] 28 | ['computer science'] 29 | ''' 30 | -------------------------------------------------------------------------------- /book/machine_learning/sklearn_one_liner_10.py: -------------------------------------------------------------------------------- 1 | # Classification with Random Forests in One Line 2 | 3 | 4 | ## Dependencies 5 | import numpy as np 6 | from sklearn.ensemble import RandomForestClassifier 7 | 8 | ## Data: student scores in (math, language, creativity) --> study field 9 | X = np.array([[9, 5, 6, "computer science"], 10 | [5, 1, 5, "computer science"], 11 | [8, 8, 8, "computer science"], 12 | [1, 10, 7, "literature"], 13 | [1, 8, 1, "literature"], 14 | [5, 7, 9, "art"], 15 | [1, 1, 6, "art"]]) 16 | 17 | ## One-liner 18 | Forest = RandomForestClassifier(n_estimators=10).fit(X[:,:-1], X[:,-1]) 19 | 20 | ## Result 21 | students = Forest.predict([[8, 6, 5], 22 | [3, 7, 9], 23 | [2, 2, 1]]) 24 | print(students) 25 | ''' 26 | ['computer science' 'art' 'literature'] 27 | ''' 28 | -------------------------------------------------------------------------------- /book/machine_learning/sklearn_one_liner_11.py: -------------------------------------------------------------------------------- 1 | # Description: Python plot 2 | 3 | ## Dependencies 4 | import matplotlib.pyplot as plt 5 | import seaborn as sns 6 | import pandas as pd 7 | 8 | # Data (Iris dataset) 9 | from sklearn.datasets import load_iris 10 | iris = load_iris() 11 | df = pd.DataFrame(iris.data, columns=iris.feature_names) 12 | 13 | # One-liner 14 | sns.pairplot(df, kind="reg") 15 | 16 | # Result 17 | plt.show() 18 | -------------------------------------------------------------------------------- /book/python_tricks/one_liner_01.py: -------------------------------------------------------------------------------- 1 | # Using List Comprehension to Find Top Earners 2 | 3 | 4 | ## Data 5 | employees = {'Alice' : 100000, 6 | 'Bob' : 99817, 7 | 'Carol' : 122908, 8 | 'Frank' : 88123, 9 | 'Eve' : 93121} 10 | 11 | 12 | ## One-Liner 13 | top_earners = [(k, v) for k, v in employees.items() if v >= 100000] 14 | 15 | 16 | ## Result 17 | print(top_earners) 18 | # [('Alice', 100000), ('Carol', 122908)] 19 | -------------------------------------------------------------------------------- /book/python_tricks/one_liner_02.py: -------------------------------------------------------------------------------- 1 | # Using List Comprehension to Find Words with High Information Value 2 | 3 | 4 | ## Data 5 | text = ''' 6 | Call me Ishmael. Some years ago - never mind how long precisely - having 7 | little or no money in my purse, and nothing particular to interest me 8 | on shore, I thought I would sail about a little and see the watery part 9 | of the world. It is a way I have of driving off the spleen, and regulating 10 | the circulation. - Moby Dick''' 11 | 12 | ## One-Liner 13 | w = [[x for x in line.split() if len(x)>3] for line in text.split('\n')] 14 | 15 | ## Result 16 | print(w) 17 | ''' 18 | [[], ['Call', 'Ishmael.', 'Some', 'years', 'never', 'mind', 'long', 'precisely', 'having'], 19 | ['little', 'money', 'purse,', 'nothing', 'particular', 'interest'], 20 | ['shore,', 'thought', 'would', 'sail', 'about', 'little', 'watery', 'part'], 21 | ['world.', 'have', 'driving', 'spleen,', 'regulating'], ['circulation.', 'Moby', 'Dick']] 22 | ''' 23 | -------------------------------------------------------------------------------- /book/python_tricks/one_liner_03.py: -------------------------------------------------------------------------------- 1 | # Reading a File 2 | 3 | print([line.strip() for line in open("one_liner_03.py")]) 4 | # Output: 5 | -------------------------------------------------------------------------------- /book/python_tricks/one_liner_04.py: -------------------------------------------------------------------------------- 1 | # Using Lambda and Map Functions 2 | 3 | ## Data 4 | txt = ['lambda functions are anonymous functions.', 5 | 'anonymous functions dont have a name.', 6 | 'functions are objects in Python.'] 7 | 8 | ## One-Liner 9 | mark = map(lambda s: (True, s) if 'anonymous' in s else (False, s), txt) 10 | 11 | ## Result 12 | print(list(mark)) 13 | ''' 14 | [(True, 'lambda functions are anonymous functions.'), 15 | (True, 'anonymous functions dont have a name.'), 16 | (False, 'functions are objects in Python.')] 17 | ''' 18 | -------------------------------------------------------------------------------- /book/python_tricks/one_liner_05.py: -------------------------------------------------------------------------------- 1 | # Using Slicing to Extract Matching Substring Environments 2 | 3 | ## Data 4 | letters_amazon = ''' 5 | We spent several years building our own database engine, 6 | Amazon Aurora, a fully-managed MySQL and PostgreSQL-compatible 7 | service with the same or better durability and availability as 8 | the commercial engines, but at one-tenth of the cost. We were 9 | not surprised when this worked. 10 | ''' 11 | 12 | ## One-Liner 13 | find = lambda x, q: x[x.find(q)-18:x.find(q)+18] if q in x else -1 14 | 15 | ## Result 16 | print(find(letters_amazon, 'SQL')) 17 | ''' 18 | a fully-managed MySQL and PostgreSQL 19 | ''' 20 | -------------------------------------------------------------------------------- /book/python_tricks/one_liner_06.py: -------------------------------------------------------------------------------- 1 | # Combining List Comprehension and Slicing 2 | 3 | ## Data (daily stock prices ($)) 4 | price = [[9.9, 9.8, 9.8, 9.4, 9.5, 9.7], 5 | [9.5, 9.4, 9.4, 9.3, 9.2, 9.1], 6 | [8.4, 7.9, 7.9, 8.1, 8.0, 8.0], 7 | [7.1, 5.9, 4.8, 4.8, 4.7, 3.9]] 8 | 9 | ## One-Liner 10 | sample = [line[::2] for line in price] 11 | 12 | ## Result 13 | print(sample) 14 | ''' 15 | [[9.9, 9.8, 9.5], 16 | [9.5, 9.4, 9.2], 17 | [8.4, 7.9, 8.0], 18 | [7.1, 4.8, 4.7]] 19 | ''' 20 | -------------------------------------------------------------------------------- /book/python_tricks/one_liner_07.py: -------------------------------------------------------------------------------- 1 | # Using Slice Assignment to Correct Corrupted Lists 2 | 3 | 4 | ## Data 5 | visitors = ['Firefox', 'corrupted', 'Chrome', 'corrupted', 6 | 'Safari', 'corrupted', 'Safari', 'corrupted', 7 | 'Chrome', 'corrupted', 'Firefox', 'corrupted'] 8 | 9 | ## One-Liner 10 | visitors[1::2] = visitors[::2] 11 | 12 | ## Result 13 | print(visitors) 14 | ''' 15 | ['Firefox', 'Firefox', 'Chrome', 'Chrome', 'Safari', 'Safari', 16 | 'Safari', 'Safari', 'Chrome', 'Chrome', 'Firefox', 'Firefox'] 17 | ''' 18 | -------------------------------------------------------------------------------- /book/python_tricks/one_liner_08.py: -------------------------------------------------------------------------------- 1 | # Analyzing Cardiac Health Data with List Concatenation 2 | 3 | ## Dependencies 4 | import matplotlib.pyplot as plt 5 | 6 | ## Data 7 | cardiac_cycle = [62, 60, 62, 64, 68, 77, 80, 76, 71, 66, 61, 60, 62] 8 | 9 | ## One-Liner 10 | expected_cycles = cardiac_cycle[1:-2] * 10 11 | 12 | ## Result 13 | plt.plot(expected_cycles) 14 | plt.show() 15 | -------------------------------------------------------------------------------- /book/python_tricks/one_liner_09.py: -------------------------------------------------------------------------------- 1 | # Using Generator Expressions to Find Companies That Pay Below Minimum Wage 2 | 3 | ## Data 4 | companies = { 5 | 'CoolCompany' : {'Alice' : 33, 'Bob' : 28, 'Frank' : 29}, 6 | 'CheapCompany' : {'Ann' : 4, 'Lee' : 9, 'Chrisi' : 7}, 7 | 'SosoCompany' : {'Esther' : 38, 'Cole' : 8, 'Paris' : 18} 8 | } 9 | 10 | ## One-Liner 11 | illegal = [x for x in companies if any(y<9 for y in companies[x].values())] 12 | 13 | ## Result 14 | print(illegal) 15 | ''' 16 | ['CheapCompany', 'SosoCompany'] 17 | ''' 18 | 19 | -------------------------------------------------------------------------------- /book/python_tricks/one_liner_10.py: -------------------------------------------------------------------------------- 1 | # Formatting Databases with the zip() Function 2 | 3 | 4 | ## Data 5 | column_names = ['name', 'salary', 'job'] 6 | db_rows = [('Alice', 180000, 'data scientist'), 7 | ('Bob', 99000, 'mid-level manager'), 8 | ('Frank', 87000, 'CEO')] 9 | 10 | ## One-Liner 11 | db = [dict(zip(column_names, row)) for row in db_rows] 12 | 13 | ## Result 14 | print(db) 15 | ''' 16 | [{'name': 'Alice', 'salary': 180000, 'job': 'data scientist'}, 17 | {'name': 'Bob', 'salary': 99000, 'job': 'mid-level manager'}, 18 | {'name': 'Frank', 'salary': 87000, 'job': 'CEO'}] 19 | ''' 20 | 21 | -------------------------------------------------------------------------------- /book/python_tricks/one_liner_11.py: -------------------------------------------------------------------------------- 1 | # Creating dictionary from 2 lists 2 | 3 | ## Data 4 | keys = ['a', 'b', 'c'] 5 | values = [1, 2, 3] 6 | 7 | ## One-liner 8 | d = dict(zip(keys, values)) 9 | 10 | ## Result 11 | print(d) -------------------------------------------------------------------------------- /book/regular_expressions/regex_one_liner_01.py: -------------------------------------------------------------------------------- 1 | # Finding Basic Textual Patterns in Strings 2 | 3 | 4 | ## Dependencies 5 | import re 6 | 7 | ## Data 8 | text = 'peter piper picked a peck of pickled peppers' 9 | 10 | ## One-Liner 11 | result = re.findall('p.*?e.*?r', text) 12 | 13 | ## Result 14 | print(result) 15 | ''' 16 | ['peter', 'piper', 'picked a peck of pickled pepper'] 17 | ''' 18 | -------------------------------------------------------------------------------- /book/regular_expressions/regex_one_liner_02.py: -------------------------------------------------------------------------------- 1 | # Writing Your First Web Scraper with Regular Expressions 2 | 3 | 4 | ## Dependencies 5 | import re 6 | 7 | ## Data 8 | text_1 = "crypto-bot that is trading Bitcoin and other currencies" 9 | text_2 = "cryptographic encryption methods that can be cracked easily with quantum computers" 10 | 11 | ## One-Liner 12 | pattern = re.compile("crypto(.{1,30})coin") 13 | 14 | ## Result 15 | print(pattern.match(text_1)) 16 | print(pattern.match(text_2)) 17 | ''' 18 | 19 | None 20 | ''' 21 | -------------------------------------------------------------------------------- /book/regular_expressions/regex_one_liner_03.py: -------------------------------------------------------------------------------- 1 | # Analyzing Hyperlinks of HTML Documents 2 | 3 | 4 | ## Dependencies 5 | import re 6 | 7 | ## Data 8 | page = ''' 9 | 10 | 11 | 12 |

My Programming Links

13 | test your Python skills 14 | Learn recursion 15 | Great books from NoStarchPress 16 | Solve more Python puzzles 17 | 18 | 19 | ''' 20 | 21 | ## One-Liner 22 | practice_tests = re.findall("()", page) 23 | 24 | ## Result 25 | print(practice_tests) 26 | ''' 27 | [('test your Python skills', 'test'), 28 | ('Solve more Python puzzles', 'puzzle')] 29 | ''' 30 | -------------------------------------------------------------------------------- /book/regular_expressions/regex_one_liner_04.py: -------------------------------------------------------------------------------- 1 | # Extracting Dollars from a String 2 | 3 | 4 | ## Dependencies 5 | import re 6 | 7 | ## Data 8 | report = ''' 9 | If you invested $1 in the year 1801, you would have $18087791.41 today. 10 | This is a 7.967% return on investment. 11 | But if you invested only $0.25 in 1801, you would end up with $4521947.8525. 12 | ''' 13 | 14 | ## One-Liner 15 | dollars = [x[0] for x in re.findall('(\$[0-9]+(\.[0-9]*)?)', report)] 16 | 17 | ## Result 18 | print(dollars) 19 | ''' 20 | ['$1', '$18087791.41', '$0.25', '$4521947.8525'] 21 | ''' 22 | -------------------------------------------------------------------------------- /book/regular_expressions/regex_one_liner_05.py: -------------------------------------------------------------------------------- 1 | # Finding Nonsecure HTTP URLs 2 | 3 | 4 | ## Dependencies 5 | import re 6 | 7 | ## Data 8 | article = ''' 9 | The algorithm has important practical applications 10 | http://blog.finxter.com/applications/ 11 | in many basic data structures such as sets, trees, 12 | dictionaries, bags, bag trees, bag dictionaries, 13 | hash sets, https://blog.finxter.com/sets-in-python/ 14 | hash tables, maps, and arrays. http://blog.finxter.com/ 15 | http://not-a-valid-url 16 | http:/bla.ba.com 17 | http://bo.bo.bo.bo.bo.bo/ 18 | http://bo.bo.bo.bo.bo.bo/333483--33343-/ 19 | ''' 20 | 21 | ## One-Liner 22 | stale_links = re.findall('http://[a-z0-9_\-.]+\.[a-z0-9_\-/]+', article) 23 | 24 | ## Results 25 | print(stale_links) 26 | ''' 27 | ['http://blog.finxter.com/applications/', 'http://blog.finxter.com/', 28 | 'http://bo.bo.bo.bo.bo.bo/', 'http://bo.bo.bo.bo.bo.bo/333483--33343-/'] 29 | ''' 30 | -------------------------------------------------------------------------------- /book/regular_expressions/regex_one_liner_06.py: -------------------------------------------------------------------------------- 1 | # Validating the Time Format of User Input, Part 1 2 | 3 | 4 | ## Dependencies 5 | import re 6 | 7 | ## Data 8 | inputs = ['18:29', '23:55', '123', 'ab:de', '18:299', '99:99'] 9 | 10 | ## One-Liner 11 | input_ok = lambda x: re.fullmatch('[0-9]{2}:[0-9]{2}', x) != None 12 | 13 | ## Result 14 | for x in inputs: 15 | print(input_ok(x)) 16 | ''' 17 | True 18 | True 19 | False 20 | False 21 | False 22 | True 23 | ''' 24 | -------------------------------------------------------------------------------- /book/regular_expressions/regex_one_liner_07.py: -------------------------------------------------------------------------------- 1 | # Validating the Time Format of User Input, Part 2 2 | 3 | 4 | ## Dependencies 5 | import re 6 | 7 | ## Data 8 | inputs = ['18:29', '23:55', '123', 'ab:de', '18:299', '99:99'] 9 | 10 | ## One-Liner 11 | input_ok = lambda x: re.fullmatch('([01][0-9]|2[0-3]):[0-5][0-9]', x) != None 12 | 13 | ## Result 14 | for x in inputs: 15 | print(input_ok(x)) 16 | ''' 17 | True 18 | True 19 | False 20 | False 21 | False 22 | False 23 | ''' 24 | -------------------------------------------------------------------------------- /book/regular_expressions/regex_one_liner_08.py: -------------------------------------------------------------------------------- 1 | # Duplicate Detection in Strings 2 | 3 | 4 | ## Dependencies 5 | import re 6 | 7 | ## Data 8 | text = ''' 9 | It was a bright cold day in April, and the clocks were 10 | striking thirteen. Winston Smith, his chin nuzzled into 11 | his breast in an effort to escape the vile wind, slipped 12 | quickly through the glass doors of Victory Mansions, 13 | though not quickly enough to prevent a swirl of gritty 14 | dust from entering along with him. 15 | -- George Orwell, 1984 16 | ''' 17 | 18 | ## One-Liner 19 | duplicates = re.findall('([^\s]*(?P[^\s])(?P=x)[^\s]*)', text) 20 | 21 | ## Results 22 | print(duplicates) 23 | ''' 24 | [('thirteen.', 'e'), ('nuzzled', 'z'), ('effort', 'f'), 25 | ('slipped', 'p'), ('glass', 's'), ('doors', 'o'), 26 | ('gritty', 't'), ('--', '-'), ('Orwell,', 'l')] 27 | ''' 28 | -------------------------------------------------------------------------------- /book/regular_expressions/regex_one_liner_09.py: -------------------------------------------------------------------------------- 1 | # Detecting Word Repetitions 2 | 3 | 4 | ## Dependencies 5 | import re 6 | 7 | ## Data 8 | text = 'if you use words too often words become used' 9 | 10 | ## One-Liner 11 | style_problems = re.search('\s(?P[a-z]+)\s+([a-z]+\s+){0,10}(?P=x)\s', ' ' + text + ' ') 12 | 13 | ## Results 14 | print(style_problems) 15 | ''' 16 | 17 | ''' 18 | -------------------------------------------------------------------------------- /book/regular_expressions/regex_one_liner_10.py: -------------------------------------------------------------------------------- 1 | # Modifying Regex Patterns in a Multiline String 2 | 3 | 4 | ## Dependencies 5 | import re 6 | 7 | ## Data 8 | text = ''' 9 | Alice Wonderland married John Doe. 10 | The new name of former 'Alice Wonderland' is Alice Doe. 11 | Alice Wonderland replaces her old name 'Wonderland' with her new name 'Doe'. 12 | Alice's sister Jane Wonderland still keeps her old name. 13 | ''' 14 | 15 | ## One-Liner 16 | updated_text = re.sub("Alice Wonderland(?!')", 'Alice Doe', text) 17 | 18 | ## Result 19 | print(updated_text) 20 | ''' 21 | 22 | Alice Doe married John Doe. 23 | The new name of former 'Alice Wonderland' is Alice Doe. 24 | Alice Doe replaces her old name 'Wonderland' with her new name 'Doe'. 25 | Alice's sister Jane Wonderland still keeps her old name. 26 | 27 | 28 | ''' 29 | -------------------------------------------------------------------------------- /one_liners.py: -------------------------------------------------------------------------------- 1 | # Palindrome Python One-Liner 2 | phrase.find(phrase[::-1]) 3 | 4 | # print N numbers Python One-Liner 5 | print(*range(N)) 6 | # Swap Two Variables Python One-Liner 7 | a, b = b, a 8 | 9 | # Sum Over Every Other Value Python One-Liner 10 | sum(stock_prices[::2]) 11 | 12 | #To input space separated integers in a list 13 | lis = list(map(int, input().split())) 14 | 15 | # Read File Python One-Liner 16 | [line.strip() for line in open(filename)] 17 | 18 | # Factorial Python One-Liner 19 | reduce(lambda x, y: x * y, range(1, n+1)) 20 | 21 | # Performance Profiling Python One-Liner 22 | python -m cProfile foo.py 23 | 24 | # Superset Python One-Liner 25 | lambda l: reduce(lambda z, x: z + [y + [x] for y in z], l, [[]]) 26 | 27 | # Generate Random Password 28 | from random import choice; print(''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789%^*(-_=+)') for i in range(10)])) 29 | 30 | # Generate Random Password without use of semicolon 31 | print(''.join([__import__("random").choice('abcdefghijklmnopqrstuvwxyz0123456789%^*(-_=+)') for _ in range(10)])) 32 | 33 | # Fibonacci Python One-Liner 34 | fib = lambda x: x if x<2 else fib(x-1) + fib(x-2) 35 | 36 | # Quicksort Python One-liner 37 | lambda L: [] if L==[] else qsort([x for x in L[1:] if x< L[0]]) + L[0:1] + qsort([x for x in L[1:] if x>=L[0]]) 38 | 39 | # Sieve of Eratosthenes Python One-liner 40 | reduce((lambda r,x: r-set(range(x**2,n,x)) if (x in r) else r), range(2,int(n**0.5)), set(range(2,n))) 41 | 42 | # Find all dividers of a number 43 | 44 | [divider for divider in range(1, YOUR_NUMBER) if YOUR_NUMBER % divider == 0] 45 | 46 | # vigenere cipher usage: vigenere(message, key, mode) mode is e for encrypt and d for decrypt, only works for Uppercase letters 47 | vigenere = lambda message, key, mode: ((lambda k_length=len(key), k_int=[ord(i) for i in key], message_int=[ord(i) for i in message]: "".join([chr(((message_int[i] + k_int[i % k_length]) % 26) + 65) for i in range(len(message_int))]))() if (mode.lower() == "e") else ((lambda k_length=len(key), k_int=[ord(i) for i in key], message_int=[ord(i) for i in message]: "".join([chr(((message_int[i] - k_int[i % k_length]) % 26) + 65) for i in range(len(message_int))]))() if mode.lower() == "d" else "")) 48 | 49 | # IMPORTLESS sha256 one-liner, usage: sha256(b"data") 50 | sha256 = lambda data: (type("SHAConstructor", (object, ) , {'__init__': lambda self, data, **kwargs: [[setattr(self, key, value) for key, value in zip(["data", "hashes", "round_constants", "preprocessed_data"], [data, [0x6A09E667,0xBB67AE85,0x3C6EF372,0xA54FF53A,0x510E527F,0x9B05688C,0x1F83D9AB,0x5BE0CD19,], [0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0x0FC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x06CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2,], self.preprocessing(data)])][0], self.finalhash()][0],'preprocessing': lambda self, data: data + b"\x80" + (b"\x00" * (63 - (len(data) + 8) % 64)) + __import__("struct").pack(">Q", (len(data) * 8)),'ror': lambda self, value, rotations: 0xFFFFFFFF & (value << (32 - rotations)) | (value >> rotations),'finalhash': lambda self: [func() for func in [lambda: setattr(self, "blocks", [self.preprocessed_data[x : x + 64] for x in range(0, len(self.preprocessed_data), 64)]),lambda: [[setattr(self, "words", list(__import__("struct").unpack(">16L", block))), setattr(self, "words", self.words + ([0] * 48)), [setattr(self, c, v) for c,v in zip(list("abcdefgh"), self.hashes)], [[(self.zero(index) if index > 15 else None), setattr(self, "S1", self.ror(self.e, 6) ^ self.ror(self.e, 11) ^ self.ror(self.e, 25)), setattr(self, "ch", (self.e & self.f) ^ ((~self.e & (0xFFFFFFFF)) & self.g)), setattr(self, "temp1", (self.h + self.S1 + self.ch + self.round_constants[index] + self.words[index]) % 0x100000000), setattr(self, "S0", self.ror(self.a, 2) ^ self.ror(self.a, 13) ^ self.ror(self.a, 22)), setattr(self, "maj", (self.a & self.b) ^ (self.a & self.c) ^ (self.b & self.c)), setattr(self, "temp2", (self.S0 + self.maj) % 0x100000000), [setattr(self, f, m) for f, m in zip(list("hgfedcba"), [self.g, self.f, self.e, ((self.d + self.temp1) % 0x100000000), self.c, self.b, self.a, ((self.temp1 + self.temp2) % 0x100000000),])]] for index in range(0,64)], self.final()] for block in self.blocks],lambda: setattr(self, "hash", "".join([hex(value)[2:].zfill(8) for value in self.hashes])),lambda: self.hash]][-1],'final': lambda self: [setattr(self, "mutated_hash_values", [self.a, self.b, self.c, self.d, self.e, self.f, self.g, self.h]), setattr(self, "hashes", [((element + self.mutated_hash_values[index]) % 0x100000000)for index, element in enumerate(self.hashes)])],'zero': lambda self, index: [setattr(self, "s0", (self.ror(self.words[index - 15], 7) ^ self.ror(self.words[index - 15], 18) ^ (self.words[index - 15] >> 3))), setattr(self, "s1", (self.ror(self.words[index - 2], 17)^ self.ror(self.words[index - 2], 19)^ (self.words[index - 2] >> 10))), self.words.__setitem__(index, (self.words[index - 16] + self.s0 + self.words[index - 7] + self.s1) % 0x100000000),], '__repr__': lambda self: self.hash, '__str__': lambda self: self.hash}))(data) 51 | 52 | # print a love emoji with a give name, here it prints my username (Zenoftech) https://github.com/zenoftech 53 | print('\n'.join([''.join([('Zenoftech'[(x-y)%9 ]if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' ') for x in range(-30,30 )])for y in range(15, -15, -1)])) 54 | 55 | # Get back rot-13 version of text you enter 56 | (lambda x, a = "abcdefghijklmnopqrstuvwxyz", b = "ABCDEFGHIJKLMNOPQRSTUVWXYZ": "".join([a[a.index(x[i]) - 13] if x[i] in a else b[b.index(x[i]) - 13] if x[i] in b else x[i] for i in range(len(x))]))(input("Enter text: ")) 57 | 58 | # Replace banned words in string with a special character 59 | lambda text, words, char = '*': [text := text.replace(word, char * len(word)) for word in words][-1] 60 | 61 | # General One-Liner Commands From https://gist.github.com/craigls/2712084 62 | ''' 63 | Some useful Python one-liners taken from http://www.reddit.com/r/Python/comments/fofan/suggestion_for_a_python_blogger_figure_out_what/ 64 | 65 | All modules listed are part of the standard library and should work with Python 2.6+ 66 | 67 | How to use: 68 | 69 | $ python -m [module] [arguments] 70 | 71 | calendar - does default to displaying a yearly calendar, but it has a bunch of options (args are year or year month, options are HTML output, calendar locale, encoding, and some type-specific stuff, see python -m calendar -h) 72 | cgi, dumps a bunch of information as HTML to stdout 73 | CGIHTTPRequestHandler - same as SimpleHTTPServer except via the CGIHTTPRequestHandler: it will executes scripts it recognizes as CGI, instead of just sending them over (has not survived the transition to Python 3) 74 | compileall - compiles a tree of Python files to bytecode, has a bunch of options. Does not compile to stripped files (pyo) 75 | cProfiler - runs the provided script file (argument) under cProfiler 76 | dis disassembles a python script 77 | doctest - runs doctests on the provided files (which can be python scripts or doctest files) 78 | encodings.rot_13 - rot13 encodes stdin to stdout (has not survived the transition to Python 3) 79 | filecmp - directory entry comparison tool 80 | fileinput - some kind of ghetto pseudo-annotate. No idea what use that thing might be of 81 | formatter - reformats the provided file argument (or stdin) to stdout: 80c paragraphs &etc 82 | ftplib - ghetto FTP client 83 | gzip - ghetto gzip (or gunzip with -d), can only compress and decompress, does not delete the archive file 84 | htmllib - strips HTML tags off of an HTML file 85 | ifc - dumps some info about the provided aiff file (if given two paths, also copies path1 to path2) 86 | imaplib - ghetto IMAP client 87 | json.tool - pretty prints JSON 88 | locale - displays current locale information 89 | mimify - converts (mail) messages to and from MIME format 90 | modulefinder - lists the modules imported by the provided script argument, and their location 91 | pdb - automatically enters PDB post-mortem mode if the script crashes 92 | platform - displays the platform string 93 | poplib - dumps a bunch of info on a POP mailbox 94 | profile - see cProfile 95 | pstats - opens a statistics browser (for profile files) 96 | pydoc - same as the pydoc command 97 | quopri / uu binhex / base64 - encode / decode - quoted-Printable / UUEncoded content. 98 | shlex - displays tokenization result of the provided file argument (one token per line prefixed with Token:) 99 | SimpleHTTPServer - serve the current directory over HTTP on port 8080 100 | SimpleXMLRPCServer - XMLRPC server for power and addition 101 | smtpd - SMTP proxy 102 | telnetlib - telnet client 103 | timeit - command line profiling interface 104 | tokenize - dumps tokenization result of a Python file 105 | urllib - fetches a url 106 | webbrowser - opens provided URL in your default web browser (options: in a new window, in a new tab) 107 | whichdb - tries to guess which db package (for db format nobody cares about) can be used to read a db file 108 | ''' 109 | --------------------------------------------------------------------------------