Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Essential Python Functions for Technical Interviews

Tech May 10 3

String split() Method

The split() method breaks a string into a list based on a delimiter. When called without arguments, it splits on whitespace.

>>> phrase = "I love China"
>>> phrase.split()
['I', 'love', 'China']

>>> text = "I love China, and you, you"
>>> text.split(", ")
['I love China', 'and you', 'you']

>>> mixed = "I#love#China#andyou#you"
>>> mixed.split("#")
['I', 'love', 'China', 'andyou', 'you']

>>> mixed.split("#", 1)
['I', 'love#China#andyou#you']

The maxsplit parameter limits the number of splits performed.

>>> sentence = "with great power comes great responsibility"
>>> sentence.split(" ", 3)
['with', 'great', 'power', 'comes great responsibility']

String Reversal with Slice Notation

The slice syntax a[start:end:step] combined with step -1 reverses sequences.

>>> text = 'the sky is blue'
>>> list(text)[::-1]
['e', 'u', 'l', 'b', ' ', 's', 'i', ' ', 'y', 'k', 's', ' ', 'e', 'h', 't']

>>> text.split()[::-1]
['blue', 'is', 'sky', 'the']

>>> text[::-1]
'eulb si yks eht'

>>> chars = ['h', 'e', 'll', 'o']
>>> chars[::-1]
['o', 'll', 'e', 'h']

Note that s[::-1] is equivaletn to s[-1::-1].

Counting Element Frequencies with Counter

The Counter class from collections tallies occurrences of eelments in any iterable, returning a dictionary-like object.

from collections import Counter

data = [1, 1, 1, 6, 6, 6, 7, 8]
frequency = Counter(data)

for key, value in frequency.items():
    print(key, value)

print(frequency)
# Output:
# 1 3
# 6 3
# 7 1
# 8 1
# Counter({1: 3, 6: 3, 7: 1, 8: 1})

The most_common(k) method returns the k most frequent elements:

from collections import Counter

data = [1, 1, 1, 6, 6, 6, 7, 8]
frequency = Counter(data)

top_items = frequency.most_common(2)
print(top_items)  # [(1, 3), (6, 3)]

result = [item[0] for item in top_items]
print(result)  # [1, 6]

Dictionary get() Method

Retrieve values safely from dictionaries using get() with optional default values.

config = {'Name': 'Runoob', 'Age': 27}

print(config.get('Age'))       # 27
print(config.get('Sex'))       # None
print(config.get('Salary', 0.0))  # 0.0

Syntax: dict.get(key[, default])

Stack Operations

Python lists support stack-like behavior:

  • stack.append(x) — push element onto top
  • stack.pop() — remove and return top element
  • stack[-1] — access top element without removal

Matrix Transposition with zip()

The zip() function combines iterables element-wise. Using * unpacking enables matrix transpose.

>>> grid = [[3, 0, 8, 4], [2, 4, 5, 7], [9, 2, 6, 3], [0, 3, 1, 0]]
>>> list(zip(*grid))
[(3, 2, 9, 0), (0, 4, 2, 3), (8, 5, 6, 1), (4, 7, 3, 0)]

>>> list(zip(grid))
[([3, 0, 8, 4],), ([2, 4, 5, 7],), ([9, 2, 6, 3],), ([0, 3, 1, 0],)]

When dimensions differ, zip() uses the shortest length. For handling unequal lengths, use itertools.zip_longest().

Converting to Tuples

The tuple() constructor converts lists, ranges, and other iterables to immutable tuples.

a = [1, 2]
b = {"1": 2, "3": 3}
c = {1, 2, 3, 3}
d = range(2, 10, 2)

print(tuple(a))  # (1, 2)
print(tuple(b))  # ('1', '3')
print(tuple(c))  # (1, 2, 3)
print(tuple(d))  # (2, 4, 6, 8)

Tuples offer immutability advantages over lists when modification should be prevented.

Double-Ended Queue with collections.deque

The deque class provides O(1) operations at both ends, functioning as both stack and queue.

import collections

dq = collections.deque()
dq.append('a')          # deque(['a'])
dq.appendleft('b')      # deque(['b', 'a'])
dq.extend('c')         # deque(['b', 'a', 'c'])
dq.extendleft('d')     # deque(['d', 'b', 'a', 'c'])

dq.append(['e', 'f'])  # deque(['d', 'b', 'a', 'c', ['e', 'f']])
dq.append(4)          # deque(['d', 'b', 'a', 'c', ['e', 'f'], 4])
dq.extend(['g', 'h']) # deque(['d', 'b', 'a', 'c', ['e', 'f'], 4, 'g', 'h'])

Key methods:

  • pop() / popleft() — remove from right/left
  • count() — total element count
  • insert(index, obj) — insert at position
  • rotate(n) — shift elements n positions right (negative for left)
  • maxlen — maximum length attribute (None if unbounded)
  • remove(x) — remove first occurrence
  • clear() — empty the deque

Enumerate Function

enumerate() generates index-value pairs for iterables, useful in for loops.

seasons = ['spring', 'summer', 'fall', 'winter']

print(list(enumerate(seasons)))
# [(0, 'spring'), (1, 'summer'), (2, 'fall'), (3, 'winter')]

for index, value in enumerate(seasons):
    print(index, value)
# 0 spring
# 1 summer
# 2 fall
# 3 winter

Syntax: enumerate(sequence, start=0)

letters = 'abcdefg'

print(list(enumerate(letters)))
# [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g')]
Tags: Python

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.