Python Flashcards

1
Q

How do you check if a character is alphanumeric in Python?

A

Use the isalnum() method of the string class. It returns True if all characters in the string are alphanumeric (letters and numbers) and there is at least one character, otherwise False.

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

How to check if a character is lowercase in Python?

A

Use the islower() method. It returns True if all cased characters in the string are lowercase and there is at least one cased character, otherwise False.

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

How do you convert a character to lowercase in Python?

A

Use the lower() method of the string class. It returns a copy of the string with all the cased characters converted to lowercase.

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

What is defaultdict() in Python and how is it used?:

A
  • defaultdict() is a subclass of the dict class that returns a default value for a missing key. Unlike dict, it does not raise a KeyError.
  • It’s useful when you need a dictionary value to have a default type or value.
from collections import defaultdict
counts = defaultdict(int)  # default value of int is 0
counts['apples'] += 1  # increments 'apples' count, initializes to 0 if n
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How is defaultdict(list) used for creating dynamic lists in Python?:

A
  • defaultdict(list) automatically initializes any new key with an empty list. It’s particularly useful for aggregating or appending elements to lists dynamically.
  • It eliminates the need to check if a key exists or initialize it as a list before appending.
from collections import defaultdict
adj_list = defaultdict(list)  # each key will have a list as its default value
adj_list['node1'].append('node2')  # appends 'node2' to the list of 'node1'
  • This is particularly handy in scenarios like building adjacency lists in graphs, where each node key can dynamically accumulate its neighbors.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to find the ASCII value a character?

A

To find the ASCII value of character, use ord(char).

ascii_a = ord('a') # Returns 97

This can be useful for character manipulations, especially in problems related to alphabets and strings.

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

How to store arrays as tuples in a dictionary in Python?

A

my_dict now contains {(1, 2, 3): ‘Array as Tuple’}

In Python, you can store arrays (or lists) as tuples in a dictionary if you need them to be immutable or used as keys.
~~~
my_dict = {}
arr = [1, 2, 3]
my_dict[tuple(arr)] = “Array as Tuple”
# my_dict now contains {(1, 2, 3): ‘Array as Tuple’}
~~~
This approach is useful when you need to store lists in a way that they can be hashed (like dictionary keys) or need to be immutable.

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

How to square numbers in Python?

A

The sq function calculates the sum of the squares of the digits of a number n. It works by repeatedly dividing n by 10 to extract each digit (using divmod), squaring the digit, and adding it to a total sum. This process continues until n becomes 0. It’s typically used in problems related to digit manipulation, like finding happy numbers.

def sq(self, n):
    total_sum = 0
    while n > 0:
        n, digit = divmod(n, 10)
        total_sum += digit ** 2
    return total_sum
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is divmod in Python, and how is it used?

A

The divmod function in Python takes two numbers and returns a pair (tuple) of their quotient and remainder. For example, divmod(n, 10) returns the quotient and remainder of n divided by 10. In the sq function, divmod(n, 10) is used to separate the last digit (remainder) from n (quotient). This digit is then squared and added to a running total, facilitating the process of summing the squares of the digits of n.

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

How do you convert a number to a list of its digits in Python?

A

To convert a number n into a list of its digits in Python, you can use a combination of list comprehension and the str function. First, convert n to a string with str(n), and then use list comprehension to convert each character back into an integer. The code looks like this:
digits = [int(d) for d in str(n)].
This approach splits n into its individual digits and stores them as integers in the list digits.

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

How do you sort a list of tuples/dictionaries/objects in Python by a specific key or attribute?

A
  • Sorting a List of Tuples: Use the sorted() function with a lambda function as the key. For example, sorted(list_of_tuples, key=lambda x: x[1]) sorts the list based on the second element of each tuple.
  • Sorting a List of Dictionaries: Similar to tuples, use sorted() with a lambda function. For instance, sorted(list_of_dicts, key=lambda x: x['age']) sorts by the ‘age’ key of each dictionary.
  • Sorting a List of Objects: If you have a list of objects, sort them by an attribute using sorted(list_of_objects, key=lambda x: x.attribute).
  • In-Place Sorting: To sort a list in place, use the list.sort() method with a key. For example, list_of_tuples.sort(key=lambda x: x[1]).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Explain the difference between / (Floating Point Division) and // (Floor Division)

A

The key difference is in handling negative numbers: // rounds away from zero, while using int() with / truncates towards zero.

Using // for Floor Division:
5 // 2 results in 2
-5 // 2 results in -3 (rounded away from zero)

Using / and then int() for Truncation:
int(5 / 2) results in 2
int(-5 / 2) results in -2 (truncated towards zero)

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

How to get the max freq element from a list?

A

numsfreq = Counter(nums)

return max(numsfreq.keys(), key=numsfreq.get)

OR

return max(numsfreq.keys(), key=lambda x: numsfreq[x])

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

How can you use a dictionary’s .get method to add the frequencies of elements in a dict?

A

Purpose: To efficiently count the number of occurrences of each element in an array using a single pass and a dictionary.

count = {}
for n in nums:
count[n] = 1 + count.get(n, 0)

How .get Works:
count.get(n, 0) looks for n in the dictionary count. If n is found, it returns its associated value (the current count). If n is not found, it returns 0.

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

How to sort array by frequency?

A

Ascending Freq:
freq = Counter(arr)
arr_rev = sorted(arr, key = lambda x: (freq[x], x))

Descending Freq:
Change to -freq[x] to sort it by desc freq

This approach first counts the frequency of each element in arr using Counter. Then, it sorts arr by using a lambda function that returns a tuple for each element x: the first element of the tuple is arr_freq[x] (the frequency of x), ensuring elements are sorted by frequency, and the second element is x itself, ensuring that elements with the same frequency are sorted by their value.

This method is particularly useful when you need to prioritize elements based on their occurrence frequency but also maintain a sorted order among elements with identical frequencies.

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

How does Python sort Boolean values, and what impact does this have when using Boolean values as sorting keys?

A

In Python, Boolean values are treated as integers for comparison and sorting purposes, with False acting as 0 and True as 1. This means in sorting operations, items that evaluate to True are considered greater than those that evaluate to False.

Example Scenario:
If you’re sorting an array with a key function that returns True for even numbers (lambda x: x % 2 == 0), the sorting will place even numbers (which evaluate to True) after odd numbers (which evaluate to False), because True (1) is greater than False (0). This is the opposite of what might be expected if intending to sort even numbers before odd numbers based on their parity.

Key Takeaway:
To ensure proper sorting order based on Boolean values (for example, placing even numbers before odd numbers), ensure the key function’s logic correctly reflects Python’s treatment of True and False in sorting, often by directly returning the Boolean expression or manipulating it to fit the intended order.

17
Q

How do you pair each element of a list nums with its original index and then sort these pairs by the element values in Python?

A

To pair each element of a list nums with its original index and then sort these pairs by the element values, you can use the enumerate function combined with the sorted function in Python. Here’s how you can do it:

nums = [your list of numbers]
sorted_pairs = sorted(enumerate(nums), key=lambda x: x[1])