function
stringlengths
18
3.86k
intent_category
stringlengths
5
24
def calculate_each_score( data_lists: list[list[float]], weights: list[int] ) -> list[list[float]]: score_lists: list[list[float]] = [] for dlist, weight in zip(data_lists, weights): mind = min(dlist) maxd = max(dlist) score: list[float] = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind))) except ZeroDivisionError: score.append(1) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind)) except ZeroDivisionError: score.append(0) # weight not 0 or 1 else: raise ValueError(f"Invalid weight of {weight:f} provided") score_lists.append(score) return score_lists
other
def generate_final_scores(score_lists: list[list[float]]) -> list[float]: # initialize final scores final_scores: list[float] = [0 for i in range(len(score_lists[0]))] for slist in score_lists: for j, ele in enumerate(slist): final_scores[j] = final_scores[j] + ele return final_scores
other
def __init__(self, literals: list[str]) -> None: # Assign all literals to None initially self.literals: dict[str, bool | None] = {literal: None for literal in literals}
other
def __str__(self) -> str: return "{" + " , ".join(self.literals) + "}"
other
def __len__(self) -> int: return len(self.literals)
other
def assign(self, model: dict[str, bool | None]) -> None: for literal in self.literals: symbol = literal[:2] if symbol in model: value = model[symbol] else: continue if value is not None: # Complement assignment if literal is in complemented form if literal.endswith("'"): value = not value self.literals[literal] = value
other
def evaluate(self, model: dict[str, bool | None]) -> bool | None: for literal in self.literals: symbol = literal.rstrip("'") if literal.endswith("'") else literal + "'" if symbol in self.literals: return True self.assign(model) for value in self.literals.values(): if value in (True, None): return value return any(self.literals.values())
other
def __init__(self, clauses: Iterable[Clause]) -> None: self.clauses = list(clauses)
other
def __str__(self) -> str: return "{" + " , ".join(str(clause) for clause in self.clauses) + "}"
other
def generate_clause() -> Clause: literals = [] no_of_literals = random.randint(1, 5) base_var = "A" i = 0 while i < no_of_literals: var_no = random.randint(1, 5) var_name = base_var + str(var_no) var_complement = random.randint(0, 1) if var_complement == 1: var_name += "'" if var_name in literals: i -= 1 else: literals.append(var_name) i += 1 return Clause(literals)
other
def generate_formula() -> Formula: clauses: set[Clause] = set() no_of_clauses = random.randint(1, 10) while len(clauses) < no_of_clauses: clauses.add(generate_clause()) return Formula(clauses)
other
def generate_parameters(formula: Formula) -> tuple[list[Clause], list[str]]: clauses = formula.clauses symbols_set = [] for clause in formula.clauses: for literal in clause.literals: symbol = literal[:2] if symbol not in symbols_set: symbols_set.append(symbol) return clauses, symbols_set
other
def find_pure_symbols( clauses: list[Clause], symbols: list[str], model: dict[str, bool | None] ) -> tuple[list[str], dict[str, bool | None]]: pure_symbols = [] assignment: dict[str, bool | None] = {} literals = [] for clause in clauses: if clause.evaluate(model): continue for literal in clause.literals: literals.append(literal) for s in symbols: sym = s + "'" if (s in literals and sym not in literals) or ( s not in literals and sym in literals ): pure_symbols.append(s) for p in pure_symbols: assignment[p] = None for s in pure_symbols: sym = s + "'" if s in literals: assignment[s] = True elif sym in literals: assignment[s] = False return pure_symbols, assignment
other
def find_unit_clauses( clauses: list[Clause], model: dict[str, bool | None] ) -> tuple[list[str], dict[str, bool | None]]: unit_symbols = [] for clause in clauses: if len(clause) == 1: unit_symbols.append(list(clause.literals.keys())[0]) else: f_count, n_count = 0, 0 for literal, value in clause.literals.items(): if value is False: f_count += 1 elif value is None: sym = literal n_count += 1 if f_count == len(clause) - 1 and n_count == 1: unit_symbols.append(sym) assignment: dict[str, bool | None] = {} for i in unit_symbols: symbol = i[:2] assignment[symbol] = len(i) == 2 unit_symbols = [i[:2] for i in unit_symbols] return unit_symbols, assignment
other
def dpll_algorithm( clauses: list[Clause], symbols: list[str], model: dict[str, bool | None] ) -> tuple[bool | None, dict[str, bool | None] | None]: check_clause_all_true = True for clause in clauses: clause_check = clause.evaluate(model) if clause_check is False: return False, None elif clause_check is None: check_clause_all_true = False continue if check_clause_all_true: return True, model try: pure_symbols, assignment = find_pure_symbols(clauses, symbols, model) except RecursionError: print("raises a RecursionError and is") return None, {} p = None if len(pure_symbols) > 0: p, value = pure_symbols[0], assignment[pure_symbols[0]] if p: tmp_model = model tmp_model[p] = value tmp_symbols = list(symbols) if p in tmp_symbols: tmp_symbols.remove(p) return dpll_algorithm(clauses, tmp_symbols, tmp_model) unit_symbols, assignment = find_unit_clauses(clauses, model) p = None if len(unit_symbols) > 0: p, value = unit_symbols[0], assignment[unit_symbols[0]] if p: tmp_model = model tmp_model[p] = value tmp_symbols = list(symbols) if p in tmp_symbols: tmp_symbols.remove(p) return dpll_algorithm(clauses, tmp_symbols, tmp_model) p = symbols[0] rest = symbols[1:] tmp1, tmp2 = model, model tmp1[p], tmp2[p] = True, False return dpll_algorithm(clauses, rest, tmp1) or dpll_algorithm(clauses, rest, tmp2)
other
def max_subarray_sum(nums: Sequence[int]) -> int: if not nums: raise ValueError("Input sequence should not be empty") curr_max = ans = nums[0] nums_len = len(nums) for i in range(1, nums_len): num = nums[i] curr_max = max(curr_max + num, num) ans = max(curr_max, ans) return ans
other
def fisher_yates_shuffle(data: list) -> list[Any]: for _ in range(len(data)): a = random.randint(0, len(data) - 1) b = random.randint(0, len(data) - 1) data[a], data[b] = data[b], data[a] return data
other
def __init__(self, key: T | None, val: U | None): self.key = key self.val = val self.next: DoubleLinkedListNode[T, U] | None = None self.prev: DoubleLinkedListNode[T, U] | None = None
other
def __repr__(self) -> str: return ( f"Node: key: {self.key}, val: {self.val}, " f"has next: {bool(self.next)}, has prev: {bool(self.prev)}" )
other
def __init__(self) -> None: self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.rear: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.head.next, self.rear.prev = self.rear, self.head
other
def __repr__(self) -> str: rep = ["DoubleLinkedList"] node = self.head while node.next is not None: rep.append(str(node)) node = node.next rep.append(str(self.rear)) return ",\n ".join(rep)
other
def add(self, node: DoubleLinkedListNode[T, U]) -> None: previous = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None previous.next = node node.prev = previous self.rear.prev = node node.next = self.rear
other
def remove( self, node: DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: if node.prev is None or node.next is None: return None node.prev.next = node.next node.next.prev = node.prev node.prev = None node.next = None return node
other
def __init__(self, capacity: int): self.list: DoubleLinkedList[T, U] = DoubleLinkedList() self.capacity = capacity self.num_keys = 0 self.hits = 0 self.miss = 0 self.cache: dict[T, DoubleLinkedListNode[T, U]] = {}
other
def __repr__(self) -> str: return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " f"capacity={self.capacity}, current size={self.num_keys})" )
other
def __contains__(self, key: T) -> bool: return key in self.cache
other
def get(self, key: T) -> U | None: # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 value_node: DoubleLinkedListNode[T, U] = self.cache[key] node = self.list.remove(self.cache[key]) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(node) return node.val self.miss += 1 return None
other
def put(self, key: T, value: U) -> None: if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity first_node = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(first_node) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 self.cache[key] = DoubleLinkedListNode(key, value) self.list.add(self.cache[key]) self.num_keys += 1 else: # bump node to the end of the list, update value node = self.list.remove(self.cache[key]) assert node is not None # node guaranteed to be in list node.val = value self.list.add(node)
other
def cache_decorator_wrapper(*args: T) -> U: if func not in cls.decorator_function_to_instance_map: cls.decorator_function_to_instance_map[func] = LRUCache(size) result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) cls.decorator_function_to_instance_map[func].put(args[0], result) return result
other
def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func]
other
def alternative_list_arrange(first_input_list: list, second_input_list: list) -> list: first_input_list_length: int = len(first_input_list) second_input_list_length: int = len(second_input_list) abs_length: int = ( first_input_list_length if first_input_list_length > second_input_list_length else second_input_list_length ) output_result_list: list = [] for char_count in range(abs_length): if char_count < first_input_list_length: output_result_list.append(first_input_list[char_count]) if char_count < second_input_list_length: output_result_list.append(second_input_list[char_count]) return output_result_list
other
def __repr__(self): return f"{self.__class__.__name__}.{self.name}"
other
def angle_comparer(point: tuple[int, int], minx: int, miny: int) -> float: # sort the points accorgind to the angle from the lowest and the most left point x, y = point return degrees(atan2(y - miny, x - minx))
other
def check_direction( starting: tuple[int, int], via: tuple[int, int], target: tuple[int, int] ) -> Direction: x0, y0 = starting x1, y1 = via x2, y2 = target via_angle = degrees(atan2(y1 - y0, x1 - x0)) via_angle %= 360 target_angle = degrees(atan2(y2 - y0, x2 - x0)) target_angle %= 360 # t- # \ \ # \ v # \| # s # via_angle is always lower than target_angle, if direction is left. # If they are same, it means they are on a same line of convex hull. if target_angle > via_angle: return Direction.left elif target_angle == via_angle: return Direction.straight else: return Direction.right
other
def __init__(self, key: T | None, val: U | None): self.key = key self.val = val self.freq: int = 0 self.next: DoubleLinkedListNode[T, U] | None = None self.prev: DoubleLinkedListNode[T, U] | None = None
other
def __repr__(self) -> str: return "Node: key: {}, val: {}, freq: {}, has next: {}, has prev: {}".format( self.key, self.val, self.freq, self.next is not None, self.prev is not None )
other
def __init__(self) -> None: self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.rear: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.head.next, self.rear.prev = self.rear, self.head
other
def __repr__(self) -> str: rep = ["DoubleLinkedList"] node = self.head while node.next is not None: rep.append(str(node)) node = node.next rep.append(str(self.rear)) return ",\n ".join(rep)
other
def add(self, node: DoubleLinkedListNode[T, U]) -> None: previous = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None previous.next = node node.prev = previous self.rear.prev = node node.next = self.rear node.freq += 1 self._position_node(node)
other
def _position_node(self, node: DoubleLinkedListNode[T, U]) -> None: while node.prev is not None and node.prev.freq > node.freq: # swap node with previous node previous_node = node.prev node.prev = previous_node.prev previous_node.next = node.prev node.next = previous_node previous_node.prev = node
other
def remove( self, node: DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: if node.prev is None or node.next is None: return None node.prev.next = node.next node.next.prev = node.prev node.prev = None node.next = None return node
other
def __init__(self, capacity: int): self.list: DoubleLinkedList[T, U] = DoubleLinkedList() self.capacity = capacity self.num_keys = 0 self.hits = 0 self.miss = 0 self.cache: dict[T, DoubleLinkedListNode[T, U]] = {}
other
def __repr__(self) -> str: return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " f"capacity={self.capacity}, current_size={self.num_keys})" )
other
def __contains__(self, key: T) -> bool: return key in self.cache
other
def get(self, key: T) -> U | None: if key in self.cache: self.hits += 1 value_node: DoubleLinkedListNode[T, U] = self.cache[key] node = self.list.remove(self.cache[key]) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(node) return node.val self.miss += 1 return None
other
def put(self, key: T, value: U) -> None: if key not in self.cache: if self.num_keys >= self.capacity: # delete first node when over capacity first_node = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert self.list.remove(first_node) is not None # first_node guaranteed to be in list del self.cache[first_node.key] self.num_keys -= 1 self.cache[key] = DoubleLinkedListNode(key, value) self.list.add(self.cache[key]) self.num_keys += 1 else: node = self.list.remove(self.cache[key]) assert node is not None # node guaranteed to be in list node.val = value self.list.add(node)
other
def cache_decorator_wrapper(*args: T) -> U: if func not in cls.decorator_function_to_instance_map: cls.decorator_function_to_instance_map[func] = LFUCache(size) result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) cls.decorator_function_to_instance_map[func].put(args[0], result) return result
other
def cache_info() -> LFUCache[T, U]: return cls.decorator_function_to_instance_map[func]
other
def get_week_day(year: int, month: int, day: int) -> str: # minimal input check: assert len(str(year)) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: century = year // 100 century_anchor = (5 * (century % 4) + 2) % 7 centurian = year % 100 centurian_m = centurian % 12 dooms_day = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 day_anchor = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) week_day = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day]
other
def __init__(self, name, value, weight): self.name = name self.value = value self.weight = weight
other
def __repr__(self): return f"{self.__class__.__name__}({self.name}, {self.value}, {self.weight})"
other
def get_value(self): return self.value
other
def get_name(self): return self.name
other
def get_weight(self): return self.weight
other
def value_weight(self): return self.value / self.weight
other
def build_menu(name, value, weight): menu = [] for i in range(len(value)): menu.append(Things(name[i], value[i], weight[i])) return menu
other
def greedy(item, max_cost, key_func): items_copy = sorted(item, key=key_func, reverse=True) result = [] total_value, total_cost = 0.0, 0.0 for i in range(len(items_copy)): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i]) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value)
other
def test_greedy():
other
def __init__( self, claim_vector: list[int], allocated_resources_table: list[list[int]], maximum_claim_table: list[list[int]], ) -> None: self.__claim_vector = claim_vector self.__allocated_resources_table = allocated_resources_table self.__maximum_claim_table = maximum_claim_table
other
def __processes_resource_summation(self) -> list[int]: return [ sum(p_item[i] for p_item in self.__allocated_resources_table) for i in range(len(self.__allocated_resources_table[0])) ]
other
def __available_resources(self) -> list[int]: return np.array(self.__claim_vector) - np.array( self.__processes_resource_summation() )
other
def __need(self) -> list[list[int]]: return [ list(np.array(self.__maximum_claim_table[i]) - np.array(allocated_resource)) for i, allocated_resource in enumerate(self.__allocated_resources_table) ]
other
def __need_index_manager(self) -> dict[int, list[int]]: return {self.__need().index(i): i for i in self.__need()}
other
def main(self, **kwargs) -> None: need_list = self.__need() alloc_resources_table = self.__allocated_resources_table available_resources = self.__available_resources() need_index_manager = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("_" * 50 + "\n") while need_list: safe = False for each_need in need_list: execution = True for index, need in enumerate(each_need): if need > available_resources[index]: execution = False break if execution: safe = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: process_number = original_need_index print(f"Process {process_number + 1} is executing.") # remove the process run from stack need_list.remove(each_need) # update available/freed resources stack available_resources = np.array(available_resources) + np.array( alloc_resources_table[process_number] ) print( "Updated available resource stack for processes: " + " ".join([str(x) for x in available_resources]) ) break if safe: print("The process is in a safe state.\n") else: print("System in unsafe state. Aborting...\n") break
other
def __pretty_data(self): print(" " * 9 + "Allocated Resource Table") for item in self.__allocated_resources_table: print( f"P{self.__allocated_resources_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print(" " * 9 + "System Resource Table") for item in self.__maximum_claim_table: print( f"P{self.__maximum_claim_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print( "Current Usage by Active Processes: " + " ".join(str(x) for x in self.__claim_vector) ) print( "Initial Available Resources: " + " ".join(str(x) for x in self.__available_resources()) ) time.sleep(1)
other
def floyd(n): for i in range(0, n): for _ in range(0, n - i - 1): # printing spaces print(" ", end="") for _ in range(0, i + 1): # printing stars print("* ", end="") print()
other
def reverse_floyd(n): for i in range(n, 0, -1): for _ in range(i, 0, -1): # printing stars print("* ", end="") print() for _ in range(n - i + 1, 0, -1): # printing spaces print(" ", end="")
other
def pretty_print(n): if n <= 0: print(" ... .... nothing printing :(") return floyd(n) # upper half reverse_floyd(n) # lower half
other
def __init__(self, n: int) -> None: self.dq_store = deque() self.key_reference = set() if not n: LRUCache._MAX_CAPACITY = sys.maxsize elif n < 0: raise ValueError("n should be an integer greater than 0.") else: LRUCache._MAX_CAPACITY = n
other
def refer(self, x: T) -> None: if x not in self.key_reference: if len(self.dq_store) == LRUCache._MAX_CAPACITY: last_element = self.dq_store.pop() self.key_reference.remove(last_element) else: self.dq_store.remove(x) self.dq_store.appendleft(x) self.key_reference.add(x)
other
def display(self) -> None: for k in self.dq_store: print(k)
other
def __repr__(self) -> str: return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}"
other
def __init__(self, multiplier, increment, modulo, seed=int(time())): # noqa: B008 self.multiplier = multiplier self.increment = increment self.modulo = modulo self.seed = seed
other
def next_number(self): self.seed = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed
other
def apply_table(inp, table): res = "" for i in table: res += inp[i - 1] return res
other
def left_shift(data): return data[1:] + data[0]
other
def xor(a, b): res = "" for i in range(len(a)): if a[i] == b[i]: res += "0" else: res += "1" return res
other
def apply_sbox(s, data): row = int("0b" + data[0] + data[-1], 2) col = int("0b" + data[1:3], 2) return bin(s[row][col])[2:]
other
def function(expansion, s0, s1, key, message): left = message[:4] right = message[4:] temp = apply_table(right, expansion) temp = xor(temp, key) l = apply_sbox(s0, temp[:4]) # noqa: E741 r = apply_sbox(s1, temp[4:]) l = "0" * (2 - len(l)) + l # noqa: E741 r = "0" * (2 - len(r)) + r temp = apply_table(l + r, p4_table) temp = xor(left, temp) return temp + right
other
def password_generator(length: int = 8) -> str: chars = ascii_letters + digits + punctuation return "".join(secrets.choice(chars) for _ in range(length))
other
def alternative_password_generator(chars_incl: str, i: int) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(chars_incl) quotient = i // 3 remainder = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) chars = ( chars_incl + random(ascii_letters, quotient + remainder) + random(digits, quotient) + random(punctuation, quotient) ) list_of_chars = list(chars) shuffle(list_of_chars) return "".join(list_of_chars) # random is a generalised function for letters, characters and numbers
other
def random(chars_incl: str, i: int) -> str: return "".join(secrets.choice(chars_incl) for _ in range(i))
other
def random_number(chars_incl, i): pass # Put your code here...
other
def random_letters(chars_incl, i): pass # Put your code here...
other
def random_characters(chars_incl, i): pass # Put your code here...
other
def is_strong_password(password: str, min_length: int = 8) -> bool: if len(password) < min_length: # Your Password must be at least 8 characters long return False upper = any(char in ascii_uppercase for char in password) lower = any(char in ascii_lowercase for char in password) num = any(char in digits for char in password) spec_char = any(char in punctuation for char in password) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters
other
def main(): length = int(input("Please indicate the max length of your password: ").strip()) chars_incl = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:", password_generator(length)) print( "Alternative Password generated:", alternative_password_generator(chars_incl, length), ) print("[If you are thinking of using this passsword, You better save it.]")
other
def print_max_activities(start: list[int], finish: list[int]) -> None: n = len(finish) print("The following activities are selected:") # The first activity is always selected i = 0 print(i, end=",") # Consider rest of the activities for j in range(n): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(j, end=",") i = j
other
def is_balanced(s): stack = [] open_brackets = set({"(", "[", "{"}) closed_brackets = set({")", "]", "}"}) open_to_closed = dict({"{": "}", "[": "]", "(": ")"}) for i in range(len(s)): if s[i] in open_brackets: stack.append(s[i]) elif s[i] in closed_brackets and ( len(stack) == 0 or (len(stack) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(stack) == 0
other
def main(): s = input("Enter sequence of brackets: ") if is_balanced(s): print(s, "is balanced") else: print(s, "is not balanced")
other
def gauss_easter(year: int) -> datetime: metonic_cycle = year % 19 julian_leap_year = year % 4 non_leap_year = year % 7 leap_day_inhibits = math.floor(year / 100) lunar_orbit_correction = math.floor((13 + 8 * leap_day_inhibits) / 25) leap_day_reinstall_number = leap_day_inhibits / 4 secular_moon_shift = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 century_starting_point = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 days_to_add = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon days_from_phm_to_sunday = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(year, 4, 19) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(year, 4, 18) else: return datetime(year, 3, 22) + timedelta( days=int(days_to_add + days_from_phm_to_sunday) )
other
def move_tower(height, from_pole, to_pole, with_pole): if height >= 1: move_tower(height - 1, from_pole, with_pole, to_pole) move_disk(from_pole, to_pole) move_tower(height - 1, with_pole, to_pole, from_pole)
other
def move_disk(fp, tp): print("moving disk from", fp, "to", tp)
other
def main(): height = int(input("Height of hanoi: ").strip()) move_tower(height, "A", "B", "C")
other
def eval_exponential(c_parameter: complex, z_values: numpy.ndarray) -> numpy.ndarray: return numpy.exp(z_values) + c_parameter
fractals
def eval_quadratic_polynomial( c_parameter: complex, z_values: numpy.ndarray ) -> numpy.ndarray: return z_values * z_values + c_parameter
fractals
def prepare_grid(window_size: float, nb_pixels: int) -> numpy.ndarray: x = numpy.linspace(-window_size, window_size, nb_pixels) x = x.reshape((nb_pixels, 1)) y = numpy.linspace(-window_size, window_size, nb_pixels) y = y.reshape((1, nb_pixels)) return x + 1.0j * y
fractals
def iterate_function( eval_function: Callable[[Any, numpy.ndarray], numpy.ndarray], function_params: Any, nb_iterations: int, z_0: numpy.ndarray, infinity: float | None = None, ) -> numpy.ndarray: z_n = z_0.astype("complex64") for _ in range(nb_iterations): z_n = eval_function(function_params, z_n) if infinity is not None: numpy.nan_to_num(z_n, copy=False, nan=infinity) z_n[abs(z_n) == numpy.inf] = infinity return z_n
fractals
def show_results( function_label: str, function_params: Any, escape_radius: float, z_final: numpy.ndarray, ) -> None: abs_z_final = (abs(z_final)).transpose() abs_z_final[:, :] = abs_z_final[::-1, :] pyplot.matshow(abs_z_final < escape_radius) pyplot.title(f"Julia set of ${function_label}$, $c={function_params}$") pyplot.show()
fractals
def ignore_overflow_warnings() -> None: warnings.filterwarnings( "ignore", category=RuntimeWarning, message="overflow encountered in multiply" ) warnings.filterwarnings( "ignore", category=RuntimeWarning, message="invalid value encountered in multiply", ) warnings.filterwarnings( "ignore", category=RuntimeWarning, message="overflow encountered in absolute" ) warnings.filterwarnings( "ignore", category=RuntimeWarning, message="overflow encountered in exp" )
fractals