task_id
stringlengths
12
14
prompt
stringlengths
273
1.94k
entry_point
stringlengths
3
31
canonical_solution
stringlengths
0
2.7k
test
stringlengths
160
1.83k
PythonSaga/0
from typing import List def extra_marks(marks:List[float])-> float: """let say i have a list of marks scored in each question by person. I want a sum of all the extra marks he/she scored in exam, extra score is whatever he scored above 100 in each question. but if marks is below 0 in any question it would reduce the total extra scores. Take input from user and return the sum of extra marks. Example: Input: [100, 120, -30, 140, -50, -60, 170, 22,55,-20] Output: -30 Input: [100, 120, -30] Output: -10 Input: [100, 22,75,99] Output: 0 """
extra_marks
extra = 0 for mark in marks: if mark > 100: extra += mark - 100 elif mark < 0: extra += mark return extra
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([100, 120, -30, 140, -50, -60, 170, 22,55,-20,-90]) == -120 assert candidate([111, 20, -130, 140, -50, -60, 170, 22,55,-20,-190]) == -329 assert candidate([170, 22,55,-20,-90]) == -40 assert candidate([100.1, 120, -30, 140, -50, -60, 170, 22,55,-20,-90]) == -119.9
PythonSaga/1
from typing import List def split_big_bag(big_bag: List[int])->bool: """i have one big bag in which there are multiple small bags fill with sand. bag of each small bag is different from each other. i want to split the big bad into 2 medium bags, such that avergae weight of each medium bag is same. Take input from user and return True if it is possible to split the big bag into 2 medium bags, else return False. Input: big_bag = [1,2,3,4,5,6,7,8] Output: true Input: big_bag = [3,1] Output: false"""
split_big_bag
total_weight = sum(big_bag) # Check if the total weight is even if total_weight % 2 != 0: return False target_weight = total_weight // 2 # Create a 2D array to store whether it's possible to achieve a certain weight with the given bags dp = [[False] * (target_weight + 1) for _ in range(len(big_bag) + 1)] # Base case: If the target weight is 0, it's always possible (by not selecting any bag) for i in range(len(big_bag) + 1): dp[i][0] = True for i in range(1, len(big_bag) + 1): for j in range(1, target_weight + 1): # If the current bag weight is greater than the target weight, skip it if big_bag[i - 1] > j: dp[i][j] = dp[i - 1][j] else: # Either include or exclude the current bag to achieve the target weight dp[i][j] = dp[i - 1][j] or dp[i - 1][j - big_bag[i - 1]] return dp[len(big_bag)][target_weight]
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([0]) == True assert candidate([5,2,3]) == True assert candidate([8]) == False assert candidate([1 2 3 4 5 6]) == False
PythonSaga/2
from typing import List def is_path_crossing(distances: List[int]) -> bool: """Check whether the path crosses itself or not. Suppose you are standing at the origin (0,0), and you are given a list of 4 distances, where each distance is a step in a direction (N, W, S, E). Take input from the user and return True if your path crosses itself, else False. Example: Input: [2, 1, 1, 1] Output: True Input: [1, 2, 3, 4] Output: False Input: [1, 2, 1, 2] Output: True """
is_path_crossing
if len(distances) < 4: return False # Initialize the starting point and direction x, y = 0, 0 directions = [(0, 1), (-1, 0), (0, -1), (1, 0)] # N, W, S, E visited = {(0, 0)} for i in range(len(distances)): # Calculate the new position based on the current direction x += distances[i] * directions[i % 4][0] y += distances[i] * directions[i % 4][1] # Check if the new position has been visited before if (x, y) in visited: return True # Add the current position to the visited set visited.add((x, y)) return False
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([1, 2, 3, 4]) == False assert candidate([1, 2, 1, 2]) == True assert candidate([2, 1, 1, 1]) == True assert candidate([11, 0, 1, 3]) == True
PythonSaga/3
from typing import List def is_boomarang(points: List[List[int]]) -> bool: """Check if the 3 points form a boomerang. A boomerang is a set of 3 points that are all distinct and not in a straight line. Take input from the user and return True if the 3 points are a boomerang and False if not. Input: [[1,1],[2,3],[3,2]] Output: True Input: [[1,1],[2,2],[3,3]] Output: False """ # Your implementation here pass
is_boomarang
# Ensure there are exactly 3 points if len(points) != 3: return False # Extract coordinates of the three points x1, y1 = points[0] x2, y2 = points[1] x3, y3 = points[2] # Check if the points are distinct if (x1, y1) == (x2, y2) or (x1, y1) == (x3, y3) or (x2, y2) == (x3, y3): return False # Check if the points are not in a straight line if (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) != 0: return True return False
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([[1, 1], [2, 3], [3, 2]]) == True assert candidate([[1, 1], [2, 2], [3, 3]]) == False assert candidate([[-1, -1], [0, 0], [1, 1]]) == False assert candidate([[0, 0], [1, 2], [3, 4]]) == True assert candidate([[0, 0], [1, 2]]) == False
PythonSaga/4
from typing import List def max_square_area(coordinates: List[List[int]]) -> int: """Find the maximum area of a square that can be formed from the given coordinates. The square has all sides equal and each side is parallel to the x or y axis with a length of at least 1 unit. Take input from the user and return the maximum area of the square that can be formed from these coordinates. Example: INPUT: [[1,1],[1,3],[3,1],[3,3],[2,2]] Output: 4 INPUT: [[1,1],[1,3],[3,1],[4,1],[4,4]] Output: 0 """
max_square_area
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([[1,1],[1,3],[4,1],[4,5],[5,3]]) == 4 assert candidate([[1,1],[1,5],[3,1],[3,3],[2,2]]) == 9 assert candidate([[1,1], [2,2],[4,1]]) == 0 assert candidate([[1, 1], [1, 3], [3, 1], [4, 1], [4, 4]]) == 4
PythonSaga/5
from typing import List def pattern1(n: int) -> List[str]: """Return the list of the specified pattern based on the input 'n'. The pattern consists of letters from 'A' to 'Z' arranged in a specific manner. Example: Input: 5 Output: [' A', ' B A', ' A B C', ' D C B A', 'E D C B A'] Input: 3 Output: [' A', ' B A', 'A B C'] """
pattern1
result = [] for i in range(n): # Add leading spaces line = ' ' * (n - i - 1) # Add characters in ascending order for j in range(i + 1): line += chr(65 + (j % 26)) if j < i: # Add a space after each character except the last one line += ' ' result.append(line) return result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(5) == [" A", " B A", " A B C", " D C B A", "E D C B A"] assert candidate(3) == [" A", " B A", "A B C"] assert candidate(1) == ["A"] assert candidate(0) == []
PythonSaga/6
def pattern2(n: int) -> str: """ take n as input from user, where n is number of terms and print the following pattern in form of string. write python code using for loop Example: Input: 5 Output: 1+4-9+16-25 Input: 3 Output: 1+4-9 """
pattern2
result = '' for i in range(1, n + 1): term = i ** 2 # Add the term to the result with the appropriate sign if i % 2 == 1: # If i is odd result += f'{term}+' else: result += f'{term}-' # Remove the trailing '+' or '-' result = result.rstrip('+-') return result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(5) == "1+4-9+16-25" assert candidate(3) == "1+4-9" assert candidate(1) == "1" assert candidate(0) == ""
PythonSaga/7
from typing import List def find_roots(a: int, b: int, c: int) -> List[int]: """ write program to find all the roots of a quadratic equation using match case in python. Take input from user that will be a, b, c of the quadratic equation. Example: Input: 1, 5, 6 Output: [-2, -3] Input: 1, 4, 4 Output: [-2, -2] """
find_roots
discriminant = b**2 - 4*a*c roots = [] if discriminant > 0: root1 = int((-b + (discriminant)**0.5) / (2*a)) root2 = int((-b - (discriminant)**0.5) / (2*a)) roots = [root1, root2] elif discriminant == 0: root = int(-b / (2*a)) roots = [root] return roots
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(1, 5, 6) == [-2, -3] assert candidate(1, 4, 4) == [-2, -2] assert candidate(1, 0, -1) == [1, -1] assert candidate(2, -8, 6) == [3, 1]
PythonSaga/8
def price_of_painting(mrp: float, age: int) -> float: """ lets say the price of painting depends on how old it is. if it is less than 5 years old, it will cost mrp + 5% of mrp if it is 5 or more than 5 years old but less than 11, it will cost mrp + 8% of mrp if it is older than 11 years it will be mrp + 10% of mrp take mrp and age of painting as input and print the final price of painting Example: Input: 1000, 5 Output: 1080.0 Input: 1000, 12 Output: 1100.0 """
price_of_painting
if age < 5: return mrp + 0.05 * mrp elif 5 <= age < 11: return mrp + 0.08 * mrp else: return mrp + 0.10 * mrp
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(1000, 5) == 1080.0 assert candidate(1000, 12) == 1100.0 assert candidate(1500, 3) == 1575.0 assert candidate(800, 8) == 864.0
PythonSaga/9
from typing import List def division(a: int, b: int) -> List[str]: """ let's say we get a, b from the user as 2 numbers, we have to return the division of a and b. solve it using a try-except block. if b is zero then print 'You cannot divide by zero!' if a and b are not numbers then print 'Please enter a valid integer!' and finally if everything is fine then print the division of a and b and also print 'This is always executed' using the finally block. Return the result in the form of a list. Example: Input: 10, 2 Output: ['5', 'This is always executed'] Input: 10, 0 Output: ['You cannot divide by zero!'] Input: 10, 'a' Output: ['Please enter a valid integer!'] """
division
from typing import List def division(a: int, b: int) -> List[str]: """ let's say we get a, b from the user as 2 numbers, we have to return the division of a and b. solve it using a try-except block. if b is zero then print 'You cannot divide by zero!' if a and b are not numbers then print 'Please enter a valid integer!' and finally if everything is fine then print the division of a and b and also print 'This is always executed' using the finally block. Return the result in the form of a list. Example: Input: 10, 2 Output: ['5', 'This is always executed'] Input: 10, 0 Output: ['You cannot divide by zero!'] Input: 10, 'a' Output: ['Please enter a valid integer!'] """ try: result = a / b return [str(result), 'This is always executed'] except ZeroDivisionError: return ['You cannot divide by zero!'] except TypeError: return ['Please enter a valid integer!'] finally: print('This is always executed')
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(10, 2) == ['5.0', 'This is always executed'] assert candidate(10, 0) == ['You cannot divide by zero!'] assert candidate(10, 'a') == ['Please enter a valid integer!'] assert candidate(20, 4) == ['5.0', 'This is always executed']
PythonSaga/10
from typing import List def pattern(n: int) -> List[str]: """ Lets say I want to create a hollow diamond shape using asterisk(*) in python of size n. where n is the number of rows from top to end. eg. if n=5 then output should be like this: * * * * * * * * Take input from the user and return the pattern in the form of a list of strings. Example: Input: 5 Output: [' * ', ' * * ', '* *', ' * * ', ' * '] Input: 3 Output: [' * ', '* *', ' * '] Input: 1 Output: ['*'] """
pattern
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(5) == [' * ', ' * * ', '* *', ' * * ', ' * '] assert candidate(3) == [' * ', '* *', ' * '] assert candidate(1) == ['*'] assert candidate(7) == [' * ', ' * * ', ' * * ', '* *', ' * * ', ' * * ', ' * ']
PythonSaga/11
from typing import List def pattern(n: int) -> List[str]: """ K shape character pattern program for n lines if n = 4 then output should be like this A B C D B C D C D D C D B C D A B C D Take input from the user and return the pattern in the form of a list of strings. Example: Input: 4 Output: ['A B C D', 'B C D', 'C D', 'D', 'C D', 'B C D', 'A B C D'] Input: 3 Output: ['A B C', 'B C', 'C', 'B C', 'A B C'] """
pattern
result = [] # Upper half of the pattern for i in range(n, 0, -1): row = ' '.join(chr(64 + j) for j in range(n - i + 1, n + 1)) result.append(row) # Lower half of the pattern for i in range(2, n + 1): row = ' '.join(chr(64 + j) for j in range(n - i + 1, n + 1)) result.append(row)
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(4) == ['A B C D', 'B C D', 'C D', 'D', 'C D', 'B C D', 'A B C D'] assert candidate(3) == ['A B C', 'B C', 'C', 'B C', 'A B C'] assert candidate(1) == ['A'] assert candidate(6) == ['A B C D E F', 'B C D E F', 'C D E F', 'D E F', 'E F', 'F', 'E F', 'D E F', 'C D E F', 'B C D E F', 'A B C D E F']
PythonSaga/12
from typing import List def pattern(n: int) -> List[int]: """ let's say given the number n, I want to print all the n prime numbers starting from 5 in such a way that, the sum of any two consecutive prime numbers is divisible by 3. Take input from the user and return the pattern in the form of a list. example: if n = 5, then output should be [5, 7, 11, 13, 17] example: if n = 6, then output should be [5, 7, 11, 13, 17, 19] """
pattern
def is_prime(num): """ Check if a number is prime. """ if num < 2: return False for i in range(2, int(num**0.5) + 1): if num % i == 0: return False return True def pattern(n: int) -> List[int]: primes = [] current_number = 5 while len(primes) < n: if is_prime(current_number): if len(primes) >= 2 and (primes[-1] + current_number) % 3 == 0: primes.append(current_number) elif len(primes) < 2: primes.append(current_number) current_number += 2 return primes
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert pattern(5) == [5, 7, 11, 13, 17] assert pattern(6) == [5, 7, 11, 13, 17, 19] assert pattern(10) == [5, 7, 11, 13, 17, 19, 23, 31, 41, 43] assert pattern(8) == [5, 7, 11, 13, 17, 19, 23, 31]
PythonSaga/13
from typing import List def pattern(n: int) -> List[int]: """ Let's say on getting n as input code gives n numbers for a particular series, which looks like 5, 7, 10, 36... and so on. where the series is based on the following rule: 5 x 1 + 2 = 7 7 x 2 - 4 = 10 10 x 3 + 6 = 36 36 x 4 - 8 = 136 .... print the series till the nth number. Take input from the user and return the pattern in the form of a list. example: Input: 5 Output: [5, 7, 10, 36, 136] Input: 7 Output: [5, 7, 10, 36, 136, 690, 4128] """
pattern
result = [5] for i in range(1, n): if i % 2 == 1: result.append(result[-1] * i + 2*i) else: result.append(result[-1] * i - 2*i) return result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(5) == [5, 7, 10, 36, 136] assert candidate(7) == [5, 7, 10, 36, 136, 690, 4128] assert candidate(3) == [5, 7, 10] assert candidate(10) == [5, 7, 10, 36, 136, 690, 4128, 28910, 231264, 2081394]
PythonSaga/14
def pattern(n: int) -> List[str]: """ Write a program that receives a number n as input and prints it in the following format as shown below. Like for n = 2 the pattern will be: 1*2*5*6 --3*4 or for n = 3 the pattern will be: 1*2*3*10*11*12 --4*5*8*9 ----6*7 Take input from the user and return the pattern in the form of a list of strings. Example: Input: 3 Output: ['1*2*3*10*11*12', '--4*5*8*9', '----6*7'] Input: 2 Output: ['1*2*5*6', '--3*4'] """
pattern
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert pattern(2) == ['1*2*5*6', '--3*4'] assert pattern(3) == ['1*2*3*10*11*12', '--4*5*8*9', '----6*7'] assert pattern(4) == ['1*2*3*4*17*18*19*20', '--5*6*7*14*15*16', '----8*9*12*13', '------10*11'] assert pattern(5) == ['1*2*3*4*5*26*27*28*29*30', '--6*7*8*9*22*23*24*25', '----10*11*12*19*20*21', '------13*14*17*18', '--------15*16']
PythonSaga/15
def toy_distribution(n: int) -> str: """ Let's say I have a bag of toys, which are 'n' in number. I know that these toys can be distributed either to n children or 1 child. I want to know what can be other ways to distribute these toys to children in such a way that each child gets at least an equal number of toys. Take input from the user for the number of toys. Use the divmod function to solve this problem. Example 1: If 15 toys are there, then 15 children can get 1 toy each or 1 child can get 15 toys or 3 children can get 5 toys each or 5 children can get 3 toys each. In this case, return 'Yes, it is possible'. Example 2: If 11 toys are there, then 11 children can get 1 toy each or 1 child can get 11 toys, that's it. In this case, return 'No, it is not possible'. """
toy_distribution
def is_prime(num): """ Check if a number is prime using divmod. """ if num < 2: return False for i in range(2, int(num**0.5) + 1): quotient, remainder = divmod(num, i) if remainder == 0: return False return True def toy_distribution(n: int) -> str: if n <= 0 or not is_prime(n): return 'Yes, it is possible' return 'No, it is not possible'
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(15) == 'Yes, it is possible' assert candidate(11) == 'No, it is not possible' assert candidate(20) == 'Yes, it is possible' assert candidate(2) == 'No, it is possible'
PythonSaga/16
from typing import List def filter_numbers(x: int, numbers: List[int]) -> List[int]: """ Filter all numbers in a list of numbers whose bitwise xor with the given value x is equal to 4 with the help of filter() in Python. Take value x and list of numbers as input from the user. input: 5, [1, 2, 3, 4, 5, 6, 7] output: [1] input: 5, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] output: [1, 9] """
filter_numbers
filtered_numbers = list(filter(lambda num: num ^ x == 4, numbers)) return filtered_numbers
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(5, [1, 2, 3, 4, 5, 6, 7]) == [1] assert candidate(3, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [7] assert candidate(2, [3, 6, 9, 12, 15, 18]) == [6] assert candidate(6, [0, 2, 4, 6, 8, 10]) == [2]
PythonSaga/17
from typing import Dict, List def patient_info(patient: Dict[str, List[float]]) -> List[Dict[str, float]]: """Take a dictionary of patient information as input and return a list of dictionaries where each dictionary contains the key as patient name and value as one of the attributes at a time. Do this using the map function. Take input from the user for the dictionary and return a list of dictionaries. Example: Input: {'patient1': [20, 50, 5.5, 20], 'patient2': [30, 60, 5.6, 21], 'patient3': [40, 70, 5.7, 22]} Output: [{'patient1': 20, 'patient2': 30 ,'patient3': 40}, {'patient1': 50, 'patient2': 60 ,'patient3': 70}, {'patient1': 5.5, 'patient2': 5.6 ,'patient3': 5.7}, {'patient1': 20, 'patient2': 21 ,'patient3': 22}]"""
patient_info
attributes = list(patient.values()) result = list(map(lambda attr: {key: value for key, value in zip(patient.keys(), attr)}, zip(*attributes))) return result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): input_data1 = {'patient1': [20, 50, 5.5, 20], 'patient2': [30, 60, 5.6, 21], 'patient3': [40, 70, 5.7, 22]} output1 = [{'patient1': 20, 'patient2': 30, 'patient3': 40}, {'patient1': 50, 'patient2': 60, 'patient3': 70}, {'patient1': 5.5, 'patient2': 5.6, 'patient3': 5.7}, {'patient1': 20, 'patient2': 21, 'patient3': 22}] input_data2 = {'patient1': [25, 55, 5.4, 25], 'patient2': [35, 65, 5.8, 23], 'patient3': [45, 75, 5.9, 24]} output2 = [{'patient1': 25, 'patient2': 35, 'patient3': 45}, {'patient1': 55, 'patient2': 65, 'patient3': 75}, {'patient1': 5.4, 'patient2': 5.8, 'patient3': 5.9}, {'patient1': 25, 'patient2': 23, 'patient3': 24}] input_data3 = {'patient1': [22, 52, 5.6, 22], 'patient2': [32, 62, 5.7, 20], 'patient3': [42, 72, 5.3, 21]} output3 = [{'patient1': 22, 'patient2': 32, 'patient3': 42}, {'patient1': 52, 'patient2': 62, 'patient3': 72}, {'patient1': 5.6, 'patient2': 5.7, 'patient3': 5.3}, {'patient1': 22, 'patient2': 20, 'patient3': 21}] input_data4 = {'patient1': [21, 51, 5.8, 23], 'patient2': [31, 61, 5.4, 22], 'patient3': [41, 71, 5.6, 25]} output4 = [{'patient1': 21, 'patient2': 31, 'patient3': 41}, {'patient1': 51, 'patient2': 61, 'patient3': 71}, {'patient1': 5.8, 'patient2': 5.4, 'patient3': 5.6}, {'patient1': 23, 'patient2': 22, 'patient3': 25}] assert candidate(input_data1) == output1 assert candidate(input_data2) == output2 assert candidate(input_data3) == output3 assert candidate(input_data4) == output4
PythonSaga/18
from typing import Dict, List def rank_students(students: Dict[str, int]) -> List[str]: """Take a dictionary of student names and their scores as input and return the rank of each student based on their score. Example: Input: {"Ankit": 92, "Bhavya": 78, "Charvi": 88} Output: ['Rank 1: Ankit scored 92', 'Rank 2: Charvi scored 88', 'Rank 3: Bhavya scored 78'] Do this using enumerate() function. Take input from the user for the dictionary and return the rank in form of list of strings."""
rank_students
sorted_students = sorted(students.items(), key=lambda x: x[1], reverse=True) result = [f"Rank {rank + 1}: {name} scored {score}" for rank, (name, score) in enumerate(sorted_students)] return result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): input_data1 = {"Ankit": 92, "Bhavya": 78, "Charvi": 88} output1 = ['Rank 1: Ankit scored 92', 'Rank 2: Charvi scored 88', 'Rank 3: Bhavya scored 78'] input_data2 = {"John": 85, "Alice": 90, "Bob": 78, "Eve": 92} output2 = ['Rank 1: Eve scored 92', 'Rank 2: Alice scored 90', 'Rank 3: John scored 85', 'Rank 4: Bob scored 78'] assert candidate(input_data1) == output1 assert candidate(input_data2) == output2
PythonSaga/19
def converter(num: int, choice: int) -> str: """I want to create converter which takes number with base 10 as input and ask user to select one of the 3 options: 1. Convert to binary 2. Convert to hexadecimal 3. Convert to octal write a code which takes input from user and convert it to binary, hexadecimal or octal based on user's choice. Example: Input: 1, 10 Output: 1010 Input: 2, 10 Output: A Input: 3, 10 Output: 12"""
converter
if choice == 1: return bin(num)[2:] elif choice == 2: return hex(num)[2:].upper() elif choice == 3: return oct(num)[2:] else: return 'Invalid choice. Please choose 1, 2, or 3.'
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert converter(10, 1) == '1010' assert converter(10, 2) == 'A' assert converter(10, 3) == '12' assert converter(111, 3) == '1101111'
PythonSaga/20
from typing import List def next_smallest(num:List[int]) -> List[int]: """let's say I have to show a trick to my friend. That there are numbers whose a digits can be read from left to right or right to left, the number remains the same. For example, 121 is such a number. If you read it from left to right, it's 121. If you read it from right to left, it's still 121. But Now he gave me some random number and asked me to tell what is the next possible smallest number which can do this trick. for example, if he gave 23544 then the next possible smallest number is 23632. Take input from user and return the next possible smallest number which can do the trick. Take input as a List of digits and return the number as list of digits. Example: Input: [2,3,5,4,4] Output: [2,3,6,3,2] Input: [1,2,2] Output: [1,3,1]"""
next_smallest
num_int = int(''.join(map(str, num))) # Check if the number is already a palindrome if str(num_int) == str(num_int)[::-1]: num_int += 1 while True: num_int += 1 # Convert the incremented number to a list of digits num_list = [int(digit) for digit in str(num_int)] # Check if the number is a palindrome when read from left to right if num_list == num_list[::-1]: return num_list
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate([2, 3, 5, 4, 4]) == [2, 3, 6, 3, 2] assert candidate([1, 2, 2]) == [1, 3, 1] assert candidate([9, 9, 9]) == [1, 0, 0, 1] assert candidate([0]) == [1]
PythonSaga/21
from typing import List def class_dict(teacher: List[str], student: List[str]) -> dict: """let's say I have to maintain dictionary for class. here first key will be class name and value will be whether it's teacher or student. if it is student value will be name of student and a key marks will be there which will have marks of student. if it is teacher value will be name of teacher and a key subject will be there which will have subject of teacher. it will be nested dictionary. example: {'class1':{ 'teacher': {'name': 'abc', 'subject': 'maths'}, 'student': {'name': 'xyz', 'marks': {'maths': 90, 'science': 80}, 'name': 'pqr', 'marks': {'maths': 80, 'science': 90}}}} Input: class name, teacher/student, name, subject/marks, subject/marks Output: dictionary Take input from user and return the dictionary. Input can be in form of list one for teacher and one for student with their respective details. Example: Input: ['class1', 'teacher', 'abc', 'maths'], ['class1', 'student', 'xyz', 'maths', 90, 'science', 80] Output: {'class1':{ 'teacher': {'name': 'abc', 'subject': 'maths'}, 'student': {'name': 'xyz', 'marks': {'maths': 90, 'science': 80}}}} Input: ['class1', 'teacher', 'xyz', 'maths'], ['class1', 'student', 'abc', 'maths', 90, 'science', 80] Output: {'class1':{ 'teacher': {'name': 'xyz', 'subject': 'maths'}, 'student': {'name': 'abc', 'marks': {'maths': 90, 'science': 80}}}}"""
class_dict
class_data = {} for t in teacher: class_name, role, name, subject = t[0], t[1], t[2], t[3] if class_name not in class_data: class_data[class_name] = {'teacher': {'name': '', 'subject': ''}, 'student': {}} if role == 'teacher': class_data[class_name]['teacher']['name'] = name class_data[class_name]['teacher']['subject'] = subject for s in student: class_name, role, name, *marks = s marks_dict = {marks[i]: marks[i + 1] for i in range(0, len(marks), 2)} if class_name not in class_data: class_data[class_name] = {'teacher': {'name': '', 'subject': ''}, 'student': {}} if role == 'student': class_data[class_name]['student'][name] = {'marks': marks_dict} return class_data
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): teacher_data_1 = [['class1', 'teacher', 'abc', 'maths']] student_data_1 = [['class1', 'student', 'xyz', 'maths', 90, 'science', 80]] assert candidate(teacher_data_1, student_data_1) == {'class1': {'teacher': {'name': 'abc', 'subject': 'maths'}, 'student': {'xyz': {'marks': {'maths': 90, 'science': 80}}}}} teacher_data_2 = [['class1', 'teacher', 'xyz', 'maths']] student_data_2 = [['class1', 'student', 'abc', 'maths', 90, 'science', 80]] assert candidate(teacher_data_2, student_data_2) == {'class1': {'teacher': {'name': 'xyz', 'subject': 'maths'}, 'student': {'abc': {'marks': {'maths': 90, 'science': 80}}}}} teacher_data_3 = [['class2', 'teacher', 'def', 'history']] student_data_3 = [['class2', 'student', 'uvw', 'history', 95, 'geography', 85]] assert candidate(teacher_data_3, student_data_3) == {'class2': {'teacher': {'name': 'def', 'subject': 'history'}, 'student': {'uvw': {'marks': {'history': 95, 'geography': 85}}}}} teacher_data_4 = [['class3', 'teacher', 'ghi', 'english'], ['class3', 'teacher', 'jkl', 'physics']] student_data_4 = [['class3', 'student', 'mno', 'english', 92, 'physics', 88]] assert candidate(teacher_data_4, student_data_4) == {'class3': {'teacher': {'name': 'jkl', 'subject': 'physics'}, 'student': {'mno': {'marks': {'english': 92, 'physics': 88}}}}}
PythonSaga/22
from typing import Tuple,Optional def new_sum(nested_tuple: Tuple[int, Optional[Tuple]]) -> int: """let's say I have a very bad habit of not using comments and I wrote something that my friend says is nested tuple. I have written a something whick looks like this: (5, (6, (1, (9, (10, None)))))) I want to do the following with each value, value1 + value2 - value3 + value4 - value5 and soo on. example: 5 + 6 - 1 + 9 - 10 = 9 Input: this nested tuple as a string from user. Output: the sum of the values in the nested tuple as shown above Example: Input: (5, (6, (1, (9, (10, None)))))) Output: 9 Input: (1, (2, (3, (4, (5, None)))))) Output: -1"""
new_sum
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate((5, (6, (1, (9, (10, None)))))) == 9 assert candidate((1, (2, (3, (4, (5, None)))))) == -1 assert candidate((10, (20, (30, (40, (50, None)))))) == -10 assert candidate((2, (4, (8, (16, (32, None)))))) == -18
PythonSaga/23
from typing import List def shoes_in_bag(bag: List[int]) -> int: """let's say I have a bag full of shoes n boxes of same and different shoe sizes. I want to sell them in market so I have to hire some labors to do the job. I want to to do in such a way that no two shoe sizes are same with one labour. what is the minimum number of labors I need to hire to do the job? example1 : bag = [1,2,3,3] , labour = {1,2,3} and {3} so minimum 2 labours are required OR {1,3} and {2,3} so minimum 2 labours are required example2 : bag = [2,4,5,6] , labour = {2,4,5,6} so minimum 1 labour is required Input: take input from user for size of shoe in form of list Output: print minimum number of labours required to do the job Take input from user for size of shoe in form of list and return the minimum number of labours required to do the job Example: Input: [1,2,3,3] Output: 2 Input: [2,4,5,6] Output: 1"""
shoes_in_bag
unique_sizes = set() labors_needed = 0 for size in bag: if size not in unique_sizes: unique_sizes.add(size) else: labors_needed += 1 unique_sizes.clear() unique_sizes.add(size) if unique_sizes: labors_needed += 1 return labors_needed
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate([1,2,3,3]) == 2 assert candidate([2,4,5,6,2,3,2]) == 3 assert candidate([1,2,3,4,5]) == 1 assert candidate([1,1,1,1,1]) == 5
PythonSaga/24
from typing import List def flower_arrangement(flowers: List[str], start: int = 0, end: int = None, result: List[List[str]] = None) -> List[List[str]]: """Let's say I have a 3 flowers which i have to lie on table in a row What are the all possible ways to arrange them. Input: Names of flowers from user Output: All possible ways to arrange them in a row Get the names of the flowers from the user and return list of lists of all possible ways to arrange them in a row Example: Input: [Rose, Lily, Jasmine] Output: [[Rose, Lily, Jasmine], [Rose, Jasmine, Lily], [Lily, Rose, Jasmine], [Lily, Jasmine, Rose], [Jasmine, Rose, Lily], [Jasmine, Lily, Rose]] Input: [Rose, Lily] Output: [[Rose, Lily], [Lily, Rose]]"""
flower_arrangement
if end is None: end = len(flowers) - 1 if result is None: result = [] if start == end: result.append(flowers.copy()) return result for i in range(start, end + 1): flowers[start], flowers[i] = flowers[i], flowers[start] flower_arrangement(flowers, start + 1, end, result) flowers[start], flowers[i] = flowers[i], flowers[start] return result
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(['Rose', 'Lily', 'Jasmine']) == [['Rose', 'Lily', 'Jasmine'], ['Rose', 'Jasmine', 'Lily'], ['Lily', 'Rose', 'Jasmine'], ['Lily', 'Jasmine', 'Rose'], ['Jasmine', 'Rose', 'Lily'], ['Jasmine', 'Lily', 'Rose']] assert candidate(['Rose', 'Lily']) == [['Rose', 'Lily'], ['Lily', 'Rose']] assert candidate(['Daisy', 'Tulip', 'Sunflower']) == [['Daisy', 'Tulip', 'Sunflower'], ['Daisy', 'Sunflower', 'Tulip'], ['Tulip', 'Daisy', 'Sunflower'], ['Tulip', 'Sunflower', 'Daisy'], ['Sunflower', 'Daisy', 'Tulip'], ['Sunflower', 'Tulip', 'Daisy']] assert candidate(['Orchid', 'Carnation', 'Daffodil']) == [['Orchid', 'Carnation', 'Daffodil'], ['Orchid', 'Daffodil', 'Carnation'], ['Carnation', 'Orchid', 'Daffodil'], ['Carnation', 'Daffodil', 'Orchid'], ['Daffodil', 'Orchid', 'Carnation'], ['Daffodil', 'Carnation', 'Orchid']]
PythonSaga/25
import cmath def phase(a: int, b: int) -> float: """I have a number which my teacher told is complex number. Now my teacher asked me to find phase of that number. He gave me one definition that "The angle or phase or argument of the complex number a + bj is the angle, measured in radians, from the point 1 + 0j to a + bj, with counterclockwise denoting positive angle." write a code to find phase of the complex number in radians. Take input from user in the form of a + bi and print the phase of the complex number. User will input a and b as integers. return float till 2 decimal places. Example: Input: -1, 0 Output: 3.14 Input: 2, 5 Output: 1.19"""
phase
complex_number = complex(a, b) phase_angle = cmath.phase(complex_number) return round(phase_angle, 2)
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(1, 0) == 0.0 assert candidate(-1, 0) == 3.14 assert candidate(0, 1) == 1.57 assert candidate(2, -2) == -0.79
PythonSaga/26
from typing import List def gate(gate_type: str, n: int, variables: List[int]) -> int: """My electronics professor was teaching us about and, or, not, xor, nand, nor gates. He said we given n variables x1, x2, x3, x4, x5, or more, 6 gates and, or, not, xor, nand, nor can be made. He asked us to make a program that will take the gate type and value of n and n variables as input and print the output. Take input from user for the gate type and value of n and n variables. Print the output based on the gate type. example: if gate type is and and n is 3 and variables are 1, 0, 1 then output will be 0. if gate type is or and n is 3 and variables are 1, 0, 1 then output will be 1. Input: "and", 3, [1, 0, 1] Output: 0 Input: "or", 3, [1, 0, 1] Output: 1 """
gate
if gate_type == "and": result = 1 # Initialize result with 1, as AND gate needs all inputs to be 1 for output to be 1. for variable in variables: result = result and variable elif gate_type == "or": result = 0 # Initialize result with 0, as OR gate needs at least one input to be 1 for output to be 1. for variable in variables: result = result or variable elif gate_type == "not": # NOT gate has only one input, so take the first variable and negate it. result = not variables[0] elif gate_type == "xor": # XOR gate output is 1 if the number of 1s in the inputs is odd. result = sum(variables) % 2 == 1 elif gate_type == "nand": # NAND gate is the opposite of AND gate. result = not gate("and", n, variables) elif gate_type == "nor": # NOR gate is the opposite of OR gate. result = not gate("or", n, variables) else: raise ValueError("Invalid gate type") return int(result)
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate("and", 3, [1, 0, 1]) == 0 assert candidate("or", 3, [1, 0, 1]) == 1 assert candidate("not", 1, [0]) == 1 assert candidate("xor", 4, [1, 0, 1, 1]) == 1
PythonSaga/27
def division(num: int, deno: int, float_num: float) -> list: """Take 2 number as input from user and return the float division of them till 2 decimals. If the second number is 0, return None. similarly take float number as input from user and return numerator and denominator of the fraction, return all such possible pair of numerator and denominator. Take input from user in for num, deno and float number. and return division of num and deno till 2 decimals. and return numerator and denominator of the float number. Example: Input: 2, 3 , 0.25 Output: [0.67 , 1 ,4] Input: 1,4, 0.67 Output: [0.25, 2, 3]"""
division
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(2, 3, 0.25) == [0.67, 1, 4] assert candidate(5, 2, 0.6) == [2.5, 3, 5] assert candidate(8, 4, 0.125) == [2.0, 1, 8] assert candidate(22, 7, 0.72) == [3.14, 18, 25]
PythonSaga/28
def check_alphabet(sentence: str) -> str: """My teacher gave me one sentence asked me to tell whether it's contains all the letters of the alphabet or not. So help me to write code which take input from user and tell whether it contains all the letters of the alphabet or not Example: The quick brown fox jumps over the lazy dog Output: It's does contain all the letters of the alphabet Example: The quick brown fox jumps over the dog Output: It's doesn't contain all the letters of the alphabet"""
check_alphabet
alphabet_set = set("abcdefghijklmnopqrstuvwxyz") sentence_set = set(sentence.lower().replace(" ", "")) if alphabet_set == sentence_set: return "It does contain all the letters of the alphabet." else: return "It doesn't contain all the letters of the alphabet."
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate("The quick brown fox jumps over the lazy dog") == "It does contain all the letters of the alphabet." assert candidate("The quick brown fox jumps over the dog") == "It doesn't contain all the letters of the alphabet." assert candidate("Pack my box with five dozen liquor jugs") == "It does contain all the letters of the alphabet." assert candidate("How razorback-jumping frogs can level six piqued gymnasts!") == "It doesn't contain all the letters of the alphabet."
PythonSaga/29
def card(color_or_number: str) -> str: """I have deck of cards, and i want to play game with my friend. My friend will pick one card and can only either tell me its color or its number. I have to predict probability of card of being that color or number in a deck of 52 cards. Take input as color or number from user and return probability of that color or number in deck of cards. Example : Input: red Output: probability of red color in deck of cards 50% Input: 1 Output: probability of 1 in deck of cards 7.69% Input: 2 Output: probability of 2 in deck of cards 7.69%"""
card
deck = {"red": ["Hearts", "Diamonds"], "black": ["Spades", "Clubs"]} numbers = list(map(str, range(1, 11))) + ["Jack", "Queen", "King", "Ace"] if color_or_number.isdigit() and 1 <= int(color_or_number) <= 10: number_prob = (4 / 52) * 100 return f"Probability of {color_or_number} in deck of cards: {number_prob:.2f}%" elif color_or_number.isdigit(): return "Invalid input. Please enter a number between 1 and 10." elif color_or_number.lower() in deck: color_prob = (1/2) * 100 return f"Probability of {color_or_number.lower()} color in deck of cards: {color_prob:.2f}%" else: return "Invalid input. Please enter a valid color or number."
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("red") == "Probability of red color in deck of cards: 50.00%" assert candidate("1") == "Probability of 1 in deck of cards: 7.69%" assert candidate("2") == "Probability of 2 in deck of cards: 7.69%" assert candidate("black") == "Probability of black color in deck of cards: 50.00%"
PythonSaga/30
from typing import List def TakeInput(marks: List[float], firstName: str, lastName: str, Class: str): """my teacher gave me ine statement which looks like this: HomeWork(12,17,16,15.5,14,firstName='James', lastName='Bond', Class='7th' ) Here 12,17,16,15.5,14 are marks scored by me in each subject. and firstName, lastName, Class are my personal details. She want me to write function HomeWork which take the given arguments and returns, and asked me to use args and kwargs. along with average marks scored by me in all subjects Output: Average Marks: 14.9 firstName is James lastName is Bond Class is 7th Take input from user for marks and personal details in function TakeInput() and pass the arguments to HomeWork() function. Example: Input: [12,17,16,15.5,14], firstName='James', lastName='Bond', Class='7th' Output: [14.9, 'James', 'Bond', '7th'] Input: [10,12,13,14,15], firstName='John', lastName='Doe', Class='8th' Output: [12.8, 'John', 'Doe', '8th']"
TakeInput
def HomeWork(*marks, **details): average_marks = sum(marks) / len(marks) result = [average_marks] for value in details.values(): result.append(value) return result def TakeInput(marks: List[float], firstName: str, lastName: str, Class: str): return HomeWork(*marks, firstName=firstName, lastName=lastName, Class=Class)
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([12, 17, 16, 15.5, 14], firstName='James', lastName='Bond', Class='7th') == [14.9, 'James', 'Bond', '7th'] assert candidate([10, 12, 13, 14, 15], firstName='John', lastName='Doe', Class='8th') == [12.8, 'John', 'Doe', '8th'] assert candidate([0, 12, 13, -1, 15], firstName='Rik', lastName='ho', Class='11th') == [7.8, 'Rik', 'ho', '11th'] assert candidate([170, 22, 55, -20, -90], firstName='Modi', lastName='Ji', Class='8th') == [27.4, 'Modi', 'Ji', '8th']
PythonSaga/31
import math def Multiple_ques(frac: str, num: int, pal: str = None, string: str = None, prime: str = None, num2: int = None): """I have 3 students, each ask me different questions. I want to answer them all in one function. 1st student always ask me factorial of a number 2nd student always ask me to check palindrome of a string 3rd student always ask me to check if a number is prime or not but it is not necessary that each of them will always ask me a question. So write me a function which will take a question and a number as input and return the answer. Take input from user for question and number and return the answer. Example: Input: "factorial", 5, "palindrome", "madam", "prime", 7 Output: ["The factorial of 5 is 120", "The string madam is a palindrome", "7 is a prime number"] Input: "factorial", 5, "palindrome", "madam" Output: ["The factorial of 5 is 120", "The string madam is a palindrome"] Input: "factorial", 5, "prime", 7 Output: ["The factorial of 5 is 120", "7 is a prime number"] """
Multiple_ques
def factorial(num): return math.factorial(num) def is_palindrome(string): return string == string[::-1] def is_prime(num): if num < 2: return False for i in range(2, int(math.sqrt(num)) + 1): if num % i == 0: return False return True def Multiple_ques(frac: str=None, num: int=None, pal: str = None, string: str = None, prime: str = None, num2: int = None): answers = [] if frac == "factorial": answers.append(f"The factorial of {num} is {factorial(num)}") if pal == "palindrome" and string is not None: answers.append(f"The string {string} is {'a' if is_palindrome(string) else 'not a'} palindrome") if prime == "prime" and num2 is not None: answers.append(f"{num2} {'is' if is_prime(num2) else 'is not'} a prime number") return answers
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("factorial", 5, "palindrome", "madam", "prime", 7) == [ "The factorial of 5 is 120", "The string madam is a palindrome", "7 is a prime number" ] assert candidate("factorial", 5, "palindrome", "madam") == [ "The factorial of 5 is 120", "The string madam is a palindrome" ] assert candidate("factorial", 5, "prime", 7) == [ "The factorial of 5 is 120", "7 is a prime number" ]
PythonSaga/32
def numbers(num:int): """my teacher gave me so a list of numbers and asked me to convert it alpabetic words. example: 123 -> one hundred twenty three 456 -> four hundred fifty six 1001 -> one thousand one Fortunately, I have a list of numbers which are between 1 to 9999. Write a function to convert the numbers to words. If number is between 1 to 100 write one function and if it is between 100 to 9999 write another function. Take the input from the user and call the function accordingly. Example: 123 -> one hundred twenty three 456 -> four hundred fifty six 8989 -> eight thousand nine hundred eighty nine"""
numbers
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(123) == "one hundred twenty three" assert candidate(456) == "four hundred fifty six" assert candidate(8989) == "eight thousand nine hundred eighty nine" assert candidate(1001) == "one thousand one"
PythonSaga/33
from datetime import datetime def date_subtract(date: str, days: int): """My friend says he can tell any date in past given the days we want to subtract to the current date. I also want to have this super power. Can you help me to write a function which takes a date and the number of days to subtract and return the date in the past. Maximum number of days to subtract is 10000. and tell whether that year is a leap year or not. Take the current date as input in the format: YYYY-MM-DD and the number of days to subtract from the user and return the date in the past along with whether that year is a leap year or not. Example: Input: 2020-02-29, 365 Output: 2019-02-28, 2019 is not a leap year Input: 2023-12-16, 1 Output: 2023-12-15, 2023 is not a leap year """
date_subtract
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("2020-02-29", 365) == ("2019-03-01", "2019 is not a leap year") assert candidate("2023-12-16", 1) == ("2023-12-15", "2023 is not a leap year") assert candidate("2022-01-01", 10000) == ("1994-08-16", "1997 is not a leap year") assert candidate("2000-02-29", 7300) == ("1980-03-05", "1980 is a leap year")
PythonSaga/34
import math def InputFunc(shape: str, action: str, *args): """Let's say I'm working with some school student and I want to teach him about different geometric shapes. I have few shapes i.e cube, cuboid, sphere, cylinder and cone. Write a code that asks user to enter the name of the shape. then ask whether user want to calculate surface area or volume of the shape. Accordingly ask dimensions of the shape and calculate the surface area or volume of the shape. for example: if user enters cube and surface area, then ask for side of cube and calculate surface area of cube. if user enters cone and volume, then ask for radius and height of cone and calculate volume of cone. Here are guidelines to write a code: create individual functions for each shape. Take input from user for shape , surface area or volume and dimensions of the shape and return the result up to 2 decimal places. Example: Input: "cube", "surface area", 5 Output: 150 Input: "cone", "volume", 5, 10 # Radius followed by height Output: 261.8"""
InputFunc
import math def InputFunc(shape: str, action: str, *args): shape = shape.lower() action = action.lower() if shape == "cube": if action == "surface area": return cube_surface_area(*args) elif action == "volume": return cube_volume(*args) elif shape == "cuboid": if action == "surface area": return cuboid_surface_area(*args) elif action == "volume": return cuboid_volume(*args) elif shape == "sphere": if action == "surface area": return sphere_surface_area(*args) elif action == "volume": return sphere_volume(*args) elif shape == "cylinder": if action == "surface area": return cylinder_surface_area(*args) elif action == "volume": return cylinder_volume(*args) elif shape == "cone": if action == "surface area": return cone_surface_area(*args) elif action == "volume": return cone_volume(*args) return "Invalid shape or action"
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("cube", "surface area", 5) == 150.0 assert candidate("cone", "volume", 5, 10) == 261.8 # assert candidate("cuboid", "surface area", 3, 4, 5) == 94.0 assert candidate("sphere", "volume", 2) == 33.51 assert candidate("cylinder", "surface area", 3, 6) == 150.8
PythonSaga/35
import math from typing import List def operation(work: List[str]) -> float: """Nowadays, I'm working a lot in maths and I want to calculate exp and log of a number a lot. Write a function that asks the operation to be performed and the number on which the operation is to be performed. There can be multiple entries for operation. Try to use the math library for this. Take input from the user and return the result up to 2 decimal places. Example: Input: ['exp', 10] Output: 22026.47 Input: ['log', 10, 100] Output: 2"""
operation
if len(work) < 2: return "Insufficient input. Please provide the operation and at least one number." operation_type = work[0].lower() if operation_type not in ['exp', 'log']: return "Invalid operation. Please choose 'exp' or 'log'." if operation_type == 'exp' and len(work) == 2: # Calculate exponential result = math.exp(work[1]) elif operation_type == 'log' and len(work) == 3: # Calculate logarithm base, x = work[1], work[2] result = math.log(x, base) else: return "Invalid input. Please provide the correct number of arguments for the selected operation." return round(result, 2)
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(['exp', 10]) == 22026.47 assert candidate(['log', 10, 100]) == 2.0 assert candidate(['exp', -1]) == 0.37 assert candidate(['log', 2, 10001]) == 9.97
PythonSaga/36
import pickle from typing import List def database(data: List[List[str]]) -> dict: """Take entry from the user Key: Ankit name: Ankit Yadav age: 21 city: Delhi Similarly take input from other users And store the information in a dictionary. later create a database dictionary and store all the information in that dictionary. with the key as the user name and value as a dictionary containing information about the user. later create a dbfile and store the dictionary in that file using binary mode Use the pickle module to store and retrieve the data. Finally, print the data from the database. Example: Input: [['Ankit', 'Ankit Yadav', '21', 'Delhi'], ['Amit', 'Amit Kumar', '21', 'Delhi']] Output: {'Ankit': {'name': 'Ankit Yadav', 'age': 21, 'city': 'Delhi'}, 'Amit': {'name': 'Amit Kumar', 'age': 21, 'city': 'Delhi'}}"""
database
db_dict = {} # Iterate through input data and create dictionary entries for entry in data: if len(entry) == 4: username, name, age, city = entry db_dict[username] = {'name': name, 'age': int(age), 'city': city} else: print(f"Invalid entry: {entry}. Each user entry should have exactly 4 elements.") # Store the dictionary in a binary file using pickle with open('dbfile.pkl', 'wb') as file: pickle.dump(db_dict, file) return db_dict
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): input_1 = [['Ank', 'Ank Ya', '21', 'Delhi'], ['Amit', 'Amit Kumar', '21', 'Delhi']] result_1 = candidate(input_1) assert result_1 == {'Ank': {'name': 'Ank Ya', 'age': 21, 'city': 'Delhi'}, 'Amit': {'name': 'Amit Kumar', 'age': 21, 'city': 'Delhi'}} input_2 = [['John', 'John Doe', '25', 'New York'], ['Mary', 'Mary Johnson', '30', 'Los Angeles']] result_2 = candidate(input_2) assert result_2 == {'John': {'name': 'John Doe', 'age': 25, 'city': 'New York'}, 'Mary': {'name': 'Mary Johnson', 'age': 30, 'city': 'Los Angeles'}} input_4 = [['Alice', 'Alice Smith', '28', 'London'], ['Bob', 'Bob Brown', '32', 'Paris', 'ExtraField']] result_4 = candidate(input_4) assert result_4 == {'Alice': {'name': 'Alice Smith', 'age': 28, 'city': 'London'}, 'Bob': {'name': 'Bob Brown', 'age': 32, 'city': 'Paris'}}
PythonSaga/37
import re def password_generator(password: str) -> str: """I want to write a function to create a password using the following rules: At least 1 letter between [a-z] At least 1 number between [0-9] At least 1 letter between [A-Z] At least 1 character from [$#@] Minimum length of transaction password: 8 Also write a function to check if the password is valid or not using regular expressions. Example : Input : "Geek12#" Output : Invalid Password! Input : "Geek12#@" Output : Valid Password Input : "Annnnnnnnnn" Output : Invalid Password!"""
password_generator
# Check if the password meets the required criteria if len(password) < 8: return "Invalid Password!" if not re.search("[a-z]", password): return "Invalid Password!" if not re.search("[0-9]", password): return "Invalid Password!" if not re.search("[A-Z]", password): return "Invalid Password!" if not re.search("[$#@]", password): return "Invalid Password!" return "Valid Password"
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("Geek12#") == "Invalid Password!" assert candidate("Geek12#@") == "Valid Password" assert candidate("Annnnnnnnnn") == "Invalid Password!" assert candidate("StrongPwd123#") == "Valid Password" assert candidate("abc123") == "Invalid Password!"
PythonSaga/38
import datetime from typing import List def calculate_interest(input_list: List) -> str: """i have to calculate interest on a given amount on per day basis. Write a functions which takes amount, rate of interest , starting date and end date as input and returns the interest amount and number of days. Use datetime module to calculate the number of days. Example: Input: [10000, 5, "2020-01-01", "2020-01-10"] Output: Interest amount is 5000.0 and number of days is 10 Input: [100, 10, "2020-01-01", "2020-01-30"] Output: Interest amount is 300.0 and number of days is 30"""
calculate_interest
try: # Extract input values amount, rate_of_interest, start_date_str, end_date_str = input_list # Convert date strings to datetime objects start_date = datetime.strptime(start_date_str, "%Y-%m-%d") end_date = datetime.strptime(end_date_str, "%Y-%m-%d") # Calculate the number of days num_days = (end_date - start_date).days + 1 # Calculate interest amount interest_amount = (amount * rate_of_interest / 100) * (num_days) return f"Interest amount is {interest_amount:.2f} and number of days is {num_days}" except ValueError: return "Invalid date format. Please use YYYY-MM-DD." except Exception as e: return f"Error: {str(e)}"
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([10000, 5, "2020-01-01", "2020-01-10"]) == "Interest amount is 500.00 and number of days is 10" assert candidate([100, 10, "2020-01-01", "2020-01-30"]) == "Interest amount is 300.00 and number of days is 30" assert candidate([5000, 8, "2022-03-15", "2022-04-15"]) == "Interest amount is 12800.00 and number of days is 32" assert candidate([1500, 12, "2021-08-01", "2021-08-10"]) == "Interest amount is 1800.00 and number of days is 10"
PythonSaga/39
from typing import List import statistics def calculate_stats(input_list: List) -> List: """I want to see the magic of statistics. Write a code to take n number from user and return following statistics. 1. mean 2. harmonic mean 3. median 4. Low median 5. high median 6. Median grouped 7. mode 8. pvariance 9. variance 10. pstdev 11. stdev Use statistics module for this. return upto 2 decimal places. Example: Input: [1,2,3,4,5] Output: [3.0, 2.19, 3, 2, 4, 3.0, 1, 2.5, 2.5, 1.58, 1.58]"""
calculate_stats
try: # Calculate various statistics using the statistics module mean = round(statistics.mean(input_list), 2) harmonic_mean = round(statistics.harmonic_mean(input_list), 2) median = round(statistics.median(input_list), 2) low_median = round(statistics.median_low(input_list), 2) high_median = round(statistics.median_high(input_list), 2) median_grouped = round(statistics.median_grouped(input_list), 2) mode = round(statistics.mode(input_list), 2) pvariance = round(statistics.pvariance(input_list), 2) variance = round(statistics.variance(input_list), 2) pstdev = round(statistics.pstdev(input_list), 2) stdev = round(statistics.stdev(input_list), 2) # Return the calculated statistics return [mean, harmonic_mean, median, low_median, high_median, median_grouped, mode, pvariance, variance, pstdev, stdev] except Exception as e: return f"Error: {str(e)}"
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([1, 2, 3, 4, 5]) == [3.0, 2.19, 3, 2, 4, 3.0, 1, 2.5, 2.5, 1.58, 1.58] assert candidate([10, 20, 30, 40, 50]) == [30, 21.9, 30, 30, 30, 30.0, 10, 200, 250, 14.14, 15.81] assert candidate([2, 4, 6, 8, 10]) == [6, 4.38, 6, 6, 6, 6.0, 2, 8, 10, 2.83, 3.16] assert candidate([5, 15, 25, 35, 45]) == [25, 13.99, 25, 25, 25, 25.0, 5, 200, 250, 14.14, 15.81]
PythonSaga/40
def peter_picked(input_string: str) -> bool: """User wants to give a long string, Find whether word Peter and picked came equally number of times or not If yes, print "True", else print "False" Take string as input from user example: Input: "Peter picked a peck of pickled peppers. A peck of pickled peppers Peter picked. If Peter picked a peck of pickled peppers, Where's the peck of pickled peppers Peter picked?" Output: True Input: "Peter Piper picked a peck of pickled peppers. A peck of pickled peppers Peter Piper picked. Out: False"""
peter_picked
# Convert the input string to lowercase for case-insensitive comparison lower_input = input_string.lower() # Count the occurrences of "peter" and "picked" count_peter = lower_input.count("peter") count_picked = lower_input.count("picked") # Check if the counts are equal return count_peter == count_picked
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("Peter picked a peck of pickled peppers. A peck of pickled peppers Peter picked. If Peter picked a peck of pickled peppers, Where's the peck of pickled peppers Peter picked?") == True assert candidate("Peter Piper picked a peck of pickled peppers. A peck of pickled peppers Peter Piper picked.") == True assert candidate("Peter picked a peck of pickled peppers, and then Peter picked some more.") == True assert candidate("Picked peppers Peter picked, but Pet didn't pick any more peppers.") == False
PythonSaga/41
from typing import List def student_marks(input_list: List[List[str]]) -> List[str]: """ Given a list of some students in a list and their corresponding marks in another list. The task is to do some operations as described below: a. i key value: Inserts key and value in the dictionary, and print 'Inserted'. b. d key: Delete the entry for a given key and print 'Deleted' if the key to be deleted is present, else print '-1'. c. key: Print marks of a given key in a statement as "Marks of student name is : marks". Take input from user and perform the operations accordingly. Example: Input: [[i, anil, 20], [i, ram, 30], [d, ankit], [p, ram]] Output: ['Inserted', 'Inserted', 'Deleted', 'Marks of ram is : 30'] Input: [[i,jhon, 1],[c, jack],[p, jhon]] Output: ['Inserted', '-1', 'Marks of jhon is : 1'] """
student_marks
student_dict = {} result = [] for operation, *args in input_list: if operation == 'i': key, value = args student_dict[key] = int(value) result.append('Inserted') elif operation == 'd': key, = args if key in student_dict: del student_dict[key] result.append('Deleted') else: result.append('-1') elif operation == 'p': key, = args if key in student_dict: result.append(f'Marks of {key} is : {student_dict[key]}') else: result.append('-1') return result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): input_1 = [['i', 'anil', '20'], ['i', 'ram', '30'], ['d', 'anil'], ['p', 'ram']] assert candidate(input_1) == ['Inserted', 'Inserted', 'Deleted', 'Marks of ram is : 30'] input_2 = [['i', 'jhon', '1'], ['c', 'jack'], ['p', 'jhon']] assert candidate(input_2) == ['Inserted', '-1', 'Marks of jhon is : 1'] input_3 = [['i', 'alice', '25'], ['i', 'bob', '35'], ['i', 'alice', '40'], ['p', 'bob'], ['d', 'charlie'], ['p', 'charlie']] assert candidate(input_3) == ['Inserted', 'Inserted', 'Inserted', 'Marks of bob is : 35', '-1', '-1'] input_4 = [['i', 'amy', '50'], ['i', 'dan', '60'], ['d', 'amy'], ['p', 'amy']] assert candidate(input_4) == ['Inserted', 'Inserted', 'Deleted', '-1']
PythonSaga/42
from typing import List def common_elements(input_list: List[List[int]]) -> List[List[int]]: """Given some elements in two sets a and b, the task is to find the elements common in two sets, elements in both the sets, elements that are only in set a, not in b. Take input from user for two sets in form of list and print the output in form of list. Example: Input: [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]] Output: [2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1] Input: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] Output: [[],[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5]]"""
common_elements
set_a, set_b = set(input_list[0]), set(input_list[1]) common_in_both = list(set_a.intersection(set_b)) elements_in_both = list(set_a.union(set_b)) elements_only_in_a = list(set_a.difference(set_b)) return [common_in_both, elements_in_both, elements_only_in_a]
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): input_1 = [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]] assert candidate(input_1) == [[2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1]] input_2 = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] assert candidate(input_2) == [[], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5]] input_3 = [[3, 6, 9, 12], [2, 4, 6, 8, 10, 12]] assert candidate(input_3) == [[6, 12], [2, 3, 4, 6, 8, 9, 10, 12], [3, 9]] input_4 = [[5, 10, 15, 20], [25, 30, 35, 40]] assert candidate(input_4) == [[], [5, 10, 15, 20, 25, 30, 35, 40], [5, 10, 15, 20]]
PythonSaga/43
from typing import List def triangle(input_string: str) -> List[str]: """Given a string of a constant length, print a triangle out of it. The triangle should start with the given string and keeps shrinking downwards by removing one character from the last of the string. The spaces on the right side of the triangle should be replaced with ' character. Take string as input from the user, return output as list of strings. Example: Input: 'Hello' Output: ['Hello', "Hell'", "Hel''", "He'''", "H''''"] Input: 'World' Output: ['World', "Worl'", "Wor''", "Wo'''", "W''''"]"""
triangle
length = len(input_string) result = [] for i in range(length, 0, -1): triangle_line = input_string[:i].ljust(length, "'") result.append(triangle_line) return result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): input_1 = 'Hello' assert candidate(input_1) == ['Hello', "Hell'", "Hel''", "He'''", "H''''"] input_2 = 'World' assert candidate(input_2) == ['World', "Worl'", "Wor''", "Wo'''", "W''''"] input_3 = 'Python' assert candidate(input_3) == ['Python', "Pytho'", "Pyth''", "Pyt'''", "Py''''", "P'''''"] input_4 = 'Triangle' assert candidate(input_4) == ['Triangle', "Triangl'", "Triang''", "Trian'''", "Tria''''", "Tri'''''", "Tr''''''", "T''''''']
PythonSaga/44
from typing import List def Y_pattern(N: int) -> List[str]: """Print a Y shaped pattern from '(',')' and '|' in N number of lines. Note: 1. N is even. 2. All the strings in the string array which you will return is of length N, so add the spaces wherever required, so that the length of every string becomes N. Take N as input from the user. and return the list of strings. Example: Input: 6 Output: ['\ /', ' \ /', ' \/ ', ' | ', ' | ', ' | '] Input: 8 Output: ['\ /', ' \ /', ' \ /', ' \/ ', ' | ', ' | ', ' | ', ' | ']"""
Y_pattern
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1 input_1 = 6 assert candidate(input_1) == ['\ /', ' \ / ', ' \/ ', ' | ', ' | ', ' | '] # Test Case 2 input_2 = 8 assert candidate(input_2) == ['\ /', ' \ / ', ' \ / ', ' \/ ', ' | ', ' | ', ' | ', ' | '] # Test Case 3 input_3 = 4 assert candidate(input_3) == ['\ /', ' \/ ', ' | ', ' | '] # Test Case 4 input_4 = 10 assert candidate(input_4) == ['\ /', ' \ / ', ' \ / ', ' \ / ', ' \/ ', ' | ', ' | ', ' | ', ' | ', ' | ']
PythonSaga/45
from typing import List def encrypt(n: int, lines: List[str], shift: int) -> List[str]: """You are assigned the task of developing a Python program that enables users to input multiple text strings. These input strings will be written to a file named 'user_input.txt.' After gathering all the input lines in the file, your program should extract the first two characters from the beginning of each paragraph and encrypt them using the Caesar cipher method. In Caesar cipher you have to just shift the character by the given shift value. for example : your string is 'Abc' and shift value is 2 then A->C, b->d and c->e. final encrypted string will be 'Cde'. You have to take two user input first is n line of string (each line you have to write in file name 'user_input.txt') , and second is integer shift (number of shift). Input will be in format of list of string and integer. Output will be encrypted string. Example: Input: 3, ['The restoring of the board is for two weeks.', 'Board officials said Silva was due to return to work.', 'Silva was due to return to work.'],4 Output: ['The file is created with name user_input.txt', 'The encrypted string is: XlFsWm']"""
encrypt
with open('user_input.txt', 'w') as file: file.write('\n'.join(lines)) # Read the contents of the file with open('user_input.txt', 'r') as file: contents = file.read() # Encrypt the first two characters of each paragraph using Caesar cipher encrypted_lines = [] for paragraph in contents.split('\n'): if len(paragraph) >= 2: encrypted_paragraph = ''.join([ chr((ord(char) - ord('A' if char.isupper() else 'a') + shift) % 26 + ord('A' if char.isupper() else 'a')) if char.isalpha() else char for char in paragraph[:2] ]) encrypted_lines.append(encrypted_paragraph) # Add additional information to the result list result = [ f'The file is created with name user_input.txt', f'The encrypted string is: {"".join(encrypted_lines)}' ] return result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1 n_1 = 3 lines_1 = [ "The restoring of the board is for two weeks.", "Board officials said Silva was due to return to work.", "Silva was due to return to work." ] shift_1 = 4 assert candidate(n_1, lines_1, shift_1) == [ 'The file is created with name user_input.txt', 'The encrypted string is: XlFsWm' ] # Test Case 2 n_2 = 2 lines_2 = [ "Sample input line one.", "Second sample input line." ] shift_2 = 2 assert candidate(n_2, lines_2, shift_2) == [ 'The file is created with name user_input.txt', 'The encrypted string is: UcUg' ] # Test Case 3 n_3 = 4 lines_3 = [ "Testing with multiple lines.", "Another line for testing.", "Third line to check functionality.", "Last line in this test." ] shift_3 = 3 assert candidate(n_3, lines_3, shift_3) == [ 'The file is created with name user_input.txt', 'The encrypted string is: WhDqWkOd' ] # Test Case 4 n_4 = 2 lines_4 = [ "AbCdeFgHiJklMnOpQrStUvWxYz", "XYZabcDEFGHIJKLMNOPQRSTUVW" ] shift_4 = 5 assert candidate(n_4, lines_4, shift_4) == [ 'The file is created with name user_input.txt', 'The encrypted string is: FgCd' ]
PythonSaga/46
from typing import List def count_words(lines: List[str]) -> str: """Your task is to create a Python program that allows users to input multiple text strings. These input strings will be written to a file named 'user_input.txt.' After saving all the input lines in the file, your program should count the number of words in the file. In this version, a word is defined as a sequence of characters separated by spaces, and punctuation marks and symbols are included in the word count. Take input from user and reuturn the count of words in the input along with the file name Input will be in list of strings Example: Input: ['Hello i am programmer. I like python. I Love India .'] Output: Number of words in the file user_input.txt is 11 Input: ['All in the village were happy. They got a new TV !!!'] Output: Number of words in the file user_input.txt is 12"""
count_words
with open('user_input.txt', 'w') as file: file.write('\n'.join(lines)) # Read the contents of the file with open('user_input.txt', 'r') as file: contents = file.read() # Count the number of words in the file words = contents.split() word_count = len(words) return f'Number of words in the file user_input.txt is {word_count}'
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1 input_1 = ['Hello i am programmer. I like python. I Love India .'] assert candidate(input_1) == 'Number of words in the file user_input.txt is 11' # Test Case 2 input_2 = ['All in the village were happy. They got a new TV !!!'] assert candidate(input_2) == 'Number of words in the file user_input.txt is 12' # Test Case 3 input_3 = ['This is a simple test case with a few words.'] assert candidate(input_3) == 'Number of words in the file user_input.txt is 10' # Test Case 4 input_4 = ['123 456 789'] assert candidate(input_4) == 'Number of words in the file user_input.txt is 3'
PythonSaga/47
from typing import List def count_words(n:int,lines: List[str],k:str) -> List[str]: """Write a Python program that processes a series of text inputs and analyzes them for words containing a specific number of lowercase consonants. You have to return list of unique words that satisfy the given condition. For Example :- file content is 'Hello I am Jone' and k=2 then final answer list should be ['Hello'] Because only word 'Hello' contains 2 lowercase consonant. Accepts the user input for the number of lines and allows the user to input strings for the specified number of lines. The program should write these strings to a file named 'user_input.txt' Reads the contents of 'user_input.txt' analyzes each word, and outputs a list of words that contain exactly k lowercase consonants. Input would be in form of list of strings and k is an integer. Example: Input: 3, ['Hello I am Jone.', 'I like programming.', 'IIT Gandhinagar.'], 2 Output: ['Hello', 'like'] Input: 2, ['out of all the places in the world', 'i love india'], 2 Output: ['out', 'all', 'the', 'love', 'india']"""
count_words
# Write user input lines to the file with open('user_input.txt', 'w') as file: file.write('\n'.join(lines)) # Read the contents of the file with open('user_input.txt', 'r') as file: contents = file.read() # Process each word and filter based on the number of lowercase consonants words = contents.split() valid_words = [word for word in words if sum(1 for char in word if char.islower() and char not in 'aeiou') == k] return valid_words
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1 n_1 = 3 lines_1 = ['Hello I am Jone.', 'I like programming.', 'IIT Gandhinagar.'] k_1 = 2 assert candidate(n_1, lines_1, k_1) == ['Hello', 'like'] # Test Case 2 n_2 = 2 lines_2 = ['out of all the places in the world', 'i love india'] k_2 = 2 assert candidate(n_2, lines_2, k_2) == ['out', 'all', 'the', 'love', 'india'] # Test Case 3 n_3 = 3 lines_3 = ['Pytho programming is fun.', 'AI and machine learning.', 'OpenAI is innovative.'] k_3 = 3 assert candidate(n_3, lines_3, k_3) == ['Pytho'] # Test Case 4 n_4 = 2 lines_4 = ['Testing with some random words.', 'Check for various situations.'] k_4 = 1 assert candidate(n_4, lines_4, k_4) == ['some', 'for']
PythonSaga/48
from typing import List from typing import Dict def merge_data(data: List[List[str]]) -> List[Dict[str, str]]: """You are tasked with processing student data provided by user. The file contains multiple entries for different subjects of each students, including Id, Student Name, Subject, and Marks. Write a Python program that reads the data from from input and merges it based on the following rules: For each unique student (identified by Roll number), consolidate their information. Combine the subjects and calculate the total marks for each student, avoiding duplicate subjects. After processing the data, save the file with name is students_data.txt with the formatted student information. The output should display the formatted contents of the updated file. Take input in form of list of list of strings. and return the list of dictionary. Example: Input: [[103, 'Maria', 'Physics', 50], [102, 'Hina', 'Math', 30], [104, 'Alex', 'Chemistry', 45], [101, 'Santosh', 'Biology', 20], [104, 'Alex', 'History', 38], [103, 'Maria', 'Chemistry', 35], [101, 'Santosh', 'Biology', 20], [101, 'Santosh', 'Biology', 20], [104, 'Alex', 'Chemistry', 45], [104, 'Alex', 'History', 38]] Output: file saved is students_data.txt, [{'Id':103,'Name': Maria,'Subject':[' Physics', ' Chemistry'],'TotalMarks': 85}, {'Id':102,'Name': Hina,'Subject':[' Math'],'TotalMarks': 30}, {'Id':104,'Name': Alex,'Subject':[' Chemistry', ' History'],'TotalMarks': 83}, {'Id':101,'Name': Santosh,'Subject':[' Biology'],'TotalMarks': 20}] """
merge_data
student_dict = {} # Process the data and merge information for each student for entry in data: roll_number, name, subject, marks = entry roll_number = int(roll_number) if roll_number not in student_dict: student_dict[roll_number] = {'Id': roll_number, 'Name': name, 'Subject': set(), 'TotalMarks': 0} # Avoid duplicate subjects for the same student if subject not in student_dict[roll_number]['Subject']: student_dict[roll_number]['Subject'].add(subject) student_dict[roll_number]['TotalMarks'] += int(marks) # Convert the dictionary values to a list of dictionaries result = list(student_dict.values()) # Save the file with formatted student information with open('students_data.txt', 'w') as file: for student_info in result: file.write(f"{student_info}\n") return result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 2 input_2 = [ [101, 'John', 'Math', 75], [102, 'Jane', 'Physics', 90], [103, 'Bob', 'Chemistry', 80], [101, 'John', 'Biology', 60], [102, 'Jane', 'Math', 85], [103, 'Bob', 'Physics', 92] ] assert candidate(input_2) == [ {'Id': 101, 'Name': 'John', 'Subject': {' Math', ' Biology'}, 'TotalMarks': 135}, {'Id': 102, 'Name': 'Jane', 'Subject': {' Physics', ' Math'}, 'TotalMarks': 175}, {'Id': 103, 'Name': 'Bob', 'Subject': {' Chemistry', ' Physics'}, 'TotalMarks': 172} ] # Test Case 3 input_3 = [ [201, 'Alice', 'English', 85], [202, 'Bob', 'History', 78], [203, 'Charlie', 'Math', 92], [201, 'Alice', 'Biology', 70], [202, 'Bob', 'English', 88], [203, 'Charlie', 'History', 80] ] assert candidate(input_3) == [ {'Id': 201, 'Name': 'Alice', 'Subject': {' English', ' Biology'}, 'TotalMarks': 155}, {'Id': 202, 'Name': 'Bob', 'Subject': {' History', ' English'}, 'TotalMarks': 166}, {'Id': 203, 'Name': 'Charlie', 'Subject': {' Math', ' History'}, 'TotalMarks': 172} ] # Test Case 4 input_4 = [ [301, 'David', 'Physics', 95], [302, 'Eva', 'Chemistry', 88], [303, 'Frank', 'Biology', 75], [301, 'David', 'Math', 85], [302, 'Eva', 'Math', 92], [303, 'Frank', 'Physics', 80] ] assert candidate(input_4) == [ {'Id': 301, 'Name': 'David', 'Subject': {' Physics', ' Math'}, 'TotalMarks': 180}, {'Id': 302, 'Name': 'Eva', 'Subject': {' Chemistry', ' Math'}, 'TotalMarks': 180}, {'Id': 303, 'Name': 'Frank', 'Subject': {' Biology', ' Physics'}, 'TotalMarks': 155} ]
PythonSaga/49
from typing import List, Dict def word_frequency(n:int,lines: List[str], k: int) -> Dict[str, int]: """Write a Python program for managing word frequency in a text file. The program should first prompt the user to input a specified number of lines, and these lines are then saved to a text file named text_file.txt The user is then prompted to input an integer representing the frequency threshold (k). Subsequently, the program reads the contents of this file, creating a dictionary that tracks the frequency of each word. The program should remove words from the file that occur more than k times and update the file accordingly. Finally, the program displays the initial word count dictionary and the total number of words in the updated file. Input will be in form of a list of strings, where each string represents a line of text. Output will be a dictionary containing the frequency of each word in the file, and the total number of words in the updated file. Example: Input: 3,["Hello can you help me","you are doing well. How can I help you.","can you help me ? I think you dont want to help me"],2 Output: {'Hello': 1, 'can': 3, 'you': 4, 'help': 4, 'me': 3, 'are': 1, 'doing': 1, 'well.': 1, 'How': 1, 'I': 2, 'you.': 1, '?': 1, 'think': 1, 'dont': 1, 'want': 1, 'to': 1},13 Input: 4,["Hello how are you","What is updates","how you will do this work","you have any idea"],2 Output: {'Hello': 1, 'how': 2, 'are': 1, 'you': 3, 'What': 1, 'is': 1, 'updates': 1, 'will': 1, 'do': 1, 'this': 1, 'work': 1, 'have': 1, 'any': 1, 'idea': 1},14"""
word_frequency
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): # Test Case 1 input_1 = 3, ["Hello can you help me", "you are doing well. How can I help you.", "can you help me ? I think you dont want to help me"], 2 assert candidate(*input_1) == ( {'Hello': 1, 'can': 3, 'you': 4, 'help': 4, 'me': 3, 'are': 1, 'doing': 1, 'well.': 1, 'How': 1, 'I': 2, 'you.': 1, '?': 1, 'think': 1, 'dont': 1, 'want': 1, 'to': 1}, 13 ) # Test Case 2 input_2 = 4, ["Hello how are you", "What is updates", "how you will do this work", "you have any idea"], 2 assert candidate(*input_2) == ( {'Hello': 1, 'how': 2, 'are': 1, 'you': 3, 'What': 1, 'is': 1, 'updates': 1, 'will': 1, 'do': 1, 'this': 1, 'work': 1, 'have': 1, 'any': 1, 'idea': 1}, 14 ) # Test Case 3 input_3 = 3, ["Python is a powerful language", "Python is widely used for data science", "Python has a large community"], 1 assert candidate(*input_3) == ( {'Python': 3, 'is': 2, 'a': 2, 'powerful': 1, 'language': 1, 'widely': 1, 'used': 1, 'for': 1, 'data': 1, 'science': 1, 'has': 1, 'large': 1, 'community': 1}, 10 )
PythonSaga/50
def infix_to_postfix_and_prefix(expression:str) -> (str,str): """My teacher gave me an mathematical equation and she wants me to convert it to postfix notation and prefix notation. She said I have to use stack to do that, but I have cricket match to play. So please write a program for me to do that. Take expression as input from user in form of string and print postfix and prefix notation of it in string format. Example: Input: Enter expression: 2+3*4 Output: Postfix: 234*+ Prefix: +2*34 Input: Enter expression: ((a^b)+c) Output: Postfix: ab^c+ Prefix: +^abc """
infix_to_postfix_and_prefix
def is_operator(char): return char in "+-*/^" def get_precedence(operator): precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} return precedence.get(operator, 0) def infix_to_postfix(infix_expr): postfix = [] stack = [] for char in infix_expr: if char.isalnum(): postfix.append(char) elif char == '(': stack.append(char) elif char == ')': while stack and stack[-1] != '(': postfix.append(stack.pop()) stack.pop() else: while stack and get_precedence(stack[-1]) >= get_precedence(char): postfix.append(stack.pop()) stack.append(char) while stack: postfix.append(stack.pop()) return ''.join(postfix) def infix_to_prefix(infix_expr): prefix = [] stack = [] for char in infix_expr[::-1]: if char.isalnum(): prefix.append(char) elif char == ')': stack.append(char) elif char == '(': while stack and stack[-1] != ')': prefix.append(stack.pop()) stack.pop() else: while stack and get_precedence(stack[-1]) > get_precedence(char): prefix.append(stack.pop()) stack.append(char) while stack: prefix.append(stack.pop()) return ''.join(prefix[::-1]) # Remove spaces from the expression expression = ''.join(expression.split()) # Call the helper functions postfix_result = infix_to_postfix(expression) prefix_result = infix_to_prefix(expression) return postfix_result, prefix_result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("2+3*4") == ('234*+', '+2*34') assert candidate("((a^b)+c)") == ('ab^c+', '+^abc') assert candidate("a+b*c-d/e^f") == ('abc*+def^/-', '-+a*bc/d^ef') assert candidate("(A*B)+(C/D)") == ('AB*CD/+', '+*AB/CD')
PythonSaga/51
def remove_three_similar_characters(string: str) -> str: """My uncle want to check my knowledge about python. He said to code me a program that will take a string as input from user and will remove three of similar characters from the string. He also said that The three characters should be of adjacent elements and after removing a three the remaining string is joined together. You can use stack to solve this problem. Example: Input: aaabbaaccd Output: bbaaccd Input: aaa Output: """
remove_three_similar_characters
if not string: return "Empty String" stack = [] for char in string: # Check if the stack is not empty and the current character matches the top of the stack if stack and char == stack[-1][0]: # Increment the count of the top element in the stack stack[-1][1] += 1 # Check if the count reaches 3, pop the element from the stack if stack[-1][1] == 3: stack.pop() else: # If the current character is different, push it onto the stack with count 1 stack.append([char, 1]) # Reconstruct the string from the stack result = ''.join(char * count for char, count in stack) return result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("aaabbaaccd") == "bbaaccd" assert candidate("aaa") == "" assert candidate("abcde") == "abcde" assert candidate("aaaabbbaaccd") == "ccd"
PythonSaga/52
def same_expression(postfix: str, prefix: str) -> str: """My friend found a expression which my friend said is postfix expression. But my other friend also have one equation which is he said is prefix expression. To find if both belongs to same expression or not. I need to convert both to infix expression. Write a program to convert both to infix expression. And check if both are same or not. If both are same print "Both are same" else print "Both are not same". Take input from user. Example: Input: Enter postfix expression: 23*5+ Enter prefix expression: +*235 Output: Both are same Input: Enter postfix expression: 23^5+ Enter prefix expression: +^236 Output: Both are not same """
same_expression
def postfix_to_infix(postfix): stack = [] for char in postfix: if char.isalnum(): # Operand stack.append(char) else: # Operator operand2 = stack.pop() operand1 = stack.pop() stack.append(f'({operand1}{char}{operand2})') return stack.pop() def prefix_to_infix(prefix): stack = [] for char in reversed(prefix): if char.isalnum(): # Operand stack.append(char) else: # Operator operand1 = stack.pop() operand2 = stack.pop() stack.append(f'({operand1}{char}{operand2})') return stack.pop() def same_expression(postfix, prefix): infix_postfix = postfix_to_infix(postfix) infix_prefix = prefix_to_infix(prefix) return "Both are same" if infix_postfix == infix_prefix else "Both are not same"
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("245/53-5^4^*+", "+2*/45^^-5354") == "Both are same" assert candidate("ABD*+AD^+*", "++A*BD^AD") == "Both are same" assert candidate("245/535^4^*+", "+2*/45^^-5354") == "Both are not same" assert candidate("ABD*+AD^*+", "++A*BD^AD") == "Both are not same"
PythonSaga/53
from typing import List def poem_stack(n:int, actions:List[str]) -> str: """Google came for interview in my college and asked me to design a game of remebmerence. They said I have a book of poems and initially i'm on index page. From there I can visit any poem or come back to previously visited poem. The task is to design a data structure and implement the functionality of visiting a poem and coming back to previously visited poem. The following functionalities should be implemented: 1. Go(poem) # poem can be name of poem 2. Next() # Go to next poem that we came back from 3. Previous(n) # Go to n poems back that you have seen before 4. Enter Over when you are done. Take actions as input from user and print the current poem we are on. Initially we are on index page. Try to use stack data structure to implement this. Example: Input: 9,[Go("Owl and the Pussycat"), Go("The Road Not Taken"), Previous(2), Next(), Go("Humpty Dumpty"), Next(), Go("House that Jack Built"), Previous(1), Over] Output: You are on the poem: Humpty Dumpty Input: 4,[Go("Owl and the Pussycat"), Go("The Road Not Taken"), Previous(3), Over] Output: You are on the poem: Index Page"""
poem_stack
class PoemStackGame: def __init__(self): self.history_stack = ["Index Page"] # Initialize with the Index Page self.forward_stack = [] def go(self, poem: str): self.history_stack.append(poem) self.forward_stack.clear() # Clear forward history since we are visiting a new poem def next(self): if self.forward_stack: self.history_stack.append(self.forward_stack.pop()) def previous(self, n: int): while n > 0 and len(self.history_stack) > 1: # Ensure we don't go beyond the Index Page self.forward_stack.append(self.history_stack.pop()) n -= 1 def current_poem(self): return self.history_stack[-1] def poem_stack(n: int, actions: List[str]) -> str: game = PoemStackGame() for action in actions: if action.startswith("Go"): _, poem = action.split('("') poem = poem.rstrip('")') game.go(poem) elif action == "Next()": game.next() elif action.startswith("Previous"): _, steps = action.split("(") steps = int(steps.rstrip(")")) game.previous(steps) elif action == "Over": break return f"You are on the poem: {game.current_poem()}"
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(6, ["Go('Poem 1')", "Go('Poem 2')", "Next()", "Previous(1)", "Next()", "Over"]) == "You are on the poem: Poem 2" assert candidate(5, ["Go('Poem A')", "Previous(3)", "Next()", "Go('Poem B')", "Over"]) == "You are on the poem: Poem B" assert candidate(8, ["Go('Poem X')", "Next()", "Go('Poem Y')", "Previous(2)", "Go('Poem Z')", "Next()", "Go('Poem W')", "Over"]) == "You are on the poem: Poem W" assert candidate(3, ["Go('Poem Alpha')", "Previous(2)", "Over"]) == "You are on the poem: Index Page"
PythonSaga/54
def book_stack(n:int, collection_a:list, collection_b:list) -> bool: """You are an avid reader with two collections of unique books, labeled A and B, each containing N books. Your task is to determine whether the arrangement of books in collection B can be obtained from collection A. Both collections are placed in seperate shelves, and once you pick book from collection A, you cannot place it back in collection A. Either you can use one box for putting it down or arrange it in collection B. Take Collection A and Collection B as input from user and return True if Collection B can be obtained from Collection A using a set of bookshelves and operations mimicking a stack with boxes. Else return False. Example 1: Input: 5, [1, 2, 3, 4, 5], [3, 2, 1, 4, 5] Output: True Input: 5, [1, 2, 3, 4, 5], [5, 4, 3, 1, 2] Output: False"""
book_stack
stack = [] # Represents the box a_pointer, b_pointer = 0, 0 # Pointers for collection A and B while b_pointer < n: # Move books from collection A to the stack until we find the next book needed for collection B while a_pointer < n and (not stack or stack[-1] != collection_b[b_pointer]): stack.append(collection_a[a_pointer]) a_pointer += 1 # If the top book on the stack is the next book needed for collection B, move it from the stack to collection B if stack and stack[-1] == collection_b[b_pointer]: stack.pop() b_pointer += 1 else: # The next book needed for collection B is not on top of the stack, so the arrangement is not possible return False # If all books in collection B are correctly placed, the arrangement is possible return True
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(5, [1, 2, 3, 4, 5], [3, 2, 1, 4, 5]) == True assert candidate(5, [1, 2, 3, 4, 5], [5, 4, 3, 1, 2]) == False assert candidate(4, [10, 20, 30, 40], [20, 10, 40, 30]) == True assert candidate(3, [7, 6, 5], [6, 5, 7]) == True
PythonSaga/55
from typing import List def reverse_book_order(n: int, books: list) -> str: """Imagine you have a bookshelf filled with books, each labeled with a number, and a sticky note indicating the next book's location. This organized system is your Linked List, with the first book indicating the Head Pointer. In the quest to rearrange your bookshelf, write a code to reverse the order of the books. Treat each book as a node, complete with its label (data) and the sticky note (pointer) to the next book. Your goal is to have the Head Pointer now point to the last book, creating a reversed order. Imagine you're rearranging your bookshelf in real life and translate this into a coding spell. Take list of books as input from user and print the reversed list of books. Example: Input: 5,[1,2,3,4,5] Output: 5<--4<--3<--2<--1 Input: 4,[A,C,D,E] Output: E<--D<--C<--A"""
reverse_book_order
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def append(self, value): if not self.head: self.head = Node(value) else: current = self.head while current.next: current = current.next current.next = Node(value) def reverse(self): prev = None current = self.head while current: next_node = current.next current.next = prev prev = current current = next_node self.head = prev def __str__(self): result = [] current = self.head while current: result.append(str(current.value)) current = current.next return '<--'.join(result) def reverse_book_order(n: int, books: List[str]) -> str: book_list = LinkedList() for book in books: book_list.append(book) book_list.reverse() return str(book_list)
def check(candidate): assert candidate(6,[10, 20, 30, 40, 50, 60]) == "60<--50<--40<--30<--20<--10" assert candidate(3,['X', 'Y', 'Z']) == "Z<--Y<--X" assert candidate(1,['SingleBook']) == "SingleBook" assert candidate(0,[]) == ""
PythonSaga/56
from typing import List def students_line(n: int, ages: list) -> int: """Given a line of students with ages represented by the Linked List, write a program to determine the minimum number of steps required to organize the students in non-decreasing order of age. In each step, rearrange the line to ensure that no student of younger age stands after an older one. Take the input from the user for the number of students and their ages. Example: Input: 11,[7,5,6,6,9,5,8,13,10,7,13] Output: 3 Input: 5,[6,7,9,11,13] Output: 0"""
students_line
# Create a list of tuples where each tuple is (age, original_index) indexed_ages = list(enumerate(ages)) # Sort the list by age indexed_ages.sort(key=lambda x: x[1]) steps = 0 visited = [False] * n # Keep track of visited nodes to avoid recounting for i in range(n): # If the student is already in the correct position or visited if visited[i] or indexed_ages[i][0] == i: continue # Find the number of nodes in this cycle cycle_size = 0 j = i while not visited[j]: visited[j] = True j = indexed_ages[j][0] # Move to the next node in the cycle cycle_size += 1 # Add the number of steps needed for this cycle (cycle_size - 1) if cycle_size > 0: steps += cycle_size - 1 return steps
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(11, [7, 5, 6, 6, 9, 5, 8, 13, 10, 7, 13]) == 12 assert candidate(5, [6, 7, 9, 11, 13]) == 0 assert candidate(7, [10, 8, 6, 12, 15, 13, 11]) == 8 assert candidate(6, [20, 18, 15, 21, 19, 22]) == 7
PythonSaga/57
from typing import List def buildings_height(n: int, heights: list) -> list: """Imagine a society with buildings of varying heights, each represented by a node in a linked list. The heights are as follows: H1 -> H2 -> H3 -> H4 -> H5 -> and so on For each building in the society, find the height of the next taller building. Take linked list as input from user and print the output as shown below. Example: Input: 5,[4,9,6,5,7] Output: [9,0,7,7,0] Input: 7,[5,3,2,9,4,6,1] Output: [9,9,9,0,6,0,0]"""
buildings_height
# Initialize the result list with 0s, as default for buildings with no taller building to the right result = [0 for _ in range(n)] stack = [] # Use a list as a stack to hold indices of the buildings for i in range(n): # While stack is not empty and the current building is taller than the building at the index at the top of the stack while stack and heights[i] > heights[stack[-1]]: index = stack.pop() # Pop the index of the shorter building result[index] = heights[i] # Update the result for that building stack.append(i) # Push the current index onto the stack # No need to explicitly set remaining buildings in stack to 0, as result is initialized with 0s return result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(5, [4, 9, 6, 5, 7]) == [9, 0, 7, 7, 0] assert candidate(7, [5, 3, 2, 9, 4, 6, 1]) == [9, 9, 9, 0, 6, 0, 0] assert candidate(4, [10, 5, 8, 12]) == [12, 8, 12, 0] assert candidate(6, [2, 5, 7, 4, 3, 1]) == [5, 7, 0, 0, 0, 0] assert candidate(3, [1, 2, 3]) == [2, 3, 0]
PythonSaga/58
from typing import List, Dict def diamond_mine(n: int, diamonds: Dict[int, List[int]]) -> List[int]: """Imagine you are the overseer of a diamond mine where diamonds are arranged in a unique structure. The mine is organized into levels, and each level represents a linked list of diamonds, sorted in ascending order. Each diamond node has two pointers: a next pointer to the next diamond in the same level and a bottom pointer to a linked list where this diamond is the head. Given a mine with diamonds arranged as follows: d1 -> d2 -> d3 -> d4 | | | | v v v v d5 d6 d7 d8 | | | | v v v v d9 d10 d11 | | | v v d12 d12 Your task is to write a function that takes diamond mine such that all diamonds appear in a single level while maintaining the sorted order. The flattened list should be printed using the bottom pointer instead of the next pointer.   Take Input from user and return the sorted list. Example: Input: 3,{4: [1, 2, 3, 4], 3: [5, None, 7, 8], 2: [9, None, 11, None]} Output: 1 2 3 4 5 7 8 9 11 Input: 3,{5: [10, 11, 12, 13, 14], 4: [15, 16, 17, None, 18], 3: [19, 20, None, None, 21]} Output: 10 11 12 13 14 15 16 17 18 19 20 21"""
diamond_mine
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(3, {4: [1, 2, 3, 4], 3: [5, None, 7, 8], 2: [9, None, 11, None]}) == [1, 2, 3, 4, 5, 7, 8, 9, 11] assert candidate(3, {5: [10, 11, 12, 13, 14], 4: [15, 16, 17, None, 18], 3: [19, 20, None, None, 21]}) == [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
PythonSaga/59
from typing import List def sitting_arrangment(n:int, roll_numbers: List[int]) -> List[int]: """In a class there are n number of students. Each student have roll number R1, R2 to Rn. We are conducting exam and we want sitting order such that they don't cheat. Make them sit in this way: R1->Rn, R2->Rn-1, R3->Rn-2 and so on. Take a linked list of students roll number as input from user and return The sitting order. Example: Input: 11,[1, 4, 6, 8, 10, 13, 15, 19, 22, 27, 33] Output: [1, 33, 4, 27, 6, 22, 8, 19, 10, 15, 13]"""
sitting_arrangment
seating_order = [] for i in range(n // 2): seating_order.append(roll_numbers[i]) seating_order.append(roll_numbers[n - 1 - i]) if n % 2 != 0: seating_order.append(roll_numbers[n // 2]) return seating_order
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(11, [1, 4, 6, 8, 10, 13, 15, 19, 22, 27, 33]) == [1, 33, 4, 27, 6, 22, 8, 19, 10, 15, 13] assert candidate(10, [2, 5, 8, 11, 14, 17, 20, 23, 26, 29]) == [2, 29, 5, 26, 8, 23, 11, 20, 14, 17] assert candidate(6, [100, 200, 300, 400, 500, 600]) == [100, 600, 200, 500, 300, 400] assert candidate(7, [3, 6, 9, 12, 15, 18, 21]) == [3, 21, 6, 18, 9, 15, 12]
PythonSaga/60
from typing import List, Tuple def bead_remove(bead_count: int, bead_numbers: List[int], remove_beads: List[int]) -> Tuple[List[int], int, int]: """My aunt has favourite bracelets where each bead points to next bead. But it's getting loose for her. So she decided to remove some beads from end. Each bead has a number on it. She wants to remove beeds with numbers in decreasing order. Write a program to help her to remove beads from end, imagine bracelet as a linked list where last bead is connected to first bead. Take input from user for number of beads and numbers on each bead, and Which bead she wants to remove. Use linked list to solve this problem. Return the linked list after removing beads and the first and last bead number. Example: Input: 11,[1,2,3,4,5,6,7,8,9,10,11],[5,10,11] Output: [1,2,3,4,6,7,8,9], 1, 9 Input: 10,[1,2,3,4,5,6,7,8,9,10],[2,4,6,8,10] Output: [1,3,5,7,9], 1, 9"""
bead_remove
from typing import List, Tuple class BeadNode: def __init__(self, number): self.number = number self.next = None def bead_remove(bead_count: int, bead_numbers: List[int], remove_beads: List[int]) -> Tuple[List[int], int, int]: # Create a linked list from the input bead_numbers beads = None current = None for number in reversed(bead_numbers): node = BeadNode(number) node.next = current current = node beads = current # Iterate through the linked list to remove beads specified in remove_beads current = beads prev = None while current: if current.number in remove_beads: if prev: prev.next = current.next else: beads = current.next else: prev = current current = current.next # Find the first and last bead number current = beads first_bead = last_bead = None while current: if first_bead is None: first_bead = current.number last_bead = current.number current = current.next # Convert linked list to list result = [] current = beads while current: result.append(current.number) current = current.next return result, first_bead, last_bead
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): input1 = (11, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [5, 10, 11]) output1 = candidate(*input1) assert output1 == ([1, 2, 3, 4, 6, 7, 8, 9], 1, 9) input2 = (10, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 4, 6, 8, 10]) output2 = candidate(*input2) assert output2 == ([1, 3, 5, 7, 9], 1, 9) input3 = (8, [10, 20, 30, 40, 50, 60, 70, 80], [20, 50, 60, 70, 80]) output3 = candidate(*input3) assert output3 == ([10, 30, 40], 10, 40) input4 = (6, [5, 10, 15, 20, 25, 30], [10, 20, 25]) output4 = candidate(*input4) assert output4 == ([5, 15, 30], 5, 30)
PythonSaga/61
from typing import List def chemistry_ele(elements: List[str], i: int, j: int) -> List[str]: """I have some chemistry experiments to do where I have long chain of different elements. Each element is linked with next and previous element. To do next experiment I want to reverse some portion of chain. So take Input from user as a string of elements and reverse the portion of chain from index i to j. Use doubly linked list to implement this. Example: Input: [O, K, H, Li, Be, B, C, N, O, F, Ne] ,2, 4 Output: [O, k, Be, Li, H, B, C, N, O, F, Ne] Input: [O, K, H, Li, Be, B, C, N, O, F, Ne] ,0, 3 Output: [Li, H, K, O, Be, B, C, N, O, F, Ne]"""
chemistry_ele
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): input1 = (['O', 'K', 'H', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne'], 2, 4) output1 = candidate(*input1) assert output1 == ['O', 'K', 'Be', 'Li', 'H', 'B', 'C', 'N', 'O', 'F', 'Ne'] input2 = (['O', 'K', 'H', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne'], 0, 3) output2 = candidate(*input2) assert output2 == ['Li', 'H', 'K', 'O', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne'] input3 = (['Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar'], 1, 5) output3 = candidate(*input3) assert output3 == ['Na', 'S', 'P', 'Si', 'Al', 'Mg', 'Cl', 'Ar'] input4 = (['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne'], 3, 8) output4 = candidate(*input4) assert output4 == ['H', 'He', 'Li', 'F', 'O', 'N', 'C', 'B', 'Be', 'Ne']
PythonSaga/62
from typing import List def eight_shape(garland1: List[str], garland2: List[str], common_bead: str) -> List[str]: """I have 2 garlands of beads of different sizes. each bead has different alphabets on it. and no two bead has same alphabet in any garland only one bead is common. I want to be creative because i'm bored. I want to create figure like digit 8 such that there is a bead in the middle of the figure and the figure is made up of beads from both the garlands. Also when i read alphabet I start from common bead and them move in upper garland in anti-clockwise and then come back to commmon bead and move to lower garland and then move in clockwise manner and come back to common bead. In this was I will read common bead thrice. So take input from user as alphabets on beads of both garlands, common bead and print alphabets in order mentioned above. Use Linked List to solve this problem. Example: Input: [A, B, C, D, E, F, G, H], [I, J, K, B, L, M], B Output: [B, C, D, E, F, G, H, A, B, L, M, I, J, K, B]"""
eight_shape
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): input1 = (['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], ['I', 'J', 'K', 'B', 'L', 'M'], 'B') output1 = candidate(*input1) assert output1 == ['B', 'C', 'D', 'E', 'F', 'G', 'H', 'A', 'B', 'L', 'M', 'I', 'J', 'K', 'B'] input2 = (['X', 'Y', 'Z'], ['A', 'B', 'C', 'X'], 'X') output2 = candidate(*input2) assert output2 == ['X', 'Y', 'Z', 'X', 'A', 'B', 'C', 'X'] input3 = (['1', '2', '3', '4'], ['9', '10', '2', '11', '12'], '2') output3 = candidate(*input3) assert output3 == ['2', '3', '4', '1', '2', '11', '12', '9', '10', '2']
PythonSaga/63
from typing import List def subset_linked_list(arr: List[float], threshold: float) -> List[List[int]]: """I have circular linked list of some numbers. My teacher gave me one number and asked to find all possible subset of digits from the circular linked list whose sum is greater than the given number. Take linked list as input from user and print all possible subsets whose sum is greater than the given number. Example: Input: [1,2,3,1], 3 Output: [[1, 2, 3, 1], [1, 2, 3], [1, 2, 1], [1, 3, 1], [1, 3], [2, 3, 1], [2, 3], [3, 1]] Input: [1,2,3,1], 4 Output: [[1, 2, 3, 1], [1, 2, 3], [1, 3, 1], [2, 3, 1], [2, 3]]"""
subset_linked_list
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): input1 = [1, 2, 3, 1] threshold1 = 3 output1 = candidate(input1, threshold1) assert output1 == [[1, 2, 3, 1], [1, 2, 3], [1, 2, 1], [1, 3, 1], [1, 3], [2, 3, 1], [2, 3], [3, 1]] input2 = [1, 2, 3, 1] threshold2 = 4 output2 = candidate(input2, threshold2) assert output2 == [[1, 2, 3, 1], [1, 2, 3], [1, 3, 1], [2, 3, 1], [2, 3]] input3 = [4, 2, 7, 3] threshold3 = 9 output3 = candidate(input3, threshold3) assert output3 == [[4, 2, 7, 3], [4, 2, 7], [4, 7, 3], [4, 7], [2, 7, 3], [7, 3]] input4 = [10, 5, 2, 8, 7] threshold4 = 15 output4 = candidate(input4, threshold4) assert output4 == [[10, 5, 2, 8, 7], [10, 5, 2, 8], [10, 5, 2, 7], [10, 5, 2], [10, 5, 8, 7], [10, 5, 8], [10, 5, 7], [10, 2, 8, 7], [10, 2, 8], [10, 2, 7], [10, 8, 7], [10, 8], [10, 7], [5, 2, 8, 7], [5, 8, 7], [2, 8, 7]]
PythonSaga/64
from typing import List def plaindrom(arr: List[str]) -> List[str]: """I have a circular doubly linked list of alphabets. Write a program to check if these alphabets form a palindrome and print the word. Use the doubly linked list created in the previous question. Take the input from the user. and return the output as Palindrome or Not a Palindrome and the word. Example: Input: [A, D, A, R] Output: ['Palindrome', 'The word is RADAR'] Input: [T, I, N, N, I] Output: ['Palindrome', 'The word is NITIN'] Input: [H, E, L, L, O] Output: ['Not a Palindrome', 'The list does not form a palindrome word.']"""
plaindrom
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): input1 = ['A', 'D', 'A', 'R'] output1 = candidate(input1) assert output1 == ['Palindrome', 'The word is RADAR'] input2 = ['T', 'I', 'N', 'N', 'I'] output2 = candidate(input2) assert output2 == ['Palindrome', 'The word is NITIN'] input3 = ['H', 'E', 'L', 'L', 'O'] output3 = candidate(input3) assert output3 == ['Not a Palindrome', 'The list does not form a palindrome word.'] input4 = ['R', 'E', 'V', 'E'] output4 = candidate(input4) assert output4 == ['Palindrome', 'The word is REVER']
PythonSaga/65
from queue import Queue from typing import List def stack_using_queue(operations: List[List[int]]) -> List[List[int]]: """We can implement stack using list. But my uncle told we can also using two queues. So, please help me to implement stack using queue. Take input from user in form of what operation he wants to perform. 1. Push 2. Pop 3. Display Example: Input: [[1, 1], [1, 2], [1, 3], [3]] Output: [[3, 2, 1]] Input: [[1, 1], [1, 2], [3], [2], [3]] Output: [[2, 1],[1]]"""
stack_using_queue
class StackUsingQueues: def __init__(self): self.main_queue = Queue() self.aux_queue = Queue() def push(self, x: int): self.main_queue.put(x) def pop(self): if self.main_queue.empty(): return "Stack is empty" # Move all elements except the last one to the auxiliary queue while self.main_queue.qsize() > 1: self.aux_queue.put(self.main_queue.get()) # The last element in the main queue is the top of the stack top_element = self.main_queue.get() # Swap the roles of the main queue and the auxiliary queue self.main_queue, self.aux_queue = self.aux_queue, self.main_queue return top_element def display(self): stack_representation = [] # Transfer elements to auxiliary queue and build stack representation while not self.main_queue.empty(): element = self.main_queue.get() stack_representation.append(element) self.aux_queue.put(element) # Transfer elements back to the main queue while not self.aux_queue.empty(): self.main_queue.put(self.aux_queue.get()) return stack_representation[::-1] # Reverse to represent the stack order def stack_using_queue(operations: List[List[int]]) -> List[List[int]]: stack = StackUsingQueues() result = [] for operation in operations: if operation[0] == 1: # Push operation stack.push(operation[1]) elif operation[0] == 2: # Pop operation stack.pop() elif operation[0] == 3: # Display operation result.append(stack.display()) return result
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate([[1, 1], [1, 2], [1, 3], [3]]) == [[3, 2, 1]] assert candidate([[1, 1], [1, 2], [3], [2], [3]]) == [[2, 1], [1]] assert candidate([[1, 5], [1, 10], [1, 15], [2], [3]]) == [[10, 5]] assert candidate([[1, 3], [1, 6],[3], [2], [1, 9], [3]]) == [[6, 3], [9, 3]]
PythonSaga/66
from typing import List def skyline(street: List[int]) -> int: """Imagine you have a city skyline represented by an array of skyscraper heights. The heights are given in the array street[]. The task is to determine how much sunlight can be captured between the buildings when the sun is at its peak. Take street[] as input from the user. Print the total sunlight that can be captured between the buildings. Example: Input: [4, 0, 4] Output: 4 Input: [3, 4, 3, 5, 4, 3, 4, 6, 5, 4, 5, 4] Output: 6"""
skyline
total_sunlight = 0 n = len(street) # Arrays to store the maximum height to the left and right of each building left_max = [0] * n right_max = [0] * n # Fill left_max array left_max[0] = street[0] for i in range(1, n): left_max[i] = max(left_max[i-1], street[i]) # Fill right_max array right_max[n-1] = street[n-1] for i in range(n-2, -1, -1): right_max[i] = max(right_max[i+1], street[i]) # Calculate total sunlight captured for i in range(n): # Sunlight on current building is the difference between its height and the height of the shadow cast by the taller buildings on its left or right, whichever is shorter. total_sunlight += min(left_max[i], right_max[i]) - street[i] return total_sunlight
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate([4, 0, 4]) == 4 assert candidate([3, 4, 3, 5, 4, 3, 4, 6, 5, 4, 5, 4]) == 9 assert candidate([1, 2, 3, 4, 5]) == 0 assert candidate([10, 5, 15, 2, 8, 12, 7]) == 19
PythonSaga/67
from typing import List def deck(queries: List[List[str]]) -> List[int]: """You have been given a special deck, represented as a double-ended queue (deque), and a set of queries to perform operations on this deck. The deck supports four types of operations: 1. Insert at Rear (ins_rear x): Use the 'Insert Rear' operation to add data x to the rear of the deck. 2. Insert at Front (ins_fr x): Use the 'Insert Front' operation to add data x to the front of the deck. 3. Delete Front (del_fr): Use the 'Delete Front' operation to remove the front element from the deck. If the deck is empty, no action is taken. 4. Delete Rear (del_rear): Use the 'Delete Rear' operation to remove the rear element from the deck. If the deck is empty, no action is taken. Take input from the user; the number of queries, and the queries themselves, and print the output for each query and final deck. Implement the above deque using a doubly linked list. Example: Input: [['ins_rear', 5], ['ins_fr', 10], ['del_fr'], ['del_rear'], ['ins_fr', 15], ['ins_rear', 20]] Output: [15, 20]"""
deck
class Node: def __init__(self, value): self.value = value self.next = None self.prev = None class Deck: def __init__(self): self.front = None self.rear = None def ins_rear(self, x): new_node = Node(x) if not self.rear: # Empty deck self.front = self.rear = new_node else: self.rear.next = new_node new_node.prev = self.rear self.rear = new_node def ins_fr(self, x): new_node = Node(x) if not self.front: # Empty deck self.front = self.rear = new_node else: self.front.prev = new_node new_node.next = self.front self.front = new_node def del_fr(self): if self.front: if self.front == self.rear: # Only one element self.front = self.rear = None else: self.front = self.front.next self.front.prev = None def del_rear(self): if self.rear: if self.front == self.rear: # Only one element self.front = self.rear = None else: self.rear = self.rear.prev self.rear.next = None def get_deck(self): current = self.front result = [] while current: result.append(current.value) current = current.next return result def deck(queries: List[List[str]]) -> List[int]: d = Deck() for query in queries: operation, *args = query if operation == "ins_rear": d.ins_rear(*args) elif operation == "ins_fr": d.ins_fr(*args) elif operation == "del_fr": d.del_fr() elif operation == "del_rear": d.del_rear() return d.get_deck()
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate([['ins_rear', 5], ['ins_fr', 10], ['del_fr'], ['del_rear'], ['ins_fr', 15], ['ins_rear', 20]]) == [15, 20] assert candidate([['ins_rear', 1], ['ins_rear', 2], ['ins_rear', 3], ['del_fr'], ['ins_fr', 4], ['del_rear']]) == [4, 2] assert candidate([['ins_rear', 10], ['ins_fr', 5], ['del_fr'], ['ins_rear', 15], ['del_rear']]) == [10] assert candidate([['ins_rear', 5], ['ins_fr', 3], ['ins_rear', 8], ['ins_fr', 2], ['del_rear'], ['del_fr']]) == [3, 5]
PythonSaga/68
from collections import deque from typing import List def delete_element(deque: List[int], index: int) -> List[int]: """I came to know that I can implement deque using collections module. But now I want to learn how to delete elements from deque. Write 4 functions to delete elements from deque. 1. to remove element from a specific index 2. to remove element in a range of index, start (inclusive) to end (exclusive). 3. to remove element from both ends. 4. to remove all elements from deque. Take input from the user to create deque and a set of operations to perform on deque. Return deque after performing all operations. EXAMPLE: Input: [1, 2, 3, 4, 5],[3] Output: [2, 3, 4] Input: [1, 2, 3, 4, 5],[4] Output: [] Input: [1, 2, 3, 4, 5],[2,1,3] # 2 is action code for remove element in range, 1 is start index and 3 is end index Output: [1, 4, 5]"""
delete_element
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate([1, 2, 3, 4, 5], [3]) == [2, 3, 4] assert candidate([1, 2, 3, 4, 5], [4]) == [] assert candidate([1, 2, 3, 4, 5], [2, 1, 3]) == [1, 4, 5] assert candidate([10, 20, 30, 40, 50], [1]) == [10, 20, 40, 50]
PythonSaga/69
from collections import deque from typing import List def office_party(n:int, snacks_preference:List[List[str]]) -> int: """Imagine an office party scenario where there are n people in the office, and an equal number of food packets are available. The food packets come in two types: French fries (represented by '|') and pizza (represented by '*'). All employees form a queue, and the food packets are stacked on a table. At each step, the person at the front of the queue has the option to take the top food packet from the stack. The preferences of the individuals are as follows: If a person prefers the food type on the top of the stack, they take it and leave the queue. If the person does not prefer the food type on the top of the stack, they leave it and move to the end of the queue. This process continues until none of the people in the queue want to take the top food packet, and they become unable to eat. You are given two arrays, employees and foodPackets, where foodPackets[i] is the type of the i​​​​th food packet on the table (i = 0 is the top of the stack), and employees[j] is the preference of the j​​​​​​th person in the initial queue (j = 0 is the front of the queue). Your task is to determine the number of people who are unable to eat. Take input from the user for the number of employees and food packets. Take foodpackets[] as input from the user. Take employees[] as input from the user. Example: Input: 4,[['*', '|', '*', '|'],['|', '|', '*', '*']] # 4 is the number of employees, [['*', '|', '*', '|'],['|', '|', '*', '*']] is food packets and food preference of employees Output: 0 Input: 6,[['|', '|', '|', '*', '*', '|'],['|', '*', '*', '*', '|', '|']] # 6 is the number of employees, [['|', '|', '|', '*', '*', '|'],['|', '*', '*', '*', '|', '|']] is food packets and food preference of employees Output: 3"""
office_party
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(4, [['*', '|', '*', '|'], ['|', '|', '*', '*']]) == 0 assert candidate(6, [['|', '|', '|', '*', '*', '|'], ['|', '*', '*', '*', '|', '|']]) == 3
PythonSaga/70
import re from typing import List def mobile_number(text: str) -> List[str]: """I have a paragraph which contain lots of phone numbers and different numbers. your task is to use regular expression to extract all the phone numbers and numbers from the paragraph. Take a paragraph as input from the user and print all the phone numbers and numbers from the paragraph. Example: Input: "Hello my Number is 12304589 and my friend's number is 987654321" Output: ["12304589", "987654321"]"""
mobile_number
pattern = r'\d+' # Regular expression pattern to match numbers numbers = re.findall(pattern, text) # Find all matches of numbers in the text return numbers
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("Hello my Number is 12304589 and my friend's number is 987654321") == ['12304589', '987654321'] assert candidate("No numbers in this text") == [] assert candidate("123on456 789") == ['123', '456', '789'] assert candidate("The quick brown fox jumps over the lazy dog") == []
PythonSaga/71
import re def space_needed(text: str) -> str: """I was distracted while typing my assignment and forgot to put space after words. Read a paragragraph and add space before every word which starts with capital letter. And also if it is a number, add ":" followed by space before number. Take input from user and print the output. Example: Input: "IamStudyingInBdsfrom24hrs." Output: "Iam Studying In Bdsfrom: 24hrs." Input: "ThisIsMyFirstAssignmentof22ndBatch." Output: "This Is My First Assignmentof: 22nd Batch.""""
space_needed
# Add space before words starting with a capital letter text_with_spaces = re.sub(r"(?<!^)(?=[A-Z])", " ", text) # Add ": " before the first number in the sequence # We use a function in sub to replace only the first occurrence def add_colon_before_number(match): return f": {match.group()}" # Find the first occurrence of a number and add ": " before it result_text = re.sub(r"\d+", add_colon_before_number, text_with_spaces, count=1) return result_text
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("IamStudyingInBdsfrom24hrs.") == "Iam Studying In Bds from: 24hrs." assert candidate("ThisIsMyFirstAssignmentof22ndBatch.") == "This Is My First Assignmentof: 22nd Batch." assert candidate("Iscored90MarksinfinalExamof12thClass.") == "Iscored: 90 Marksinfinal Examof: 12th Class." assert candidate("HisDateOfBirthis5thMarch1990.") == "His Date Of Birthis: 5th March: 1990."
PythonSaga/72
import re def date_format(text: str) -> str: """I met an accountant who has some text material in which he has days and dates. But now to coap up with the new technology he wants to convert all the dates into a standard format. The standard format is DD-MM-YYYY. But the problem is dates in his text is in 2 different format. 1. YYYY-MM-DD and 2. DD-YYYY-MM. So you have to convert all the dates into standard format. And also if day is return in abbrivation [Mon, Tue, Wed, Thu, Fri, Sat, Sun] then you have to convert it into full form [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]. Take a text as input and return the text with all the dates and days in standard format. Example: Input: "On 2023-01-15, we had a meeting. The financial report for the month was presented. On Thu, 2023-01-18, the board discussed the budget. 2023-02-20 is the deadline for submitting expense reports. Please submit them by then. We also have a meeting scheduled for Wed, 2023-03-22. " Output: "On 15-01-2023, we had a meeting. The financial report for the month was presented. On Thursday, 18-01-2023, the board discussed the budget. 20-02-2023 is the deadline for submitting expense reports. Please submit them by then. We also have a meeting scheduled for Wednesday, 22-03-2023. " """
date_format
text = re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3-\2-\1", text) text = re.sub(r"(\d{2})-(\d{4})-(\d{2})", r"\1-\3-\2", text) days_dict = { "Mon": "Monday", "Tue": "Tuesday", "Wed": "Wednesday", "Thu": "Thursday", "Fri": "Friday", "Sat": "Saturday", "Sun": "Sunday" } for day in days_dict: text = text.replace(day, days_dict[day]) return text
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): text1 = "On 2023-01-15, we had a meeting. The financial report for the month was presented." expected1 = "On 15-01-2023, we had a meeting. The financial report for the month was presented." assert candidate(text1) == expected1 text2 = "On Thu, 2023-01-18, the board discussed the budget. 2023-02-20 is the deadline for submitting expense reports." expected2 = "On Thursday, 18-01-2023, the board discussed the budget. 20-02-2023 is the deadline for submitting expense reports." assert candidate(text2) == expected2 text3 = "Please submit them by then. We also have a meeting scheduled for Wed, 2023-03-22." expected3 = "Please submit them by then. We also have a meeting scheduled for Wednesday, 22-03-2023." assert candidate(text3) == expected3 text4 = "The last date for registration is 15-2023-02. Classes will start from 01-2023-06." expected4 = "The last date for registration is 15-02-2023. Classes will start from 01-06-2023." assert candidate(text4) == expected4
PythonSaga/73
from typing import List, Tuple def vowels(text: str) -> Tuple[bool, List[List[str]]]: """Write a Python program that takes a string with some words. For two consecutive words in the string, check whether the first word ends with a vowel and the next word begins with a vowel. If the program meets the condition, return true, otherwise false. Only one space is allowed between the words. Take input from user and return true if the condition is met, otherwise false, also return two words which met the condition Example: Input: "Python PHP" Output: (False, []) Input: "These exercises can be used for practice." Output: (True, [['These','exercises'], ['be', 'used']])"""
vowels
text = text.lower() words = text.split(" ") vowels = "aeiou" result = [] for i in range(len(words)-1): word1 = words[i] word2 = words[i+1] if word1[-1] in vowels and word2[0] in vowels: result.append([word1, word2]) if result: return True, result else: return False, []
METADATA = { 'author': 'ay', 'dataset': 'test' } def test(candidate): text1 = "Python PHP" expected_output1 = (False, []) assert candidate(text1) == expected_output1 text2 = "These exercises can be used for practice." expected_output2 = (True, [['These','exercises'], ['be', 'used']]) assert candidate(text2) == expected_output2 text3 = "cats and dogs are common pets" expected_output3 = (False, []) assert candidate(text3) == expected_output3 text4 = "abcde efgh hijkl mnopq rstu vwxyz" expected_output4 = (True, [['abcde', 'efgh']]) assert candidate(text4) == expected_output4
PythonSaga/74
import re def find_urls(text: str) -> str: """My boss gave me work to find all the urls in the given text and print them. Write a code which take text as input from user and print all the urls in the text. Note: url should start with https:// or http:// and can end with any thing like .com, .in, .org etc. where there is "." before the ending part. But if url is not ending properly then it should not print that url. Example: Input:"Check out the latest news on https://www.example.com. You can also visit our blog at http://bloexample for more information." Output: "https://www.example.com " Input:"For more details, visit https://www.example.com and http://test.com" Output: "https://www.example.com, http://test.com" """
find_urls
urls = re.findall(r'(https?://[^ ]*)\.', text) return ' '.join(urls)
METADATA = { 'author': 'ay', 'dataset': 'test' } def test(candidate): text1 = "For more details, visit https://www.example.com and http://test.com" expected_output1 = "https://www.example.com, http://test.com" assert candidate(text1) == expected_output1 text2 = "You can find us at https://www.mywebsite.com or http://127" expected_output2 = "https://www.mywebsite.com" assert candidate(text2) == expected_output2 text3 = "Visit https://test.org or http://test.com." expected_output3 = "https://test.org, http://test.com" assert candidate(text3) == expected_output3 text4 = "No urls to find in this text" expected_output4 = "" assert candidate(text4) == expected_output4
PythonSaga/75
from collections import defaultdict from typing import List, Dict def hash_table(seq:List)-> Dict: """In local school games students who won there names were noted in sequence of there winning But if person won more than once his name will be repeated in sequence so that he can be declared as man of the match Take input from user and print the name of the person who won maximum number of times followed by the number of times he won followed by second person and so on. You can use hash table to solve this problem Example: Input: [A,B,C,A,B,A,Z,A,A,F,S,S,C,F,S,A] Output: {'A':6, 'S':3, 'F':2, 'C':2, 'B':2, 'Z':1}"""
hash_table
table = defaultdict(int) for name in seq: table[name] += 1 sorted_table = dict(sorted(table.items(), key=lambda x: x[1], reverse=True)) return sorted_table
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(['X', 'Y', 'Z', 'X', 'X', 'Z']) == {'X': 3, 'Z': 2, 'Y': 1} assert candidate(['A', 'A', 'A', 'A', 'A', 'A']) == {'A': 6} assert candidate(['Dog', 'Cat', 'Bird', 'Dog', 'Cat', 'Dog']) == {'Dog': 3, 'Cat': 2, 'Bird': 1}
PythonSaga/76
from typing import List, Tuple, Optional def hash_function(n:int, entries:List[List[str,int]]) -> List: """My teacher taught us hashing in class today and its advanced version that is open addressing. He gave us task to implement it in python. With following functions: 1. Insert 2. Search 3. Delete 4. Display Take input from user about the size of hash table and and action to perform otherwise exit. Example: Input: 5,[[insert,5],[insert,10],[insert,15],[display],[search,10],[delete,10],[display]] Output: [[5,10,15,None,None], 1,[5,None,15,None,None]]"""
hash_function
from typing import List, Tuple, Optional class HashTable: def __init__(self, size: int): self.size = size self.table = [None] * size def hash(self, key: int) -> int: return key % self.size def insert(self, key: int): index = self.hash(key) while self.table[index] is not None: index = (index + 1) % self.size self.table[index] = key def search(self, key: int) -> bool: index = self.hash(key) start_index = index while self.table[index] is not None: if self.table[index] == key: return True index = (index + 1) % self.size if index == start_index: break return False def delete(self, key: int): index = self.hash(key) start_index = index while self.table[index] is not None: if self.table[index] == key: self.table[index] = None return True index = (index + 1) % self.size if index == start_index: break return False def display(self) -> List[Optional[int]]: return self.table def hash_function(n: int, entries: List[List[str]]) -> List: hash_table = HashTable(n) result = [] for entry in entries: if len(entry) == 1: operation = entry[0] else: operation, value = entry if operation == 'insert': hash_table.insert(value) elif operation == 'delete': hash_table.delete(value) elif operation == 'search': found = hash_table.search(value) result.append(1 if found else 0) elif operation == 'display': result.append(hash_table.display()) return result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(3, [['insert', 1], ['insert', 4], ['display']]) == [[None, 1, 4]] assert candidate(5, [['insert', 10], ['insert', 20], ['insert', 30], ['search', 20]]) == [1] assert candidate(4, [['insert', 8], ['insert', 12], ['delete', 8], ['display']]) == [[None, 12, None, None]] assert candidate(6, [['insert', 11], ['insert', 22], ['insert', 33], ['delete', 22], ['search', 22], ['display']]) == [-1, [None, None, None, 33, None, 11]]
PythonSaga/77
from typing import List, Tuple, Optional def sum_pair(entries:List[int], target:int) -> List[Tuple[int,int]]: """I have very simple problem that I'm unable to solve and need your help in. I have a number and I want to know is there any pair of numbers in the list whose sum is equal to the given number. But the twist is I have to do it using hashing. Take list of numbers from user and the number to be checked and return the pair of numbers whose sum is equal to the given number otherwise return -1. Example: Input: [1,2,3,4,5,6,7,8,9,10],11 Output: [(1,10), (2,9) ,(3,8), (4,7), (5,6) ] Example: Input: [-1,33,2,-33,99,101,-2,0],0 Output: [(-33,33), (-2,2)] """
sum_pair
seen = set() pairs = set() for number in entries: complement = target - number if complement in seen: pairs.add((min(number, complement), max(number, complement))) seen.add(number) if not pairs: return -1 return list(pairs)
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 11) == [(1, 10), (2, 9), (3, 8), (4, 7), (5, 6)] assert candidate([-1, 33, 2, -33, 99, 101, -2, 0], 0) == [(-33, 33), (-2, 2)] assert candidate([10, 20, -10, -20], 0) == [(-20, 20), (-10, 10)] assert candidate([1, 3, 5, 7], 10) == []
PythonSaga/78
from typing import List, Optional def balanced_substring(string:str, k:int) -> List[str]: """My teacher said we have to find balanced subtrings in a string. A string is balanced if: 1. Number of vowels and consonants are equal 2. ((Number of vowels)*(Number of consonants))%k == 0 You can use hashing to solve this problem. Take input of string and k from user and return balanced substrings if any else return empty list. Example: Input: string = "xioyz", k = 2 Output: ['ioyz', 'xioy'] Input: string = "ixxi", k=1 Output: ['ixxi', 'ix', 'xi']"""
balanced_substring
vowels = set('aeiouAEIOU') result = [] for i in range(len(string)): for j in range(i+1, len(string) + 1): substring = string[i:j] vowel_count = sum(1 for char in substring if char in vowels) consonant_count = len(substring) - vowel_count if vowel_count == consonant_count and (vowel_count * consonant_count) % k == 0: result.append(substring) return result if result else -1
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("xioyz", 2) == ['xioy', 'ioyz'] assert candidate("ixxi", 1) == ['ix', 'ixxi', 'xi'] assert candidate("abcde", 3) == []
PythonSaga/79
from typing import List def minTime(val: List[int]) -> int: """At each unit of time, we perform the following operation on the list For every index i in the range [0, n - 1], replace val[i] with either val[i], val[(i - 1 + n) % n], or val[(i + 1) % n]. Note that all the elements get replaced simultaneously. Return the minimum number of units of times we need to make all elements in the list val equal. Take input of list from user and print the minimum number of units of times we need to make all elements in the list val equal. Example 1 Input: [1,2,1,2] Output: 1 Input: [2,1,3,3,2] Output: 2 Input: [3,3,3,3] Output: 0"""
minTime
# Check if all elements are equal if len(set(val)) == 1: return 0 # Check for an alternating pattern if all(val[i] != val[i + 1] for i in range(len(val) - 1)) and val[0] != val[-1]: return 1 # Implement logic for the general case # Placeholder for the general case logic # This part needs a more detailed implementation based on specific rules or patterns # As a placeholder, return 2 for the general case # This needs to be replaced with actual logic return 2
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([1, 2, 1, 2]) == 1 assert candidate([2, 1, 3, 3, 2]) == 2 assert candidate([3, 3, 3, 3]) == 0
PythonSaga/80
from typing import List def floor_ceil(arr:List, x:int)->List: """I have a sorted list of numbers and number x and the task given to me is to find the ceil and floor of x in the list. The floor of x is the largest number in the list which is smaller than or equal to x, and the ceil of x is the smallest number in the list which is greater than or equal to x. But the challenge is to solve this problem in O(logn) time complexity. Take input list and x from the user and print the floor and ceil of x in the list if any. Example: Input: [1,2,3,4,5,6,7,8,9,10],11 Output: [10,None] Input: [11, 14, 23, 45, 56, 67, 78, 89, 90],11 Output: [11,11]"""
floor_ceil
n = len(arr) floor, ceil = None, None low, high = 0, n - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == x: return [x, x] elif arr[mid] < x: floor = arr[mid] low = mid + 1 else: ceil = arr[mid] high = mid - 1 return [floor, ceil]
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 11) == [10, None] assert candidate([11, 14, 23, 45, 56, 67, 78, 89, 90], 11) == [11, 14] assert candidate([1, 2, 8, 10, 10, 12, 19], 5) == [2, 8] assert candidate([2, 8, 10, 10, 12, 19], 11) == [10, 12]
PythonSaga/81
from typing import List def chef(box:int, eggs:List, chefs:int)->int: """In a restaurant, there are N boxes of eggs, each containing a different number of eggs. The boxes are arranged in sorted order based on the number of eggs in each box. Now, the restaurant has received an order and the owner has to distribute these N boxes among M chefs for breaking the eggs. The goal is to assign the boxes to chefs in such a way that the maximum number of eggs assigned to any chef is minimized. Each chef is tasked with breaking eggs from a consecutive range of boxes. Take input from the user for the number of boxes and the number of eggs in those and the number of chefs. Try to do in O(logn) time complexity. Example: Input: 4,[12,34,67,90],2 Output: 113"""
chef
def chef(box: int, eggs: List[int], chefs: int) -> int: def is_valid(mid, eggs, chefs): count = 0 current_sum = 0 for egg in eggs: current_sum += egg if current_sum > mid: count += 1 current_sum = egg count += 1 # Include the last batch return count <= chefs low, high = max(eggs), sum(eggs) result = high while low <= high: mid = (low + high) // 2 if is_valid(mid, eggs, chefs): result = mid high = mid - 1 else: low = mid + 1 return result
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(4, [12, 34, 67, 90], 2) == 113 assert candidate(6, [10, 20, 30, 40, 50, 60], 3) == 90 assert candidate(5, [5, 10, 15, 20, 25], 2) == 45 assert candidate(3, [1, 2, 3], 1) == 6
PythonSaga/82
from typing import List def stones(sizes: List[int], target: int) -> List[int]: """Imagine you are in a store to find stones for your backyard garden. The store has an unsorted row of N stones, each labeled with a non-negative integer representing its size. Your goal is to select a continuous set of stones (subarray) from this row in such a way that the sum of their sizes matches a given target value S. You need to return two elements, left and right, representing the indexes of the selected subarray. If no such subarray exists, return an array consisting of element [-1]. Take input from the user for the size of stones in the row and target value S. Try to do it in O(n) time complexity. Example 1: # Indexing starts from 1 Input: [1, 2, 3, 7, 5], 12 Output: [2, 4] """
stones
left, right = 0, 0 current_sum = 0 while right < len(sizes): current_sum += sizes[right] while current_sum > target: current_sum -= sizes[left] left += 1 if current_sum == target: return [left + 1, right + 1] right += 1 return [-1]
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate([1, 2, 3, 7, 5], 12) == [2, 4] assert candidate([10, 2, 3, 1, 7], 15) == [1, 3] assert candidate([1, 2, 3, 4, 5], 11) == [-1]
PythonSaga/83
from typing import List def ride(ages: List) -> int: """Imagine you are operating a ride for kids at a fair, and each kid is assigned a distinct age. The kids are standing in a line, represented by an integer list ages, where the value at each position corresponds to the age of the kid. You can perform the following operations until the line is empty: If the first kid in the line has the smallest age, let them ride and remove them from the line. Otherwise, move the first kid to the end of the line. The task is to determine the number of operations it takes to make the line empty, ensuring that kids with the smallest ages get the first priority to ride. Take a list ages input from the user and print the number of operations it takes to make the line empty. Example 1: Input: [3,4,1] Output: 5 Input: [1,2,4,3] Output: 5"""
ride
sorted_ages = sorted(ages) operations = 0 while ages: if ages[0] == sorted_ages[0]: ages.pop(0) sorted_ages.pop(0) operations += 1 else: ages.append(ages.pop(0)) operations += 1 return operations
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([3, 4, 1]) == 5 assert candidate([1, 2, 4, 3]) == 5 assert candidate([5, 2, 1, 6, 4, 3]) == 16 assert candidate([1, 2, 3, 4, 5]) == 5
PythonSaga/84
from typing import List, Tuple def stupid_pair(nums: List) -> int: """Given an integer array nums, return the number of Stupid pairs in the array. A Stupid pair is a pair (i, j) where: i > 2 * j and index of i < index of j. Take a list of integers as input and return the number of reverse pairs in the list. Example 1: Input: [1,3,2,3,1] Output: 2 Input: [2,4,3,5,1] Output: 3"""
stupid_pair
def stupid_pair(nums: List[int]) -> int: def merge_and_count(left: List[int], right: List[int]) -> Tuple[List[int], int]: merged = [] count = 0 i, j = 0, 0 while i < len(left) and j < len(right): if left[i] > 2 * right[j]: count += len(left) - i j += 1 else: i += 1 i, j = 0, 0 while i < len(left) and j < len(right): if left[i] <= right[j]: merged.append(left[i]) i += 1 else: merged.append(right[j]) j += 1 merged += left[i:] merged += right[j:] return merged, count def merge_sort_and_count(nums: List[int]) -> Tuple[List[int], int]: if len(nums) <= 1: return nums, 0 mid = len(nums) // 2 left, count_left = merge_sort_and_count(nums[:mid]) right, count_right = merge_sort_and_count(nums[mid:]) merged, count_merge = merge_and_count(left, right) return merged, count_left + count_right + count_merge _, count = merge_sort_and_count(nums) return count
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([1, 3, 2, 3, 1]) == 2 assert candidate([2, 4, 3, 5, 1]) == 3 assert candidate([5, 4, 3, 2, 1]) == 4 assert candidate([1, 2, 3, 4, 5]) == 0
PythonSaga/85
from typing import List def shoes_missing(table1: List[int], table2: List[int]) -> List[List[int]]: """You are given two tables, table1 and table2, representing shelves of a shoe store where shoes of different sizes are arranged. Each table is sorted in ascending order of shoe sizes. Your task is to implement a functions: 1. which will merge the two tables into one, 2. which will keep only those shoes that are available in both tables, 3. which will keep only those shoes that are available in unique on both tables., Take input from user for the size of the shoes and display the result accordingly. Input [1, 4, 7, 9, 11] [2, 4, 4, 7, 8, 11, 12] Output [[1, 2, 4, 4, 4, 7, 7, 8, 9, 11, 11, 12] ,[4, 7, 11], [1, 2, 8, 9, 12]]"""
shoes_missing
def merge_tables(table1: List[int], table2: List[int]) -> List[int]: return sorted(table1 + table2) def find_common_elements(table1: List[int], table2: List[int]) -> List[int]: common = [] for size in set(table1): if size in table2: common.append(size) return sorted(common) def find_unique_elements(table1: List[int], table2: List[int]) -> List[int]: unique = [] for size in merge_tables(table1, table2): if size in table1 and size not in table2 or size in table2 and size not in table1: unique.append(size) return unique def shoes_missing(table1: List[int], table2: List[int]) -> List[List[int]]: merged_table = merge_tables(table1, table2) common_elements = find_common_elements(table1, table2) unique_elements = find_unique_elements(table1, table2) return [merged_table, common_elements, unique_elements]
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([1, 4, 7, 9, 11], [2, 4, 4, 7, 8, 11, 12]) == [[1, 2, 4, 4, 4, 7, 7, 8, 9, 11, 11, 12], [4, 7, 11], [1, 2, 8, 9, 12]] assert candidate([5, 8, 10, 12, 15], [2, 7, 10, 12, 14, 16]) == [[2, 5, 7, 8, 10, 10, 12, 12, 14, 15, 16], [10, 12], [2, 5, 7, 8, 14, 15, 16]] assert candidate([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]) == [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] assert candidate([10, 20, 30], [40, 50, 60, 70]) == [[10, 20, 30, 40, 50, 60, 70], [], [10, 20, 30, 40, 50, 60, 70]] assert candidate([], [1, 2, 3, 4, 5]) == [[1, 2, 3, 4, 5], [], [1, 2, 3, 4, 5]]
PythonSaga/86
from typing import List def quick_sort_hoare_partitioning(nums: List[int]) -> List[List[int]]: """My teacher taught that there are various ways to sort a list. and quick sort is one of them. She asked us to do some research about quick sort and implement it in python but in a different way. One is using Lumoto partitioning and the other is using Hoare partitioning. Please help me to implement the Hoare partitioning in python. Take input from the user and sort the list using Hoare partitioning and Lumoto partitioning. Example: Input: [3, 9, 1, 7, 22, 0, 1] Output: [[0, 1, 1, 3, 7, 9, 22], [0, 1, 1, 3, 7, 9, 22]]"""
quick_sort_hoare_partitioning
def hoare_partition(nums: List[int], low: int, high: int) -> int: pivot = nums[low] i = low - 1 j = high + 1 while True: # Move the left index to the right at least once and while the element at # the left index is less than the pivot i += 1 while nums[i] < pivot: i += 1 # Move the right index to the left at least once and while the element at # the right index is greater than the pivot j -= 1 while nums[j] > pivot: j -= 1 # If the indices have crossed, return if i >= j: return j # Swap the elements at the left and right indices nums[i], nums[j] = nums[j], nums[i] def quick_sort_hoare(nums: List[int], low: int, high: int): if low < high: # Partition the array pivot = hoare_partition(nums, low, high) # Sort the two halves quick_sort_hoare(nums, low, pivot) quick_sort_hoare(nums, pivot + 1, high) def quick_sort_hoare_partitioning(nums: List[int]) -> List[List[int]]: sorted_nums_hoare = nums[:] quick_sort_hoare(sorted_nums_hoare, 0, len(sorted_nums_hoare) - 1) return [sorted_nums_hoare]
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([3, 9, 1, 7, 22, 0, 1]) == [[0, 1, 1, 3, 7, 9, 22],[0, 1, 1, 3, 7, 9, 22]] assert candidate([5, 2, 8, 4, 1, 9, 3]) == [[1, 2, 3, 4, 5, 8, 9],[1, 2, 3, 4, 5, 8, 9] ] assert candidate([10, 7, 15, 3, 8, 12, 6]) == [[3, 6, 7, 8, 10, 12, 15], [3, 6, 7, 8, 10, 12, 15]] assert candidate([6, 3, 2, 10, 1, 5, 7, 8]) == [[1, 2, 3, 5, 6, 7, 8, 10], [1, 2, 3, 5, 6, 7, 8, 10]]
PythonSaga/87
from typing import List def chemicals(grp: int, pairs: List[List[int]]) -> int: """The director of your laboratory is planning to conduct some experiments. However, they want to ensure that the selected chemicals are from different groups. You will be given a list of pairs of chemical IDs. Each pair is composed of chemicals from the same group. Determine how many pairs of chemicals from different groups they can choose from. Take input for the number of pairs of chemicals and pairs of chemicals from user and return the number of pairs of chemicals from different groups. Example: Input: 3, [[1, 2], [3, 4], [1, 5]] Output: 6 Input: 2, [[1, 2], [2, 3]] Output: 0"""
chemicals
def find(parent, i): if parent[i] == i: return i parent[i] = find(parent, parent[i]) # Path compression return parent[i] def union(parent, rank, x, y): xroot = find(parent, x) yroot = find(parent, y) if xroot != yroot: # Merge only if x and y are not already in the same set if rank[xroot] < rank[yroot]: parent[xroot] = yroot elif rank[xroot] > rank[yroot]: parent[yroot] = xroot else: parent[yroot] = xroot rank[xroot] += 1 def chemicals(grp: int, pairs: List[List[int]]) -> int: # Map chemical IDs to consecutive indices id_map = {} next_id = 1 for pair in pairs: for chem in pair: if chem not in id_map: id_map[chem] = next_id next_id += 1 parent = [i for i in range(next_id)] rank = [0] * next_id # Union step for pair in pairs: a, b = pair union(parent, rank, id_map[a], id_map[b]) # Count step group_count = {} for i in range(1, next_id): root = find(parent, i) if root not in group_count: group_count[root] = 1 else: group_count[root] += 1 # Calculate step total = sum(group_count.values()) result = 0 for count in group_count.values(): total -= count result += count * total return result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(3, [[1, 2], [3, 4], [1, 5]]) == 6 assert candidate(2, [[1, 2], [2, 3]]) == 0 assert candidate(4, [[1, 2], [3, 4], [2, 3], [4, 5]]) == 0 assert candidate(1, [[1, 2], [2, 3], [5, 4], [4, 5]]) == 10
PythonSaga/88
from typing import List def ship(ships: int, arrival_departure: List[List[int]]) -> int: """Given arrival and departure times of all ships that arrive at a seaport, find the minimum number of berths required for the seaport so that no ship is kept waiting. Consider that all the ships arrive and depart on the same day. Arrival and departure times can never be the same for a ship, but it's possible for the arrival time of one ship to be equal to the departure time of another ship. At any given instance of time, the same berth cannot be used for both the departure of a ship and the arrival of another ship. In such cases, different berths are needed. Note: Time intervals are in the 24-hour format(HHMM) , where the first two characters represent hour (between 00 to 23 ) and the last two characters represent minutes (this may be > 59). Take input from the user for the number of ships, arrival and departure times of each ship. and return the minimum number of berths required. Example 1: Input: 3, [[1000, 1030], [1004, 1130], [1130, 1200]] Output: 2"""
ship
events = [] for ship_info in arrival_departure: arrival, departure = ship_info events.append((arrival, 1)) # 1 represents arrival events.append((departure, -1)) # -1 represents departure events.sort() current_berths = 0 max_berths_required = 0 for event_time, event_type in events: current_berths += event_type max_berths_required = max(max_berths_required, current_berths) return max_berths_required
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(3, [[1000, 1030], [1004, 1130], [1130, 1200]]) == 2 assert candidate(4, [[900, 930], [930, 1000], [945, 1100], [1100, 1130]]) == 2 assert candidate(5, [[1000, 1030], [1030, 1100], [1045, 1130], [1115, 1200], [1130, 1200]]) == 2
PythonSaga/89
from typing import List def alloy(strengths: List[int]) -> int: """We are working in laboratory to create alloy with maximum strength. We are given list of strength of different elements. Using those elements we have to create alloy. maximal strength is defined as nums[i0] * nums[i1] * nums[i2] * ... * nums[iK​], where the strength of elements of indices i0, i1, i2, ... , ik. We have to find the maximum strength of alloy that we can create. Take input from user in form of list and print the maximum strength of alloy that we can create. Example 1: Input: [3, -1, -5, 2, 5, -9] Output: 1350 Input: [-4, -5, -4] Output: 20"""
alloy
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([3, -1, -5, 2, 5, -9]) == 1350 assert candidate([-4, -5, -4]) == 20 assert candidate([2, -3, -2, 4, -1, -6, 1, 3]) == 864 assert candidate([1,-2,3,-4,0,5]) == 120
PythonSaga/90
import math def rankOfPermutation(strg: str) -> int: """Take a string as input from user and print its rank among all the possible permutations sorted lexicographically. Example: Input: 'acb' Output: 2 Input: 'abc' Output: 1 Input: 'string' Output: 598"""
rankOfPermutation
n = len(strg) rank = 1 for i in range(n): smaller_count = 0 for j in range(i + 1, n): if strg[j] < strg[i]: smaller_count += 1 rank += smaller_count * math.factorial(n - i - 1) return rank
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate('acb') == 2 assert candidate('abc') == 1 assert candidate('string') == 598 assert candidate('cba') == 6
PythonSaga/91
from typing import List def longestStretch(arr: List[str]) -> int: """Let's say you attend a car show where cars of different brands are showcased in a row. Find the length of the longest stretch where no two cars are of the same brand. Take the input from the user for the brands of the cars in the order they are placed in the row. Print the length of the longest stretch where no two cars are of the same brand. Example: Input: ['A', 'B', 'D', 'E', 'F', 'G', 'A', 'B', 'E', 'F'] Output: 6 Input: ['B', 'B', 'B', 'A', 'C', 'B'] Output: 3"""
longestStretch
char_index_map = {} # To store the last index where each car brand was seen start = 0 # Start index of the current stretch max_length = 0 # Length of the longest stretch without repeating car brands for end in range(len(arr)): if arr[end] in char_index_map and char_index_map[arr[end]] >= start: # If the car brand is repeated, update the start index start = char_index_map[arr[end]] + 1 char_index_map[arr[end]] = end # Update the last index of the car brand max_length = max(max_length, end - start + 1) # Update the maximum length return max_length
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(['A', 'B', 'D', 'E', 'F', 'G', 'A', 'B', 'E', 'F']) == 6 assert candidate(['B', 'B', 'B', 'A', 'C', 'B']) == 3 assert candidate(['A', 'A', 'B', 'B', 'C', 'C', 'D', 'E', 'F']) == 4 assert candidate(['A', 'B', 'A', 'C', 'A', 'D', 'A', 'E', 'A']) == 2
PythonSaga/92
def cookies_matter(n: int, m: int, tray1: str, tray2: str) -> str: """Let's say I have row of cookie of different types in two trays arranged in a row I want to find smallest window in tray 1 that contains all the cookies in tray 2( including duplicates). Return '-NULL-' if no such window exists. In case there are multiple such windows of same length, return the one with the least starting index. Take input from user for number of cookies in tray 1 and tray 2. Then take input for cookies brand name starting letter for tray 1 and 2 in form of one string. Then take input for cookies brand name starting letter for tray 2 in form of one string. Example: Input: 11,3, 'zoomlazapzo', 'oza' # 11 cookies in tray 1, 3 cookies in tray 2, cookies brand name starting letter for tray 1: zoomlazapzo, cookies brand name starting letter for tray 2: oza Output: apzo Input: 14,3, 'timetopractice', 'toe' # 14 cookies in tray 1, 3 cookies in tray 2, cookies brand name starting letter for tray 1: timetopractice, cookies brand name starting letter for tray 2: toe Output: eto"""
cookies_matter
if n < m or not tray1 or not tray2: return "-NULL-" char_count_tray2 = {} for char in tray2: char_count_tray2[char] = char_count_tray2.get(char, 0) + 1 char_count_current_window = {} required_count = len(char_count_tray2) left, right = 0, 0 min_length = float('inf') min_window_start = 0 while right < n: char_right = tray1[right] char_count_current_window[char_right] = char_count_current_window.get(char_right, 0) + 1 if char_right in char_count_tray2 and char_count_current_window[char_right] == char_count_tray2[char_right]: required_count -= 1 while required_count == 0: if right - left < min_length: min_length = right - left min_window_start = left char_left = tray1[left] char_count_current_window[char_left] -= 1 if char_left in char_count_tray2 and char_count_current_window[char_left] < char_count_tray2[char_left]: required_count += 1 left += 1 right += 1 if min_length == float('inf'): return "-NULL-" else: return tray1[min_window_start:min_window_start + min_length + 1]
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(11, 3, 'zoomlazapzo', 'oza') == 'apzo' assert candidate(14, 3, 'timetopractice', 'toe') == 'eto' assert candidate(5, 2, 'abcbc', 'bc') == 'bc' assert candidate(13, 5, 'Itsgettinghot', 'thing') == 'tingh'
PythonSaga/93
def strong_pass(password: str) -> int: """A strong password meets following conditions: 1. It has at least 6 characters and at most 20 characters. 2. It contains at least one lowercase letter, at least one uppercase letter, and at least one digit. 3. It does not contain three repeating characters in a row (abxxxcA0 is weak but abxxcxA0 is strong). Given a string password, return the minimum number of steps required to make password strong. if password is already strong, return 0. In one step, you can: a. Insert one character to password, b. Delete one character from password, or c. Replace one character of password with another character. Take string input from user and return the minimum number of steps required to make password strong Example 1: Input: 'b' Output: 5 Input: 'aA0' Output: 3"""
strong_pass
# Condition 1: Length between 6 and 20 n = len(password) steps = 0 # Condition 2: At least one lowercase, one uppercase, and one digit has_lowercase = any(char.islower() for char in password) has_uppercase = any(char.isupper() for char in password) has_digit = any(char.isdigit() for char in password) # Count of missing character types missing_types_count = 3 - (has_lowercase + has_uppercase + has_digit) # If the length is less than 6, add the difference to the steps if n < 6: steps += max(0, 6 - n) # If the length is more than 20, add the difference to the steps elif n > 20: extra_chars = max(0, n - 20) steps += extra_chars # Condition 3: Check for repeating characters for i in range(2, n): if password[i] == password[i - 1] == password[i - 2]: steps += 1 # Choose the maximum between missing character types and steps return max(missing_types_count, steps)
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate('b') == 5 assert candidate('aA0') == 3 assert candidate('aaaaAA12345') == 2 assert candidate('abcdefghijABCDEFGHIJ12345') == 5
PythonSaga/94
def overlap_substring(s: str) -> str: """Given a string s, find and return any substring of s that occurs two or more times, allowing for overlapping occurrences. The goal is to return a duplicated substring with the maximum length. If no such duplicated substring exists, the output should be an 'EMPTY' string. Take input from user and print the output. Example 1: Input: 'banana' Output: 'ana' Input: 'abcdcdbacd' Output: 'cd'""" n = len(s) result = 'EMPTY' for i in range(n): for j in range(i + 1, n): if s[i:j] in s[j:]: if len(s[i:j]) > len(result): result = s[i:j] return result
overlap_substring
length = len(s) result = "" for i in range(length): for j in range(i + 1, length): substring = s[i:j] if substring in s[j:]: if len(substring) > len(result): result = substring return result if result else "EMPTY"
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate('banana') == 'ana' assert candidate('abcdcdbacd') == 'cd' assert candidate('abcdefg') == 'EMPTY' assert candidate('ababcabab') == 'abab'
PythonSaga/95
from typing import List def find_two_odd_occuring_numbers(numbers: List[int]) -> List[int]: """I have am unsorted list of numbers. In that list other than two numbers all other numbers have occured even number of times. Find those two numbers in O(n) time ( you can use bit manipulation for this) Take input from user and print the output. Use bit manipulation to solve this problem. Example: Input: [11, 22, 33, 11, 11, 22, 11, 44] Output:[33, 44] Input: [10, 11] Output:[10, 11]"""
find_two_odd_occuring_numbers
# Step 1: Find XOR of all elements xor_result = 0 for num in numbers: xor_result ^= num # Step 2: Find the rightmost set bit rightmost_set_bit = xor_result & -xor_result # Step 3: Divide the list into two sublists group1, group2 = 0, 0 for num in numbers: if num & rightmost_set_bit: group1 ^= num else: group2 ^= num return [group1, group2]
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert set(candidate([11, 22, 33, 11, 11, 22, 11, 44])) == [33, 44] assert set(candidate([10, 11])) == [11, 10] assert set(candidate([1, 1, 2, 2, 3, 4, 4, 5])) == [3, 5] assert set(candidate([5, 5, 7, 7, 9, 9, 11, 11, 13, 13, 15,0])) == [15, 0]
PythonSaga/96
from typing import List def find_max_and_or(numbers: List[int]) -> List[int]: """My teacher gave me list of numbers and asked me to find 'maximum AND value 'and 'maximum OR value' generated by any pair of numbers. Try to use bit manipulation to solve this problem. Take input from user and find the maximum and value and maximum or value generated by any pair of numbers. Expected Time Complexity: O(N * log M), where M is the maximum element of the array. Example: Input: [4, 8, 12, 16] Output: [8, 28] # Maximum AND value = 8, Maximum OR value = 28 Input: [4, 8, 16, 2] Output: [0, 24] # Maximum AND value = 0, Maximum OR value = 24"""
find_max_and_or
max_num = max(numbers) max_and, max_or = 0, 0 # Calculate maximum OR value by ORing all numbers for num in numbers: max_or |= num # Iterate over each bit position for bit in range(max_num.bit_length(), -1, -1): # Filter numbers that have the current bit set candidates = [num for num in numbers if num & (1 << bit)] # If at least two numbers have this bit set, update max_and if len(candidates) >= 2: max_and |= (1 << bit) # Update the numbers list to only include these candidates # as further bits set will only be found within these numbers numbers = candidates return [max_and, max_or]
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([4, 8, 12, 16]) == [8, 28] assert candidate([4, 8, 16, 2]) == [0, 24] assert candidate([7, 15, 22, 19]) == [18, 23] assert candidate([3, 5, 10, 15]) == [10, 15]
PythonSaga/97
def set_bits(n:int) -> int: """Today in class we were taught that we can written any number in form of 0 and 1. My tutor asked me to find number of set bits are present in a number from 1 to n( both inclusive). Take a input from user and print the number of set bits in that number. Example: Input: 4 Output: 5 Input: 17 Output: 35"""
set_bits
def count_set_bits(n: int) -> int: count = 0 while n: n &= (n - 1) count += 1 return count def set_bits(n: int) -> int: total_set_bits = 0 for i in range(1, n + 1): total_set_bits += count_set_bits(i) return total_set_bits
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(4) == 5 assert candidate(17) == 35 assert candidate(10) == 17 assert candidate(7) == 12
PythonSaga/98
def quotient(dividend:int, divisor:int) -> int: """My teacher gave me divident and divisor and asked me to find quotient. But the condition is that I have to divide two integers without using multiplication, division, and mod operator. Take input from user and print the quotient. The The integer division should truncate toward zero, which means losing its fractional part. For example, 9.343 would be truncated to 9, and -1.335 would be truncated to -1. Example 1: Input:10,3 # 10 is the dividend and 3 is the divisor Output:3 # 3 is the quotient Input:7,-3 Output:-2"""
quotient
# Determine the sign of the quotient sign = -1 if (dividend < 0) ^ (divisor < 0) else 1 # Take the absolute values of dividend and divisor dividend = abs(dividend) divisor = abs(divisor) quotient_result = 0 # Bitwise division while dividend >= divisor: dividend -= divisor quotient_result += 1 return sign * quotient_result
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(10, 3) == 3 assert candidate(7, -3) == -2 assert candidate(-20, 4) == -5 assert candidate(15, 2) == 7
PythonSaga/99
from typing import List def good_subset(arr: List[int]) -> int: """I found one interesting question help me to solve this problem. I have a list of numbers and I want to find all the subsets of this list which are amazing. A group of numbers is said amazing if its product can be represented as a product of one or more distinct prime numbers. Take input from user and print total number of different amazing subsets of the given list. Return the final output modulo 10^9+7. Example: Input: [1,2,3,4] Output: 6 # 6 good subsets Input: [4,2,3,15] Output: 5 """
good_subset
MOD = 10**9 + 7 max_val = max(arr) # Sieve of Eratosthenes to find primes up to max_val prime = [True for _ in range(max_val + 1)] p = 2 while (p * p <= max_val): if (prime[p] == True): for i in range(p * p, max_val + 1, p): prime[i] = False p += 1 primes = [p for p in range(2, max_val + 1) if prime[p]] # Dynamic programming array dp = [0] * (1 << len(primes)) dp[0] = 1 # Empty subset for num in arr: if num == 1: # Special case for 1 for i in range(len(dp)): dp[i] = (dp[i] * 2) % MOD continue # Find prime factors of num and update dp array mask = 0 for i, p in enumerate(primes): if num % p == 0: count = 0 while num % p == 0: num //= p count += 1 if count > 1: # Skip if p^2 divides num mask = 0 break mask |= 1 << i if mask > 0: for i in range(len(dp) - 1, -1, -1): if dp[i] > 0 and (i & mask) == 0: dp[i | mask] = (dp[i | mask] + dp[i]) % MOD return (sum(dp) - 1) % MOD # Exclude empty subset
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([1, 2, 3, 4]) == 6 assert candidate([4, 2, 3, 15]) == 5