python_core Flashcards

(8 cards)

1
Q

Reverse a string

A

def reverse_string(s):
return s[::-1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Check if a string is a palindrome

A

def is_palindrome(s):
s = s.lower()
return s == s[::-1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Find the missing number from 0..n

A

def missing_number(nums):
n = len(nums)
return n * (n + 1) // 2 - sum(nums)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Count character frequency

A

from collections import Counter

def char_count(s):
return Counter(s)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Two Sum

A

def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
diff = target - num
if diff in seen:
return [seen[diff], i]
seen[num] = i

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Balanced brackets {},(),[]

A

def is_balanced(s):
stack = []
pairs = {‘)’:’(‘, ‘}’:’{‘, ‘]’:’[’}
for ch in s:
if ch in pairs.values():
stack.append(ch)
elif ch in pairs:
if not stack or stack[-1] != pairs[ch]:
return False
stack.pop()
return not stack

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Remove duplicates (preserve order)

A

def remove_dupes(nums):
seen = set()
result = []
for n in nums:
if n not in seen:
seen.add(n)
result.append(n)
return result

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Merge two sorted lists

A

def merge_sorted(a, b):
i = j = 0
result = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
result.extend(a[i:])
result.extend(b[j:])
return result

How well did you know this?
1
Not at all
2
3
4
5
Perfectly