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...
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([10...
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. ...
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...
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 r...
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][...
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: [...
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 poi...
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 cand...
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 ...
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...
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 ...
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...
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 ...
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 ente...
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 ente...
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...
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 fr...
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. E...
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'...
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....
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: ...
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 =...
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 ...
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) ==...
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...
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 ...
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...
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 th...
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}, ...
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_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 = ...
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, hexad...
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, i...
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 palind...
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 whic...
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_...
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': 'ma...
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 d...
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. wha...
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 ...
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], flo...
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([...
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...
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 pr...
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...
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 suc...
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 jum...
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." asse...
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 numb...
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:...
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 ca...
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 first...
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=first...
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...
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 ...
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, n...
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, "palindr...
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 conv...
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 retur...
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 no...
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 whe...
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 == "cuboi...
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 asser...
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 multipl...
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 ...
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 ...
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 ...
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...
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 pas...
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 ...
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 can...
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 da...
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_da...
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" as...
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 ...
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 = roun...
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...
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 ...
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 p...
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'...
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] resu...
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'...
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 li...
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...
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
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 can...
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...
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) == ['\ /', ' \ / ', ' \ / ', ' ...
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...
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 le...
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 asse...
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 n...
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 ...
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. ...
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...
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...
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 t...
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...
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': ...
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', ...
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...
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, ...
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 ...
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...
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...
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 co...
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...
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() de...
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("...
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. ...
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 ...
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 ...
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...
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(...
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, ...
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 ...
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 c...
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 ensur...
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 pos...
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 nex...
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 ...
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,...
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 ...
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...
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, R...
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, ...
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...
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...
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 =...
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 ta...
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...
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...
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', ...
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. T...
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 output...
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 r...
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 NITI...
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...
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 ...
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]...
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...
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]...
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 'Inser...
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....
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, ...
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. t...
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...
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 ...
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'] ...
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 pr...
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 occur...
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("Iscored90Marksinfina...
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 diffe...
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: ...
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 ...
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, r...
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']]) a...
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 ...
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....
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 inpu...
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 inpu...
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] i...
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], [...
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...
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)] ...
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 probl...
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...
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....
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 imple...
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 n...
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...
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 d...
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...
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...
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 t...
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 li...
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 ...
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 implemen...
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 fin...
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,...
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 ...
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: ...
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]) == ...
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 ...
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...
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 o...
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 +...
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], [11...
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] * ... * n...
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 orde...
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...
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',...
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 ...
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: ...
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 ...
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 missi...
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'...
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 inp...
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 ...
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...
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 maximu...
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...
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: Inp...
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...
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 * ...
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 on...
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...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([1, 2, 3, 4]) == 6 assert candidate([4, 2, 3, 15]) == 5