Dataset Viewer
Auto-converted to Parquet Duplicate
prompt
stringlengths
35
69
output
stringlengths
814
2.5k
Write a Python function to reverse a string
Certainly! Below is a simple Python function that takes a string as input and returns its reverse: ```python def reverse_string(s): # Initialize an empty string to store the reversed result reversed_s = "" # Iterate over the input string in reverse order for char in reversed(s): # Append e...
Write a Python function to check if prime
Sure! Below is a Python function that checks if a given number is prime: ```python def is_prime(n): # Check if the number is less than 2 if n <= 1: return False # Check if the number is 2 if n == 2: return True # Check if the number is even if n % 2 == 0: retur...
Write a Python function to find factorial
```python def factorial(n): """ Calculate the factorial of a non-negative integer n. Args: n (int): A non-negative integer whose factorial is to be calculated. Returns: int: The factorial of n. """ if n < 0: raise ValueError("Factorial is not defined for negative number...
Write a Python function to check palindrome
Certainly! A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward. Here's a simple Python function to check if a given string is a palindrome: ```python def is_palindrome(s): # Normalize the string by removing spaces and converting to lowercase normalize...
Write a Python function to find maximum in list
Certainly! Below is a simple Python function that finds the maximum value in a given list using the built-in `max()` function: ```python def find_maximum(lst): """ Finds the maximum value in a list. Parameters: lst (list): A list of numbers. Returns: int or float: The maximum value in the lis...
Write a Python function to sort a list
Certainly! Below is a simple Python function that sorts a list in ascending order. You can use this function by passing your list as an argument: ```python def sort_list(input_list): # Sort the list in ascending order sorted_list = sorted(input_list) return sorted_list # Example usage: my_list = [5, 3, 8,...
Write a Python function to count vowels
Certainly! Below is a Python function that counts the number of vowels in a given string: ```python def count_vowels(text): # Define a string of vowels vowels = "aeiouAEIOU" # Initialize a counter for vowels count = 0 # Iterate over each character in the text for char in text: # Ch...
Write a Python function to sum of digits
```python def sum_of_digits(number): """ Calculate the sum of digits of a given number. Args: number (int): The number whose digits are to be summed. Returns: int: The sum of the digits of the given number. """ # Ensure the number is positive for simplicity number = abs(number) ...
Write a Python function to check leap year
```python def is_leap_year(year): """ Check if a given year is a leap year. A leap year is a year that is divisible by 4 but not by 100, unless it is also divisible by 400. Args: year (int): The year to check. Returns: bool: True if the year is a leap year, False otherwise...
Write a Python function to celsius to fahrenheit
Certainly! To convert a temperature from Celsius to Fahrenheit, you can use the following Python function: ```python def celsius_to_fahrenheit(celsius): """ Convert a temperature from Celsius to Fahrenheit. Parameters: celsius (float): The temperature in Celsius. Returns: float: The t...
Write a Python function to swap two numbers
Certainly! Below is a simple Python function that takes two numbers as input and swaps them. This function is straightforward and easy to understand. ```python def swap_numbers(x, y): # Temporary variable to hold the value of x temp = x # Assign the value of y to x x = y # Assign the value stored i...
Write a Python function to find GCD
Certainly! Below is a Python function that calculates the Greatest Common Divisor (GCD) using the Euclidean algorithm. The Euclidean algorithm is an efficient method for computing the greatest common divisor of two numbers. ```python def gcd(a, b): # Base case: if b is 0, return a if b == 0: return a ...
Write a Python function to find LCM
Certainly! Below is a Python function that calculates the Least Common Multiple (LCM) of two numbers: ```python def lcm(a, b): """ Calculate the Least Common Multiple (LCM) of two numbers a and b. Parameters: a (int): The first number. b (int): The second number. Returns: int: The LCM of ...
Write a Python function to check armstrong number
Certainly! An Armstrong number is a number that is equal to the sum of the cubes of its digits. Here's a Python function to check if a given number is an Armstrong number: ```python def is_armstrong(num): # Convert the number to a string to easily iterate over each digit digits = str(num) # Calculate the n...
Write a Python function to print multiplication table
```python def print_multiplication_table(start=1, end=10): """ Prints the multiplication table from 'start' to 'end' (inclusive). Parameters: start (int): The starting number of the multiplication table. end (int): The ending number of the multiplication table. Returns: None ""...
Write a Python function to fibonacci series
Certainly! Below is a Python function that generates the Fibonacci sequence up to a given number of terms: ```python def fibonacci(n): # Check if the input is a positive integer if not isinstance(n, int) or n <= 0: raise ValueError("Input must be a positive integer.") # Initialize the first tw...
Write a Python function to check perfect number
```python def is_perfect(n): """ Check if a number is a perfect number. A perfect number is a positive integer that is equal to the sum of its positive divisors. For example, 28 is a perfect number because 1 + 2 + 4 + 7 + 14 = 28. Args: n (int): The number to check. Returns: ...
Write a Python function to find average of list
Certainly! Below is a simple Python function to calculate the average of a list of numbers: ```python def average(numbers): if not numbers: return 0 # Return 0 if the list is empty return sum(numbers) / len(numbers) # Example usage: numbers = [1, 2, 3, 4, 5] print(average(numbers)) # Output: 3.0 ```...
Write a Python function to count words in string
Certainly! Below is a Python function that counts the number of words in a given string. The function splits the string into words based on spaces and then counts the number of elements in the resulting list. ```python def count_words(s): # Split the string into words based on spaces words = s.split() # Re...
Write a Python function to remove vowels from string
```python def remove_vowels(s): """ Remove all vowels from the given string. Args: s (str): The input string from which vowels will be removed. Returns: str: The string with all vowels removed. """ vowels = 'aeiouAEIOU' return ''.join([char for char in s if char not in vowels]) # ...
Write a Python function to capitalize first letter
Certainly! Below is a Python function that capitalizes the first letter of a given string: ```python def capitalize_first_letter(s): if not s: # Check if the string is empty return s return s[0].upper() + s[1:] # Example usage: print(capitalize_first_letter("hello world")) # Output: "Hello world" pr...
Write a Python function to check anagram
Certainly! An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Here's a Python function to check if two strings are anagrams: ```python def is_anagram(str1, str2): # Remove any spaces and convert to lowercase for uni...
Write a Python function to find second largest
Certainly! Below is a Python function that finds the second largest element in an array: ```python def find_second_largest(arr): if len(arr) < 2: return None # Not enough elements to have a second largest # Initialize the first and second largest elements first_largest = second_largest = float('-...
Write a Python function to remove duplicates
Sure! Below is a simple Python function that removes duplicates from a list using a set: ```python def remove_duplicates(lst): # Convert the list to a set to remove duplicates unique_set = set(lst) # Convert the set back to a list unique_list = list(unique_set) return unique_list # Example usage: ...
Write a Python function to merge two lists
Certainly! Below is a Python function that merges two lists into a single list: ```python def merge_lists(list1, list2): """ Merges two lists into a single list. Parameters: list1 (list): The first list. list2 (list): The second list. Returns: list: A new list containing all elements from...
Write a Python function to intersection of lists
Certainly! Below is a Python function that takes two lists as input and returns their intersection. The function uses set intersection to efficiently find common elements between the two lists. ```python def intersection(list1, list2): # Convert lists to sets to remove duplicates and perform intersection set1 ...
Write a Python function to difference of lists
Certainly! Below is a Python function that calculates the difference between two lists. The difference is defined as the elements in the first list that are not present in the second list. ```python def list_difference(list1, list2): # Use set difference to find elements that are in list1 but not in list2 retu...
Write a Python function to check subset
Certainly! Below is a Python function that checks if one set is a subset of another: ```python def is_subset(set1, set2): # Use the built-in issubset method to check if set1 is a subset of set2 return set1.issubset(set2) # Example usage: set1 = {1, 2, 3} set2 = {1, 2, 3, 4, 5} print(is_subset(set1, set2)) # ...
Write a Python function to flatten nested list
```python def flatten_nested_list(nested_list): """ Flattens a nested list into a single list. Args: nested_list (list): A potentially nested list of elements. Returns: list: A flattened list containing all elements from the nested structure. """ flattened_list = [] for ite...
Write a Python function to rotate list
Certainly! Below is a Python function that rotates a given list to the left by a specified number of positions. If the rotation count exceeds the length of the list, the list is rotated cyclically. ```python def rotate_list(lst, k): """ Rotate the given list lst to the left by k positions. Args: l...
Write a Python function to find missing number
Certainly! To find a missing number in a list of numbers, we can use a simple mathematical approach. The sum of the first `n` natural numbers is given by the formula `n * (n + 1) / 2`. By calculating this sum and subtracting the sum of the numbers in the list, we can determine the missing number. Here's a Python funct...
Write a Python function to find duplicate number
Certainly! Below is a Python function that finds the duplicate number in an array of integers. This function uses the Floyd's Tortoise and Hare algorithm to detect the cycle in the linked list formed by the array elements. ```python def find_duplicate(nums): # Initialize two pointers tortoise = nums[0] har...
Write a Python function to find common elements
Certainly! Below is a Python function that finds common elements between two lists: ```python def find_common_elements(list1, list2): # Use set intersection to find common elements common_elements = list(set(list1) & set(list2)) return common_elements ``` ### Explanation: 1. **Convert Lists to Sets**: Bot...
Write a Python function to chunk a list
```python def chunk_list(lst, chunk_size=5): """ Splits a list into chunks of a specified size. Parameters: lst (list): The list to be chunked. chunk_size (int): The size of each chunk. Defaults to 5. Returns: list: A list of chunks, each containing up to chunk_size elements. """ r...
Write a Python function to zip two lists
Certainly! Below is a simple Python function that takes two lists as input and returns a new list that is the element-wise product of the two lists. ```python def zip_lists(list1, list2): # Check if both lists have the same length if len(list1) != len(list2): raise ValueError("Both lists must have the ...
Write a Python function to unzip list of tuples
Certainly! Here's a Python function that takes a list of tuples and returns a list of lists, where each sublist contains the elements of the corresponding tuple: ```python def unzip_tuples(tuples_list): # Using list comprehension to iterate over each tuple and extract the elements return [list(tup) for tup in ...
Write a Python function to transpose matrix
Certainly! Below is a Python function to transpose a matrix using list comprehension. The function takes a 2D list (matrix) as input and returns the transposed matrix. ```python def transpose_matrix(matrix): # Check if the input is a valid 2D list if not all(isinstance(row, list) for row in matrix) or not all(...
Write a Python function to multiply matrices
Certainly! Below is a Python function that multiplies two matrices. This function assumes that the number of columns in the first matrix is equal to the number of rows in the second matrix. ```python def multiply_matrices(matrix1, matrix2): # Check if the number of columns in the first matrix is equal to the numbe...
Write a Python function to find determinant
Sure! To find the determinant of a matrix in Python, you can use the NumPy library, which provides a function `numpy.linalg.det` for this purpose. Below is a simple function that takes a 2D list (matrix) as input and returns its determinant. ```python import numpy as np def find_determinant(matrix): """ Calcu...
Write a Python function to check symmetric matrix
Certainly! A symmetric matrix is a square matrix that is equal to its transpose. In other words, if `A` is a symmetric matrix, then `A[i][j] == A[j][i]` for all `i` and `j`. Here's a Python function to check if a given matrix is symmetric: ```python def is_symmetric(matrix): """ Check if the given matrix is s...
Write a Python function to implement binary search
Certainly! Binary search is a highly efficient algorithm for finding an element in a sorted list. It works by repeatedly dividing the search interval in half until the target value is found or the interval is empty. Here's a simple implementation of binary search in Python: ```python def binary_search(arr, target): ...
Write a Python function to implement quicksort
Certainly! Below is a Python function that implements the quicksort algorithm: ```python def quicksort(arr): if len(arr) <= 1: return arr else: pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr...
Write a Python function to implement merge sort
Certainly! Below is a Python function that implements the merge sort algorithm. This function takes a list as input and returns a sorted list using the merge sort algorithm. ```python def merge_sort(arr): # Base case: if the array has 0 or 1 element, it is already sorted if len(arr) <= 1: return arr ...
Write a Python function to implement bubble sort
Certainly! Bubble sort is a simple sorting algorithm that repeatedly steps through a list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. Here is the implementation of the bubble sort algorithm in Python: ```python def bubble_s...
Write a Python function to implement insertion sort
Certainly! Below is a Python function that implements the insertion sort algorithm. This function takes a list as input and sorts it in ascending order using the insertion sort technique. ```python def insertion_sort(arr): # Traverse through all elements in the list for i in range(1, len(arr)): key = a...
Write a Python function to implement selection sort
Certainly! Selection sort is a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted part of the list and moving it to the beginning of the sorted part. Here's a step-by-step implementation of the selection sort algorithm in Python: ```python def selection_sort(arr): # Ite...
Write a Python function to implement heap sort
Certainly! Heap sort is a comparison-based sorting algorithm that uses a binary tree to represent the heap. Here's a Python implementation of heap sort: ```python import heapq def heap_sort(arr): # Convert the list into a heap heapq.heapify(arr) # Pop elements from the heap and store them in a new li...
Write a Python function to implement counting sort
Certainly! Counting sort is a sorting algorithm that sorts elements by counting the number of occurrences of each unique element and using this information to determine the positions of the elements in the final sorted array. Here's a step-by-step explanation and the implementation of the counting sort function in Pyth...
Write a Python function to implement radix sort
Certainly! Below is a Python function that implements the radix sort algorithm. This function sorts a list of non-negative integers using the radix sort algorithm, which is efficient for large datasets and works well with stable sorting. ```python def radix_sort(arr): if not arr: return [] # Find the ...
Write a Python function to implement stack using list
Sure, here is a simple implementation of a stack using Python's list: ```python class Stack: def __init__(self): self.items = [] # Initialize an empty list def is_empty(self): return len(self.items) == 0 # Return True if the stack is empty def push(self, item): self.items.append...
Write a Python function to implement queue using list
Certainly! Below is a simple Python function to implement a queue using a list. The queue operations include `enqueue`, `dequeue`, and `peek`, along with a `is_empty` method to check if the queue is empty. ```python class Queue: def __init__(self): # Initialize an empty list to store the queue elements ...
Write a Python function to implement linked list
```python # Define the Node class for linked list class Node: def __init__(self, data): # Initialize the node with data and a pointer to the next node self.data = data self.next = None # Define the LinkedList class class LinkedList: def __init__(self): # Initialize the linked li...
Write a Python function to implement doubly linked list
```python class Node: def __init__(self, data=None, previous=None, next=None): self.data = data self.previous = previous self.next = next class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def append(self, data): new_node = Node(da...
Write a Python function to implement circular linked list
Certainly! Below is a simple implementation of a circular linked list in Python. This implementation includes the necessary classes and methods to create, insert, remove, and traverse the list. ```python class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedLi...
Write a Python function to implement binary tree
Sure, here is a simple implementation of a binary tree in Python: ```python class Node: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right class BinaryTree: def __init__(self): self.root = None def insert(self, value)...
Write a Python function to implement BST insert
Certainly! Below is a Python function that implements the BST (Binary Search Tree) insert operation. This function takes a value to be inserted into the BST and inserts it into the correct position. ```python class TreeNode: def __init__(self, value): self.value = value self.left = None sel...
Write a Python function to implement BST search
Certainly! Below is a Python function that implements the Binary Search Tree (BST) search algorithm: ```python class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def inse...
Write a Python function to implement graph using dict
Certainly! Below is a simple implementation of a graph using a dictionary in Python. This graph will support adding vertices, edges, and traversing the graph. ```python class Graph: def __init__(self): # Initialize the graph with an empty dictionary to store vertices and their connections self.vert...
Write a Python function to implement BFS
Certainly! Below is a Python function that implements the Breadth-First Search (BFS) algorithm. BFS is an algorithm for traversing or searching tree or graph data structures. It starts from a given node and explores all its neighbors before moving to the next level. ```python from collections import deque def bfs(gra...
Write a Python function to implement DFS
Certainly! DFS (Depth-First Search) is a recursive algorithm for traversing a graph or tree. Below is a simple implementation of DFS in Python: ```python def dfs(graph, start): # Initialize a set to keep track of visited nodes visited = set() # Define a recursive helper function def dfs_helper(nod...
Write a Python function to implement Dijkstra
Certainly! Dijkstra's algorithm is a widely used algorithm for finding the shortest path in a graph with non-negative edge weights. Here's a step-by-step implementation in Python: 1. Define the graph using adjacency lists. 2. Initialize the distance array and the visited array. 3. Use a priority queue to keep track of...
Write a Python function to implement Bellman-Ford
Certainly! Below is a Python function implementing the Bellman-Ford algorithm. This algorithm finds the shortest paths from a single source vertex to all other vertices in a weighted graph. ```python import sys def bellman_ford(graph, start): n = len(graph) distances = [float('inf')] * n distances[start] ...
Write a Python function to implement Floyd-Warshall
Certainly! Floyd-Warshall's algorithm is used to find the shortest paths between all pairs of vertices in a weighted graph. Here's a step-by-step implementation in Python: ```python def floyd_warshall(graph): # Get the number of vertices V = len(graph) # Initialize the distance matrix with the graph w...
Write a Python function to implement Kruskal
Certainly! Kruskal's algorithm is a greedy algorithm used to find the minimum spanning tree (MST) of a connected weighted undirected graph. Here's a step-by-step implementation of Kruskal's algorithm in Python: ```python def find(parent, i): if parent[i] == i: return i return find(parent, parent[i]) d...
Write a Python function to implement Prim
Prim's algorithm is a greedy algorithm used to find the Minimum Spanning Tree (MST) of a connected undirected graph. The algorithm works as follows: 1. Start with an arbitrary vertex. 2. Select the lightest edge that connects the selected vertex to an unvisited vertex. 3. Mark this edge as part of the MST and add the ...
Write a Python function to implement BST delete
```python class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, data): if not self.root: self.root = TreeNode(data) else: ...
Write a Python function to implement topological sort
Certainly! Topological sort is an algorithm that sorts the vertices of a directed acyclic graph (DAG) in such a way that for every directed edge `(u, v)`, vertex `u` comes before vertex `v` in the ordering. Here's a step-by-step explanation of how the topological sort works and how you can implement it in Python. ### ...
Write a Python function to implement LRU cache
Certainly! Below is a Python function that implements the LRU (Least Recently Used) cache using a dictionary to store the items and a list to keep track of the order of access. The function includes methods to add items, retrieve items, and remove the least recently used item. ```python class LRUCache: def __init_...
Write a Python function to implement LFU cache
Sure, I can help you with that. LFU (Least Frequently Used) cache is a type of cache that stores the least frequently accessed items first. Here's a simple implementation of an LFU cache in Python: ```python from collections import OrderedDict class LFUCache: def __init__(self, capacity): self.capacity = ...
Write a Python function to implement trie
Certainly! Below is a simple implementation of a trie in Python. A trie is a tree-like data structure that stores a collection of strings. Each node in the trie has pointers to other nodes, one for each character in the alphabet. The root node has no character and is used as a starting point. ```python class TrieNode:...
Write a Python function to implement segment tree
```python class SegmentTree: def __init__(self, arr): self.arr = arr self.tree = [0] * (4 * len(arr)) self.build_tree(0, len(arr) - 1, 0) def build_tree(self, start, end, index): if start == end: self.tree[index] = self.arr[start] else: mid = (sta...
Write a Python function to implement fenwick tree
Certainly! A Fenwick tree is a data structure that allows efficient updates and queries on an array of integers. It can be used to quickly compute the sum of elements in a range or to efficiently update the sum of an element. Here's a simple implementation of a Fenwick tree in Python: ```python class FenwickTree: ...
Write a Python function to implement disjoint set
Certainly! Below is a Python function to implement the disjoint set data structure. This function includes operations to find the root of a set, union two sets, and find the total number of disjoint sets. ```python class DisjointSet: def __init__(self, n): self.parent = list(range(n)) # Initialize each el...
Write a Python function to implement memoization decorator
```python def memoize(func): """Decorator to add memoization to a function.""" cache = {} def wrapper(*args): if args in cache: return cache[args] result = func(*args) cache[args] = result return result return wrapper ``` This Python function, `memoize`, tak...
Write a Python function to implement timing decorator
Sure, here's a basic implementation of a timing decorator in Python: ```python import time def timing_decorator(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"Function {func.__name__} took {end_time - star...
Write a Python function to implement retry decorator
```python import time def retry(max_attempts=3, delay=1): def decorator(func): def wrapper(*args, **kwargs): attempts = 0 while attempts < max_attempts: try: return func(*args, **kwargs) except Exception as e: a...
Write a Python function to implement cache decorator
Certainly! Below is a simple Python function that implements a cache decorator using a dictionary to store results of expensive function calls. This decorator will cache the results of the function for a specified number of seconds, and it will invalidate the cache if the expiration time is reached. ```python import f...
Write a Python function to implement context manager
Sure, I can help you with that. Here's an example of a Python function that implements a context manager: ```python class MyContextManager: def __init__(self): print("Entering context") def __enter__(self): print("Entering context (inside __enter__)") return "Inside context" def _...
Write a Python function to implement generator for fibonacci
Sure! Here's a simple Python function to implement the Fibonacci generator: ```python def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b # Example usage for num in fibonacci(): if num > 100: break print(num) ``` In this function, we initialize two variables `a` a...
Write a Python function to implement coroutine
To implement a coroutine in Python, you can use the `asyncio` library. Below is a simple example of how to create a coroutine that prints numbers from 1 to 10: ```python import asyncio async def my_coroutine(): for i in range(1, 11): print(f"Number: {i}") await asyncio.sleep(1) # Pause for 1 seco...
Write a Python function to implement async function
Certainly! Below is a simple Python function that demonstrates how to implement an asynchronous function using the `asyncio` library. This example will include a basic async function that prints "Hello, World!". ```python import asyncio # Define an asynchronous function async def say_hello(): print("Hello, World!...
Write a Python implementation to implement a metaclass
Certainly! Below is a simple implementation of a metaclass in Python. A metaclass is a class that creates and controls classes. This allows you to customize how classes are created and manipulated. ```python # Define a metaclass class Meta(type): def __new__(cls, name, bases, dct): # This method is called ...
Write a Python implementation to implement a descriptor
Sure! Below is a simple implementation of a descriptor in Python. A descriptor is a class that provides a way to customize attribute access, assignment, and deletion. Here, we'll create a descriptor that converts an attribute to uppercase. ```python # Define the descriptor class class UppercaseDescriptor: def __in...
Write a Python implementation to implement a singleton pattern
Certainly! Below is a simple implementation of the singleton pattern in Python. The singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. ```python class Singleton: _instance = None def __new__(cls, *args, **kwargs): # Check if an instance...
Write a Python implementation to implement factory pattern
The factory pattern is a creational design pattern that provides an interface for creating objects, but allows subclasses to alter the type of objects that will be created. In this example, we'll create a simple factory for creating different types of animals. ```python # Define the base animal class class Animal: ...
Write a Python implementation to implement observer pattern
Sure! Below is an implementation of the observer pattern in Python. The pattern involves a subject class that maintains a list of observers and notifies them when its state changes. Each observer can subscribe to the subject and receive updates. ```python class Observer: def update(self, subject): """Updat...
Write a Python implementation to implement decorator pattern
Sure, I can help you implement the Decorator pattern in Python. The Decorator pattern allows you to add new functionality to an existing object without altering its structure. Here's a simple example: ```python # Define the base component interface class Component: def operation(self): pass # Concrete com...
Write a Python implementation to implement strategy pattern
Sure! The Strategy pattern is a behavioral design pattern that lets you define a family of algorithms, encapsulate each one, and make them interchangeable. This pattern allows a client to choose the algorithm at runtime. Here's a simple implementation of the Strategy pattern in Python: ```python # Define the strategy...
Write a Python implementation to implement adapter pattern
Sure! The Adapter pattern is a structural design pattern that allows incompatible classes to work together by creating a new class that acts as an adapter. In this example, I'll create an adapter for a `Dog` class to make it compatible with an `Animal` interface. First, let's define the `Animal` interface: ```python ...
Write a Python implementation to read CSV and compute averages
Certainly! Below is a Python implementation that reads a CSV file and computes the average of each column. This example assumes that the CSV file has a header row and that the data is numerical. ```python import csv def compute_column_averages(file_path): with open(file_path, mode='r', newline='') as file: ...
Write a Python implementation to parse JSON and filter data
Certainly! Below is a Python implementation to parse JSON and filter data based on a specific condition. This example demonstrates how to parse a JSON string, filter the data based on a condition, and print the filtered results. ```python import json # Example JSON string json_data = ''' [ {"name": "Alice", "age"...
Write a Python implementation to scrape a website with requests
Certainly! To scrape a website using Python's `requests` library, you need to follow these steps: 1. Install the `requests` library if it's not already installed: ```bash pip install requests ``` 2. Write a Python script to send HTTP requests and parse the HTML content. Here's a simple example that scrapes ...
Write a Python implementation to send email with smtplib
Certainly! Below is a Python implementation that uses the `smtplib` library to send an email. This example assumes you have a Gmail account and you have enabled "Less secure apps" in your Google account settings for testing purposes. ```python import smtplib from email.mime.text import MIMEText def send_email(subject...
Write a Python implementation to connect to PostgreSQL
```python import psycopg2 def connect_to_postgresql(host, dbname, user, password, port=5432): """ Establishes a connection to a PostgreSQL database. Args: host (str): The hostname of the PostgreSQL server. dbname (str): The name of the database to connect to. user (str): The username for the d...
Write a Python implementation to connect to MongoDB
Certainly! To connect to MongoDB, you can use the `pymongo` library, which is a Python driver for MongoDB. Here's a step-by-step example of how to connect to MongoDB and perform a basic operation: 1. Install the `pymongo` library using pip: ```bash pip install pymongo ``` 2. Write the Python code to connect to MongoD...
Write a Python implementation to connect to Redis
To connect to Redis, you can use the `redis` library in Python. Here's a basic example of how to establish a connection: ```python import redis # Create a Redis client instance r = redis.Redis(host='localhost', port=6379, db=0) # Check if the connection is successful if r.ping(): print("Connected to Redis succes...
Write a Python implementation to build REST API with FastAPI
Sure! Below is a simple example of a REST API built with FastAPI. This API will have two endpoints: one to list all users and another to get a specific user by ID. First, make sure you have FastAPI installed. You can install it using pip: ```bash pip install fastapi uvicorn ``` Now, create a new file called `main.py...
Write a Python implementation to build REST API with Flask
Certainly! Below is a simple implementation of a REST API using Flask. This example includes basic CRUD operations (Create, Read, Update, Delete) for a simple resource (e.g., a list of items). First, make sure you have Flask installed. You can install it using pip: ```bash pip install Flask ``` Then, create a new Py...
Write a Python implementation to build CLI with argparse
```python import argparse def main(): parser = argparse.ArgumentParser(description='A simple CLI with argparse') parser.add_argument('--version', action='version', version='0.1', help='Show version') parser.add_argument('command', help='The command to execute') parser.add_argument('--arg1', type=str, h...
Write a Python implementation to build CLI with click
Sure! Below is a simple example of a CLI application using the `click` library in Python. This CLI will allow users to perform basic arithmetic operations. First, make sure you have the `click` library installed. You can install it using pip: ```sh pip install click ``` Then, create a new file called `cli.py` and ad...
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
77