Python3 - Functions Flashcards
Pure Functions
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
Higher-Order Functions
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]))
Recursion
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)
Nested Function
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
Closure
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
Enclosing
Ability of a nested function to access variables defined in enclosing function (surrounding scope)
Nonlocal Variable
variable set to be accessible beyond current scope (nested function variable defined with nonlocal keyword)
*args and **kwargs
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)
lambda functions
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)
Comprehensions
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}
Decorators
function that returns another function as an argument, returns a modified version of the function. efined using @symbol.
@make_pretty
def ordinary():
print(something”)
built-in functions:
Map
Filter
reduce
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
What is the difference between “expression” and “statement”
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)
When should you use lambda, when should you not?
yes for one-off functions. NOT for loops.
Write a program to remove specific words from a given list using lambda
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)
Write a program to sort a list of strings(numbers) numerically. use lambda
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)
Write a program to calculate the sum of the positive and nevative numbers of a given list of numbers sing lambda function
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
Using list comprehension, construct a list from the squares of each element in the given list
def sqrt_even_elements(numbers):
return [x ** 2 for x in numbers if x % 2 == 0]
Write a function that receives the dictionary with the names of products and their prices and returns the dictionary with 10% sale price
def sale_pricing(products, discount_percentage):
return {product: price * (1 - (discount_percentage / 100)) for product, price in products.items()}
Gematria Function reminder
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
Linux Boot Process
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
rename files in a directory. in bash
newname=”toot_”
for file in $1
do
if [ -f “$file” ]
then
mv “$file” “${newname}_${file}”
fi
done
return copy of string (yes I’m borrowing Caesar’s answer sorry he’s a great coder)
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; }
C Build Process
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.)