prompt
stringlengths
61
10.5k
completion
stringlengths
8
4.98k
domain
stringclasses
1 value
def filter_square_dict_values(dictionary): """ Create a function called "filter_square_dict_values" that takes in a dictionary as input and returns a new dictionary with the positive values squared. The function should include the following steps: 1. Initialize an empty dictionary called "new_dict" to ...
new_dict = {} if len(dictionary) == 0: return new_dict for key, value in dictionary.items(): if not isinstance(key, int) or not isinstance(value, int): continue if value < 0: continue squared_value = value ** 2 new_dict[key] = squared_valu...
code
import math def compute_surface_areas(input_list): """ Construct a Python function that computes the surface area of a specific geometric shape, specifically a circular sector, a spherical sector, and a torus. This function should take the radius, central angle, and in the case of a torus, the tube rad...
surface_areas = [] for item in input_list: # Unpack the tuple radius, central_angle, torus_radius = item # Handle negative radii or angles and angles exceeding 360 if radius < 0 or torus_radius < 0 or central_angle < 0 or central_angle > 360: surface_areas.append('...
code
def square_and_divisible(lst): """ Given a list of integers, write a Python program to create a new list that contains the square of every element in the original list. Additionally, for each square, if it is divisible by 3, append the string "divisible by 3" to the new list; if it is divisible by 5...
new_lst = [] for num in lst: square = num ** 2 if square % 3 == 0 and square % 5 == 0: new_lst.append(square) new_lst.append("divisible by both 3 and 5") elif square % 3 == 0: new_lst.append(square) new_lst.append("divisible by 3") ...
code
def print_greater_than_two(arr): """ Create a method that prints all elements of an array, but also includes a condition that only prints elements greater than 2. """
for element in arr: if element > 2: print(element)
code
def shiftingLetters(S, shifts): """ Consider a scenario where you are given a string `S` composed of lowercase letters and an integer array `shifts`. The shift of a letter is defined as the subsequent letter in the alphabet, with the condition that `&#39;z&#39;` wraps around to become `&#39;a&#39;`....
totalShifts = sum(shifts) result = [] for i,shift in enumerate(shifts): # Calculate the new character using modulus operation newChar = chr((ord(S[i]) - 97 + totalShifts % 26) % 26 + 97) result.append(newChar) totalShifts -= shift return ''.join(result)
code
def are_anagrams(num1, num2): """ Devise a Python code that takes two numerical inputs encoded as strings, scrutinizes them, and verifies if they are numeric anagrams of each other, essentially permutations achieved by reordering the digits. If they are anagrams, the program should return True. If n...
def is_prime(n): if n == 1: return False for i in range(2, n): if n % i == 0: return False return True # remove any non numeric characters num1 = "".join([i for i in num1 if i.isdigit()]) num2 = "".join([i for i in num2 if i.isdigit()]) ...
code
def add(a, b): """ Identify a potential bug in the following code and provide a solution to fix it. def add(a, b): c = a + b return c Requirements: - The code should handle both integer and floating-point inputs for a and b. - The code should return the result rounded to the nearest whole number if ...
if a is None or b is None: return None elif isinstance(a, (str, list, dict)) or isinstance(b, (str, list, dict)): return None elif isinstance(a, int) and isinstance(b, int): return round(a + b) else: return round(a + b, 2)
code
def longest_common_prefix(strings): """ Write a code to find the longest common prefix among a given set of strings. The code should have a time complexity of O(n * m), where n is the number of strings in the set and m is the average length of the strings. Handle the case where the given set of stri...
if not strings: return "" # Return empty string if the set of strings is empty # Find the minimum length of the strings min_length = min(len(string) for string in strings) # Iterate through each character in the minimum length of the strings for i in range(min_length): # Check if...
code
def is_prime(n): """ &lt;p&gt;Let $T = \{3, 5, 7, \dots, 9999\}$ be the set of prime numbers less than $10000$ that are not divisible by $2$ or $5$.&lt;/p&gt; &lt;p&gt;Find the number of subsets of $T$, the product of whose elements is a prime number.&lt;br&gt; Enter the rightmost $20$ digits as you...
if n in (2,3): return True if n % 2 == 0 or n == 1: return False for current in range(3, int(n ** 0.5) + 1, 2): if n % current == 0: return False return True
code
def fibonacci_sequence(n): """ Design a function in Python to calculate the Fibonacci sequence up to a particular number, but also implement error handling for invalid input. """
if not isinstance(n, int) or n <= 0: raise ValueError("Invalid input! Please provide a positive integer.") sequence = [0, 1] while sequence[-1] < n: sequence.append(sequence[-1] + sequence[-2]) return sequence[:-1]
code
import re import heapq def sentence_to_priority_queue(sentence): """ Develop a Python code snippet for isolating the individual words within a specific sentence and retaining those word components in a priority queue structure sorted by the word length. The code should ignore any punctuation and be cas...
sentence = re.sub(r'[^\w\s]', '', sentence) # convert to lowercase sentence = sentence.lower() # split words words = sentence.split() # define a comparator for the priority queue class Word: def __init__(self, word): self.word = word self.length = len(word...
code
def multiply_by_two(arr): """ Consider an assortment of unique integer values given in an array. I need you to construct and produce a fresh array resulting from a computational operation where you multiply each individual element of the original array with a scalar factor of two. With an input such...
return [i * 2 for i in arr]
code
import re def process_escape_sequences(input_string): """ You are tasked with creating a program that processes escape sequences in a given string. Escape sequences are used to represent characters that are difficult or impossible to represent directly in a string. For example, the escape sequence "\n"...
input_string = re.sub(r'\\x([0-9a-fA-F]{2})', lambda x: chr(int(x.group(1), 16)), input_string) # Replace \uhhhh sequences input_string = re.sub(r'\\u([0-9a-fA-F]{4})', lambda x: chr(int(x.group(1), 16)), input_string) # Replace \Uhhhhhhhh sequences input_string = re.sub(r'\\U([0-9a-fA-F]{8})', l...
code
def count_series(total): """ Can you determine the quantity of possible arithmetic series made up of sequential odd integer values with a cumulative total of 240? """
count = 0 a = 1 while True: n = (2*total) / (2*a + 2) if n < 1: break if n == int(n): count += 1 a += 2 return count
code
import datetime import pytz def convert_timezone(time, origin_timezone, target_timezone): """ Design a program which can convert the given time from one timezone to another, where the input is not fixed and can be any legitimate time on the 24 hour clock format. The original timezone (e.g. India Standa...
try: # create datetime object with given time and current date given_time = datetime.datetime.now().replace(hour=int(time[:2]), minute=int(time[3:])) # create timezone objects origin_tz = pytz.timezone(origin_timezone) target_tz = pytz.timezone(target_timezone) # l...
code
import re def extract_license_text(source_code): """ You are tasked with creating a program that parses and extracts license information from source code files. The license information is typically included at the beginning of source files in a specific format. The license text is enclosed within comme...
multi_line_comment_pattern = r'#(.*?)#' # Regular expression pattern to match single-line comments single_line_comment_pattern = r'#(.*)' # Search for multi-line comments and extract the license text multi_line_matches = re.findall(multi_line_comment_pattern, source_code, re.DOTALL) if multi_l...
code
def ProcessData(a, b): """ Enhance the following Python code: import collections import math # Build a function that handles four distinct type of data: lists, sets, dictionaries, and numbers (integers & floats). # For numbers, it should return the maximum number. # For lists and sets, it should ret...
if type(a) != type(b) or a == b: return None # for numbers elif isinstance(a, (int, float)): return max(a, b) # for lists and sets elif isinstance(a, (list, set)): return sorted(set(a) | set(b), reverse=True) # for dictionaries elif isinstance(a, dict): me...
code
def is_isomorphic(str1, str2): """ Provide a Python code snippet that, given two different strings as input, will perform a check to determine any isomorphic properties between them, meaning the code needs to ascertain whether the strings can be mapped to one another in such a way that each characte...
def get_pattern(s): return [s.index(i) for i in s] return get_pattern(str1) == get_pattern(str2)
code
def fibonacci(n): """ You are given a code snippet that seems to be incomplete. Your task is to complete the code by implementing a function that calculates the Fibonacci sequence. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starti...
if n <= 0: return 0 elif n == 1: return 1 else: a, b = 0, 1 for _ in range(2, n + 1): a, b = b, a + b return b
code
from sympy import together, symbols def simplify_rational_function(expression): """ You are given a mathematical expression in the form of a string representing a rational function. Your task is to write a function that simplifies the rational function by combining like terms and presenting the result ...
function, denom1, denom2 = expression.split('/')[0].split('+') # Create symbolic variables for the function and denominators x, f = symbols('x f') # Construct the rational function using the symbolic variables rational_function = f / x + f / (x ** 2) # Simplify the rational function using th...
code
def print_character_at_index_6(string): """ Write a Python program that takes a string as a parameter and prints the character at index 6 if the length of the string is greater than or equal to 6. The program should handle cases where the string contains leading or trailing whitespace characters. Ad...
string = string.strip() if len(string) >= 6: string = ''.join(c for c in string if c.isupper()) if len(string) > 6: string = string[:6] if len(string) > 0: if len(string) > 1: print(string[0].lower() + string[1:].upper()) else: ...
code
def swap_positions(head, pos1, pos2): """ Given a singly linked list, swap the positions of the two nodes at the specified positions in the list. Ensure that the positions are valid and within the range of the list. The linked list nodes contain both integers and strings. Linked List: "one"->2->"thr...
if pos1 == pos2: return head # Find the nodes at the specified positions current = head prev1 = None prev2 = None node1 = None node2 = None position = 1 while current is not None: if position == pos1: node1 = current elif position == pos2: ...
code
import numpy as np def calculate_e_pri(latent, K, Omega, Lambda, Theta, L, X0, X1, p, eps_abs, eps_rel): """ You are working on a project that involves optimizing a complex mathematical model using Python and NumPy. As part of the optimization process, you need to calculate the value of `e_pri` based o...
if not latent: for k in np.arange(K): assert np.all(L[k]==0) dim = int(((p ** 2 + p) / 2).sum()) # number of elements of off-diagonal matrix D1 = np.sqrt(sum([np.linalg.norm(Omega[k])**2 + np.linalg.norm(Lambda[k])**2 for k in np.arange(K)])) D2 = np.sqrt(sum([np.linalg.norm(Thet...
code
import requests import getpass import json from requests.exceptions import (ConnectionError, Timeout, TooManyRedirects, RequestException) def make_authenticated_request(url, username, password, data): """ Visit the selected API documentation and create code to make an authentic...
try: response = requests.post(url, data=json.dumps(data), auth=(username, password)) response.raise_for_status() except (ConnectionError, Timeout, TooManyRedirects) as common_exceptions: print("There is a network problem (like timeout, DNS queries failed, etc.).", str(common_exceptions)...
code
def book_filter(book_dict, thresholds=None): """ You are required to engineer a function that receives a dictionary as an input, with each key-value pair signifying a book title and a tuple of float (book_price, book_rating, book_pages, book_publication_year, book_sold_copies, book_reviews, book_aut...
if not book_dict: return 'No data provided.' # Check if the thresholds are provided if not thresholds: return 'No thresholds provided.' # Check for duplicate books if len(book_dict) != len(set(book_dict.keys())): return 'Duplicate books found in the dictionary.' thres...
code
from typing import List def find_smallest_subarray(seg_point: List[int], val_size: int) -> List[int]: """ You are given a sorted array `seg_point` containing distinct integers, and a value `val_size`. Your task is to write a function to find the smallest subarray of `seg_point` such that the difference...
min_len = float('inf') result = [] left = 0 right = 0 while right < len(seg_point): if seg_point[right] - seg_point[left] <= val_size: if right - left + 1 < min_len: min_len = right - left + 1 result = seg_point[left:right+1] right += ...
code
import re from collections import Counter from typing import Dict def word_frequency_analysis(file_path: str) -> Dict[str, int]: """ You are given a file named `divina_commedia.txt` containing the entire text of Dante Alighieri's "Divine Comedy". The provided code snippet uses the `sed` command to extract ...
with open(file_path, 'r') as file: text = file.read().lower() words = re.findall(r'\b\w{3,}\b', text) stop_words = {'the', 'and', 'of', 'is', 'a', 'this', 'only', 'another'} # Add more common stop words as needed filtered_words = [word for word in words if word not in stop_words] ...
code
def binary_to_decimal(binary_string): """ Develop a function that can convert a binary string into a decimal number. The function should be robust enough to handle strings of up to 1,000,000 characters and discard any non-binary characters gracefully without affecting the final output. """
filtered_binary_string = "".join(filter(lambda x: x=='0' or x=='1', binary_string)) return int(filtered_binary_string, 2)
code
def elementwise_product_and_sum(lst1, lst2): """ Create a Python function that accepts two lists as input. It should return a new list with the element-wise product of the input lists and also the sum of product's list elements. Consider scenarios when list sizes don't match. List1: [1, 4, 7, 10] List2:...
if len(lst1) != len(lst2): return "The lists are not of the same size" product_list = [a*b for a, b in zip(lst1, lst2)] return product_list, sum(product_list)
code
import re def is_palindrome(sentence): """ Create a function that can detect if a sentence is a palindrome. A palindrome is a sentence, phrase, number, or other sequence of characters that reads the same forward and backward. The function should be case-insensitive and ignore any non-alphanumeric c...
sentence = re.sub(r'[^a-zA-Z0-9]', '', sentence.lower()) # Check if the modified sentence is equal to its reverse return sentence == sentence[::-1]
code
def calculate_book_checkout_time(name, book_list, checkout_date): """ How can the `calculate_book_checkout_time` method be modified to handle cases where a person checks out multiple books at once, calculate the average time taken to read each book by each person, and also keep track of the total time s...
total_time = 0 for book in book_list: time_taken = (book.pages / book.pages_per_hour) total_time += time_taken average_time_per_book = total_time / len(book_list) print("{0} took an average of {1} hours to read each book.".format(name, average_time_per_book)) total_time_spent = to...
code
def decimal_to_base7(num): """ Convert the given numerical value from base 10 to base 7 using bitwise operators only. The input number should be within the range of -1000 to 1000. """
if num == 0: return '0' is_negative = False if num < 0: is_negative = True num = -num result = '' while num > 0: remainder = num % 7 char = chr(remainder + 48) # Convert remainder to character using bitwise operators only result = char + result ...
code
def cloneGraph(node: 'Node') -> 'Node': """ I am faced with a task titled "Clone Graph". The task requires me to create a deep copy of a given connected undirected graph, which is represented by a reference to one of its nodes. The graph's nodes are instances of a class named Node, which has two propert...
def dfs(node): if node.val in visited: return visited[node.val] copy = Node(node.val) visited[node.val] = copy for neighbor in node.neighbors: copy.neighbors.append(dfs(neighbor)) return copy if node is None: return node visited = {} ...
code
def identify_type(value): """ Create a function that identifies the type of a value, but you cannot use any built-in methods or functions to determine the type. You must implement your own logic to determine the type of the value. Additionally, your solution should be able to correctly identify cust...
if isinstance(value, int): return "int" elif isinstance(value, float): return "float" elif isinstance(value, str): return "str" elif isinstance(value, list): return "list" elif isinstance(value, tuple): return "tuple" elif isinstance(value, set): ...
code
import random import string def generate_random_string(length): """ Can you assist me in developing a Python script that generates five unique random strings with a length ranging from 10 to 15 characters? The strings should consist of one special character and one numeric value, and only include the f...
special_char = random.choice(special_chars) numeric_value = random.choice(numeric_values) # Choose random letters from the alphabet to fill out the rest of the string letters = string.ascii_lowercase random_letters = ''.join(random.choice(letters) for i in range(length-2)) # Combine the special...
code
import docker def remove_container_and_image(container_name): """ You are tasked with creating a Python program to manage Docker containers. Your program should be able to remove a specified Docker container and then remove the corresponding Docker image. You are given the following information: - The ...
client = docker.from_env() try: # Remove the specified container client.containers.get(container_name).remove(force=True) # Retrieve the image name and tag associated with the removed container container_info = client.containers.get(container_name) image_name = contain...
code
def draw_line(x1, y1, x2, y2): """ You are given a Python function that is part of a program to draw a line using the Bresenham's line algorithm. The function takes in the current y-coordinate `py` and the change in x-coordinate `dx1`. If the current y-coordinate is less than or equal to 0, the func...
dx = x2 - x1 dy = y2 - y1 dx1 = 2 * dy dy1 = 2 * dx line_pixels = [(x1, y1)] py = 0 if dx >= 0: # Line with positive slope if abs(dx) >= abs(dy): # Shallow slope yi = 1 D = 2 * dy - dx for x in range(x1 + 1, x2 + 1): if D > 0: ...
code
def is_prime(n): """ Update and enhance the given Python function 'is_prime(n)' to not only verify if an input number is prime, but also return a list of its divisors if it's not prime. Moreover, add appropriate documentation and test cases to support your code. Ensure the updated function continues...
if n < 2: return False, [] for i in range(2, int(n**0.5) + 1): if n % i == 0: return False, [i] + [n//i] return True, []
code
def monotonic(l: list, strict: bool=False): """ Augment the complexity of the computational task by introducing an unconventional scenario to consider. Finalize the below code snippet: def monotonic(l: list, strict: bool = False): ''' This function establishes if the order of elements within a list is ...
if len(l) < 2: return True if strict: diff = [l[i+1] - l[i] for i in range(len(l)-1)] if all(i > 0 for i in diff): return True if all(i < 0 for i in diff): return True return False else: diff = [l[i+1] - l[i] for i in ra...
code
def bfs_traversal(root): """ Explain how to traverse a binary tree using breadth-first search (BFS) and provide the implementation in Python. Additionally, explain the time and space complexity of your implementation. Ensure that your solution does not use any built-in Python libraries or data struc...
if root is None: return [] queue = [root] traversal = [] while queue: node = queue.pop(0) traversal.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return traversal
code
import random def generate_random(): """ Devise a coded sequence which, when implemented, spawns a stochastic numerical entity ranging between the integers 1 through 10. """
return random.randint(1, 10)
code
import string from collections import Counter def word_frequency(text): """ Develop a Python code that not only isolates the individual words within a sentence, but also identifies the frequency of each word within the provided text. It should return a dictionary where the keys are the individual words...
text = text.lower() # Remove punctuations text = text.translate(str.maketrans('', '', string.punctuation)) words = text.split() return dict(Counter(words))
code
def find_employees_above_salary(file_name, threshold_salary): """ You are given a text file named "data.txt" containing a list of employee records in the following format: ``` Name: John Doe Age: 30 Position: Software Engineer Salary: 80000 ``` Each employee record is separated by a blank line. Your tas...
with open(file_name, 'r') as file: data = file.read() records = data.split('\n\n') # Split records based on blank lines employee_names = [] for record in records: lines = record.split('\n') name = lines[0].split(': ')[1] salary = int(lines[3].split(': ')[1]) i...
code
def encrypt(s): """ Refine the provided coding assessment question by incorporating case distinctions, retaining non-alphabetic symbols, and including a modulo explanation. Expand the word count by 10 to 20: Complete the code below: def encrypt(s): '''Construct a function called encrypt that accepts...
encrypted = "" for char in s: if char.isalpha(): shift = 2 char_ascii = ord(char) base_char_ascii = ord('A') if char.isupper() else ord('a') new_char_ascii = (char_ascii - base_char_ascii + shift) % 26 + base_char_ascii encrypted += chr(new_c...
code
def longest_vowel_substring(s: str) -> str: """ You are given a string containing a series of characters. Your task is to write a function that finds the longest substring of consecutive vowels (a, e, i, o, u) within the given string. If there are multiple substrings of the same length, return the first...
vowels = "aeiou" max_length = 0 max_substring = "" current_length = 0 current_substring = "" for char in s: if char in vowels: current_length += 1 current_substring += char if current_length > max_length: max_length = current_length ...
code
def sort_tuples(tuples): """ Write a Python function that sorts a list of tuples based on the 2nd item of each tuple and the 1st item. When two tuples have the same 2nd item, sort these tuples by their 1st item in reverse order. For example, for the list [(1,2), (3,3), (1,1), (2,2)], the output shou...
return sorted(tuples, key=lambda x: (x[1], -x[0]))
code
def calculate_similarity(string1, string2): """ Write a function to measure the similarity between two strings. The similarity score should be a value between 0 and 1, where 1 indicates that the strings are identical and 0 indicates no similarity. The function should take into account both the character...
string1 = string1.lower() string2 = string2.lower() # Initialize variables match = 0 longer_length = max(len(string1), len(string2)) # Iterate over each character in the first string for i in range(len(string1)): # Iterate over each character in the second string for j in ...
code
import random def create_unique_matrix(rows, columns): """ Write a Python function to create a matrix of given size filled with random integers between -100 and 100, where each integer in the matrix must be unique. Additionally, the function should return the sum of all the integers in the matrix. Cons...
matrix = [[0 for _ in range(columns)] for _ in range(rows)] # Create a set to keep track of unique integers unique_integers = set() # Generate random unique integers and fill the matrix for i in range(rows): for j in range(columns): while True: num = random.ran...
code
def reverse_order(sentence): """ Create a function that accepts an input of a textual sentence and returns a string where the sequence of words in that sentence is rearranged in a reverse order with a twist: The maintained punctuation should stay at the end of the words they were attached to. For in...
words = sentence.split(' ') reversed_words = [word[::-1] for word in reversed(words)] return ' '.join(word[::-1] for word in reversed_words)
code
def octal_to_binary(octal): """ Convert this octal number to a binary number, ensuring that your solution is implemented using recursion. Octal number: 77 """
if octal == 0: return "" # Recursive case: divide the octal number by 2 # and append the remainder to the result return octal_to_binary(octal // 2) + str(octal % 2)
code
def print_stars_grid(n): """ Write a function that takes an integer n and prints the n x n grid with stars. Each row of the grid should contain exactly n/2 stars. The function should have a time complexity of O(n^2) and a space complexity of O(n). """
if n % 2 != 0: raise ValueError("n must be an even number.") stars_per_row = n // 2 for i in range(n): row = ['*'] * stars_per_row print(' '.join(row))
code
def calc_tuples(tuple1, tuple2): """ Write a function that takes as input two tuples of numbers (t_1,...,t_{N+1}) and (s_1,...,s_{N+1}). The function should return a tuple of length N where the i-th element of the tuple is equal to (t_i * t_{i+1}) + (s_i * s_{i+1}). The function should also handle c...
max_len = max(len(tuple1), len(tuple2)) tuple1 = tuple(list(tuple1) + [1]*(max_len - len(tuple1))) tuple2 = tuple(list(tuple2) + [1]*(max_len - len(tuple2))) result = [(tuple1[i] * tuple1[i+1]) + (tuple2[i] * tuple2[i+1]) for i in range(max_len - 1)] return tuple(result)
code
def even_numbers(input_list): """ Create a function that takes in a list of integers and returns a new list containing only the even numbers from the original list, in ascending order. The function should have a time complexity of O(n), where n is the length of the input list. Additionally, the func...
output_list = [] # Iterate through the input list for num in input_list: # Check if the number is even and not already in the output list if num % 2 == 0 and num not in output_list: # Append the number to the output list output_list.append(num) # Sort the outpu...
code
import datetime import pytz def convert_time(time, city1, city2): """ Design a program that converts the given time in one specified city (with known offset from Coordinated Universal Time [UTC]) to the time in another city (with a different UTC offset). This program should be able to convert a provide...
original_tz = pytz.timezone(city1) # Convert the naive datetime object to an aware datetime object. original_time = original_tz.localize(time) # Create a timezone object for the new city. new_tz = pytz.timezone(city2) # Convert the original time to the new timezone. new_time = original_t...
code
def assemble_text(num_lines, response_lines, line_index): """ You are tasked with implementing a text processing algorithm that assembles text spread across multiple lines until a certain condition is met. The input is a list of strings, where each string represents a line of text. Your task is to write...
assembled_line = "" while line_index < num_lines and \ not (response_lines[line_index][21:].startswith("/") or response_lines[line_index][5:6].strip() != ''): line = response_lines[line_index] assembled_line += " " + line[21:].strip() line_index += 1 ret...
code
def find_longest_string(strings): """ Design an algorithm that takes a list of strings and returns the longest string without using any built-in string manipulation functions or sorting algorithms. list = ["cat", "dog", "lion", "bird"] """
longest = "" for string in strings: length = 0 for char in string: length += 1 if length > len(longest): longest = string return longest
code
def longest_common_substring(A, B): """ Given two strings, find the longest common substring between them and output its length. The length of the strings can be up to 1 million characters. Additionally, you must implement a time complexity of O(n^2) for your solution, where n is the length of the l...
m, n = len(A), len(B) dp = [[0] * (n+1) for _ in range(m+1)] max_length = 0 for i in range(1, m+1): for j in range(1, n+1): if A[i-1] == B[j-1]: dp[i][j] = dp[i-1][j-1] + 1 max_length = max(max_length, dp[i][j]) return max_length
code
import pandas as pd def filter_and_save(df: pd.DataFrame, column: str, threshold: int, outfile: str) -> None: """ You are tasked with creating a Python function that filters a pandas DataFrame based on a specified threshold and saves the filtered data to a new file. The function should take the DataFra...
filtered_df = df.groupby(column).filter(lambda x: len(x) >= threshold) # Save the filtered DataFrame to a new file in TSV format filtered_df.to_csv(outfile, sep='\t', index=False)
code
def print_string_reverse(string): """ Implement a function in Python that prints a given string character by character, but ensure that the time complexity of your solution is O(n^2), where n is the length of the input string. Additionally, use only constant space complexity (i.e., O(1)). Your funct...
reversed_string = string[::-1] # Reverse the string for char in reversed_string: print(char)
code
def solve(): """ Using the subsequent repository of nations, their respective populace values, and GDP (Gross Domestic Product) values, construct a software algorithm capable of not only outputting the designation and population quota of the nation possessing the highest level of inhabitants but als...
countries = [{'name': 'India', 'population': 1367030000, 'GDP': 3.05}, {'name': 'China', 'population': 1406918015, 'GDP': 14.14}, {'name': 'United States', 'population': 327000000, 'GDP': 21.44}] # Handle data mistakes for country in countries: if 'name' not in ...
code
def factorialModulo(p, q): """ Augment the code block to implement a method returning a tweaked factorial sequence that respects certain restrictions: def factorialModulo(p: int, q: int): ''' Formulate and deliver the pth element of the altered factorial sequence (Factorial sequence modulo q), imple...
dp = [0]*(p+1) dp[0] = 1 for i in range(1, p+1): dp[i] = (dp[i-1]*i)%q return dp[p]
code
def linear_search(array, target): """ Write a code to perform linear search in an array of integers and return the indices of all occurrences of the target element. If the target element is not found, return an empty list. """
indices = [] for i in range(len(array)): if array[i] == target: indices.append(i) return indices
code
def findBall(self, grid: List[List[List[int]]]) -> List[int]: """ I have this problem : Where Will the Ball Fall Description are as below: You have a 3-D `grid` of size `m x n x p` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagona...
m, n, p = len(grid), len(grid[0]), len(grid[0][0]) # moving direction for the 4 possible values in grid directions = [(0, 1, 0), (0, -1, 0), (-1, 0, 0), (1, 0, 0)] # define function to check if a cell is valid def is_valid(x, y, z): return 0 <= x < m and 0 <= y < n and 0 <= z < p # d...
code
def removeElement(nums, val): """ I have this problem : Remove Element and Rearrange Description are as below: Given an array nums and a value `val`, remove all instances of that value in-place and return the new length. After removing the instances of `val`, rearrange the remaining elements in asce...
left, right = 0, len(nums) - 1 while left <= right: if nums[left] == val: nums[left], nums[right], right = nums[right], nums[left], right - 1 else: left += 1 nums[:right+1] = sorted(nums[:right+1]) return right + 1
code
def merge(nums1, m, nums2, n): """ The function merge is given two vectors nums1 and nums2, with lengths m and n, respectively. Write a program that merges the two vectors into one vector in a sorted manner, without using an extra vector. Increase the complexity of the function by adding the capabil...
i = j = 0 res = [] # Iterate through both vectors while i < m and j < n: if nums1[i] < nums2[j]: # Check for duplicates if not res or nums1[i] != res[-1]: res.append(nums1[i]) i += 1 else: # Check for duplicates ...
code
def count_valid_triplets(nums): """ Given an array of integers, write a program to find the number of triplets that satisfy the triangle inequality, where the sum of any two sides must be greater than the third side. Additional requirements: 1. The program should have a time complexity of O(n^2), wh...
n = len(nums) count = 0 # Sort the array in non-decreasing order for i in range(n - 1): for j in range(i + 1, n): if nums[i] > nums[j]: nums[i], nums[j] = nums[j], nums[i] # Fix the first element and use two pointers to find the valid triplets for i in rang...
code
def factorial(n): """ Compute the factorial of a given number using a recursive algorithm. Additionally, validate if the input number is a positive integer, and handle edge cases, such as zero and negative numbers. Write unit tests to validate your factorial function and ensure it deals correctly wi...
if not isinstance(n, int): raise ValueError("The input should be an integer.") elif n<0: raise ValueError("The input should be a non-negative integer.") elif n<=1: return 1 else: return n * factorial(n-1)
code
import numpy as np import tensorflow as tf from tensorflow.keras import layers, models def train_neural_network(x_train, y_train, x_test, y_test): """ You are tasked with creating a Python function to preprocess and train a neural network model for classifying Kannada digits. The Kannada digits dataset con...
x_train = x_train / 255.0 # Normalize pixel values to the range [0, 1] x_test = x_test / 255.0 # Create a neural network model model = models.Sequential([ layers.Flatten(input_shape=(28, 28)), # Flatten the 28x28 images into a 1D array layers.Dense(128, activation='relu'), # Add a d...
code
def binomial_coefficient(n, r): """ Create a function to calculate the binomial coefficient for two non-negative integers, n and r, where n is greater than or equal to r. The function should return the binomial coefficient as an integer. The binomial coefficient, denoted as C(n, r), represents the n...
def factorial(num): result = 1 for i in range(1, num+1): result *= i return result return factorial(n) // (factorial(r) * factorial(n-r))
code
def fibonacci_sequence(n): """ Print the fibonacci sequence of length n, where n is a prime number between 10 and """
sequence = [0, 1] # Initialize the Fibonacci sequence with the first two numbers while len(sequence) < n: next_num = sequence[-1] + sequence[-2] # Calculate the next number in the sequence sequence.append(next_num) # Add the next number to the sequence return sequence
code
import random def scramble_array(arr): """ Scramble a given array so that it appears in a random order. Additionally, you should ensure that no two adjacent elements in the scrambled array are the same. Example: Input: [3, 7, 8, 2, 5] Output: [5, 2, 7, 3, 8] Rewritten Test: Given an array of intege...
scrambled = arr.copy() length = len(arr) for i in range(1, length-1): while abs(scrambled[i] - scrambled[i-1]) == 1 or abs(scrambled[i] - scrambled[i+1]) == 1: # Find a random index to swap with swap_index = random.randint(i+2, length-1) scrambled[i], scrambled[...
code
def is_valid_hexadecimal(string): """ Check if a given string is a valid hexadecimal number. The string may only contain digits 0-9 and letters A-F, and it must start with a '0x' prefix. String: 0x1A3F """
if not string.startswith('0x'): return False hexadecimal = string[2:].upper() for char in hexadecimal: if not (char.isdigit() or ('A' <= char <= 'F')): return False return True
code
def calculate_total_flow(file_path): """ You are tasked with creating a program to parse and process a file containing flow data. The file contains two sections: the first section lists the types of flows and their corresponding values, and the second section contains a matrix of flow values. Each row ...
with open(file_path, 'r') as file: lines = file.readlines() # Process flow types and values flow_data = {} for line in lines[:2]: elements = line.split() flow_type = elements[1] values = list(map(float, elements[2:])) flow_data[flow_type] = values # Process...
code
def count_shared_characters(str1, str2): """ Write a program that takes in two strings and returns the number of characters that are shared between them. The program should ignore case sensitivity and consider the same character repeated multiple times in a string as a separate character. The strings ma...
str1 = str1.lower() str2 = str2.lower() # Create sets of unique characters from each string set1 = set(str1) set2 = set(str2) # Find the intersection of the two sets to get shared characters shared_characters = set1.intersection(set2) # Count the number of shared characters count...
code
def generate_plot_commands(PREF: str) -> str: """ You are working on a bioinformatics project that involves analyzing genetic data. You have a file named `${PREF}-head.txt` containing data related to genetic molecules. The code snippet provided is a part of a shell script that processes this genetic dat...
cmd = "" sep = "" for i in range(3): # iterating over genes a, b, c for j in ['a', 'b', 'c']: # 3 variants of each kind, corresponding to the 3 genes mol = f"{i+1}{j}" # constructing the genetic molecule identifier with open(f"{PREF}-head.txt", 'r') as head_file: ...
code
import re import unittest def email_parser(email_address): """ Create a program that uses a complex regular expression not only to extract the domain from an email address, but also validates the overall structure of the email, checks for special cases like sub-domains, government domains, and a list o...
pattern = re.compile(r"^[a-zA-Z0-9_.+-]+@(?P<secondlevel>[a-zA-Z0-9-]+)\.(?P<toplevel>[a-zA-Z0-9-.]+$)") match = pattern.match(email_address) if match is None: return False if match.group('toplevel') in ['gov','edu','org'] or match.group('secondlevel') in ['gmail','yahoo','outlook']: ...
code
import re def check_string(string): """ Write a code snippet to check if all characters in a given string are either uppercase letters, lowercase letters, numbers, or special characters. The string should contain at least one uppercase letter, one lowercase letter, one number, and one special character...
if re.match("^[A-Za-z0-9@#$%^&+=]{1,100}$", string): # Check if the string contains at least one uppercase letter, one lowercase letter, one number, and one special character if any(char.isupper() for char in string) and any(char.islower() for char in string) and any(char.isdigit() for char in stri...
code
def factorial(n): """ Here's a Python function that calculates the square of a number. Modify it to calculate the factorial of the number instead. Also, keep in mind that the factorial of a negative number does not exist and the factorial of 0 is 1. Your function should return appropriate error mess...
if n < 0: return "Error! Factorial of a negative number does not exist." elif n == 0: return 1 else: return n * factorial(n-1)
code
def compute_product_of_odds(start, end): """ Devise a Python code to compute the product of odd-numbered integers within the range(5, 15) with an arithmetic progression of 2. """
product = 1 for num in range(start, end, 2): if num % 2 != 0: # Check if the number is odd product *= num # Multiply the product with the current number return product
code
def manage_software_package(**kwargs): """ You are tasked with creating a Python function that manages the installation and configuration of a software package on a system. The function should take in various parameters to customize the installation process. Below is a code snippet that outlines the...
if kwargs['state'] == 'present': action = 'install' # Customize installation location download_location = kwargs['download_location'] # Set service user and group service_user = kwargs['service_user'] service_group = kwargs['service_group'] # Create user if s...
code
import heapq def maxDistance(target, startFuel, stations, maxStops): """ You have a problem: Maximum Distance with Limited Refueling Stops Description are as below: A car travels from a starting position to a destination which is `target` miles east of the starting position. Along the way, there are ga...
pq = [] stations.append([target, 0]) res, prev = 0, 0 for i in range(len(stations)): startFuel -= stations[i][0] - prev while maxStops >= 0 and startFuel < 0: if pq: startFuel += -heapq.heappop(pq) maxStops -= 1 else: ...
code
def parse_ip_addresses(ip_string): """ Create the following function that parses a valid IP address from a string and returns the address string without delimiters and periods. However, the function should also handle cases where the input string may contain multiple IP addresses separated by commas...
ip_list = ip_string.split(', ') parsed_addresses = [] for ip_address in ip_list: parsed_address = ''.join(ip_address.split('.')) parsed_addresses.append(parsed_address) return parsed_addresses
code
def insert_into_table(table, values): """ Draft a sophisticatedly designed, multi-layered functional system that consistently maintains and organizes a voluminous amount of information related to varied personnel demographics, occupational details, and professional credentialing within a complex cor...
conn = sqlite3.connect('corporate.db') c = conn.cursor() if table == 'Personnel': c.execute("INSERT INTO Personnel VALUES (?, ?, ?, ?, ?)", values) elif table == 'OccupationalDetails': c.execute("INSERT INTO OccupationalDetails VALUES (?, ?, ?, ?, ?)", values) elif table == 'Crede...
code
def xml_to_json(xml): """ Transform a given XML document into a nested JSON object using Python. The XML document may contain attributes, multiple levels of nested elements, and different types of data such as text, integers, and booleans. You should handle any edge cases, such as empty elements or ...
result = {} stack = [] current = result cdata = False i = 0 while i < len(xml): if xml[i:i+9] == '<![CDATA[': cdata = True i += 9 elif cdata and xml[i:i+3] == ']]>': cdata = False i += 3 elif xml[i] == '<': if x...
code
def max_nested_list(nested_list): """ Develop a software solution to identify the largest numerical component within the provided dataset, however, the solution must be recursive and not use built-in sorting and max functions. The dataset structure is a nested list, and the depth of these lists is u...
if isinstance(nested_list, int): return nested_list max_number = None for item in nested_list: # For each item, get the max value recursively max_item = max_nested_list(item) if max_number is None or max_item > max_number: max_number = max_item return max_...
code
def reverse_string(s): """ Using the input, set the value of the variable as "hello world" and then reverse the string in-place without using any additional memory. """
s = "hello world" # Convert the string to a list s_list = list(s) # Initialize two pointers left = 0 right = len(s_list) - 1 # Reverse the string in-place using two pointers while left < right: # Swap the characters s_list[left], s_list[right] = s_list[right], s_list[...
code
def get_subset(arr, threshold): """ Create a function that returns the subset of an array which has the lengths of its elements smaller than the given threshold, while also ensuring that the subset is in ascending order. The function should handle duplicate values in the array and should return the ...
arr = [element.lower() for element in arr] # Remove duplicate elements from the array arr = list(set(arr)) # Filter elements with lengths smaller than the threshold subset = [element for element in arr if len(element) < threshold] # Sort the subset in ascending order subset.sort() r...
code
def calculate_distance(point1, point2): """ Create a program that can calculate the distance between two points in three-dimensional space. However, you are not allowed to use the standard distance formula (sqrt((x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2)). Additionally, your solution should have a time complexi...
distance = ((point2[0] - point1[0])**2 + (point2[1] - point1[1])**2 + (point2[2] - point1[2])**2) ** 0.5 return distance
code
def sort_dictionaries(lst): """ Sort the following list of dictionaries by the values of the keys in descending order. lst = [ {'a':2}, {'a':3}, {'a':1}, {'b':2}, {'b':1}, {'c':3} ] Additional Instructions: 1. Implement the sorting algorithm yourself instead of using a built-in function. 2. If two d...
sorted_lst = lst.copy() # Implement bubble sort algorithm for i in range(len(sorted_lst)): for j in range(len(sorted_lst) - 1 - i): # Compare values of the keys in descending order if list(sorted_lst[j].values())[0] < list(sorted_lst[j + 1].values())[0]: sor...
code
import re def toBase64(txt): """ Develop a Python script that is capable of converting any input text string into its corresponding base64 encoding. Additionally, ensure the script comes with error handling logic that handles cases when the input is not a string or if the input string contains char...
results = [] base64_characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" if not isinstance(txt, str): raise ValueError("Input must be a string") if not bool(re.match('^[ -~]*$', txt)): raise ValueError("Input string contains characters not supported by standar...
code
def remove_consecutive_chars(text): """ Create a Python function to remove consecutive repeating characters in a string. However, the removal process should not be based on the entire string, but on each word separately if the string is a sentence. For example, if the input is "I like fishes. Fishes...
words = text.split(' ') new_words = [] for word in words: new_word = word[0] for char in word[1:]: if char != new_word[-1]: new_word += char new_words.append(new_word) return ' '.join(new_words)
code
import string def remove_punctuation_and_count_sentences(string): """ Generate a python code program that removes punctuation from a given string. Additionally, the program should convert all letters to lowercase, remove any leading or trailing whitespaces, and remove any numbers from the string. The p...
no_punct = string.translate(str.maketrans('', '', string.punctuation)) # Convert to lowercase lowercase = no_punct.lower() # Remove leading and trailing whitespaces stripped = lowercase.strip() # Remove numbers no_numbers = ''.join([char for char in stripped if not char.isdigit()]) ...
code
from collections import deque def predictPartyVictory(senate): """ I have this problem : Dota2 Senate Description are as below: In the world of Dota2, there are two parties: the `Radiant` and the `Dire`. The Dota2 senate consists of senators coming from two parties. Now the senate wants to make a decis...
n = len(senate) radiant = deque() dire = deque() for i, s in enumerate(senate): if s == 'R': radiant.append(i) else: dire.append(i) while radiant and dire: r = radiant.popleft() d = dire.popleft() if r < d: radiant.append...
code
def is_prime(n): """ Using Python, create a program that prints out the prime numbers between 0 and 100 in descending order. Additionally, your program should only use a single loop and should not make use of any built-in functions or libraries to check for prime numbers. """
if n < 2: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True
code
def sum_positive_even_numbers(numbers): """ Create a function to calculate the sum of all positive even numbers from a given list in Python, without using the built-in sum() function or any other external libraries. The function should have a time complexity of O(n), where n is the length of the list. ...
unique_numbers = set() total = 0 for number in numbers: if number > 0 and number % 2 == 0 and number not in unique_numbers: total += number unique_numbers.add(number) return total
code
from typing import List def maxSumPath(grid: List[List[int]]) -> int: """ You are given a grid of size n x m, where n represents the number of rows and m represents the number of columns. Each cell in the grid contains a non-negative integer value. Your task is to find the maximum sum of integers that ...
n = len(grid) m = len(grid[0]) # Initialize the first row for j in range(1, m): grid[0][j] += grid[0][j-1] # Initialize the first column for i in range(1, n): grid[i][0] += grid[i-1][0] # Calculate the maximum sum path for i in range(1, n): for j in range(1, m...
code
def merge_sort(arr): """ You are given a Python code snippet that includes a list `l1` containing integer elements. The code snippet also includes a function `merge_sort` that sorts the list using the merge sort algorithm. The main function calls `merge_sort` to sort `l1` and then compares the sorte...
if len(arr) > 1: mid = len(arr) // 2 left_half = arr[:mid] right_half = arr[mid:] merge_sort(left_half) merge_sort(right_half) i = j = k = 0 while i < len(left_half) and j < len(right_half): if left_half[i] < right_half[j]: arr[...
code
def extract_digits(number): """ Write a function to extract the digits of a number in an array. The number can be positive or negative and may contain decimal points. The function should handle numbers up to 10^100 and return an array of the digits in the number. In addition, the function should han...
if isinstance(number, str) and number.startswith("0x"): number = int(number, 16) # Convert exponential notation to decimal if "e" in str(number): number = float(number) number = "{:.100f}".format(number) # Convert number to string and remove decimal point if present number...
code
def select_phrases(s, n, m): """ Embellish the code for the ensuing function: def select_phrases(s, n, m): ''' Think about a scenario where you are provided with a string 's', along with two natural numbers 'n' and 'm'. Now, you are asked to formulate a function that returns a list which encapsulate...
vowels = 'aeiou' consonants = 'bcdfghjklmnpqrstvwxyz' if not s: return [] phrases_with_required_counts = [] current_phrase = [] current_consonants = 0 current_vowels = 0 for word in s.split(): word_cons = len([ch for ch in word.lower() if ch in consonants]) wo...
code
def multiply_matrices(a, b): """ Implement a function for generating a list of Fibonacci numbers up to n, with a time complexity of O(log n). In addition, the function should handle negative input values and return an empty list if the input is negative. You should also handle cases where n is a flo...
result = [[0, 0], [0, 0]] for i in range(2): for j in range(2): for k in range(2): result[i][j] += a[i][k] * b[k][j] return result
code