Skip to content

Instantly share code, notes, and snippets.

@sourhub226
Last active June 17, 2021 15:13
Show Gist options
  • Save sourhub226/d4e3629e5f8a157bdf44043d35e2042b to your computer and use it in GitHub Desktop.
Save sourhub226/d4e3629e5f8a157bdf44043d35e2042b to your computer and use it in GitHub Desktop.
Python One-Liners -> Powerful snippets of code that solves a problem in a single line.

Python One-Liners

Powerful snippets of code that solves a problem in a single line

1. Palindrome

string = "madam"

# One-Liner
is_palindrome = not bool(string.find(string[::-1]))

print(is_palindrome)

Output:

True

2. Swapping two variables

a = 10
b = 5

# One-Liner
a, b = b, a

print(f"a = {a}")
print(f"b = {b}")

Output:

a = 5
b = 10

3. n-th Fibonacci number

# Assuming first two fibonacci numbers as 0 and 1

# One-liner
fib = lambda x: 0 if x == 1 else 1 if x == 2 else fib(x - 1) + fib(x - 2)

print(fib(4))

Output:

13

4. Quicksort

# One-Liner
qsort = (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]]))

print(qsort([6, 2, 9, 1]))

Output:

[1, 2, 6, 9]

5. Power set (Set of all subsets)

from functools import reduce

# One-Liner
set = lambda l: reduce(lambda z, x: z + [y + [x] for y in z], l, [[]])

print(set([6, 2, 9, 1]))

Output:

[[], [6], [2], [6, 2], [9], [6, 9], [2, 9], [6, 2, 9], [1], [6, 1], [2, 1], [6, 2, 1], [9, 1], [6, 9, 1], [2, 9, 1], [6, 2, 9, 1]]

6. Factorial

# One-Liner
factorial = lambda n: 1 if n <= 1 else n * factorial(n - 1)

print(factorial(5))

Output:

120

7. Prime numbers upto n

from functools import reduce

n = 10

# One-Liner
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)))

print(primes)

Output:

{2, 3, 5, 7}

8. Input and print

# One-Liner
print("Hello " + input("Enter your name: ") + ", Have a nice day!")

Output:

Enter your name: Sourabh
Hello Sourabh, Have a nice day!

9. Input space separated integers in a list

# One-Liner
mylist = list(map(int, input().split()))

print(mylist)

Input:

3 6 1 8

Output:

[3, 6, 1, 8]

10. Input 2D matrix

# Given number of rows and columns
R = 2
C = 3

# One-Liner
matrix = [[int(input()) for _ in range(C)] for _ in range(R)]

print(matrix)

Input:

8
3
1
7
9
6

Output:

[[5, 3, 8], [5, 1, 8]]

11. Even numbers upto n

n = 15

# One-Liners
even_numbers = [x for x in range(n+1) if x % 2 == 0]

print(even_numbers)

Output:

[0, 2, 4, 6, 8, 10, 12, 14]

12. Odd numbers upto n

n = 15

# One-Liners
odd_numbers = [x for x in range(n+1) if x % 2 != 0]

print(odd_numbers)

Output:

[1, 3, 5, 7, 9, 11, 13, 15]

13. Pyramid pattern 1

n = 5

# One-Liner
print("\n".join("* " * i for i in range(1, n + 1)))

Output:

*
* *
* * *
* * * *
* * * * *

14. Sum of a 2 vectors

A = [1, 2, 3]
B = [5, 8, 10]

# One-Liner
vsum = [(x + y) for [x,y] in zip(A,B)]

print(vsum)

Output:

[6, 10, 13]

15. Dot product of a 2 vectors

A = [1, 2, 3]
B = [5, 8, 10]

# One-Liner
dot = sum((x*y) for (x, y) in zip(A, B))

print(dot)

Output:

51

16. Transpose of a matrix

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# One-Liner
transpose = [list(i) for i in zip(*a)]

print(transpose)

Output:

[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

17. Password generator

# Assuming password max-length = 16
import string
import random

# One-Liner
password = "".join(random.sample(string.ascii_letters + string.digits + string.punctuation,16))

print(password)

Output:

e0l>A0VWzk/2Y3iv

18. RGB to HEX

RGB = (252, 186, 3)

# One-Liner
HEX = "#{0:02x}{1:02x}{2:02x}".format(max(0, min(RGB[0], 255)), max(0, min(RGB[1], 255)), max(0, min(RGB[2], 255)))

print(HEX)

Output:

#fcba03

19. HEX to RGB

HEX = "#f703ab"

# One-Liner
RGB = tuple(int(HEX.lstrip("#")[i : i + 2], 16) for i in (0, 2, 4))

print(RGB)

Output:

(247, 3, 171)

20. Distance between 2 points in 3D space

# One-Liner
dist = lambda w,v : (sum((wi - vi)**2 for wi,vi in zip(w,v)))**.5

print(dist((0,0,0), (1,1,1)))

Output:

1.7320508075688772

21. Cut an array into subarrays

A = [6, 1, 9]

# One-Liner
sub_arrays = [list(x) for x in zip(A)]

print(sub_arrays)

Output:

[[6], [1], [9]]

22. Sum of digits of a number

num = 1245

# One-Liner
sum_of_digits = sum(map(int, str(num)))

print(sum_of_digits)

Output:

12

23. Reversing a string

string = "python"

# One-Liner
string = string[::-1]

print(string)

Output:

nohtyp

24. Reversing a list

alist = [5,8,1,7,4,2]

# One-Liner
alist = alist[::-1]

print(alist)

Output:

[2, 4, 7, 1, 8, 5]

25. Pyramid pattern 2

# One-Liner
pattern = "\n".join(((" ".join(" " if index_num > row_num else str(index_num) for index_num in range(10, 1, -1))) + " " + (" ".join(" " if index_num > row_num else str(index_num) for index_num in range(1, 10)))for row_num in range(1, 10)))

print(pattern)

Output:

                1
              2 1 2
            3 2 1 2 3
          4 3 2 1 2 3 4
        5 4 3 2 1 2 3 4 5
      6 5 4 3 2 1 2 3 4 5 6
    7 6 5 4 3 2 1 2 3 4 5 6 7
  8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9

26. Substrings of a string

string="python"

# One-Liner
substr=[string[i: i + j] for i in range(len(string)) for j in range(1, len(string) + 1 - i)]

print(substr)

Output:

['p', 'py', 'pyt', 'pyth', 'pytho', 'python', 'y', 'yt', 'yth', 'ytho', 'ython', 't', 'th', 'tho', 'thon', 'h', 'ho', 'hon', 'o', 'on', 'n']

27. Binary search

l = [2, 9, 12, 36, 59]
x = 36

# One-Liner
bs = (lambda l, x, lo=0, hi=len(l) - 1: -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))


print(f"The element {x} was found at position {bs(l, x)+1}")

Output:

The element 36 was found at position 4

28. Heart pattern

# One-Liner
heart = '\n'.join("".join('Love'[(x - y) % len('Love')] 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(30, -30, -1))

print(heart)

Output:

            veLoveLov           veLoveLov
        eLoveLoveLoveLove   eLoveLoveLoveLove
      veLoveLoveLoveLoveLoveLoveLoveLoveLoveLov
     veLoveLoveLoveLoveLoveLoveLoveLoveLoveLoveL
    veLoveLoveLoveLoveLoveLoveLoveLoveLoveLoveLov
    eLoveLoveLoveLoveLoveLoveLoveLoveLoveLoveLove
    LoveLoveLoveLoveLoveLoveLoveLoveLoveLoveLoveL
    oveLoveLoveLoveLoveLoveLoveLoveLoveLoveLoveLo
    veLoveLoveLoveLoveLoveLoveLoveLoveLoveLoveLov
    eLoveLoveLoveLoveLoveLoveLoveLoveLoveLoveLove
     oveLoveLoveLoveLoveLoveLoveLoveLoveLoveLove
      eLoveLoveLoveLoveLoveLoveLoveLoveLoveLove
      LoveLoveLoveLoveLoveLoveLoveLoveLoveLoveL
        eLoveLoveLoveLoveLoveLoveLoveLoveLove
         oveLoveLoveLoveLoveLoveLoveLoveLove
          eLoveLoveLoveLoveLoveLoveLoveLove
            veLoveLoveLoveLoveLoveLoveLov
              oveLoveLoveLoveLoveLoveLo
                LoveLoveLoveLoveLoveL
                   LoveLoveLoveLov
                      LoveLoveL
                         Lov
                          v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment