Python Flashcards

1
Q

Find length of list

A

length = len(list)

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

For loop for list

A

for element in list:

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

If, elif, else

A

if condition1:

elif condition2:

else:

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

If, elif, else

A

if condition1:

elif condition2:

else:

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

Print value

A

print(value)

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

Print floating point number with precision

A

print(f’{value:.6f}’)

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

Initiate variable

A

variable = 0

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

Increase a count

A

count += 1

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

Decrease a count

A

count -= 1

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

Initialise a variable to positive infinity

A

variable = float(‘inf’)

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

Initialise a variable to negative infinity

A

variable = -float(‘inf’)

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

Print multiple values in one line in Python

A

print(f’{value1} {value2}’)

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

Replace a substring in a string in python

A

new_string = old_string.replace(‘old_substring’, ‘new_substring’)

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

Check if substring in string

A

if ‘substring’ in string:

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

How to get a substring of first n numbers of characters

A

substring = string[:2]

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

Get substring of characters after first 2

A

substring = string[2:]

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

Convert string to int

A

number = int(string)

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

Convert number to string

A

str(number)

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

Replace first occurrence of a substring in Python

A

new_string = old_string.replace(‘old_substring’, ‘new_substring’, 1)

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

How to iterate from 1 to n inclusive in a for loop using range

A

for i in range(1, n+1)

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

Iterate from 0 to n exclusive in a for loop using range

A

for i in range(n):

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

Iterate from starting value to an ending value with a specific step in a for loop

A

for i in range(start, stop, end):

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

How to check if a number is divisible by another number

A

number % division == 0

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

Iterate backwards from n to 1 inclusive using range

A

for i in range(n, 0, -1):

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Sort list in place
list.sort()
26
Find floor of a number
import math math.floor(number)
27
Find ceiling of a number
import math math.ceil(number)
28
Create an empty dictionary
dictionary = {}
29
Check if key exists in dictionary
if key in dictionary:
30
Delete key value pair
del dictionary[key]
31
Add key value pair
dictionary[key] = value
32
Get list of all keys in a dictionary
keys = list(dictionary.keys())
33
Calculate the trace of diagonal elements
import numpy as np np.trace(matrix)
34
Transpose a matrix and find trace
import numpy as np np.trace(matrix.T)
35
Iterate through the rows of a square matrix
for i in range(len(matrix)):
36
Access elements on the primary diagonal of a square matrix
matrix[i][i]
37
Access element on the secondary diagonal of a square matrix
matrix[len(matrix) - 1 - i][i]
38
Find absolute value of a number
abs(number)
39
Initialise an array with zeros in Python
array = [0] * size
40
Initialise an array with a specific value using list comprehension in Python
array = [value for x in range(size)]
41
Initialise a list with a given size and fill with None values
array = [None] * size
42
What is counting sort
Counting sort is a non-comprehension-based sorting algorithm that sorts integers by counting the number of occurrences of each unique element. It then calculates the positions of each element in the sorted array
43
When to use Counting Sort
Counting sort is efficient when the range of input values (k) is not significantly larger than the number of elements (n) to be sorted. It is ideal for sorting integers within a limited range
44
Time complexity of counting sort
O(n+k) where n is the number of elements in the input array and k is the range of the input
45
How to find the minimum value in a list in Python
min_value = min(list)
46
Find maximum value in a list in Python
max_value = max(list)
47
Calculate the range of elements in a list
range_of_elements = max_value - min_value
48
Find maximum value of many values
max_value = max(value1, value2, value3, value4)
49
Swap two elements in a list
list[index1], list[index2] = list[index2], list[index1]
50
Unpack a list into separate arguments
function(*list) print(*list)
51
Find index of a character in a string in Python
index = string.find(character)
52
Get character at index Python
character = string[index]
53
Concatenate string Python
result = string1 + string2
54
Check if character in string
if character in string
55
Create a list with list comprehension
new_list = [expression for item in iterable]
56
Iterate from both ends of a string towards the center
left, right = 0, len(string) - 1 while left < right: #proces left += 1 right -= 1
57
Check if string is a palindrome
string == string[::-1]
58
Slice a string to remove character at index
new_string = string[:index] + string[index+1:]
59
Sort each row in a 2D list in Python
sorted_grid = [sorted(row) for row in grid]
60
How to sort in place
string.sort()
61
Sort and return new string
sorted(string)
62
Check if stack (list) is empty before accessing the top element
if stack and stack[-1] == element:
63
Remove last element in stack
stack.pop()
64
Remove element with index
stack.pop(index)
65
Add to end of a list
list.append(value)
66
Count occurrences of elements in a list using a dictionary in Python
string_counts = {} for s in list_of_strings: if s in string_counts: string_counts[s] += 1 else: string_counts[s] = 1
67
Retrieve a value from a dictionary with a default if the key is not present. So we can have a value if there is no key
value = dictionary.get(key, default_value) # Example: count = string_counts.get(query, 0)
68
Make string lower case
str.lower()
69
Make python string upper case
str.upper
70
Convert string to a set. This is a set of unique characters
set(string)
71
Check if a set is a subset of another set
set1.issubset(set2) Where set1 is the constraint set like alphabet, so you would see if set2 contains the whole alphabet
72
Convert first letter to capital in string
str.capitalise()
73
Center a string after padding with a specified character
str.center(width, [fillchar]) E.g., str.center(24, ‘*’)
74
Return number of occurrences of a substring in a given string
str.count(substring, start, end) str.count(‘p’)
75
Return true if a string ends with a specified suffix
str.endswith(‘PM’)
76
Return index of first occurrence of substring if found, if not found returns -1
str.find(‘fun’)
77
Return index of first occurrence of substring if found, if not found returns -1
str.find(‘fun’)
78
Return true if all characters in string are alphanumeric, if not false
str.isalnum()
79
Find if string is all alphabet characters, either upper or lower case
str.isalpha()
80
Return true if all characters in a string are digits
str.isdigit()
81
Return true if all characters are lower case
str.islower()
82
Return true is all characters are upper case
str.isupper()
83
Join all elements of an iterable list separated by a given separator
‘ ‘.join(array)
84
Convert characters in a string to the opposite case
str.swapcase()
85
Replace a substring with another string, this is for every occurrence
str.replace(‘ba’, ‘ro’)
86
Split a string to an array with a chose separator
str.split() str.split(separator)
87
Split a string to an array with a chose separator
str.split() str.split(separator)
88
Sort list in ascending order
list.sort()
89
Sort list in descending order
list.sort(reverse=True)
90
Calculate the sum of a subarray
subarray_sum = sum(list[start:end])
91
Calculate the sum of a subarray
subarray_sum = sum(list[start:end])
92
Iterate over all possible subarrays of a given length
for i in range(len(list) - subarray_length + 1): # access the subarray with list[i:i+subarray_length]
93
Remove value from array
stack.remove(num)
94
Count occurrences of elements in a list using a dictionary
sock_counts = {} for sock in list_of_socks: if sock in sock_counts: sock_counts[sock] += 1 else: sock_counts[sock] = 1
95
Iterate through values in dictionary
for value in dictionary.value():
96
Calculate the number of pairs from a count of items
pairs = count // 2 This is integer division, essentially calculating the number of times 2 goes completely into pairs