Python Flashcards
How do you check if a character is alphanumeric in Python?
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 to check if a character is lowercase in Python?
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 do you convert a character to lowercase in Python?
Use the lower()
method of the string class. It returns a copy of the string with all the cased characters converted to lowercase.
What is defaultdict() in Python and how is it used?:
-
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 is defaultdict(list) used for creating dynamic lists in Python?:
-
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 to find the ASCII value a character?
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 to store arrays as tuples in a dictionary in Python?
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 to square numbers in Python?
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
What is divmod in Python, and how is it used?
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 do you convert a number to a list of its digits in Python?
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 do you sort a list of tuples/dictionaries/objects in Python by a specific key or attribute?
- 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])
.
Explain the difference between / (Floating Point Division) and // (Floor Division)
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 to get the max freq element from a list?
numsfreq = Counter(nums)
return max(numsfreq.keys(), key=numsfreq.get)
OR
return max(numsfreq.keys(), key=lambda x: numsfreq[x])
How can you use a dictionary’s .get method to add the frequencies of elements in a dict?
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 to sort array by frequency?
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.