Skip to content

Latest commit

 

History

History
275 lines (233 loc) · 5.61 KB

File metadata and controls

275 lines (233 loc) · 5.61 KB

Cheat Sheet for Algorithm - Python

TOC

I/O

⬆ Top

print('hello world')
input_str = input()

Assignment

⬆ Top

test_str = "0 1 2"

# map : a=0, b=1, c=2
a, b, c = map(int, test_str.split())

# arr = [0,1,2]
arr = [int(n) for n in test_str.split()]

Calculations

⬆ Top

x**y   # Exponentiation(x^y)

x%y    # Remainder(x%y)

x // y # Division(x/y)

abs(x) # Absolute Value(|x|)
  • No Prefix/Postfix Operator
i += 1 # i++ or ++i

Condition

⬆ Top

name = input()

if name == 'godori':
  print("Hi, godori")
elif name == 'irodog':
  print("Hi, irodog")
else:
  print("Who are you?")
  • and (&&) or(||)
a = true
b = false
if a == true and b == true:
  print('can not reach here')

if a == true or b == true:
  print('you are here!')

Loop

⬆ Top

members = ['godori', 'irodog', 'roodig']

# for item in items
for member in members:
  print(member)

# for idx in range(number)
for i in range(len(members)):
  print(members[i])

# enumerate()
for idx, val in enumerate(arr):
  print(idx, val)

Function

⬆ Top

  • Function call with parameter & return

    def func(num):
        return 'godori' * num
    
    print(func(3))
  • Function string & number parameters

    def func(str, num):
        return str * num
    
    print(func('hey', 3))

String

⬆ Top

  • loop through
    str = 'hello'
    for s in str:
      print(s)
  • Reverse String
    str = "GODORI"
    str[::-1]       # "IRODOG"

List

⬆ Top

  • Length
    arr = [1, 2, 3]
    len(arr)
  • Append
    arr = [1, 2, 3]
    arr.append(4)
  • Sort
    arr = [3, 1, 2]
    arr.sort()
  • Initialize
    arr = [0] * 3    # [0,0,0]

Stack

⬆ Top

  • using list like stack
  • push
    stack = []
    stack.append(1) # add item into the last index
    stack.append(2)
    # stack = [1,2]
  • pop
    stack = [1,2,3] # remove tail item
    stack.pop()
    # stack = [1,2]

Heap

⬆ Top

  • Using list and heapq (built-in)
  myheap = []
  
  heapq.heappush(myheap, 2)
  heapq.heappush(myheap, 1)
  heapq.heappush(myheap, 3)
  

Dictionary

⬆ Top

  dic = dict()              # {}
  dic = {}
  
  dic['name'] = 'godori'    # {'name': 'godori'}
  dic['job'] = 'developer'  # {'job':'developer', 'name': 'godori'} (no order)
  print('name' in dic)      # true
  len(dic)                  # 2
  • Count Frequency of characters in string
   dic = {}
   for c in str:
      if c in dic:
        dic[c] += 1
      else:
        dic[c] = 0

String Indexing

⬆ Top

  • str[first:last(not inclding)]
  s = "Life is too short, You need Python"
  s[0]     # L
  s[0:3]   # Lif

Type Check

⬆ Top

  • isalpha(): Check if alphabet
  • isdigit(): Check if number
  s = 'str'
  k = '!@#'
  n = 123
  
  if s.isalpha():
    print('is string')
  
  if k.isalpha():
    print('Are you an alphabet?')
  else:
    print('no i am not an alphabet')
    
  if n.isdigit():
    print('is number')

Type Conversion

⬆ Top

  • string to int

    int('13')
  • int to string

    str(13)

OS

⬆ Top

  • Access environment from python
    $ export OUTPUT_PATH="filename.txt"
    $ echo $OUTPUT_PATH  # filename.txt
    import os
    
    if __name__ == '__main__':
      f = open(os.environ['OUTPUT_PATH'], 'w')
      f.write('write something...')
      f.close()

Pipenv

⬆ Top Run pipenv shell

$ pipenv shell

Trivial Python Tips

⬆ Top

  • Booleans represent True/False (not true/false)
  • Using and, || instead of &&, ||
  • Python has no switch/case
  • Check indentation