# Using Python for Coding Interview Tips

February 24, 2019

Initialize array

``nums = *10``

Print array

``````nums = [1, 2, 3, 4, 5]
print(*nums)``````

Convert string to char array

``````chars = list("abc")
chars = 'x'``````

You can access string char using array index, but you can’t assign them

``````text = 'hello'
if text == 'h':
text = 'x' # error, you can't do character assignment to string``````

Remove element from list

``del nums[index]``

Convert char to ascii, and ascii to char

``````ord('a') # 97
chr(97)  # a``````

## List index

``nums = [1, 2, 3, 4, 5]``

First element.

``nums``

Last element.

``nums[-1]``

First n elements.

``nums[:n]``

Last n elements.

``nums[-n:]``

Insert character

``````text = 'abde' # insert c -> abcde
index = 2
value = text[:index] + 'c' + text[index:]``````

## Integer overflow

Integer won’t overflow in Python (theoretically limited by memory)

``````import sys
value = sys.maxsize

print(value) # 9223372036854775807
print(value ** 10) # 4455508415646675013373597242420117818453694838130159772560668808816707086990958982033203334310070688731662890013605553436739351074980172000127431349940128178077122187317837794167991459381249``````

However, float could overflow.

## Python for loop with index

``nums = [1, 2, 3, 4, 5]``

Python for loop, start from index 0.

NOTE: For technical test, for loop with index is more convinient so you can do things like `nums[i] + nums[i+1]`.

``````for i in range(len(nums)): # 0,1,2,3,4
print(nums[i]) ``````

Python for loop, start from index 1.

NOTE: For technical test, for loop with index allow you start start with any index or end with any index.

``````for i in range(1, len(nums)+1): # 1,2,3,4,5
print(nums[i-1])``````

Python for loop, reverse fron n-1 to 0.

``````for i in range(len(nums)-1, -1, -1): # 4, 3, 2, 1, 0
print(nums[i])``````

## Data Structure

Queue in Python

``````from collections import deque
q = deque([1, 2, 3]) # initialize
q.append(4)

q.popleft() # 1
q.popleft() # 2``````

Stack in Python

``````s = []
s.append(1)
s.append(2)
s.append(3)
s.pop() # 3
s.pop() # 2
s.pop() # 1``````