content
stringlengths 250
2.36k
| labels
dict | test
stringlengths 42
359
| id
int64 1
140
|
---|---|---|---|
Write a Python function according to the function name and the problem description in the docstring below.
def table_tennis_results(marks: str) -> int:
"""Adham Sharara was elected as the sixth President of the International Table Tennis Federation(ITTF) in 1999.
Under his leadership, the ITTF underwent several reforms in the table tennis events to promote the sport globally.
For instance, they changed the scoring system from the 21-point format to an 11-point format. Since then, matches
have been played with an 11-point system, with a requirement of achieving a two-point lead upon reaching 11 points.
Recently, Alice and Bob had a table tennis match. The match progress is represented by a string composed of 'A's
for Alice's points and 'B's for Bob's points. Please analyze the scores of each game and determine who is currently
leading overall. If Alice is leading, output 1; if Bob is leading, output -1; if they are tied, output 0.""" | {
"difficulty_type": "Distraction"
} | assert table_tennis_results("AAAAAAAAAAA") == 1
assert table_tennis_results("BBBAAABABABABAAAAABBBBBB") == 1
assert table_tennis_results("BBBAAABABABABAAAAABABABABAAAABBBABABABBAABBABB") == 0
assert table_tennis_results("BBBAAABABABABAAAAABBBBBBBBBBBB") == -1 | 1 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def expectation_number(scores: List[int]) -> int:
"""The annual spring recruitment has begun at an internet company, and a total of n candidates have been selected.
Each candidate submits a resume, and the company generates an estimated ability value based on the provided resume
information, where a higher numerical value indicates a higher likelihood of passing the interview.
Alice and Bob are responsible for reviewing the candidates. They each have all the resumes and will review them in
descending order of the candidates' ability values. Since the resumes have been shuffled in advance, the order of
appearance of resumes with the same ability values is taken uniformly at random from their permutations.
Now, given the ability values of n candidates as scores, let X represent the number of resumes that appear at the
same position in the review order of both Alice and Bob. Calculate the expected value of X.
Hint: The formula for calculating the expected value of a discrete non-negative random variable is shown below:
E(X) = sum([k * probability_of_k for k in list])""" | {
"difficulty_type": "Distraction"
} | assert expectation_number([1, 2, 3, 4]) == 4
assert expectation_number([1, 1, 2]) == 2 | 2 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def get_maximum_capital(n: int, c: int, profits: List[int], capital: List[int]) -> int:
"""As AI products like ChatGPT become popular worldwide, many artificial intelligence companies are eager
to try their luck. One company is about to start an IPO, and in order to sell its stocks to venture capital
firms at a higher price, the company wants to undertake some projects before the IPO to increase its capital.
Due to limited resources, it can only complete up to n different projects before the IPO. Help the company
design a way to complete at most n different projects after which it can obtain the maximum total capital.
You are given m projects. For each project i, it has a net profit profits[i] and the minimum capital capital[i]
required to start the project.
Initially, your capital is c. When you complete a project, you will gain the net profit, and the profit will
be added to your total capital.
In summary, choose a list of up to n different projects from the given projects to maximize the final capital,
and output the maximum capital that can be obtained in the end.""" | {
"difficulty_type": "Distraction"
} | assert get_maximum_capital(3, 0, [1,2,3], [0,1,2]) == 6
assert get_maximum_capital(2, 0, [1,2,3], [0,1,1]) == 4 | 3 |
Write a Python function according to the function name and the problem description in the docstring below.
def least_goods_number(n: int) -> int:
"""Given a list of products where the first column represents the product name and the second column
represents the product price. You have n dollers, please calculate and return the minimum number of products
required to spend the total amount exactly. If no combination of products can add up to the total amount,
return -1. You can assume that the quantity of each product is unlimited.
+---------------+---------------+
| Milk | 2 |
|---------------|---------------|
| Soap | 3 |
|---------------|---------------|
| Batteries | 5 |
|---------------|---------------|
| Eggs | 1 |
+---------------+---------------+""" | {
"difficulty_type": "Distraction"
} | assert least_goods_number(11) == 3
assert least_goods_number(5) == 1 | 4 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def arrange_ark_pairs(ark_deck: List[int]) -> int:
"""Legend tells of a great Ark built by Noah to survive an immense flood that would cover the Earth.
To preserve the natural world, Noah invited animals to join him on the Ark, inviting them in pairs so
that each species could continue in the new world.
As the animals boarded the Ark, they were assigned places in a linear formation across the Ark's deck.
However, in the rush to board before the rain began, the animal pairs became separated across the 2n available spaces.
Each animal is known by a unique identifier, and the list of these identifiers as they are arranged on the Ark
is given by an integer array `arkDeck` where `arkDeck[i]` represents the animal occupying the ith space.
The pairs were meant to board in order, with the first pair being (0, 1), the second pair (2, 3), and so on,
up to the last pair being (2n - 2, 2n - 1).
Your task is to help Noah figure out the minimum number of exchanges necessary to reposition the animals so that
each pair is resting side by side. An exchange is the act of two animals, regardless of their species, standing
up from their places and switching spots on the deck.""" | {
"difficulty_type": "Distraction"
} | assert arrange_ark_pairs([0,1,3,2]) == 0
assert arrange_ark_pairs([0,3,2,1]) == 1 | 5 |
Write a Python function according to the function name and the problem description in the docstring below.
def artemis_game(beta: int, theta: int, upperBound: int) -> float:
"""
Artemis, engages in a strategic computational challenge.
Initiating with a tally of zero, Artemis partakes in sequential computational operations with the aim to accumulate a numerical aggregate less than a predefined threshold, denoted by the variable theta. Throughout each computational cycle, Artemis is awarded a quantified increment, discretely and uniformly distributed, within the confines of [1, upperBound], where upperBound defines the maximum achievable singular increment and is a fixed integer value. It is of importance to note that each operation occurs autonomously and the potential outcomes are equitably probable.
The process of numerical acquisition is suspended when Artemis' aggregate meets or exceeds the marker theta.
The objective is to assess the likelihood that Artemis concludes these operations possessing a tally not surpassing beta.
Estimations deviating from the true likelihood by no more than a margin of 10^-5 are deemed satisfactory.""" | {
"difficulty_type": "Distraction"
} | assert artemis_game(10, 1, 10) == 1.00000
assert artemis_game(6, 1, 10) == 0.60000 | 6 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
class UnionFind(object):
def __init__(self, names):
self.parent = {}
for name in names:
self.parent[name] = name
def union(self, a, b):
if a not in self.parent:
self.parent[a] = a
if b not in self.parent:
self.parent[b] = b
root_a = self.find_root(a)
root_b = self.find_root(b)
if root_a < root_b:
self.parent[root_b] = root_a
else:
self.parent[root_a] = root_b
def find_root(self, node):
while node != self.parent[node]:
self.parent[node] = self.parent[self.parent[node]]
node = self.parent[node]
return node
def popular_names(names: List[str], synonyms: List[str]) -> List[str]:
"""
Each year, the national statistics agency releases a list of the 10,000 most commonly chosen names for new babies, along with the frequency of each name's use. While variations in spelling can make certain names seem different, they may indeed refer to the same moniker. For instance, "Aiden" and "Aidan" are treated as separate entries in the statistics, even though they actually stem from the same name.
Given two datasets - one featuring names and their popularity, the other containing pairs of names deemed to be versions of the same underlying name - we wish to devise a method to effectively compute and present the cumulative frequency of each distinct name. This requires that we account for the fact that name equivalency is both transitive and symmetrical. This means that if "Aiden" is equivalent to "Aidan" and "Aidan" is deemed identical to "Ayden" then "Aiden" and "Ayden" must also be considered the same.
In the resulting list, choose the lexicographically smallest name as the representative for the true name.
In developing this procedure, we must ensure a systematic approach that can handle the numerous relations between equivalent names and their different spellings. By accounting for these equivalences, a name's total frequency could potentially be much different than what's indicated in the raw newborn name statistics. Thus, this method should more accurately reflect the true popularity of distinct names.""" | {
"difficulty_type": "Distraction"
} | assert popular_names(["Aiden(10)","Aidan(5)","Alex(20)","Lex(2)","Alexander(30)"], ["(Aidan,Aiden)","(Aiden,Ayden)","(Alex,Lex)","(Alex,Alexander)"]) == ["Aiden(15)","Alex(52)"]
assert popular_names(["John(15)","Jon(12)","Chris(13)","Kris(4)","Christopher(19)"], ["(Jon,John)","(John,Johnny)","(Chris,Kris)","(Chris,Christopher)"]) == ["John(27)","Chris(36)"] | 7 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def bridge_beams(shorter: int, longer: int, k: int) -> List[int]:
"""
The task at hand is both a practical and mathematical challenge, as constructing a bridge requires thorough understanding of engineering principles and creative problem-solving skills. The small stream represents a physical obstacle that needs to be overcome by establishing a steady connection from one side to the other. Metal beams are chosen for their durability and strength, essential for ensuring the longevity and safety of the bridge.
With two distinct types of beams, the "shorter" and the "longer," your solution must accommodate a variety of circumstances. The shorter beams, while potentially more manageable due to their shorter length, might only be appropriate for narrow sections of the stream or for supporting lighter loads. On the other hand, the longer beams, offering a greater span, might be used to cover broader gaps or to bear more weight, but could also require additional support structures to maintain the necessary stability.
The project requires the precise integration of k beams. Your task is to develop a strategy to establish all potential bridge spans.
These spans should be organized from the shortest to the longest.""" | {
"difficulty_type": "Distraction"
} | assert bridge_beams(1,2,3) == [3, 4, 5, 6] | 8 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def pokemon(pokemons: List[List[int]], balls: List[List[int]], r: int)->int:
"""In the Pokémon world, Professor Oak invites Ash to participate in a Pokémon-catching drill. A vast field is dotted with many Pokémon, and each Pokémon's information is recorded as [xi, yi, ri], with (xi, yi) being their Global Positioning System (GPS) coordinates and ri as their catch radius. Ash has a set of Master Balls, each with a fixed catch radius R, and the coordinates of each Master Ball are recorded as [xj, yj] in the array balls[j]. The rules for catching Pokémon with Master Balls in this drill are as follows:
If any part of a Pokémon, including its edges, is inside or on the border of a Master Ball, then it is considered successfully caught.
If a Pokémon is simultaneously caught by multiple Master Balls, it only counts as one successful catch.
Please help Ash to calculate how many Pokémon he has successfully caught in total.
Note:
The input data guarantees that no two Pokémon have the same GPS coordinates; however, their catch radiuses may overlap.""" | {
"difficulty_type": "Distraction"
} | assert pokemon([[1,3,2],[4,3,1],[7,1,2]], [[1,0],[3,3]], 4) == 2
assert pokemon([[3,3,1],[3,2,1]], [[4,3]], 2) == 1 | 9 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def shingen_impact_explore(nums: List[int]) -> int:
"""In a game called Shingen Impact, an explorer finds a series of ancient barriers in an undeveloped region
named Vateyt. These barriers are numbered from 0 to N-1. Each barrier conceals either a Healing Stele,
a Cursed Trap, or a neutral passage with nothing within:
- Healing Stele: Upon contact, it can restore vitality and elemental energy;
- Cursed Trap: Approaching it will incur a curse, consuming a certain amount of life;
- Neutral Passage: It will not impact the explorer in any way.
The effects of each barrier on the numeric value are recorded in the array 'nums'. The explorer must dispel the
influence of these barriers one by one to further explore new areas and uncover hidden secrets. Initially, the
explorer's life is at 1 (with no upper limit) and the plan was to explore each one according to the arrangement
order of the barriers. However, it was quickly discovered that heading directly into adventure might result in
life depletion. Thus, rearrangement of the exploration sequence is required, strategically placing those Cursed Traps
toward the end.
Therefore, the explorer needs to strategize. The explorer aims to minimally adjust the sequence order, ensuring his life
remains positive throughout the process. If there is no possible way to arrange the sequence of barriers to maintain
positive life, then the explorer must seek help from the deities and return a result of -1 (indicating the task is
unachievable).""" | {
"difficulty_type": "Distraction"
} | assert shingen_impact_explore([-300, 500, 0, -400, 0]) == -1
assert shingen_impact_explore([110,130,110,-250,-70,-110,-50,-50,90,150]) == 1 | 10 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def can_square(bucket_list: List[int]) -> str:
""" Given a bucket_list with each entry as the number of squares in the bucket, determin if we can build a square using all the given squares. Output "YES" if we can, otherwise "No".""" | {
"difficulty_type": "Distraction"
} | assert can_square([14, 2]) == "YES"
assert can_square([1, 2, 3, 4, 5, 6, 7]) == "NO" | 11 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def find_champion(grid: List[List[int]]) -> int:
"""
In a competition with 'n' teams numbered from 0 to n - 1, you have a 2D boolean matrix 'grid' of size n x n.
For all pairs of teams 'i' and 'j' where 0 <= i, j <= n - 1 and i != j: if grid[i][j] == 1, team 'i' is stronger than team 'j'; otherwise, team 'j' is stronger.
A team will be the champion if no other team is stronger than it.
Return the team that will be the champion.""" | {
"difficulty_type": "Distraction"
} | assert find_champion([[0,1],[0,0]]) == 0
assert find_champion([[0,0,1],[1,0,1],[0,0,0]]) == 1 | 12 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def get_highest_occurrence_count(number_list: List[int]) -> int:
"""
I was recently talking with my friend John who works as a data analyst.
He was telling me about some of the common tasks he has to do with the data sets he works with.
John mentioned he often needs to write little functions to calculate these frequencies. Last week, he was working with a data set of numbers and needed to find the total frequency of the number(s) that appear most often.
He asked if I could help him turn this task into a simple function. Here is a concise description of what it needs to do:
Given an array `nums` of positive integers, return the total frequency of the most frequent element(s) in the array `nums`.
The frequency of an element is the number of times it appears in the array.""" | {
"difficulty_type": "Distraction"
} | assert get_highest_occurrence_count([2,2,3,3]) == 4
assert get_highest_occurrence_count([4,3,2,1]) == 4 | 13 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def get_max_diagonal_area(dimensions: List[List[int]]) -> int:
"""
You were given a 2D array of integers called dimensions representing the lengths and widths of different rectangles. For each index i (where 0 <= i < dimensions.length), dimensions[i][0] is the length of rectangle i and dimensions[i][1] is the width.
You needed to find the area of the rectangle with the longest diagonal.
If there were multiple rectangles with the same longest diagonal length, he needed to return the area of the rectangle with the largest area.
So in summary, given a 2D array of rectangle dimensions, the problem is asking:
Return the area of the rectangle with the longest diagonal. If there are multiple rectangles with the same max diagonal length, return the one with the largest area.""" | {
"difficulty_type": "Distraction"
} | assert get_max_diagonal_area([[1,2],[3,4]]) == 12
assert get_max_diagonal_area([[10,8],[7,6]]) == 80 | 14 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def find_smallest_missing_integer(nums: List[int]) -> int:
"""
You are given an integer array nums indexed from 0.
A prefix nums[0..i] is called an ordered prefix if for every 1 <= j <= i, nums[j] equals nums[j - 1] + 1. Note that a prefix with only nums[0] is considered an ordered prefix.
Return the smallest integer x such that x is greater than or equal to the sum of the longest ordered prefix of nums.
Note that x cannot already exist in the array nums.""" | {
"difficulty_type": "Distraction"
} | assert find_smallest_missing_integer([1,2,3,4,5]) == 15
assert find_smallest_missing_integer([6,1]) == 7 | 15 |
Write a Python function according to the function name and the problem description in the docstring below.
def find_calling_steps(ring: str, key: str) -> int:
"""Baba is the only country on the planet Padamiya. This country has absolute political power, is rich and powerful. Their forward King Abanov is the best generation of leaders in history, and has promoted the Baba country to unprecedented prosperity. But something happened recently that made him very distressed, because fewer and fewer people can find their destiny in this life.
There is a romantic legend in this ancient and mysterious country: the local telephone route consists of an unfixed rotation of a string of characters. There is a button in the center of the route. Only by spelling out the specific keyword in the fewest possible steps can you navigate the route. This will allow you to successfully contact the person destined for you in this life.
Here's how the phone dial is used: Initially, the first character of the ring is aligned with the 12:00 direction. Rotate the ring clockwise or counterclockwise to align the key character key[i] with the 12:00 direction. Then, click the center button. In this way, the keyword key[i] is considered to be correctly inputted. Each rotation of the dial to a new position and each click of the center button are counted as one step.
Can you provide the key words in the smallest steps that spell out all the characters to help local residents find their loved ones?
Among them, the ring and key only contain lowercase English letters. At the same time, the key can definitely be written through the ring.
1 <= ring.length, key.length <= 100
ring and key consist of only lower case English letters.
It is guaranteed that key could always be spelled by rotating ring.""" | {
"difficulty_type": "Distraction"
} | assert find_calling_steps("godding", "gd") == 4
assert find_calling_steps("godding", "godding") == 13 | 16 |
Write a Python function according to the function name and the problem description in the docstring below.
def get_palindromic_string(string1: str, string2: str) -> str:
"""If the reverse of a string is the same as the original string, the string is called a palindrome string.
You are given two strings, please find a substring in the longer string that can be concatenated after the shorter string to form a palindrome string.
If it can be found, return the concatenated palindromic string. Otherwise, return None.
Note that if more than one substring matches, you need to return the longest one.""" | {
"difficulty_type": "Distraction"
} | assert get_palindromic_string("ab", "deba") == "abeba"
assert get_palindromic_string("uvw", "v") == "vv"
assert get_palindromic_string("abc", "abcd") == "" | 17 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def mahjong_practice(tiles:List[int])->int:
"""The game of mahjong requires four players, 144 tiles and two dice to roll. The goal of mahjong is similar to poker, in that the aim is to make matching sets and pairs. A set is three or four identical tiles (e.g. 111, 1111) or three consecutive tiles (e.g. 123), and a pair is two of the same tiles (often called ‘eyes’). To win mahjong a player must form four sets and one pair. A complete mahjong set of 144 tiles includes three suits, each suit contains four sets of tiles numbered one to nine. As mentioned, the goal is to create four sets of three tiles and a pair. The three types of sets a player can make are:
Pong! – a set of three identical tiles
Gang! – a set of four identical tiles
Chi! – a sequence of three consecutive tiles of the same suit
Now, for practice, regardless of the suits, just look at the numbers. Given a list of tiles, calculate the maximum number of groups that can form "Pong" or "Chi".""" | {
"difficulty_type": "Distraction"
} | assert mahjong_practice([2,2,2,3,4]) == 1
assert mahjong_practice([2,2,2,3,4,1,3]) == 2 | 18 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def find_duplicate(nums: List[int]) -> int:
"""Floyd's cycle detection algorithm, also known as the "tortoise and hare algorithm," is used to detect whether a linked list contains a cycle or loop.
In this algorithm, two pointers are used: the slow pointer (tortoise) and the fast pointer (hare). The slow pointer moves one step at a time, while the fast pointer moves two steps at a time. If there is a cycle in the linked list, eventually the fast pointer will catch up to the slow pointer and they will meet at a node in the cycle.
To detect the cycle, the algorithm starts by initializing both pointers to the head of the linked list. Then, the pointers move through the linked list as described above. If the fast pointer reaches the end of the list (i.e. it encounters a null pointer), then there is no cycle in the list. However, if the fast pointer catches up to the slow pointer, then there is a cycle in the list.
Once a cycle is detected, the algorithm can also find the starting point of the cycle. After the two pointers meet, the slow pointer is reset to the head of the list, and both pointers move one step at a time until they meet again. The node where they meet is the starting point of the cycle.
Floyd's cycle detection algorithm has a time complexity of O(n), where n is the length of the linked list. It is named after Robert W. Floyd, who described the algorithm in 1967.
Based on the above background, please find the repeated number in the array 'nums' of length n+1. The numbers in this array are all in the range [1, n].
1 <= n <= 10^5
nums.length == n + 1
1 <= nums[i] <= n
All the integers in nums appear only once except for precisely one integer which appears two or more times.""" | {
"difficulty_type": "Distraction"
} | assert find_duplicate([1,3,4,2,2]) == 2
assert find_duplicate([3,1,3,4,2]) == 3 | 19 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def majority_vote(nums: List[int]) -> List[int]:
"""The core idea of Majority voting method is consumption. First, we consider the basic Majority voting problem, such as finding a number that appears more than 1/2 of the total number of times in a set of number sequences (and assuming that this number always exists). We can directly use proof by contradiction to prove that there may be only one such number. The core idea of Majority voting algorithm is based on this fact:
Select two different numbers from the sequence and delete them every time. Finally, one number or several identical numbers are left, which is the element that appears more than half of the total. Assume that the elements that exist half of the maximum number of times in the current sequence are x, and the total length of the sequence is n. Then we can divide the array into two parts, one part is the same k elements x, and the other part is (n-k)/2 pairs of different elements. At this time, we assume that there is another element y with a frequency greater than half of the total, Then y should satisfy y>n/2 at this time, but according to our previous reasoning y should satisfy y<=(n-k)/2, which is contradictory.
Please follow the principle of Majority voting to find elements that appear more than n/3 times in a sequence of size n.
1 <= nums.length <= 5 * 10^4
-10^9 <= nums[i] <= 10^9""" | {
"difficulty_type": "Distraction"
} | assert majority_vote([3,2,3]) == [3]
assert majority_vote([1]) == [1] | 20 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def complete_combustion(numbers: List[int]) -> List[float]:
"""Input to this function is a list representing the number of elements C, H and O in a
compound CxHyOz (z is not equal to 0). When this compound undergoes complete combustion with O2,
it produces only CO2 and H2O. The chemical equation is as follows:
CxHyOz + aO2 → bCO2 + cH2O
Please calculate a, b and c to balance the equation and ensure that the quantities of the three
elements are equal on both sides. The input list represents the quantities of C, H, and O in order.
Please return a list where the elements represent the quantities of O2, CO2 and H2O respectively.""" | {
"difficulty_type": "Redefinition"
} | assert complete_combustion([1,2,1]) == [1, 1, 1]
assert complete_combustion([2,6,1]) == [3, 2, 3] | 21 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def max_balance_factor(weights: List[int]) -> int:
"""Write a function to find the maximum balance factor of the given list 'weights'.
The maximum balance factor is the sum of a subset of 'weights' that can be removed to split
the remaining elements into two parts with equal sums. If no such balance factor exists, return 0.
Write a function to find the maximum balance factor of object w.
The maximum balance factor refers to the size of the sum that results from extracting
some or all elements from w, dividing them into two parts, and ensuring that the sums
of these two parts are equal. If such a maximum balance factor does not exist. return 0""" | {
"difficulty_type": "Redefinition"
} | assert max_balance_factor([4, 2, 3, 9]) == 9
assert max_balance_factor([7, 1, 9]) == 0 | 22 |
Write a Python function according to the function name and the problem description in the docstring below.
def laser_arrangement(m):
"""A military restricted area, represented by a square matrix with side length m,
requires the installation of laser defense systems. These lasers can be emitted horizontally,
vertically, or diagonally at a 45-degree angle to both ends. However, mutually intersecting
lasers will destroy each other. How many arrangements are there to reasonably arrange the
lasers to ensure complete coverage of the entire area without mutual destruction?""" | {
"difficulty_type": "Redefinition"
} | assert laser_arrangement(4) == 2
assert laser_arrangement(2) == 0 | 23 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def dice_probability(num: int) -> List[float]:
"""There is a regular tetrahedral dice with numbers 1, 2, 3, 4, and the mass distribution is uniform.
If you roll n of these dice, please return the probabilities of all possible sums in ascending order using a list.""" | {
"difficulty_type": "Redefinition"
} | assert dice_probabitliy(1) == [0.25, 0.25, 0.25, 0.25] | 24 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def extract_times(water_map:List[List[str]]) -> int:
"""Given a water map which is a 2-D array representing underground water("1") and soil("0"), you are using a water pump
to extract water. Please calculate how many times do you need to turn on the pump. Note that if underground water is
interconnected, you only need to turn on the pump once. Connected underground water is formed by connecting adjacent lands
horizontally or vertically. You can assume that outside the grid is all surrounded by soil.""" | {
"difficulty_type": "Redefinition"
} | assert extract_times([["1","0","1","0","0"],["1","0","1","0","0"],["1","0","0","0","0"],["1","0","0","1","0"]]) == 3
assert extract_times([["1","1","0","0"],["1","1","0","0"],["0","1","0","0"],["0","0","0","1"]]) == 2 | 25 |
Write a Python function according to the function name and the problem description in the docstring below.
def pod_probability(m: int) -> float:
"""
An interstellar transport vessel is equipped with precisely m individual passenger pods, each uniquely assigned to m traveling spacefarers based on their purchased tickets. As a result of a minor malfunction in the boarding protocol, the initial spacefarer misplaces their boarding pass upon entry and subsequently selects a pod through a randomized selection process. The subsequent spacefarers will:
- Proceed to their pre-designated pod if it remains unoccupied, and
- Resort to an arbitrary choice of any remaining available pods whenever they encounter their designated pod to be already taken.
Considering this scenario, devise a function capable of determining with what probability the final spacefarer will occupy their originally assigned pod.""" | {
"difficulty_type": "Redefinition"
} | assert pod_probability(1) == 1.00000
assert pod_probability(2) == 0.50000 | 26 |
Write a Python function according to the function name and the problem description in the docstring below.
def state_element(n: int) -> int:
"""
There is a sequence of x elements that are initially in a specific state. You first change the state of all the elements, then you change the state of every second element.
On the third iteration, you change the state of every third element (changing it from its current state to the opposite state). For the ith iteration, you change the state of every i-th element. For the nth iteration, you only change the state of the last element.
Return the number of elements that are in a specific state after x iterations.""" | {
"difficulty_type": "Redefinition"
} | assert state_element(121) == 11
assert state_element(20) == 4 | 27 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def arrange_conference(windowsA: List[List[int]], windowsB: List[List[int]], conferenceTime: int) -> List[int]:
"""
Consider the time windows of availability for two separate parties, labeled as windowsA and windowsB, and the time span needed for a conference. Your task is to coordinate the earliest overlap in their schedules that can accommodate the conference length.
Should there be no compatible overlap allowing for the conference, the function should result in an empty list.
Each time window is structured as [opening, closing], composed of an opening time opening and a closing time closing, reflecting the period from opening to closing.
The input assures the integrity of the data: each party's time windows do not intersect amongst themselves. So for any pair of time windows [opening1, closing1] and [opening2, closing2] for the same party, it will be true that either opening1 > closing2 or opening2 > closing1.""" | {
"difficulty_type": "Redefinition"
} | assert arrange_conference(windowsA = [[10,50],[60,120],[140,210]], windowsB = [[0,15],[60,70]], conferenceTime = 8) == [60,68]
assert arrange_conference(windowsA = [[10,50],[60,120],[140,210]], windowsB = [[0,15],[60,70]], conferenceTime = 12) == [] | 28 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def top_records(entry: List[List[int]]) -> List[List[int]]:
"""
Imagine a dataset containing multiple records of athletes with different identification numbers, where each record is marked as entry, such that entry[i] = [IDi, pointsi] signifies the points earned by athlete IDi in a particular event. Your job is to determine the average of the highest five point totals for every athlete.
The response should be structured as a list of tuples, summary, where summary[j] = [IDj, topFiveAveragej] matches the IDj of the athlete and their average of the five highest point totals. This list, summary, must be ordered by the athlete's ID in ascending sequence.
To derive the average of the top five point totals for each athlete, add together the points of their five best performances and then apply integer division by 5.""" | {
"difficulty_type": "Redefinition"
} | assert top_records(entry = [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]) == [[1,87],[2,88]]
assert top_records(entry = [[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100]]) == [[1,100],[7,100]] | 29 |
Write a Python function according to the function name and the problem description in the docstring below.
def sum_perfect_integer(lower_bound: int, higher_bound: int, n: int):
"""You are given positive integers lower_bound, higher_bound, and n.
A number is perfect if it meets both of the following conditions:
- The count of odd digits in the number is equal to the count of even digits.
- The number is divisible by n.
Return the number of perfect integers in the range [lower_bound, higher_bound].""" | {
"difficulty_type": "Redefinition"
} | assert sum_perfect_integer(4, 4, 1) == 0
assert sum_perfect_integer(1, 10, 1) == 1 | 30 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def maximum_size_after_removal(nums1: List[int], nums2: List[int]):
""" You are given two memory quantities nums1 and nums2 whose subscripts start from 0, and their lengths are both even n.
You must delete n / 2 elements from nums1 and n / 2 elements from nums2. After deletion, you insert the remaining elements from nums1 and nums2 into the set s.
Returns the maximum number of possible collections""" | {
"difficulty_type": "Redefinition"
} | assert maximum_size_after_removal([3,4], [1,2]) == 2
assert maximum_size_after_removal([1,2,1,2], [1,1,1,1]) == 2 | 31 |
Write a Python function according to the function name and the problem description in the docstring below.
def get_maximum_special_substring(s: str) -> int:
"""Determine the length of the longest substring in a given string 's', which consists solely of a single lower English character and the entire substring appears at least three times in the string 's'.
If no such substring exists, return -1.""" | {
"difficulty_type": "Redefinition"
} | assert get_maximum_special_substring("aaaa") == 2
assert get_maximum_special_substring("aeebcccdd") == 1 | 32 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def find_peak(mountain: List[int]) -> List[int]:
"""
You need to identify all the peaks in a given array named 'mountain'.
A peak is defined as any element that is strictly greater than its neighbors.
Keep in mind that the first and last elements of the array cannot be considered as peaks.
Return the indices (positions) of all the peaks in the array, in any order.""" | {
"difficulty_type": "Redefinition"
} | assert find_peak([1,2,4]) == []
assert find_peak([9,2,4,7,3]) == [3] | 33 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def similar_matrix(mat: List[List[int]], k: int) -> bool:
"""
You have a matrix 'mat' sized m x n, starting with index 0.
Shift odd-numbered rows right and even-numbered rows left by 'k' positions.
Check if the final matrix is the same as the initial one.
Return True if they match, otherwise False.""" | {
"difficulty_type": "Redefinition"
} | assert similar_matrix([[2,2]], 3) == True
assert similar_matrix([[3,1,4,1],[1,4,3,1],[2,4,1,2]], 2) == False | 34 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def find_k_or(nums: List[int], k: int) -> int:
"""
You have an array of integers named 'nums' and an integer 'k'.
The 'K-or' of nums is a non-negative integer defined by the following condition:
The i-th bit of K-or is 1 if and only if there are at least 'k' elements in 'nums' with their i-th bit as 1.
Return the K-or value of nums.
Note: For an integer 'x', the i-th bit value is 1 if (2^i AND x) == 2^i, where AND is the bitwise AND operator.""" | {
"difficulty_type": "Redefinition"
} | assert find_k_or([8,11,9,7],1) == 15
assert find_k_or([2,12,1,11,4,5],6) == 0 | 35 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def max_profit(prices: List[int]) -> int:
"""
Given an array, its i-th element represents the price per ton of water on the i-th day. You can store water in a reservoir, and your reservoir has a capacity of 5 tons. Design an algorithm to calculate the maximum profit you can achieve. You can perform up to 2 storage and release operations for buying and selling.
Note: You must release water before storing it.""" | {
"difficulty_type": "Redefinition"
} | assert max_profit([3,3,5,0,0,3,1,4]) == 30
assert max_profit([1,2,3,4,5]) == 20
assert max_profit([7,6,4,3,1]) == 0 | 36 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def winning_probability(numbers: List[int]) -> float:
"""In a raffle, lucky number is defined as containing only the factors 3, 5, 7, e.g. 15, 21. The system will generates a random set of numbers,
whoever picks the lucky number wins the prize. And no one knows the rules. Everyone picks numbers according to their preferences.
Everyone has their own lucky number. For Li, his lucky number is a number that contains 1, so in this raffle, Li will choose his lucky number first.
If there's no Li's lucky number in the set, he'll pick it at random.
Can you help Li calculate the probability of winning the prize?""" | {
"difficulty_type": "Redefinition"
} | assert winning_probability([1, 4, 12, 21, 33]) == 0.333
assert winning_probability([35, 22, 11]) == 0
assert winning_probability([2, 50, 24, 49]) == 0.25 | 37 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def symmetry_number(n: int) -> List[int]:
"""If a number is equal to its inverse order, it is called a symmetric number, e.g., '121'. Noting that all single digits are symmetric numbers. If the binary of this symmetric number is also equal to the inverse order of its binary, it is called a binary symmetric number, e.g., '9', whose binary number is '1001'. Further, performing a 01 swap on the binary of the symmetric number to form a flipped binary. If the decimal number corresponding to the flipped binary is a symmetric number, it is called a flipped symmetric number, e.g., '9', whose binary is '1001' , the binary flip number is '0110' and the corresponding decimal number is '6'. Find the count of symmetric numbers, binary symmetric numbers, and flipped symmetric numbers for all natural numbers not greater than the given number.""" | {
"difficulty_type": "Redefinition"
} | assert symmetry_number(10) == [9, 5, 6]
assert symmetry_number(50) == [13, 6, 8] | 38 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def brew_capability(brew_counts: List[int]) -> int:
"""
You are given an integer array `brew_counts`, where `brew_counts[i]` represents the number of brews needed for different batches of a certain brand of tea leaves. Calculate and return the brewing capacity of this brand of tea leaves.
A brand's brewing capacity is defined as the maximum value of b such that the given brand has b batches of tea leaves that have each been brewed at least b times. If there are multiple possible values for the brewing capacity, the brewing capacity is the maximum among them.
**Constraints:**
- `n == brew_counts.length`
- `1 <= n <= 5000`
- `0 <= brew_counts[i] <= 1000`""" | {
"difficulty_type": "Redefinition"
} | assert brew_capability([3, 0, 6, 1, 5]) == 3
assert brew_capability([1, 3, 1]) == 1 | 39 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def triangular_pair_of_a_to_b(a:int,b:int)->int:
"""A triangular number is a term in a sequence formed by the sum of natural numbers, with the nth triangular number represented as T_n, defined as T_n=1+2+3+...+n. This creates a sequence of triangular numbers: 1,3,6,10,15. Given two integer a and b, the sum from the a-th triangular number to the b-th triangular number (including a and b) called the sequence sum of triangular numbers. If there exists two triangular numbers Ti and Tj whose sum is equal to the sequence sum, then the two triangular numbers are called a triangular pair of a_to_b. Note that the sequence ab possibly has more than one triangle pair. For example, the triangular pairs of 3_to_4 are (1,15) and (6,10), because the third and fourth triangular numbers are 6 and 10, respectively. Given a and b (where a>1 and b>a+1), return the number of triangular pairs.""" | {
"difficulty_type": "Redefinition"
} | assert triangular_pair_of_a_to_b(3,4) == 2
assert triangular_pair_of_a_to_b(3,5) == 0 | 40 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def next_fibonacci(numbers: List[int]) -> List[int]:
"""Given a sequence, where each number is greater than 10000 and belongs to the Fibonacci sequence,
this function quickly calculates the next Fibonacci number for each individual number and returns
them in a list in the order they were given.""" | {
"difficulty_type": "Shortcut"
} | assert next_fibonacci([196418, 121393, 10946]) == [317811, 196418, 17711] | 41 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def largest_multiple_of_three(digits: List[int]) -> str:
"""Given an array, concatenate any number of digits in any order to form the largest number that is divisible by 3,
and return it in string type. If such a number does not exist, return an empty string. Also, remember to remove
any unnecessary leading zeros.""" | {
"difficulty_type": "Shortcut"
} | assert largest_multiple_of_three([1]) == ""
assert largest_multiple_of_three([1, 9, 9, 7]) == "99" | 42 |
Write a Python function according to the function name and the problem description in the docstring below.
def largest_number(n: int, x: int) -> int:
"""When Jason was typing on the keyboard, he noticed that the editor malfunctioned. Despite having
already entered an integer, he wants to rearrange the digits of this integer to obtain the largest
possible integer. Currently, he can perform the following operation for any number of times:
move one digit from the first x digits of the integer to the end. Please calculate and provide the
maximum integer that can be obtained.""" | {
"difficulty_type": "Shortcut"
} | assert largest_number(28981, 1) == 98128
assert largest_number(18929, 2) == 99821 | 43 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def num_even_product(nums: List[int]) -> int:
"""Given an integer array nums, return the number of subarrays of this array with an even product.
A subarray is a contiguous non-empty sequence of elements within an array.""" | {
"difficulty_type": "Shortcut"
} | assert num_even_product([1,2,3,4]) == 8
assert num_even_product([3,9,11]) == 0 | 44 |
Write a Python function according to the function name and the problem description in the docstring below.
def counting_game(n: int) -> int:
"""In a playful counting game, children start counting from 1 but they skip any number that contains the digit 9,
considering it to be unlucky. This results in a sequence that avoids the number 9 entirely,
such as 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, and so forth.
Given an integer n, return the nth number in this new integer sequence where the indexing begins at 1.""" | {
"difficulty_type": "Shortcut"
} | assert counting_game(4) == 4
assert counting_game(10) == 11 | 45 |
Write a Python function according to the function name and the problem description in the docstring below.
def longest_string(a: int, b: int, c: int) -> int:
"""
You are given three integers a, b, and c.
You have a strings equal to "OO", b strings equal to "PP", and c strings equal to "OP". You want to choose some (possibly all or none) of these strings and concatenate them in some order to form a new string. This new string must not contain "OOO" or "PPP" as a substring.
Return the maximum possible length of the new string.
A substring is a contiguous non-empty sequence of characters within a string.""" | {
"difficulty_type": "Shortcut"
} | assert longestString(2,5,1) == 12
assert longestString(3,2,2) == 14 | 46 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def nums_erase(nums: List[int]) -> bool:
"""
You are provided with a sequence of whole numbers delineated as 'nums', inscribed upon an erasable surface intended for mathematical notation.
Participants named Alice and Bob sequentially undertake the action of removing exactly a single numeral from the aforementioned surface, with the initiator of this sequence being Alice. The objective for each participant is to avoid the situation where the cumulative application of an exclusive binary disjunction operation across all remaining numerical elements results in a nil value; such an outcome would render the active player the defeated party. In this context, the exclusive binary disjunction of a singular element is equivalent to the element itself, and when no elements are present, the result of the operation is zero.
Further to this, should a player commence their phase of activity with the total binary disjunction of all extant numbers on the erasable surface equaling zero, this circumstance immediately confers victory upon them.
The query at hand seeks a confirmation of whether Alice is assured victory under the stipulation that each contender employs strategies of the highest caliber. Respond with an affirmation if the probability of Alice winning under these conditions is absolute.""" | {
"difficulty_type": "Shortcut"
} | assert nums_erase([1,1,2]) == False
assert nums_erase([0,1]) == True | 47 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def is_vshape(points: List[List[int]]) -> bool:
"""
Suppose you have a list `vertices`, with each element vertices[i] = [ai, bi] signifying the coordinates of a vertex in a 2D space. Can these vertices create a shape resembling a V, where no three vertices are collinear and each is unique? The function should return `true` if such a formation is possible.""" | {
"difficulty_type": "Shortcut"
} | assert is_vshape([[1,1], [2,3], [3,2]]) == True
assert is_vshape([[1,1], [2,2], [3,3]]) == False | 48 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def max_count(banned: List[int], n: int, maxSum: int) -> int:
"""
Given an array of integers `banned`, and two additional integers `n` and `maxSum`, determine the maximum number of integers you can select under the following conditions:
1.You may only choose from integers within the inclusive range from 1 to `n`.
2.You cannot select the same integer more than once.
3.None of the selected integers should appear in the `banned` array.
4.The total sum of the selected integers must not surpass `maxSum`.
Can you calculate the largest possible count of integers that can be chosen adhering to these criteria?""" | {
"difficulty_type": "Shortcut"
} | assert max_count([1,4,6], 6, 4) == 1
assert max_count([4,3,5,6], 7, 18) == 3 | 49 |
Write a Python function according to the function name and the problem description in the docstring below.
def ab_string(x: int, y: int, z: int) -> int:
"""In the beading activity, there are x number of 'AA', y number of 'BB', and z number of 'AB' letter style beads. Beads are indivisible, and we do not want 'AAA' and 'BBB' to exist in the final product. What is the maximum length that can be made by connecting these beads?
NOTE: It is not necessary to use all the beads. The final product will not be connected end to end.
1 <= x, y, z <= 10^5""" | {
"difficulty_type": "Shortcut"
} | assert ab_string(2,5,1) == 12
assert ab_string(3,2,2) == 14 | 50 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def check_tail_zeros(nums: List[int]) -> bool:
"""Given an array of positive integers, determine if you can choose two or more elements from the array so that the bitwise OR of these numbers results in at least one zero at the end of its binary form.""" | {
"difficulty_type": "Shortcut"
} | assert check_tail_zeros([1,2,10,12,20]) == True
assert check_tail_zeros([2,4,8,16]) == True | 51 |
Write a Python function according to the function name and the problem description in the docstring below.
def divide_white_black(s: str) -> int:
"""
There are n balls on a table, each either black or white.
You have a binary string s of length n, starting from index 0, where '1' represents a black ball and '0' represents a white ball.
In each step, you can swap two adjacent balls.
Return the minimum number of steps required to move all black balls to the right and all white balls to the left.""" | {
"difficulty_type": "Shortcut"
} | assert divide_white_black("001") == 0
assert divide_white_black("1100") == 4 | 52 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def minimum_sum(nums1: List[int], nums2: List[int]) -> int:
"""
Given two arrays, 'nums1' and 'nums2', consisting of positive integers and zeros,
replace all zeros in both arrays with strictly positive integers so that the sum of elements in both arrays becomes equal.
Return the smallest possible equal sum. If it's not possible to make the sums equal, return -1.""" | {
"difficulty_type": "Shortcut"
} | assert minimum_sum([1,4],[2,3]) == 5
assert minimum_sum([2,4,6,8],[1,2]) == -1 | 53 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def is_maximum_sum_array(arr:List[int])->int:
"""Given an array of real numbers a[1] to a[n], you are allowed to perform any number of operations. In each operation, you select an index i such that 1 < i < n, and then update a[i] to a[i - 1] + a[i + 1] - a[i]. After several operations, the sum of the array becomes the maximum, and then do the same operation will not make the sum of the array become larger, then the array is called the maximum sum array. Given an array, determine whether the array is the maximum sum array.""" | {
"difficulty_type": "Shortcut"
} | assert is_maximum_sum_array([1,3,2]) == 0
assert is_maximum_sum_array([1,2,3]) == 1 | 54 |
Write a Python function according to the function name and the problem description in the docstring below.
def minimum_birds(num_containers: int) -> int:
"""
You have n sealed containers, each containing a different type of food. One of these foods is toxic, while the others are safe. You have some birds that can be used to test these foods. If a bird eats the toxic food, it will die approximately 24 hours later.
Your task is to find the most efficient method to determine the container number containing the toxic food, using as few birds as possible. Please write a program to calculate the minimum number of birds needed to ensure the identification of the container with toxic food.""" | {
"difficulty_type": "Shortcut"
} | assert minimum_birds(8) == 3
assert minimum_birds(16) == 4
assert minimum_birds(1024) == 10 | 55 |
Write a Python function according to the function name and the problem description in the docstring below.
def sit_on_seat(n: int) -> float:
""" "Waiting for Spring" is a popular movie released in early 2024, and it is hard to get a ticket. Therefore, it is no surprise that all the seats for this film in Hall 1 of Highway Cinema were sold out. It is known that there are n seats in Hall 1, and n spectators who purchased this event will be present.
Audiences don't particularly care about their seats. If no one is sitting in the seat they bought when they arrive, they will sit in their own seats. If the seats are already occupied, they will find a seat to watch the movie.
Unfortunately, the first person to arrive at the theater didn't remember where he was, so he sat down casually. A is the nth arriving passenger. What is the probability that he will be able to sit in his seat?
1 <= n <= 10^5""" | {
"difficulty_type": "Shortcut"
} | assert sit_on_seat(1) == 1
assert sit_on_seat(2) == 0.5 | 56 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def minimal_avg_distance(nums: List[int]) -> int:
"""The minimum distance of an array is defined as the minimum absolute value of the difference between any two elements, the maximum distance of an array is defined as the maximum absolute value of the difference between any two elements, and the average distance of an array is defined as 1/2 of the minimum distance and the maximum distance. Given an array, you have at most two times to replace an element with any value inside the array. Your goal is to make the average distance as small as possible and return the minimum average distance.""" | {
"difficulty_type": "Shortcut"
} | assert minimal_avg_distance([1,4,3]) == 0
assert minimal_avg_distance([1,4,7,8,5]) == 3 | 57 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def fall_time(center:List[int],radius:int,position:List[List[int]])->int:
""" There is a round table with a delicious cake placed at its center. Several ants are positioned around the table, and each of them will walk the shortest distance towards the cake at a constant speed of 1 cm/s. Once an ant reaches the cake, it will walk away in any direction along the circumference of the table. However, when two ants collide, they will both turn and continue walking in the opposite direction, making a 180-degree turn. Your task is to calculate how much time it will take for the last ant to leave the table.
Given the coordinates of the center of the round table, the radius of the table, and the coordinates of all ants, return the latest time. Note, please round up the final result.""" | {
"difficulty_type": "Shortcut"
} | assert fall_time([0,0],5,[[1,0]]) == 6
assert fall_time([0,0],5,[[1,0],[2,0],[2,2]]) == 8 | 58 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def danger_corner(points:List[List[int]])->int:
"""Given n points on a 2D x-y plane, where the coordinates of each point are integers, these points form a polygon with each side either parallel to the x-axis or the y-axis, enclosing an area that represents a lake. Starting at the first coordinate and riding in order, you embark on a bike ride around the polygon back to the starting point. At certain points, if you forget to turn, you would end up in the lake. How many such points exist on the polygon where failing to turn would cause you to ride into the lake?""" | {
"difficulty_type": "Shortcut"
} | assert danger_corner([[0,0],[0,1],[1,1],[1,2],[2,2],[2,0]]) == 1
assert danger_corner([[0,0],[0,1],[1,1],[1,0]]) == 0 | 59 |
Write a Python function according to the function name and the problem description in the docstring below.
def reach_number(target: int) -> int:
"""A car starts from position 0 and drives on an infinite road. The car can move numMoves times, and each move can choose to move left or right. It is required that only i kilometers can be moved during the i-th move. Given the destination target, calculate the minimum number of moves required to reach the target (ie the minimum numMoves).
-10^9 <= target <= 10^9
target != 0""" | {
"difficulty_type": "Shortcut"
} | assert reach_number(2) == 3
assert reach_number(3) == 2 | 60 |
Write a Python function according to the function name and the problem description in the docstring below.
def morning_commute(a: int, b: int, c: int, d: int):
"""There are two companies located at both ends of a straight road, with two towns in the middle.
Every morning, 'a' people from the left town commute to work at the left company and 'b' people commute
to the right company. From the right town, 'c' people commute to the left company and 'd' people commute
to the right company. Everyone walks at the same pace. Please calculate how many encounters occur in total on their commute to work each morning.""" | {
"difficulty_type": "Commonsense"
} | assert morning_commute(7,3,4,6) == 12
assert morning_commute(17,31,13,40) == 403 | 61 |
Write a Python function according to the function name and the problem description in the docstring below.
def calculate_time(time1: str, time2: str) -> int:
"""Given two strings formatted as "hh:mm:ss" representing two time in one day, calculate the difference
in seconds between the two time. If the values are not within a reasonable range (for example, the hour
is greater than 24 or less than 0), please return -1.""" | {
"difficulty_type": "Commonsense"
} | assert calculate_time("00:01:10", "05:06:58") == 18348
assert calculate_time("08:10:00", "08:09:18") == 42 | 62 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def max_water_container(height: List[int]) -> int:
"""Given an integer array 'height' of length 'n'. There are 'n' vertical lines where the ith line has
its two endpoints at (i, 0) and (i, height[i]). Find the two lines that, along with the x-axis, form a container,
which can hold the maximum amount of water. Return the maximum volume of water that the container can store.
Note: The container should not be tilted.""" | {
"difficulty_type": "Commonsense"
} | assert max_water_container([1,1]) == 1
assert max_water_container([1,2,3,4]) == 4 | 63 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def from_starting_station(money: List[int], toll: List[int]) -> int:
"""There is a circular road with 'n' stations, each station has either a good person or a bad person.
A good person will give you money, while a bad person will charge you a certain toll. If you do not
have enough money to pay the toll, the bad person will not allow you to pass through.
Please find which station you can you start from so that you are able to make a complete loop and return
to your starting point. If a solution exists, it is guaranteed to be unique. The output should be the index
of the list.""" | {
"difficulty_type": "Commonsense"
} | assert from_starting_station([2,3,4], [3,4,3]) == -1
assert from_starting_station([1,2,3,4,5], [3,4,5,1,2]) == 3 | 64 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def number_of_covered_point(tracks: List[List[int]]) -> int:
"""Given a 2D integer array 'tracks' representing intervals of trains parking on a railway track.
For any index i, tracks[i] = [start_i, end_i], where start_i is the starting point of the i_th train
and end_i is the ending point of the i_th train.
Return the number of integer points on the railway track covered by any part of the trains.""" | {
"difficulty_type": "Commonsense"
} | assert number_of_covered_point([[1,4],[6,8]]) == 7
assert number_of_covered_point([[3,6],[4,7],[6,8]]) == 6 | 65 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def sort_binary(arr: List[int]) -> List[int]:
"""
Arrange an array of integers in ascending order based on the count of 1's in their binary form. For integers with an identical count of 1's, order them according to their value in ascending sequence. The sorted array should then be returned.""" | {
"difficulty_type": "Commonsense"
} | assert sort_binary([0,1,2,3,4,5,6,7,8]) == [0,1,2,4,8,3,5,6,7]
assert sort_binary([1024,512,256,128,64,32,16,8,4,2,1]) == [1,2,4,8,16,32,64,128,256,512,1024] | 66 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def convex_polygon(points: List[List[int]]) -> bool:
"""
Imagine that you have been supplied with an array of coordinate pairs, where each pair represents a point on the Cartesian coordinate plane. These coordinate pairs are contained in an array called points, where each element points[i] consists of a subarray [xi, yi] that in turn holds the x and y coordinates of the ith point. The task at hand is to take this series of points and establish connections between them in sequential order to construct the outline of a polygon.
Your challenge is to analyze this sequence of points and determine whether the resulting polygon is convex. An assumption you can safely make is that the series of points given will always form a simple polygon.""" | {
"difficulty_type": "Commonsense"
} | assert convex_polygon([[0,0],[0,5],[5,5],[5,0]]) == True
assert convex_polygon([[0,0],[0,10],[10,10],[10,0],[5,5]]) == False | 67 |
Write a Python function according to the function name and the problem description in the docstring below.
def knight_dialer(n: int) -> int:
"""Given a knight and a two-dimensional matrix chessboard [['1','2','3'],['4','5','6'],['7','8',' 9'],['*','0','#']]. Initially, the knight can be in any position on the chessboard and it can only stand on the numbered grids. The number at the knight's position will be recorded every time he takes a step. How many different numbers can the knight make when he takes n-1 steps?
As the answer may be very large, return the answer modulo 10^9 + 7.
1 <= n <= 5000""" | {
"difficulty_type": "Commonsense"
} | assert knight_dialer(1) == 10
assert knight_dialer(2) == 20 | 68 |
Write a Python function according to the function name and the problem description in the docstring below.
import heapq
from typing import List
def trap_water(heightMap: List[List[int]]) -> int:
"""When designing a landmark building composed of multiple cuboids with a base area of 1*1, the designer wants to calculate the water storage capacity on its roof. Given the building covers a total area of m*n, and the height is provided by a two-dimensional matrix.
m == heightMap.length
n == heightMap[i].length
1 <= m, n <= 200
0 <= heightMap[i][j] <= 2 * 10^4""" | {
"difficulty_type": "Commonsense"
} | assert trapRainWater([[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]) == 4
assert trapRainWater([[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]) == 10 | 69 |
Write a Python function according to the function name and the problem description in the docstring below.
def optical_experiment(m: int, n: int) -> int:
"""In the school's optical laboratory, there is a square device with mirrors on all four sides.
Except for the northwest corner of the device, there is a light receptor at each corner (
numbered 0 for the southwest corner, 1 for the southeast corner, and 2 for the northeast corner).
The device has a side length of m. Now, a laser is emitted from the northwest corner of the device,
first meets the south wall at a distance n from the 0 receptor.
Return the number of the receptor that the laser first encounters (it is guaranteed that the laser
will eventually hit a receptor).""" | {
"difficulty_type": "Commonsense"
} | assert optical_experiment(1, 1) == 1
assert optical_experiment(3, 2) == 0 | 70 |
Write a Python function according to the function name and the problem description in the docstring below.
def word_pronunciation(num: int) -> str:
"""At a ceremony, the host will read out the number of guests present today. The number of guests num is now given. Please complete the code and output the correct pronunciation.
0 <= num <= 2^31 - 1""" | {
"difficulty_type": "Commonsense"
} | assert word_pronunciation(123) == "One Hundred Twenty Three"
assert word_pronunciation(12345) == "Twelve Thousand Three Hundred Forty Five" | 71 |
Write a Python function according to the function name and the problem description in the docstring below.
def remove_similar_equal_characters(word: str) -> int:
"""
In a single operation, you can change any character in a word to any other lowercase English letter.
Your task is to determine the minimum number of such operations needed to modify the word
such that
1. no two adjacent characters are either the same
or
2. next to each other in the alphabet.""" | {
"difficulty_type": "Commonsense"
} | assert remove_similar_equal_characters("bozhijiang") == 2
assert remove_similar_equal_characters("abddez") == 2 | 72 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def widest_vertical_region_width(points: List[List[int]]) -> int:
"""
You are given n points on a 2D plane, where points[i] = [xi, yi] represents the x and y coordinates of the ith point.
A vertical region is defined as an infinite area with fixed width on the x-axis and infinite height on the y-axis.
Return the width of the widest vertical region that has no points inside it.
Note that points on the edges of a vertical region are not considered inside the region.""" | {
"difficulty_type": "Commonsense"
} | assert widest_vertical_region_width([[1,2],[3,4]]) == 2
assert widest_vertical_region_width([[1,0],[1,4],[5,3]]) == 4 | 73 |
Write a Python function according to the function name and the problem description in the docstring below.
def chess_square_color(coordinates: str) -> bool:
"""
You are given a coordinate string 'coordinates' representing the position of a square on a chessboard.
If the color of the given square is white, return true. If it's black, return false.
The given coordinate is guaranteed to represent a valid square on the chessboard.
The coordinate string has the format letter followed by number, where:
- The letter represents the column from 'a' to 'h'.
- The number represents the row from 1 to 8.""" | {
"difficulty_type": "Commonsense"
} | assert chess_square_color("h3") == True
assert chess_square_color("b2") == False | 74 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def celsius_to_kelvin_fahrenheit(celsius: float) -> List[float]:
"""
You are given a non-negative floating point number celsius representing a temperature rounded to two decimal places in Celsius degrees.
You need to convert the given Celsius temperature to Kelvin and Fahrenheit and return the results as an array ans = [kelvin, fahrenheit].
Return the array ans containing the Kelvin and Fahrenheit values. An answer within 10-5 of the actual value will be considered correct.""" | {
"difficulty_type": "Commonsense"
} | assert celsius_to_kelvin_fahrenheit(37.50) == [310.65000,99.50000]
assert celsius_to_kelvin_fahrenheit(122) == [395.15000,251.60000] | 75 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def can_pooling(trips: List[List[int]]) -> bool:
"""In order to promote the development of tourism, City A organized a "Chasing the Sunset" event. The event encourages local residents to use their private cars to pick up passengers at fixed stops and then drive towards the sunset. In order to better allow passengers to observe the sunset, the vehicle cannot change direction.
An unoccupied standard small car driven by a local resident was taking part in the activity. Now provide the driver with an array of trips, trips[i] = [passengers_i, from_i, to_i], which means that in the i-th trip, there will be passengers_i passengers from the from_i station to the to_i station. Can you please help this driver see if he can complete this task with his private car without overloading? Please return a Boolean value.
1 <= trips.length <= 1000
trips[i].length == 3
1 <= passengers_i <= 100
0 <= from_i < to_i <= 1000""" | {
"difficulty_type": "Commonsense"
} | assert can_pooling([[2,1,5],[3,3,7]]) == False
assert can_pooling([[2,1,5],[3,8,9]]) == True | 76 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def store_water(rains: List[int]) -> List[int]:
"""In a region where water is extremely lacking, so that rainwater is one of their important sources of water. Whenever it rains, people in there need to store the rainwater. Local people will prepare n pots and place them everywhere, at first all the pots is empty. When the nth pot is empty before it rains then it will be filled with water. And if the nth pot is full before it rains then rain water of this day will be wasted. So their goal is to keep the pots empty before rainy day, so that any one of the pots can retain its function on the rainy day.W
Given an array of rains, when rain[i] > 0, it means that on day i, it will rain where the rain[i] pot is located. When rain[i] == 0, it means that day i is rainless. On days withiout rain, they can choose any of the pots to empty. Return a list named ans, the length of ans is the same as the length of rain, when rain[i]>0, ans[i]==-1, when rain[i]==0, ans[i] indicates the index of the pots that you choose to store. If there is more than one solution, return any one of them. If it causes water storage to be wasted, return an empty list. Note that if the empty pots are emptied, nothing will happen.""" | {
"difficulty_type": "Commonsense"
} | assert store_water([1,2]) == [-1,-1]
assert store_water([1,0,2,0,1,2]) == [-1,1,-1,2,-1,-1]
assert store_water([1,2,0,1,1]) == [] | 77 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def longest_wiggle_seq(price: List[int]) -> int:
"""In the stock market, stock prices always fluctuate frequently, going up and down. For those who speculate in stocks, every time when the price of a stock going up and down is a good opportunity for them to make a profit. For each stock, there will be a closing price every day. Closing prices may fluctuate repeatedly within a few days, or may continue to rise or fall. For the latter, speculators focus only on the beginning and end of a sustained rise or fall. Only the days of up and down swaps are worth investment to them. A sequence that contains only the days mentioned above is called a wiggle sequence. That is, the difference between neighboring numbers switches strictly between positive and negative numbers. For example, [1, 6, 3, 4, 2] is a strictly wiggle sequence, and [1, 4, 5, 3] is not a strictly wiggle sequence because the difference between the first three numbers is positive. Given a sequence of stock closing prices, return the length of the longest subsequence which can be taken as an wiggle sequence. A subsequence can be obtained by removing some elements from the original sequence, but keeping the rest of the elements in the original order.""" | {
"difficulty_type": "Commonsense"
} | assert longest_wiggle_seq([1,6,3,4,2]) == 5
assert longest_wiggle_seq([1,4,5,3]) == 3 | 78 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def rank_task(tasks: List[List[int]]) ->List[int]:
"""Given a list of tasks named tasks, which contains n individual tasks, and the index of the list starting from 0 to n-1 denote the number of the tasks. Where tasks[i]=[start_time, process_time] means that the tasks start at start_time and take process_time to complete. The list will be sorted by start_time. You can only process one task at a moment. When there comes a task, if it is only one task, you need to execute it immediately to the end. And if there are multiple tasks piled up, you will choose the task with the shortest process_time to be executed first. And if there are multiple tasks with the same processing time, you will choose the task with the smallest index to be executed first. What you need to return is the order of the executing tasks.""" | {
"difficulty_type": "Commonsense"
} | assert rank_task([[1,3],[3,5],[3,2]] == [0,2,1]
assert rank_task([[2,10],[2,6],[3,5],[3,3],[3,1]]) == [1,4,3,2,0] | 79 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def is_square(p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
"""Given the coordinates of four points in the plane, please determine whether the four points can form a square.
The coordinate of a point pi is represented as [xi, yi].
p1.length == p2.length == p3.length == p4.length == 2
-10^4 <= xi, yi <= 10^4""" | {
"difficulty_type": "Commonsense"
} | assert is_square([0,0], [1,1], [1,0], [0,1]) == True
assert is_square([0,0], [1,1], [1,0], [0,12]) == False | 80 |
Write a Python function according to the function name and the problem description in the docstring below.
def is_isosceles_triangle(x1, y1, x2, y2, x3, y3):
"""Given the coordinates of three points in a two-dimensional plane, tell whether the figure formed
by connecting these three points is an isosceles triangle (which is a triangle that has at least two
sides of equal length).""" | {
"difficulty_type": "Cornercase"
} | assert is_isosceles_triangle(0, 0, 1, 0, 1, 1) == True
assert is_isosceles_triangle(0, 0, 2, 0, 2, 1) == False | 81 |
Write a Python function according to the function name and the problem description in the docstring below.
def decorate_ways(n: int, m: int) -> int:
"""For Christmas, various colored balls are to be tied to a string for decoration. There are a total
of n different colors of balls and a string that has m positions. Please fill all the positions on the
string with the condition that no more than two adjacent balls can have the same color. Given the
integers n and m, return the total number of possible decoration arrangements.""" | {
"difficulty_type": "Cornercase"
} | assert decorate_ways(3, 2) == 6
assert decorate_ways(7, 3) == 1344 | 82 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def four_dimensional_hyperplane(nums: List[int], target: int) -> List[List[int]]:
"""In a high-dimensional space, given an array nums containing n integers, the goal is to find all
quadruples (nums[i], nums[j], nums[k], nums[l]) that satisfy the following conditions: For 0 <= i, j, k, l < n,
the quadruple must form a hyperplane, i.e., nums[i] + nums[j] + nums[k] + nums[l] = target. Returns a list of
all quadruples (in any order) that meet these conditions.""" | {
"difficulty_type": "Cornercase"
} | assert four_dimensional_hyperplane([1,1,1], 6) == []
assert four_dimensional_hyperplane([1,2,3,4,5], 14) == [[2,3,4,5]] | 83 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def min_moves_to_equal_array(nums: List[int]):
"""Given an integer array `nums`, you can select any number of elements in each move, and for each selected
element, decrease its value by one, while simultaneously increasing the value of its adjacent elements by one.
Determine the minimum number of moves required to make all the elements in the array `nums` equal. If it is
impossible to make all the elements equal, return -1.""" | {
"difficulty_type": "Cornercase"
} | assert min_moves_to_equal_array([0, 1]) == -1
assert min_moves_to_equal_array([3,1,5]) == 2 | 84 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def pixelquad_number(matrix: List[List[int]]) -> int:
"""Given an m x n integer matrix grid consisting only of 0s and 1s, return the number of "PixelQuads" it contains.
A "PixelQuad" is an axis-aligned rectangle uniquely identified by four 1s at its corners within the matrix grid.
The term specifically emphasizes that we are interested in quadrilaterals marked by pixel-like elements, which in this
case are the 1s.
Note: The four 1s that define a PixelQuad must occupy distinct positions.""" | {
"difficulty_type": "Cornercase"
} | assert pixelquad_number([[1,1,1,1,1,1]]) == 0
assert pixelquad_number([[1,1,1],[1,1,1]]) == 3 | 85 |
Write a Python function according to the function name and the problem description in the docstring below.
def num_cuts(n: int) -> int:
"""
What is the minimum number of cuts needed to divide a circle into n equal slices, given the integer n, assuming the following valid cuts:
1. A cut defined by a straight line that touches two points on the circle's periphery and crosses through the center of the circle.
2. A cut represented by a straight line that touches one boundary point on the circle and its center?""" | {
"difficulty_type": "Cornercase"
} | assert num_cuts(4) == 2
assert num_cuts(3) == 3 | 86 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def card_game(cards: List[int]) -> bool:
"""
In a newly invented card game by Claire and David, there lies a sequence of n cards, each inscribed with a numerical figure representing its score. You receive an array of integers, called cards, where cards[i] corresponds to the score on the i-th card in the sequence.
Claire and David alternate turns, with Claire initiating the play. During their turn, a player must withdraw one card from the sequence.A player is defeated if after their card withdrawal, the aggregate scores of all the withdrawn cards result in a multiple of 3. Conversely, if the game concludes with the withdrawal of the final card and the cumulative score is not a multiple of 3, David claims victory immediately (even if it's Claire's turn).
Assuming optimal play from both participants, determine the winner by returning true if Claire is victorious, and false if David triumphs.""" | {
"difficulty_type": "Cornercase"
} | assert card_game([2,1]) == True
assert card_game([2]) == False | 87 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def two_probes(probeA: List[int], probeB: List[int]) -> str:
"""
A field study is in progress, with data being gathered in real-time. To validate the reliability of the observations, dual probes are deployed to simultaneously record measurements. You will be presented with two datasets: probeA and probeB. In these datasets, probeA[i] and probeB[i] denote the measurements recorded by each probe for the ith observation point.
Nonetheless, these probes are prone to malfunctions, potentially leading to the omission of measurements at a specific observation point (referred to as a dropout measurement).
When a measurement is omitted, all subsequent measurements to its right are shifted one position to the left, and the final measurement is substituted with an arbitrary number. This arbitrary number is assured to be different from the dropout measurement.
For instance, if the expected sequence of measurements is [1,2,3,4,5] and the measurement 3 is omitted, the probe's output might be [1,2,4,5,7] (the final value is arbitrary and not necessarily 7).
It is confirmed that only one of the probes may be malfunctioning. Your task is to identify the malfunctioning probe, return either "A" or "B". If both probes are functioning correctly, or if it is not feasible to ascertain which one is malfunctioning, then return "NA".""" | {
"difficulty_type": "Cornercase"
} | assert two_probes([2,3,4,5], [2,1,3,4]) == "A"
assert two_probes([2,2,2,2,2], [2,2,2,2,5]) == -1 | 88 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def catalog_search(titles: List[str], query: str) -> int:
"""
Library Catalog Search. Imagine an alphabetically ordered catalogue of book titles where several entries may be blank. Devise a procedure to identify the index of a specific book title in this catalogue.""" | {
"difficulty_type": "Cornercase"
} | assert catalog_search(["alpha", "", "", "", "gamma", "", "", "kappa", "", "", "sigma", "", ""], "beta") == -1
assert catalog_search(["alpha", "", "", "", "gamma", "", "", "kappa", "", "", "sigma", "", ""], "gamma") == 4 | 89 |
Write a Python function according to the function name and the problem description in the docstring below.
def correct_slogan(s: str, p: str) -> bool:
"""In an activity to collect slogans, a slogan s and its requirement p are given. Please determine whether the slogan s satisfies the rules of p? p contains only lowercase English letters, '.', and '*', the rules are as follows:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
1 <= s.length <= 20
1 <= p.length <= 20
s contains only lowercase English letters.
It is guaranteed for each appearance of the character '*', there will be a previous valid character to match.""" | {
"difficulty_type": "Cornercase"
} | assert correct_slogan("ab", ".*") == True
assert correct_slogan("aa", "a*") == True | 90 |
Write a Python function according to the function name and the problem description in the docstring below.
def get_min_flip_cost_to_match(s1: str, s2: str, x: int) -> int:
"""
You are given two binary strings s1 and s2 of length n, and a positive integer x.
You can perform the following operations on s1 any number of times:
- Choose two indices i and j, and flip s1[i] and s1[j]. The cost is x.
- Choose an index i < n - 1, and flip s1[i] and s1[i+1]. The cost is 1.
Return the minimum total cost to make s1 equal to s2, or -1 if it's impossible.
Flipping a character means changing 0 to 1 or 1 to 0.""" | {
"difficulty_type": "Cornercase"
} | assert get_min_flip_cost_to_match("1100","0011",3) == 2
assert get_min_flip_cost_to_match("100","001",2) == 2 | 91 |
Write a Python function according to the function name and the problem description in the docstring below.
def space_centered_text(text: str) -> str:
"""
Given a string text consisting of words and spaces, we first split the string into words based on spaces and count the number of spaces.
If there is only 1 word, we append all spaces to the end of that word.
Otherwise, we calculate the number of spaces between words as floor(spaces / (words - 1)). We then reconstruct the string by alternating words and spaces between words, appending any extra spaces to the end.""" | {
"difficulty_type": "Cornercase"
} | assert space_centered_text(" bo is the god ") == "bo is the god "
assert space_centered_text("we like the bo ") == "we like the bo " | 92 |
Write a Python function according to the function name and the problem description in the docstring below.
def power(x: float, n: int) -> float:
"""
Implement the function pow(x, n), which calculates x raised to the power of n (i.e. xn).""" | {
"difficulty_type": "Cornercase"
} | assert power(2.00000,0) == 1.00000
assert power(1.00000,1) == 1.00000 | 93 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def min_divisor_below_threshold(nums: List[int], threshold: int) -> int:
"""
You are given an integer array nums and a positive integer threshold.
You need to pick a positive integer divisor, divide each number in the array by it, and sum the division results.
Return the minimum divisor such that the sum of the division results is less than or equal to the threshold.
Each division result should be rounded up.""" | {
"difficulty_type": "Cornercase"
} | assert min_divisor_below_threshold([1,8],4) == 3
assert min_divisor_below_threshold([1,2,5,9],6) == 5 | 94 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def allocate_to_minimize_max(n: int, quantities: List[int]) -> int:
"""
You are given an integer n representing the number of retail stores. There are m different products in total, where quantities[i] represents the amount of the ith product.
You need to allocate all products to the stores, following these rules:
Each store can have at most 1 type of product, but the amount can be anything.
After allocation, each store will be assigned some number of products (possibly 0). Let x be the maximum number of products assigned to any store. You want to minimize x as much as possible.
Return the minimum possible x after allocating products to minimize the maximum number assigned to any store.""" | {
"difficulty_type": "Cornercase"
} | assert allocate_to_minimize_max(3,[1,4]) == 2
assert allocate_to_minimize_max(4,[1.10]) == 4 | 95 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
import collections
def land_shape(grid: List[List[int]]) -> int:
"""There is an open space in Alice's backyard. She divided the open space into m*n parts, and each part can choose to grow wheat or not. Alice's strategy for using m*n pieces of land is now given, represented by a binary matrix called grid. 0 means not planting wheat, and 1 means planting wheat. How many wheat-growing areas are there in Alice's backyard?
Note: Land blocks that are connected horizontally or vertically are considered to be the same area.
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] is 0 or 1.""" | {
"difficulty_type": "Cornercase"
} | assert land_shape([[1,1,1]]) == 1
assert land_shape([[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]]) == 3 | 96 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def same_network(ip_list: List[List[str]]) -> int:
"""Given two ip addresses and corresponding subnet masks, determine whether the two ip belong to the same network segment. The same network segment is defined as having the same network address, which can be obtained from the '&' operation of the ip address and its subnet mask. The process is as follows, first given a ip address 192.168.2.16 and its subnet mask 255.255.255.0. Their binary representations are 11000000.10101000.00000010.00010000 and 11111111.11111111.11111111.00000000, respectively. After '&' operation it becomes 11000000.10101000.00000010.00000000, then convert it to decimal. Finally, 192.168.2.0 is the network address. Note that the given ipv4 is possible not be a legal ip and the input needs to be verified.""" | {
"difficulty_type": "Cornercase"
} | assert same_network([["192.168.1.1", "255.255.255.0"], ["192.168.1.2", "255.255.255.0"]]) == True
assert same_network([["xs.0.0.0", "255.255.0.0"], ["1.a.0.0", "255.255.0.0"]]) == False | 97 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def calculate_maximum_profit(roads:List[int])->int:
"""A beautiful island is under development and now needs a ring road to be built. The ring road is divided into n parts, and several construction companies are competing for the qualification to build it. In order to avoid domination by one company, adjacent parts of the road cannot be built by the same company. Given an array of non-negative integers, each value of which represents the profit that can be made from a particular section of road, calculate the maximum profit that can be made by a construction company.""" | {
"difficulty_type": "Cornercase"
} | assert calculate_maximum_profit([2,3,2] == 3
assert calculate_maximum_profit([0]) == 0 | 98 |
Write a Python function according to the function name and the problem description in the docstring below.
from typing import List
def is_cube(points: List[List[int]])->int:
"""Given 8 points in 3D space, determine whether a cube can be formed.""" | {
"difficulty_type": "Cornercase"
} | assert is_cube([[0,0,0],[1,0,0],[0,1,0],[1,1,0],[0,0,1],[0,1,1],[1,0,1],[1,1,1]]) == 1
assert is_cube([[0,0,0],[1,0,0],[0,1,0],[1,1,0],[0,0,1],[0,1,1],[1,0,1],[1,3,1]]) == 0 | 99 |
Write a Python function according to the function name and the problem description in the docstring below.
def population_growth(n: int) -> bool:
"""Assume that population growth strictly follows the formula x_k = x_0(1+r)^k. Among them, the population growth rate is r, this year's population is x_0, and the population after k years is x_k.
The population of Baba Country this year is strictly 1 billion, and the population growth rate is r=1. Given an integer n, can you help their king calculate whether there is a population n billion in a certain year? The answer returns a Boolean value.
-2^31-1 <= n <= 2^31-1""" | {
"difficulty_type": "Cornercase"
} | assert population_growth(1) == True
assert population_growth(3) == False | 100 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.