Utils Documentation
Module to store utility functions for test purposes.
- mylib.utils.build_graph(edges)
Converts a list of directed edges into a graph represented as a dictionary. This function takes a list of tuples, where each tuple represents a directed edge from one node to another in the graph. The graph is represented as a dictionary where each key is a node and its value is a list of all nodes it has edges to.
- Param:
edges (list of tuples): Each tuple contains two elements, representing a directional link from the first element (source node) to the second element (destination node).
- Returns:
dict: A dictionary representation of the graph where keys are source nodes and values are lists of destination nodes.
- Example:
Given edges [(0, 1), (0, 2), (1, 2), (2, 3)], the function returns {0: [1, 2], 1: [2], 2: [3]}.
- mylib.utils.create_download_directory()
Creates a download directory if it doesn’t exist
- Returns:
True or False
- mylib.utils.find_cycles(graph)
Finds all unique cycles in the graph using a Breadth-First Search (BFS) approach and returns them as a list of tuples, where each tuple represents a cycle.
This function iterates over each node in the graph, using BFS to explore reachable nodes. It keeps track of the path taken to reach each node. If it encounters a node that completes a cycle back to the starting node, and the set of nodes in the cycle has not been encountered before, it records this cycle.
- Param:
graph (dict): A graph represented as a dictionary where each key is a node and its value is a list of nodes it has edges to.
- Returns:
list of tuples: Each tuple contains nodes forming a cycle, including the starting node repeated at the end to signify the cycle closure.
- Example:
Given a graph {0: [1, 2], 1: [2], 2: [3], 3: [0]}, the function may return [(0, 1, 2, 3, 0), (0, 2, 3, 0)] as it identifies the cycles in the graph.
- Note:
The function ensures that each cycle is unique based on the members of the cycle, not the starting point of the cycle in the path. Cycles that contain the same set of nodes but start at different points are considered the same and only one is returned.
- mylib.utils.two_sum(nums, target)
Find the index of the two first numbers that add up to target.
- Parameters:
nums – a list of numbers
target – the value to reach
- Returns:
a list of the index of the two numbers
- Raises:
TypeError – if the target is not a number