Python Workout Flashcards

(77 cards)

1
Q

Create a random number between 10 and 30 in Python

A
import random
num = random.randint(10, 30)

alternate way: from random import randint

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

Python function used to prompt the user to enter text?

A

input()

input() returns string

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

Validate that string name contains only digits.

A

name.isdigit()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
  1. Convert ‘5’ to 5
  2. Convert 5 to ‘5’
A
  1. int(‘5’)
  2. str(5)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What will happen with below code:

int('34e5')
A

ValueError will be thrown.

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

Print a list of first 5 even numbers without using for loop.

A
print(list(range(2,11,2)))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

_ operator allows a function to receive an unknown (0 or more) num
ber of arguments.

A

splat

 mysum(*[1,2,3]) = mysum(1,2,3)

argument becomes a tuple

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

condition for empty string str in Python

A

if not str

same expression for non-zeroness

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

Round up mins (float) to two decimal places.

A

round(mins, 2)

In f-string: f”{mins: .2f}”

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

Convert one_run into float and throw error if it is non-numeric.

A
try:
            mins = float(one_run)
        except ValueError as e:
            print(f"{one_run} is not a valid number. Digits expected!")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Traverse through each digit of a decimal number num
Print index (position) and digit in reverse order (right to left).

A
for i, d in enumerate(reversed(str(num))):
print(f'position: {i}, digit: {d}')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q
  1. Python function to find unicode code point of a character string.
  2. Convert a non-digit hexadecimal character hnum (string) to its decimal equivalent.
A
  1. ord()
  2. ord(hnum) - ord('a') + 10

Alternatively, int(hnum, 16)

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

Check if ‘a’ is present in ‘abcd’

A

if 'a' in 'abcd'

same for any sequence: list or tuple

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q
numbers = [5, 2, 9, 1, 5, 6, 9, 7]

Find unique numbers from the numbers list.

A
set(numbers)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q
a,b,c = 3,4,8

Swap the three variables, such that after swapping:
a=4, b=8, c=3.

Hint: In-place replacement in Python

A
a,b,c = b, c, a
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Use Python to create a safe “lowest possible” numeric value.

Hint: float

A
neg_inf = float('-inf')
print(neg_inf < -10**9)  # True
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Write function third_max to find the third maximum number in a numeric list.

numbers = [5, 2, 9, 1, 5, 6, 9, 7]

A
from typing import List, Optional
def third_max(numbers: List[int]) -> Optional[int]:
	''' 
		Write function `third_max` to find the third maximum number in a numeric list.
	'''
	unique_nums = set(numbers)
	if len(unique_nums) < 3:
		print('Not sufficient numbers')
		return None
	firstM = secondM = thirdM = float('-inf')	# firstM >= secondM >= thirdM
	for num in unique_nums:
		if num > firstM:
			firstM, secondM, thirdM = num, firstM, secondM
		elif num > secondM:
			secondM, thirdM = num, secondM
		elif num > thirdM:
			thirdM = num
	return int(thirdM)

print(third_max([5, 2, 9, 1, 5, 6, 9, 7]))  # should return 6
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Return ‘bdf’ from ‘abcdef’ using slicing in Python

A
'abcdef'[1::2]

type of the sliced output is same as input’s type

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

Break string ‘abc def ghi’ apart based on spaces.

A
'abc def ghi'.split()

output of split() is list

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

join a list of strings ['abc', 'def', 'ghi'] by spaces.

A
' '.join(['abc', 'def', 
'ghi'])

output of join depends on type of items in list

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

defining a function name a second time will overwrite the first definition.
(T/F)

A

True

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

Which of the following will throw error?
1. print('data engineer'.split(None))
2. print('data engineer'.split(''))
3. print('data engineer'.split())
4. print('data engineer'.split(' '))

A
  1. will print ['data', 'engineer']
  2. will throw ValueError: empty separator
  3. will print ['data', 'engineer']
  4. will print ['data', 'engineer']

default value of sep is None

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

generic way to create empty list/tuple/str from given argument?

A
def first_last(seq):
    if not seq:
        return seq
    output = type(seq[0])()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q
  1. Return subsequence containing first element of list/tuple/str.
  2. Return subsequence containing last element of list/tuple/str.
A
  1. seq[:1]
  2. seq[-1:]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
join two items of a sequence (list/tuple/str) in generic way.
Using `+` operator.
26
Remove leading nd trailing whitespaces from a string str.
str.strip()
27
Get position of first matching substring (`sp`) in a given string.
1. `str.find('sp')` 2. `str.index('sp')` ## Footnote If substring not found, index throws exception while find returns -1.
28
Write function `find_second_substr` to find the second substring `sub` in `s` ## Footnote `print(find_second_substr('sahil will kill it', 'ill')) # should return 12`
``` if not s or not sub: return -1 first_idx = s.find(sub) if first_idx == -1: return -1 second_idx = s.find(sub, first_idx+1) return second_idx ```
29
`numbers = [1, 3, 5, 6, 8]` Return index of first even number from numbers list.
``` def find_first_even(nums): for i,n in enumerate(nums): if n%2 == 0: return i return -1 ```
30
`items = [1, 3, 5, 6, 8]` Write code to generate tuple of even numbers from items list.
``` gen = (x for x in items if x%2==0) ``` ## Footnote next(gen) returns next even number from items
31
Difference between list comprehension [...] and generator expression (...)
generator expression 1. follows lazy evaluation, i.e., generates value only when needed (not entire list). 2. is more memory efficient than list comprehension.
32
Print every third number from 10 to 30.
``` for x in range(10, 30, 3): print(x) ```
33
_ operator in Python can sum numbers, concatenate strings and join lists.
`+`
34
Give example of inline if else clause, which assigns 0 if empty and count of list otherwise
``` count = 0 if not mylist else len(mylist) ```
35
make a string `name` to lowercase.
`name.lower()`
36
Python strings are _ . (mutable/immutable)
immutable ## Footnote Note: strings are commonly used as dict keys, which should be immutable by design
37
Three key benefits of immutable types in programming?
1. If passed to a function as argument, we get assurance that it won't be modified inside the function. 2. If shared across multiple threads, we don't need to worry about locking it. 3. If we invoke a method on immutable type, we get new object while original object stays unmodified.
38
1. `sorted()` returns _ . 2. `reversed()` returns _ . 3. `enumerate()` returns _ .
1. a list 2. an iterator 3. an iterator
39
`mylist = [1,-2,-4,3,5]` Sort mylist based on absolute values.
``` sorted(mylist, key= lambda num: abs(num)) ``` ## Footnote Note: sorted always returns a list.
40
Open a file to read & print one line at a time.
``` with open("example.txt", "r") as file: for line in file: print(line.strip()) ```
41
In Python, lists are _ while tuple are _ . (mutable/immutable)
1. mutable 2. immutable ## Footnote lists are meant to be used for sequences of the same type, whereas tuples are meant for sequences of different types.
42
Return the index of the second occurrence of substring `sub` in string `s` ## Footnote print(find_second_substr('sahil will kill it hil', 'hil')) print(find_second_substr('sahil will kill it', 'ill'))
``` def find_second_substr(s: str, sub: str) -> int: if not s or not sub: return -1 first_index = s.find(sub) if first_index == -1: return -1 # Substring not found at all second_index = s.find(sub, first_index + len(sub)) return second_index ```
43
Call myzip([10, 20,30], 'abc'), the result will be [(10, 'a'), (20,'b'), (30, 'c')], i.e., a list of tuples. You can assume that all of the iterables are of the same length.
``` def myzip(mylist, mystr): output = list() for i in range(len(mylist)): output.append((mylist[i], mystr[i])) return output print(myzip([10, 20, 30], 'abc')) ```
44
Find the number of bytes consumed by the list you created.
``` import sys result = [(10, 'a'), (20, 'b'), (30, 'c')] print(sys.getsizeof(result)) ``` ## Footnote prints 88
45
Python allocates some extra space in its list (which is implemented as array of pointers), such that we can add a few items to it. But at a certain point, if we add enough items to our list, these spare locations will be used up, thus forcing Python to allocate a new array and move all of the pointers to that location. Write a program to validate that the memory size of list jumps in chunks, i.e., Python over-allocates size of list to reduce frequent reallocations.
``` import sys lst = [] for i in range(100): lst.append(i) print(f"Length: {len(lst)}, Size: {sys.getsizeof(lst)} bytes") ```
46
Which of the following is considered false in an if clause? 1. None 2. False 3. 0 4. empty collection
all of them considered false. Except these four, everything else is considered true in an if clause.
47
Return the index of the first number in the list that satisfies the condition, or -1 if there are none. `def find_first_where(satisfy, nums):` ## Footnote `satisfy` is a lambda here.
``` def find_first_where(satisfy, nums): for i,n in enumerate(nums): if (satisfy(n)): return i return -1 print(find_first_where(lambda x: x%2 == 0, [1,3,5,7,4])) ``` ## Footnote As a follow up, try the same problem using generator expression.
48
Return the sum of numbers that satisfy the given condition.
``` def conditional_sum(satisfy, numbers): '''Returns the sum of numbers that satisfy the given condition.''' gen = (n for n in numbers if satisfy(n)) return sum(gen) numbers = [10, 20, 30, 40] print(conditional_sum(lambda x: x > 20, numbers)) ``` ## Footnote prints 70
49
print all key value pairs from given dict, in the format: `k:v`
``` for k,v in mydict.items(): print(f'{k}:{v}') ```
50
Check if key is present in mydict
`if key in mydict`
51
Write program to flatten list of dicts. ``` input = [ {'first':'Reuven', 'last':'Lerner','email':'reuven@lerner.co.il'}, {'first':'Donald', 'last':'Trump','email':'president@whitehouse.gov'}, {'first':'Vladimir', 'last':'Putin','email':'president@kremvax.ru'} ] ``` Output = ``` { 'first':['Reuven', 'Donald', 'Vladimir'] 'last':['Lerner', 'Trump', 'Putin'] 'email':['reuven@lerner.co.il', 'president@whitehouse.gov', 'president@kremvax.ru'] } ```
52
Sort list of integers by their absolute values. ## Footnote `print(abs_based_sorting([1,-2,-4,3,5]))`
``` def abs_based_sorting(numbers): if not numbers: return [] return sorted(numbers, key = abs) ```
53
Return name of student with maximum marks from student_dict having key = name and value = marks.
``` return max(student_dict, key=lambda name: student_dict[name]) ```
54
While enumerting, whenever you slice a list but still care about the original indices, use _ to keep them aligned.
`enumerate(..., start=offset)`
55
What happens when you try to access a missing key from a dictionary in Python?
KeyError
56
A _ is a function that takes another function as input and returns a new function with enhanced functionality. It allows you to modify or extend the behavior of a function or method without changing its actual code.
decorator ## Footnote Decorators are often used for logging, authentication, timing, caching, etc.
57
You have a function: ``` @my_decorator def say_hello(): print("Hello, World!") ``` Write a custom decorator: `my_decorator` to achieve following output on function call `say_hello()`: ``` Before function call Hello, World! After function call ```
``` def my_decorator(func): def wrapper(): print("Before function call") func() print("After function call") return wrapper @my_decorator def say_hello(): print("Hello, World!") say_hello() ``` ## Footnote Note: `@my_decorator` is shorthand for `say_hello = my_decorator(say_hello)`. The wrapper function (`my_decorator`) adds behavior before and after the original function.
58
What will be the output? ``` def repeat(n): def decorator(func): def wrapper(*args, **kwargs): for _ in range(n): func(*args, **kwargs) return wrapper return decorator @repeat(3) def greet(name): print(f"Hello, {name}!") greet("Sahil") ```
``` Hello, Sahil! Hello, Sahil! Hello, Sahil! ```
59
``` @timing_decorator def compute(): sum([i**2 for i in range(10**6)]) compute() ``` Write `timing_decorator` that prints: ``` "{func.__name__} executed in {end - start:.6f} seconds" ```
``` import time def timing_decorator(func): def wrapper(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) end = time.perf_counter() print(f"{func.__name__} executed in {end - start:.6f} seconds") return result return wrapper ```
60
Decorator _ preserves the original function’s metadata (name, docstring). Give example.
`functools.wraps` ``` from functools import wraps def my_decorator(func): @wraps(func) def wrapper(*args, **kwargs): print("Extra behavior") return func(*args, **kwargs) return wrapper ```
61
In Python, _ are viewed as data structures to which we can write strings, and from which we can read strings.
files
62
Open a text file, save its content as string and then close the file.
``` f = open('example.txt', 'r') data = f.read() f.close() ```
63
What will be printed in each of the following print statements? ``` with open("example.txt") as f: print(f.read()) with open("example.txt") as f: print(f.read(5)) with open("example.txt") as f: print(f.readline()) with open("example.txt") as f: print(f.readlines()) ```
1. Full content of file as string 2. First 5 characters of file 3. First line of file 4. List of all lines of file
64
The safest option for cross-platform projects is to explicitly set file encoding=
"utf-8" ## Footnote ``` with open("README.md", encoding="utf-8") as f: text = f.read() ```
65
If you open a `UTF-8` encoded file on Windows without specifying encoding, Python will use the system’s default locale encoding (like `cp1252`). If the file contains non‑ASCII characters, then reading it using: ``` with open("README.md") as f: text = f.read() ``` will raise an exception called _
`UnicodeDecodeError`
66
Use the current system locale encoding to read the file.
``` with open("README.md", encoding="locale") as f: text = f.read() ```
67
In the case of invalid or inaccessible file names and paths, _ is thrown by Python.
`OSError exception`
68
A context manager is any Python object that defines how to set up and clean up resources. It implements two special methods: * _ sets up the resource * _ cleans up the resource ## Footnote The `with` statement is used to wrap the execution of a block of code inside a context manager
1. `__enter__()` 2. `__exit__()`
69
``` class MyContext: def __enter__(self): print("Entering context...") return "Resource Ready" def __exit__(self, exc_type, exc_value, traceback): print("Exiting context... Cleaning up!") ``` Wrap the execution of a block of code inside `MyContext` object (a context manager)
``` with MyContext() as resource: print(resource) ```
70
Adds elements `10, 20, 30` to a set `s`.
``` s.update([10, 20, 30]) ```
71
write a function (`get_final_line`) that takes a filename as an argument. The function should return that file’s final line on the screen. ## Footnote ignore lines containing nothing but whitespace and the ones starting with #
``` def get_final_line(filename): final_line = '' for current_line in open(filename): final_line = current_line return final_line print(get_final_line('/etc/passwd')) ```
72
1. Check if variable `item` is an `int` 2. Check if variable `item` is a `list`
1. `if isinstance(item, int)` 2. `if isinstance(item, list)`
73
Flatten the nested list in Python using recursion ## Footnote Example usage ```input_data = [1, [2, 3], [4, 5, [6, 7]], 8] output_data = flatten_list(input_data) print(output_data) # [1, 2, 3, 4, 5, 6, 7, 8] ```
``` def flatten_list(nested_list): flat = [] for item in nested_list: if isinstance(item, list): flat.extend(flatten_list(item)) else: flat.append(item) return flat ```
74
``` stack = [] stack.append('a') stack.append('b') stack.pop() print(stack) ``` What will be the output?
``` ['a'] ```
75
Recursively remove adjacent identical letters from given string, until none remains. ## Footnote Examples ``` print(reduce_string('xybaabxy')) # Output: 'xyxy' print(reduce_string('xybaabyx')) # Output: '' ```
``` def reduce_string(s: str) -> str: stack = [] for char in s: if stack and stack[-1] == char: stack.pop() # remove the adjacent pair else: stack.append(char) return ''.join(stack) ```
76
Slice `item[::-1]` returns _ , whereas `reversed(item)` returns _ , which consumes less memory.
1. a reversed string 2. a reversed iterator
77