Python3 - Functions Flashcards

1
Q

Pure Functions

A

Have no side effects.

output of a pure functions is determined entirely by input, and do not modify any state outside of itself (even print modifies the state of the console).

comprehensible, easier to reason, debug and parallelize (execute multiple at the same time)

def square (x): return x * x

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

Higher-Order Functions

A

take one or more function as an argument, or return one or more function as a result.

list ( map ( lambda x: x * x, [1, 2, 3]))

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

Recursion

A

Programming technique where function calls itself.

takes base case (case where recursion finishes) and recursive case (reason to call itself)

def factorial(n):

if n == 1:
return 1
else:
return n * factorial(n-1)

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

Nested Function

A

function inside function.

helps encapsulate code to be easier to read and maintain, but can be harder to understand if overused.

creates closures, comprehensions and decorators

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

Closure

A

creates functions with access to variables in surrounding scope. creates reusable functions that work with different data

(generators, decorators, higher order functions.

def make_multiplier(factor):
def multiplier(number):
return number * factor
return multiplier

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

Enclosing

A

Ability of a nested function to access variables defined in enclosing function (surrounding scope)

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

Nonlocal Variable

A

variable set to be accessible beyond current scope (nested function variable defined with nonlocal keyword)

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

*args and **kwargs

A

permit variable number of arguments as parameters.
kwargs permits key-value pairs.

def print_args(*args):
for arg in args:
print(arg)

def prints_kwargs( **kwargs):
for key, value in kwargs.items():
print(key, value)

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

lambda functions

A

one-lined function defined using lambda keyword.

“anonymous” function, quick and compact. takes a single expresison and any number of arguments, ad returns the result of the expression, per argument. good for map, filter and reduce.

squares = (lambda x: x * x, numbers_list)

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

Comprehensions

A

concise way to make lists, sets, dictionaries and generators.

used to create new sequences from existing sequences.

squares_list = [x * x for x in range(1, 11) ]
even_numbers_set = { x for x in range(1, 11) if x % 2 == 0 }

squares_dict = {x: x * x for x in range(10)}
evens_only_squares_dict = {x: x * x for x in range(10) if x % 2 == 0}

> > > evens_only_squares_dict
{0: 0, 4: 16, 8: 64}

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

Decorators

A

function that returns another function as an argument, returns a modified version of the function. efined using @symbol.

@make_pretty
def ordinary():
print(something”)

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

built-in functions:
Map
Filter
reduce

A

numbers = [1, 2, 3, 4, 5]

squared_numbers = map(lambda x: x * x, numbers)
# Output: [1, 4, 9, 16, 25]

even_numbers = filter(lambda x: x % 2 == 0, numbers)
# Output: [2, 4]

product_of_numbers = reduce(lambda x, y: x * y, numbers)
# Output: 120

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

What is the difference between “expression” and “statement”

A

expression is a combination of variables the evaluates to a single value,

but a statement has a side effect (x = 2 * 2 vs 2 * 2)

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

When should you use lambda, when should you not?

A

yes for one-off functions. NOT for loops.

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

Write a program to remove specific words from a given list using lambda

A

def remove_words(lst, remove_from_list):
return list(filter(lambda word: word not in remove_from_list, lst))

my_list = [“Python”, “C”, “BashScript”, “JavaScript”, “COBOL”, “Java”]
remove_list = [“COBOL”, “Java”]

filtered_list = remove_words(my_list, remove_list)

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

Write a program to sort a list of strings(numbers) numerically. use lambda

A

def sort_list_and_convert_to_int(lst):
return [int(x) for x in sorted(lst, key=lambda x: int(x))]

num_string_list = [“5”, “1”, “3”, “2”, “4”]
sorted_list = sort_list_and_convert_to_int(num_string_list)

17
Q

Write a program to calculate the sum of the positive and nevative numbers of a given list of numbers sing lambda function

A

def calculate_sum(numbers):
pos_sum = sum(filter(lambda x: x > 0, numbers))
neg_sum = sum(filter(lambda x: x < 0, numbers))
return pos_sum, neg_sum

18
Q

Using list comprehension, construct a list from the squares of each element in the given list

A

def sqrt_even_elements(numbers):
return [x ** 2 for x in numbers if x % 2 == 0]

19
Q

Write a function that receives the dictionary with the names of products and their prices and returns the dictionary with 10% sale price

A

def sale_pricing(products, discount_percentage):
return {product: price * (1 - (discount_percentage / 100)) for product, price in products.items()}

20
Q

Gematria Function reminder

A

def validate_credit_card(num):
# Convert the number to a list of digits
digits = [int(digit) for digit in str(num)]

# Double every other digit starting from the second-to-last digit
doubled_digits = [2 * digit if idx % 2 == len(digits) % 2 else digit for idx, digit in enumerate(digits[::-1])][::-1]

# Subtract 9 from doubled digits greater than 9
summed_digits = [digit - 9 if digit > 9 else digit for digit in doubled_digits]

# Calculate the total sum of all digits
total_sum = sum(summed_digits)

# Check if the total sum is divisible by 10
return total_sum % 10 == 0
21
Q

Linux Boot Process

A

BIOS:
-performs POST, checking CPU, memory and disk drives functional, and compatible with OS
- searches for Boot Loader in MBR (special area in hard drive that stores boot loaders)

Boot Loader:
- loads kernel into memory (Kernel is core of the OS. manages hardware, starts processes and and loads file systems)

Kernel initializes hardware
-configures hardware
-loads necessary drivers
-kernel mounts the file systems (so OS can access files)
-starts init (daemon responsible for starting over processes and managing system resources)

Init:
- runs startup scripts (scripts in /etc/init.d that start services and loading drivers. The drivers not required up until now.)
- efffectively starts the Shell, GUI, and and services needed to start OS

22
Q

rename files in a directory. in bash

A

newname=”toot_”

for file in $1
do
if [ -f “$file” ]
then
mv “$file” “${newname}_${file}”
fi
done

23
Q

return copy of string (yes I’m borrowing Caesar’s answer sorry he’s a great coder)

A

char *StringDup(char *str, char *copy_str);

int main()
{
char *str = “Hello”;
char *copy_str = malloc(sizeof(char) * strlen(str) + 1);
copy_str = StringDup(str, copy_str);

printf("Original String is: %s\n", str);
printf("Duplicated string is %s\n", copy_str);

free(copy_str);
return 0; }

char *StringDup(char *str, char *copy_str)
{
size_t i;

for(i = 0; i < strlen(str); ++i)
{
	copy_str[i] = str[i];
}

return copy_str; }
24
Q

C Build Process

A

Preprocessor: takes .C file, outputs .i file
- removes comments, expands macros, runs #includes,

Compiler: takes .i file, outputs .asm file.
-parsing (breaks code down to sequence of tokens, to generate sequence of instructions pushq etc.)