identifier
string | space
string | input
string | target
float64 | metric_type
string | metadata
string |
---|---|---|---|---|---|
APPS_11588
|
APPS
|
Given an array of integers arr. Return the number of sub-arrays with odd sum.
As the answer may grow large, the answer must be computed modulo 10^9 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Example 4:
Input: arr = [100,100,99,99]
Output: 4
Example 5:
Input: arr = [7]
Output: 1
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 100
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'class Solution:\n def numOfSubarrays(self, arr: List[int]) -> int:\n A = [i%2 for i in arr]\n n = len(A)\n \n lst = [[0,0]]\n lst[0][A[0]&1] = 1\n \n for i in range(1, n):\n if A[i]:\n lst.append([lst[-1][1], 1+lst[-1][0]])\n else:\n lst.append([1+lst[-1][0], lst[-1][1]])\n \n # print(lst)\n \n return sum([x[1] for x in lst]) % (10**9+7)'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'numOfSubarrays'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 6,036 |
memory_bytes
|
{'question_id': '0291', 'solution_index': '131', 'qid_solution': '0291,131', 'num_inputs': '1', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '2', 'runs_succeeded': '2', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '3', 'static_max_nesting': '3', 'static_loop_count': '1', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '2', 'wall_min_s': '0.042731589', 'wall_median_s': '0.0435259065', 'wall_mean_s': '0.0435259065', 'wall_p90_s': '0.044320224', 'wall_max_s': '0.044320224', 'wall_stddev_s': '0.0007943175', 'wall_variance_s2': '6.3094029080625e-07', 'cpu_min_s': '0.042312999', 'cpu_median_s': '0.042923499', 'cpu_mean_s': '0.042923499', 'cpu_p90_s': '0.043533999', 'cpu_max_s': '0.043533999', 'cpu_stddev_s': '0.0006105', 'cpu_variance_s2': '3.7271025e-07', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-14T22:06:58Z', 'dyn_line_events': '20', 'dyn_py_calls': '3', 'dyn_max_call_depth': '2', 'dyn_peak_alloc_bytes': '6036', 'dyn_alloc_bytes_pos': '752', 'dyn_alloc_count_pos': '8', 'dyn_rss_peak_bytes': '19927040'}
|
APPS_85535
|
APPS
|
Complete the method which accepts an array of integers, and returns one of the following:
* `"yes, ascending"` - if the numbers in the array are sorted in an ascending order
* `"yes, descending"` - if the numbers in the array are sorted in a descending order
* `"no"` - otherwise
You can assume the array will always be valid, and there will always be one correct answer.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'def is_sorted_and_how(arr):\n if sorted(arr) == arr:\n return "yes, ascending"\n return "yes, descending" if sorted(arr, reverse=True) == arr else "no"'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'is_sorted_and_how'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,354 |
memory_bytes
|
{'question_id': '4146', 'solution_index': '77', 'qid_solution': '4146,77', 'num_inputs': '3', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '6', 'runs_succeeded': '6', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '3', 'static_max_nesting': '2', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.032403129', 'wall_median_s': '0.043437404', 'wall_mean_s': '0.041511761', 'wall_p90_s': '0.043688702', 'wall_max_s': '0.043688702', 'wall_stddev_s': '0.004089930287106534', 'wall_variance_s2': '1.6727529753391335e-05', 'cpu_min_s': '0.031976999', 'cpu_median_s': '0.0430134995', 'cpu_mean_s': '0.04109016583333334', 'cpu_p90_s': '0.043255999', 'cpu_max_s': '0.043255999', 'cpu_stddev_s': '0.004091784184497043', 'cpu_variance_s2': '1.6742697812500132e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T20:16:57Z', 'dyn_line_events': '2', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5354', 'dyn_alloc_bytes_pos': '94', 'dyn_alloc_count_pos': '1', 'dyn_rss_peak_bytes': '94441472'}
|
APPS_85418
|
APPS
|
A special type of prime is generated by the formula `p = 2^m * 3^n + 1` where `m` and `n` can be any non-negative integer.
The first `5` of these primes are `2, 3, 5, 7, 13`, and are generated as follows:
```Haskell
2 = 2^0 * 3^0 + 1
3 = 2^1 * 3^0 + 1
5 = 2^2 * 3^0 + 1
7 = 2^1 * 3^1 + 1
13 = 2^2 * 3^1 + 1
..and so on
```
You will be given a range and your task is to return the number of primes that have this property. For example, `solve(0,15) = 5`, because there are only `5` such primes `>= 0 and < 15`; they are `2,3,5,7,13`. The upper limit of the tests will not exceed `1,500,000`.
More examples in the test cases.
Good luck!
If you like Prime Katas, you will enjoy this Kata: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'from math import*;solve=lambda x,y:len({2**m*3**n+1\nfor n in range(0,ceil(log(y-1,3)))\nfor m in range(ceil(log(max(~-x/3**n,1),2)),ceil(log(~-y/3**n,2)))\nif all((2**m*3**n+1)%d for d in range(2,int((2**m*3**n+1)**.5)+1))})'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'solve'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 7,244 |
memory_bytes
|
{'question_id': '4141', 'solution_index': '8', 'qid_solution': '4141,8', 'num_inputs': '13', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '26', 'runs_succeeded': '26', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '1', 'static_max_nesting': '0', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '2', 'wall_min_s': '0.031108813', 'wall_median_s': '0.042704609', 'wall_mean_s': '0.0393404991923077', 'wall_p90_s': '0.044312264', 'wall_max_s': '0.044486505', 'wall_stddev_s': '0.0056501748697376135', 'wall_variance_s2': '3.192447605861446e-05', 'cpu_min_s': '0.030709999', 'cpu_median_s': '0.0422674995', 'cpu_mean_s': '0.038901345730769234', 'cpu_p90_s': '0.043921999', 'cpu_max_s': '0.044069999', 'cpu_stddev_s': '0.005646382575277178', 'cpu_variance_s2': '3.1881636186393735e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T20:15:21Z', 'dyn_line_events': '45', 'dyn_py_calls': '13', 'dyn_max_call_depth': '3', 'dyn_peak_alloc_bytes': '7244', 'dyn_alloc_bytes_pos': '928', 'dyn_alloc_count_pos': '11', 'dyn_rss_peak_bytes': '94441472'}
|
APPS_93858
|
APPS
|
Complete the function/method so that it takes CamelCase string and returns the string in snake_case notation. Lowercase characters can be numbers. If method gets number, it should return string.
Examples:
``` javascript
// returns test_controller
toUnderscore('TestController');
// returns movies_and_books
toUnderscore('MoviesAndBooks');
// returns app7_test
toUnderscore('App7Test');
// returns "1"
toUnderscore(1);
```
``` coffeescript
# returns test_controller
toUnderscore 'TestController'
# returns movies_and_books
toUnderscore 'MoviesAndBooks'
# returns app7_test
toUnderscore 'App7Test'
# returns "1"
toUnderscore 1
```
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = "def to_underscore(xs):\n return ''.join(('_' if i and x.isupper() else '') + x.lower() for i, x in enumerate(str(xs)))"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'to_underscore'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 6,591 |
memory_bytes
|
{'question_id': '4510', 'solution_index': '8', 'qid_solution': '4510,8', 'num_inputs': '5', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '10', 'runs_succeeded': '10', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '2', 'static_max_nesting': '1', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '1', 'wall_min_s': '0.03083721', 'wall_median_s': '0.0431950475', 'wall_mean_s': '0.039519223799999996', 'wall_p90_s': '0.043568345', 'wall_max_s': '0.043610546', 'wall_stddev_s': '0.005669852685353241', 'wall_variance_s2': '3.2147229473607355e-05', 'cpu_min_s': '0.030427999', 'cpu_median_s': '0.0427659995', 'cpu_mean_s': '0.039081999299999996', 'cpu_p90_s': '0.043141999', 'cpu_max_s': '0.043176', 'cpu_stddev_s': '0.005669911478356625', 'cpu_variance_s2': '3.214789617240021e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T23:13:24Z', 'dyn_line_events': '16', 'dyn_py_calls': '16', 'dyn_max_call_depth': '2', 'dyn_peak_alloc_bytes': '6591', 'dyn_alloc_bytes_pos': '406', 'dyn_alloc_count_pos': '5', 'dyn_rss_peak_bytes': '94441472'}
|
APPS_37440
|
APPS
|
Coach Khaled is a swag teacher in HIT (Hag Institute of Technology). However, he has some obsession problems.
Recently, coach Khaled was teaching a course in building 8G networks using TV antennas and programming them with assembly. There are $N$ students (numbered $1$ through $N$) in his class; for some reason, this number is always a multiple of $4$. The final exam has finished and Khaled has all the scores of his $N$ students. For each valid $i$, the score of the $i$-th student is $A_i$; each score is an integer between $0$ and $100$. Currently, the score-grade distribution is as follows:
- grade D for score smaller than $60$
- grade C for score greater or equal to $60$, but smaller than $75$
- grade B for score greater or equal to $75$, but smaller than $90$
- grade A for score greater or equal to $90$
However, coach Khaled is not satisfied with this. He wants exactly $N/4$ students to receive each grade (A, B, C and D), so that the grades are perfectly balanced. The scores cannot be changed, but the boundaries between grades can. Therefore, he wants to choose three integers $x$, $y$ and $z$ and change the grade distribution to the following (note that initially, $x = 60$, $y = 75$ and $z = 90$):
- grade D for score smaller than $x$
- grade C for score greater or equal to $x$, but smaller than $y$
- grade B for score greater or equal to $y$, but smaller than $z$
- grade A for score greater or equal to $z$
Your task is to find thresholds $x$, $y$ and $z$ that result in a perfect balance of grades. If there are multiple solutions, choose the one with the maximum value of $x+y+z$ (because coach Khaled wants seem smarter than his students); it can be proved that there is at most one such solution. Sometimes, there is no way to choose the thresholds and coach Khaled would resign because his exam questions were low-quality.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
-----Output-----
For each test case, if there is no solution, print a single line containing the integer $-1$; otherwise, print a single line containing three space-separated integers $x$, $y$ and $z$.
-----Constraints-----
- $1 \le T \le 1,000$
- $4 \le N \le 100$
- $N$ is divisible by $4$
- $0 \le A_i \le 100$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $5,000$
-----Subtasks-----
Subtask #1 (100 points): original constraints
-----Example Input-----
6
4
90 25 60 75
8
27 29 92 92 67 67 85 92
4
0 1 2 3
4
100 100 100 100
4
30 30 40 50
4
30 40 40 50
-----Example Output-----
60 75 90
-1
1 2 3
-1
-1
-1
-----Explanation-----
Example case 1: The default distribution is the correct one.
Example case 4: All students have the same score and grade, so there is no way to choose the thresholds and coach Khaled must resign.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
ns = {"__name__": "__main__"}
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = '# cook your dish here\nt= int(input())\nfor _ in range(t):\n n=int(input())\n l = list(map(int,input().split()))\n a = n//4\n l.sort()\n if(l[a] == l[a-1] or l[2*a]==l[2*a-1] or l[3*a]==l[3*a-1]):\n print(-1)\n else:\n print(l[a],l[2*a],l[3*a])'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
```
| 13,235 |
memory_bytes
|
{'question_id': '1284', 'solution_index': '17', 'qid_solution': '1284,17', 'num_inputs': '1', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '2', 'runs_succeeded': '2', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '3', 'static_max_nesting': '2', 'static_loop_count': '1', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.042620449', 'wall_median_s': '0.042881995', 'wall_mean_s': '0.042881995', 'wall_p90_s': '0.043143541', 'wall_max_s': '0.043143541', 'wall_stddev_s': '0.000261546', 'wall_variance_s2': '6.8406310116e-08', 'cpu_min_s': '0.042219999', 'cpu_median_s': '0.0424674995', 'cpu_mean_s': '0.0424674995', 'cpu_p90_s': '0.042715', 'cpu_max_s': '0.042715', 'cpu_stddev_s': '0.0002475005', 'cpu_variance_s2': '6.125649750025e-08', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T00:03:30Z', 'dyn_line_events': '44', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '13235', 'dyn_alloc_bytes_pos': '1217', 'dyn_alloc_count_pos': '14', 'dyn_rss_peak_bytes': '27267072'}
|
APPS_93111
|
APPS
|
If you have not ever heard the term **Arithmetic Progrossion**, refer to:
http://www.codewars.com/kata/find-the-missing-term-in-an-arithmetic-progression/python
And here is an unordered version. Try if you can survive lists of **MASSIVE** numbers (which means time limit should be considered). :D
Note: Don't be afraid that the minimum or the maximum element in the list is missing, e.g. [4, 6, 3, 5, 2] is missing 1 or 7, but this case is excluded from the kata.
Example:
```python
find([3, 9, 1, 11, 13, 5]) # => 7
```
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'def find(a):\n return (max(a) + min(a)) * (len(a) + 1) / 2 - sum(a)'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'find'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,448 |
memory_bytes
|
{'question_id': '4475', 'solution_index': '1', 'qid_solution': '4475,1', 'num_inputs': '3', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '6', 'runs_succeeded': '6', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '1', 'static_max_nesting': '1', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.030461138', 'wall_median_s': '0.0366485025', 'wall_mean_s': '0.03687947933333333', 'wall_p90_s': '0.043615697', 'wall_max_s': '0.043615697', 'wall_stddev_s': '0.006089732193175648', 'wall_variance_s2': '3.7084838184599886e-05', 'cpu_min_s': '0.029863', 'cpu_median_s': '0.0362415', 'cpu_mean_s': '0.03641249966666667', 'cpu_p90_s': '0.043185999', 'cpu_max_s': '0.043185999', 'cpu_stddev_s': '0.006128343939107875', 'cpu_variance_s2': '3.7556599436000224e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T23:00:27Z', 'dyn_line_events': '1', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5448', 'dyn_alloc_bytes_pos': '236', 'dyn_alloc_count_pos': '4', 'dyn_rss_peak_bytes': '94441472'}
|
APPS_93802
|
APPS
|
Share price
===========
You spent all your saved money to buy some shares.
You bought it for `invested`, and want to know how much it's worth, but all the info you can quickly get are just the change the shares price made in percentages.
Your task:
----------
Write the function `sharePrice()` that calculates, and returns the current price of your share, given the following two arguments:
- `invested`(number), the amount of money you initially invested in the given share
- `changes`(array of numbers), contains your shares daily movement percentages
The returned number, should be in string format, and it's precision should be fixed at 2 decimal numbers.
Have fun!
>**Hint:** Try to write the function in a functional manner!
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = "from functools import reduce\n\ndef share_price(invested, changes):\n r = reduce(lambda acc, x: acc + x * acc * 0.01, changes, invested)\n return '{:.2f}'.format(r)"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'share_price'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,539 |
memory_bytes
|
{'question_id': '4504', 'solution_index': '4', 'qid_solution': '4504,4', 'num_inputs': '5', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '10', 'runs_succeeded': '10', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '1', 'static_max_nesting': '1', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.030920638', 'wall_median_s': '0.043217265', 'wall_mean_s': '0.0407382679', 'wall_p90_s': '0.043500567', 'wall_max_s': '0.0435813', 'wall_stddev_s': '0.00472261914146649', 'wall_variance_s2': '2.2303131555345688e-05', 'cpu_min_s': '0.030510999', 'cpu_median_s': '0.0427754995', 'cpu_mean_s': '0.0403314995', 'cpu_p90_s': '0.043130999', 'cpu_max_s': '0.043172', 'cpu_stddev_s': '0.004722165505178768', 'cpu_variance_s2': '2.229884705830025e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T23:11:25Z', 'dyn_line_events': '2', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5539', 'dyn_alloc_bytes_pos': '327', 'dyn_alloc_count_pos': '6', 'dyn_rss_peak_bytes': '94441472'}
|
APPS_67321
|
APPS
|
###Introduction
The [I Ching](https://en.wikipedia.org/wiki/I_Ching) (Yijing, or Book of Changes) is an ancient Chinese book of sixty-four hexagrams.
A hexagram is a figure composed of six stacked horizontal lines, where each line is either Yang (an unbroken line) or Yin (a broken line):
```
--------- ---- ---- ---------
---- ---- ---- ---- ---------
---- ---- ---- ---- ---------
--------- ---- ---- ---- ----
--------- --------- ---- ----
---- ---- ---- ---- ---------
```
The book is commonly used as an oracle. After asking it a question about one's present scenario,
each line is determined by random methods to be Yang or Yin. The resulting hexagram is then interpreted by the querent as a symbol of their current situation, and how it might unfold.
This kata will consult the I Ching using the three coin method.
###Instructions
A coin is flipped three times and lands heads
or tails. The three results are used to
determine a line as being either:
```
3 tails ----x---- Yin (Moving Line*)
2 tails 1 heads --------- Yang
1 tails 2 heads ---- ---- Yin
3 heads ----o---- Yang (Moving Line*)
*See bottom of description if curious.
```
This process is repeated six times to determine
each line of the hexagram. The results of these
operations are then stored in a 2D Array like so:
In each array the first index will always be the number of the line ('one' is the bottom line, and 'six' the top), and the other three values will be the results of the coin flips that belong to that line as heads ('h') and tails ('t').
Write a function that will take a 2D Array like the above as argument and return its hexagram as a string. Each line of the hexagram should begin on a new line.
should return:
```
---------
---------
----x----
----o----
---- ----
---- ----
```
You are welcome to consult your new oracle program with a question before pressing submit. You can compare your result [here](http://www.ichingfortune.com/hexagrams.php). The last test case is random and can be used for your query.
*[1] A Moving Line is a Yang line that will change
to Yin or vice versa. The hexagram made by the coin
throws represents the querent's current situation,
and the hexagram that results from changing its
moving lines represents their upcoming situation.*
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = "ORDER = ('six', 'five', 'four', 'three', 'two', 'one')\nYIN_YANG = {'hhh': '----o----', 'hht': '---- ----',\n 'htt': '---------', 'ttt': '----x----'}\n\n\ndef oracle(arr):\n return '\\n'.join(YIN_YANG[''.join(sorted(a[1:]))] for a in\n sorted(arr, key=lambda b: ORDER.index(b[0])))\n"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'oracle'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 6,162 |
memory_bytes
|
{'question_id': '3320', 'solution_index': '5', 'qid_solution': '3320,5', 'num_inputs': '10', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '20', 'runs_succeeded': '20', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '1', 'static_max_nesting': '1', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '1', 'wall_min_s': '0.030912913', 'wall_median_s': '0.043021748', 'wall_mean_s': '0.0412224745', 'wall_p90_s': '0.043571621', 'wall_max_s': '0.044607717', 'wall_stddev_s': '0.004220814593158914', 'wall_variance_s2': '1.781527582982325e-05', 'cpu_min_s': '0.030481', 'cpu_median_s': '0.042589', 'cpu_mean_s': '0.040798799549999994', 'cpu_p90_s': '0.043161', 'cpu_max_s': '0.044191', 'cpu_stddev_s': '0.0042206442902737295', 'cpu_variance_s2': '1.7813838225020238e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T14:39:35Z', 'dyn_line_events': '16', 'dyn_py_calls': '14', 'dyn_max_call_depth': '2', 'dyn_peak_alloc_bytes': '6162', 'dyn_alloc_bytes_pos': '566', 'dyn_alloc_count_pos': '7', 'dyn_rss_peak_bytes': '65073152'}
|
APPS_88209
|
APPS
|
Write a function which converts the input string to uppercase.
~~~if:bf
For BF all inputs end with \0, all inputs are lowercases and there is no space between.
~~~
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = "def make_upper_case(s):\n # Code here\n u = s.upper()\n return (u)\n \n \nprint(( make_upper_case('matrix')))\n \n"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'make_upper_case'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,360 |
memory_bytes
|
{'question_id': '4255', 'solution_index': '83', 'qid_solution': '4255,83', 'num_inputs': '5', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '10', 'runs_succeeded': '10', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '1', 'static_max_nesting': '1', 'static_loop_count': '0', 'static_recursion': 'True', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.030786002', 'wall_median_s': '0.042167757', 'wall_mean_s': '0.039913753600000004', 'wall_p90_s': '0.042989777', 'wall_max_s': '0.043631034', 'wall_stddev_s': '0.004638419770397569', 'wall_variance_s2': '2.151493796641504e-05', 'cpu_min_s': '0.030341', 'cpu_median_s': '0.041752499', 'cpu_mean_s': '0.039483699299999994', 'cpu_p90_s': '0.042583', 'cpu_max_s': '0.043218999', 'cpu_stddev_s': '0.004658877166333128', 'cpu_variance_s2': '2.1705136450980208e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T21:32:29Z', 'dyn_line_events': '2', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5360', 'dyn_alloc_bytes_pos': '100', 'dyn_alloc_count_pos': '2', 'dyn_rss_peak_bytes': '94441472'}
|
APPS_35721
|
APPS
|
Little Elephant is playing a game with arrays. He is given an array A0, A1, ..., AN−1 of N integers. And then Q queries are given, each containing an integer K. He has to tell how many subarrays satisfy the condition: the function foo returns K when it is applied to the subarray.
In this problem, a subarray is defined as a sequence of continuous elements Ai, Ai+1, ..., Aj where 0 ≤ i ≤ j ≤ N−1. The function foo, when applied to an array, returns the minimum of all the elements in the array.
For example, foo returns 5 when it is applied to the array [7, 5, 10, 7, 5, 8]. Please note that the subarrays Ai, Ai+1, ..., Aj and Ak, Ak+1, ..., Al are different if and only if i ≠ k or j ≠ l in this problem.
-----Input-----
The first line of input contains N, denoting the size of the array. The next line contains N space separated integers A0, A1, ..., AN−1, denoting the array. Then the next line contains Q, denoting the number of queries. Each query consists of one integer per line, denoting K.
-----Output-----
For each query, print the required number of subarrays.
-----Constraints-----
- 1 ≤ N ≤ 50
- 1 ≤ Ai ≤ 1000000 (106)
- 1 ≤ Q ≤ 10
- 1 ≤ K ≤ 1000000 (106)
-----Example-----
Input:
5
4 1 2 3 4
4
3
4
6
1
Output:
2
2
0
8
-----Explanation-----
Query 1. Only the two subarrays [3, 4] and [3] satisfy.
Query 2. Again only the two subarrays [4] and [4] satisfy. Please note that these subarrays (A0 and A4) are considered different.
Query 3. No subarray satisfies.
Query 4. The eight subarrays [4, 1], [4, 1, 2], [4, 1, 2, 3], [4, 1, 2, 3, 4], [1], [1, 2], [1, 2, 3] and [1, 2, 3, 4] satisfy.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
ns = {"__name__": "__main__"}
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'n = int(input())\nl = list(map(int, input().split()))\nfor i in range(int(input())):\n c = 0\n quer = int(input())\n for i in range(n):\n for j in range(i+1, n+1):\n if min(l[i:j]) == quer:\n c += 1\n print(c)'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
```
| 13,123 |
memory_bytes
|
{'question_id': '1166', 'solution_index': '14', 'qid_solution': '1166,14', 'num_inputs': '1', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '2', 'runs_succeeded': '2', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '5', 'static_max_nesting': '4', 'static_loop_count': '3', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.042617344', 'wall_median_s': '0.042729687', 'wall_mean_s': '0.042729687', 'wall_p90_s': '0.04284203', 'wall_max_s': '0.04284203', 'wall_stddev_s': '0.000112343', 'wall_variance_s2': '1.2620949649e-08', 'cpu_min_s': '0.042179999', 'cpu_median_s': '0.0423129995', 'cpu_mean_s': '0.0423129995', 'cpu_p90_s': '0.042446', 'cpu_max_s': '0.042446', 'cpu_stddev_s': '0.0001330005', 'cpu_variance_s2': '1.768913300025e-08', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-14T23:51:00Z', 'dyn_line_events': '195', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '13123', 'dyn_alloc_bytes_pos': '816', 'dyn_alloc_count_pos': '9', 'dyn_rss_peak_bytes': '27267072'}
|
APPS_16666
|
APPS
|
A conveyor belt has packages that must be shipped from one port to another within D days.
The i-th package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D days.
Example 1:
Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5
Output: 15
Explanation:
A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
Example 2:
Input: weights = [3,2,2,4,1,4], D = 3
Output: 6
Explanation:
A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
Example 3:
Input: weights = [1,2,3,1,1], D = 4
Output: 3
Explanation:
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
Constraints:
1 <= D <= weights.length <= 50000
1 <= weights[i] <= 500
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'class Solution:\n def shipWithinDays(self, weights: List[int], D: int) -> int:\n def possible(cap):\n s = 0\n ship = 0\n i = 0\n while i<len(weights):\n s = s+weights[i]\n if s>cap:\n ship=ship+1\n s=0\n elif s<cap:\n i = i+1\n else:\n ship=ship+1\n s=0\n i=i+1\n if s==0:\n return ship<=D\n else:\n return (ship+1)<=D\n lo = max(weights)\n hi = sum(weights)\n while lo<=hi:\n mid= lo+(hi-lo)//2\n if possible(mid):\n hi = mid-1\n else:\n lo = mid+1\n return lo'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'shipWithinDays'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,752 |
memory_bytes
|
{'question_id': '0360', 'solution_index': '74', 'qid_solution': '0360,74', 'num_inputs': '1', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '2', 'runs_succeeded': '2', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '7', 'static_max_nesting': '5', 'static_loop_count': '2', 'static_recursion': 'True', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.031212954', 'wall_median_s': '0.0316376895', 'wall_mean_s': '0.0316376895', 'wall_p90_s': '0.032062425', 'wall_max_s': '0.032062425', 'wall_stddev_s': '0.0004247355', 'wall_variance_s2': '1.8040024496025e-07', 'cpu_min_s': '0.030843999', 'cpu_median_s': '0.031256499', 'cpu_mean_s': '0.031256499', 'cpu_p90_s': '0.031668999', 'cpu_max_s': '0.031668999', 'cpu_stddev_s': '0.0004125', 'cpu_variance_s2': '1.7015625e-07', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-14T22:25:17Z', 'dyn_line_events': '379', 'dyn_py_calls': '6', 'dyn_max_call_depth': '2', 'dyn_peak_alloc_bytes': '5752', 'dyn_alloc_bytes_pos': '508', 'dyn_alloc_count_pos': '4', 'dyn_rss_peak_bytes': '27267072'}
|
APPS_48141
|
APPS
|
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $1$ to $n$ and then $3n$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $7n+1$ times instead of $3n$ times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
-----Input-----
In the first line of input there is one integer $n$ ($10^{3} \le n \le 10^{6}$).
In the second line there are $n$ distinct integers between $1$ and $n$ — the permutation of size $n$ from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose $n$ — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
-----Output-----
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
-----Example-----
Input
5
2 4 5 1 3
Output
Petr
-----Note-----
Please note that the sample is not a valid test (because of limitations for $n$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
ns = {"__name__": "__main__"}
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = "input()\na=list(map(int,input().split()))\nn=len(a)\nu=n\nfor i in range(n):\n\tj=i\n\tk=0\n\twhile a[j]>0:\n\t\tk+=1\n\t\tt=j\n\t\tj=a[j]-1\n\t\ta[t]=0\n\tif k>0:\n\t\tu+=1-k%2\ns='Petr'\nif u%2>0:\n\ts='Um_nik'\nprint(s)\n"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
```
| 13,083 |
memory_bytes
|
{'question_id': '2336', 'solution_index': '5', 'qid_solution': '2336,5', 'num_inputs': '1', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '2', 'runs_succeeded': '2', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '5', 'static_max_nesting': '2', 'static_loop_count': '2', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.030952829', 'wall_median_s': '0.036838175', 'wall_mean_s': '0.036838175', 'wall_p90_s': '0.042723521', 'wall_max_s': '0.042723521', 'wall_stddev_s': '0.005885346', 'wall_variance_s2': '3.4637297539716e-05', 'cpu_min_s': '0.030455999', 'cpu_median_s': '0.036392499', 'cpu_mean_s': '0.036392499', 'cpu_p90_s': '0.042328999', 'cpu_max_s': '0.042328999', 'cpu_stddev_s': '0.0059365', 'cpu_variance_s2': '3.524203225e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T03:07:29Z', 'dyn_line_events': '60', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '13083', 'dyn_alloc_bytes_pos': '734', 'dyn_alloc_count_pos': '8', 'dyn_rss_peak_bytes': '45297664'}
|
APPS_65786
|
APPS
|
# Task
Some people are standing in a row in a park. There are trees between them which cannot be moved.
Your task is to rearrange the people by their heights in a non-descending order without moving the trees.
# Example
For `a = [-1, 150, 190, 170, -1, -1, 160, 180]`, the output should be
`[-1, 150, 160, 170, -1, -1, 180, 190]`.
# Input/Output
- `[input]` integer array `a`
If a[i] = -1, then the ith position is occupied by a tree. Otherwise a[i] is the height of a person standing in the ith position.
Constraints:
`5 ≤ a.length ≤ 30,`
`-1 ≤ a[i] ≤ 200.`
- `[output]` an integer array
`Sorted` array a with all the trees untouched.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'def sort_by_height(a):\n people = sorted([j for j in a if j != -1])\n for i in range(len(a)):\n if a[i] != -1:\n a[i] = people.pop(0)\n return a\n \n'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'sort_by_height'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,536 |
memory_bytes
|
{'question_id': '3247', 'solution_index': '6', 'qid_solution': '3247,6', 'num_inputs': '3', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '6', 'runs_succeeded': '6', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '3', 'static_max_nesting': '3', 'static_loop_count': '1', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '1', 'wall_min_s': '0.030818864', 'wall_median_s': '0.042739818', 'wall_mean_s': '0.039017586666666666', 'wall_p90_s': '0.044050719', 'wall_max_s': '0.044050719', 'wall_stddev_s': '0.005763412135541314', 'wall_variance_s2': '3.321691944410489e-05', 'cpu_min_s': '0.030375', 'cpu_median_s': '0.0423129995', 'cpu_mean_s': '0.03858683316666667', 'cpu_p90_s': '0.043644', 'cpu_max_s': '0.043644', 'cpu_stddev_s': '0.005777485111548693', 'cpu_variance_s2': '3.3379334214166806e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T14:18:29Z', 'dyn_line_events': '33', 'dyn_py_calls': '2', 'dyn_max_call_depth': '2', 'dyn_peak_alloc_bytes': '5536', 'dyn_alloc_bytes_pos': '276', 'dyn_alloc_count_pos': '3', 'dyn_rss_peak_bytes': '65073152'}
|
APPS_28861
|
APPS
|
Chef has been working in a restaurant which has N floors. He wants to minimize the time it takes him to go from the N-th floor to ground floor. He can either take the elevator or the stairs.
The stairs are at an angle of 45 degrees and Chef's velocity is V1 m/s when taking the stairs down. The elevator on the other hand moves with a velocity V2 m/s. Whenever an elevator is called, it always starts from ground floor and goes to N-th floor where it collects Chef (collecting takes no time), it then makes its way down to the ground floor with Chef in it.
The elevator cross a total distance equal to N meters when going from N-th floor to ground floor or vice versa, while the length of the stairs is sqrt(2) * N because the stairs is at angle 45 degrees.
Chef has enlisted your help to decide whether he should use stairs or the elevator to minimize his travel time. Can you help him out?
-----Input-----
The first line contains a single integer T, the number of test cases. Each test case is described by a single line containing three space-separated integers N, V1, V2.
-----Output-----
For each test case, output a single line with string Elevator or Stairs, denoting the answer to the problem.
-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ N, V1, V2 ≤ 100
-----Example-----
Input:
3
5 10 15
2 10 14
7 14 10
Output:
Elevator
Stairs
Stairs
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
ns = {"__name__": "__main__"}
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = "t = int(input())\nfor i in range(t):\n nums = [int(x) for x in input().strip().split(' ')]\n stairs = (((2**0.5)*nums[0])/nums[1])\n elevator = (((2)*nums[0])/nums[2])\n if stairs <= elevator :\n print('Stairs')\n else:\n print('Elevator')"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
```
| 13,033 |
memory_bytes
|
{'question_id': '0686', 'solution_index': '23', 'qid_solution': '0686,23', 'num_inputs': '1', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '2', 'runs_succeeded': '2', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '3', 'static_max_nesting': '2', 'static_loop_count': '1', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '1', 'wall_min_s': '0.030572117', 'wall_median_s': '0.036645792', 'wall_mean_s': '0.036645792', 'wall_p90_s': '0.042719467', 'wall_max_s': '0.042719467', 'wall_stddev_s': '0.006073675', 'wall_variance_s2': '3.6889528005625e-05', 'cpu_min_s': '0.030139', 'cpu_median_s': '0.0362179995', 'cpu_mean_s': '0.0362179995', 'cpu_p90_s': '0.042296999', 'cpu_max_s': '0.042296999', 'cpu_stddev_s': '0.0060789995', 'cpu_variance_s2': '3.695423492100025e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-14T23:12:31Z', 'dyn_line_events': '32', 'dyn_py_calls': '4', 'dyn_max_call_depth': '2', 'dyn_peak_alloc_bytes': '13033', 'dyn_alloc_bytes_pos': '760', 'dyn_alloc_count_pos': '12', 'dyn_rss_peak_bytes': '27267072'}
|
APPS_84748
|
APPS
|
# Task
**_Given_** an *array/list [] of n integers* , *find maximum triplet sum in the array* **_Without duplications_** .
___
# Notes :
* **_Array/list_** size is *at least 3* .
* **_Array/list_** numbers could be a *mixture of positives , negatives and zeros* .
* **_Repetition_** of numbers in *the array/list could occur* , So **_(duplications are not included when summing)_**.
___
# Input >> Output Examples
## **_Explanation_**:
* As the **_triplet_** that *maximize the sum* **_{6,8,3}_** in order , **_their sum is (17)_**
* *Note* : **_duplications_** *are not included when summing* , **(i.e) the numbers added only once** .
___
## **_Explanation_**:
* As the **_triplet_** that *maximize the sum* **_{8, 6, 4}_** in order , **_their sum is (18)_** ,
* *Note* : **_duplications_** *are not included when summing* , **(i.e) the numbers added only once** .
___
## **_Explanation_**:
* As the **_triplet_** that *maximize the sum* **_{12 , 29 , 0}_** in order , **_their sum is (41)_** ,
* *Note* : **_duplications_** *are not included when summing* , **(i.e) the numbers added only once** .
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
___
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'def max_tri_sum(numbers):\n return sum([number for number in sorted(list(set(numbers)))[-1:-4:-1]])'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'max_tri_sum'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,482 |
memory_bytes
|
{'question_id': '4104', 'solution_index': '75', 'qid_solution': '4104,75', 'num_inputs': '10', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '20', 'runs_succeeded': '20', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '1', 'static_max_nesting': '1', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '1', 'wall_min_s': '0.030570162', 'wall_median_s': '0.0321680185', 'wall_mean_s': '0.03538157075', 'wall_p90_s': '0.042871371', 'wall_max_s': '0.04366142', 'wall_stddev_s': '0.0052440040049887724', 'wall_variance_s2': '2.749957800433829e-05', 'cpu_min_s': '0.030162999', 'cpu_median_s': '0.0317665', 'cpu_mean_s': '0.0349455497', 'cpu_p90_s': '0.042405', 'cpu_max_s': '0.043231999', 'cpu_stddev_s': '0.005244699164206676', 'cpu_variance_s2': '2.7506869323030212e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T20:03:34Z', 'dyn_line_events': '5', 'dyn_py_calls': '2', 'dyn_max_call_depth': '2', 'dyn_peak_alloc_bytes': '5482', 'dyn_alloc_bytes_pos': '222', 'dyn_alloc_count_pos': '3', 'dyn_rss_peak_bytes': '94441472'}
|
APPS_84055
|
APPS
|
#Permutation position
In this kata you will have to permutate through a string of lowercase letters, each permutation will start at ```a``` and you must calculate how many iterations it takes to reach the current permutation.
##examples
```
input: 'a'
result: 1
input: 'c'
result: 3
input: 'z'
result: 26
input: 'foo'
result: 3759
input: 'aba'
result: 27
input: 'abb'
result: 28
```
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'permutation_position=lambda p:sum(26**i*(ord(c)-97)for i,c in enumerate(p[::-1]))+1'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'permutation_position'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,624 |
memory_bytes
|
{'question_id': '4072', 'solution_index': '7', 'qid_solution': '4072,7', 'num_inputs': '5', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '10', 'runs_succeeded': '10', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '1', 'static_max_nesting': '0', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '1', 'wall_min_s': '0.03060617', 'wall_median_s': '0.0422071655', 'wall_mean_s': '0.0391045161', 'wall_p90_s': '0.043844107', 'wall_max_s': '0.043858093', 'wall_stddev_s': '0.005552879444247507', 'wall_variance_s2': '3.083447012234649e-05', 'cpu_min_s': '0.030177', 'cpu_median_s': '0.0417959995', 'cpu_mean_s': '0.038673599700000005', 'cpu_p90_s': '0.043437999', 'cpu_max_s': '0.043443999', 'cpu_stddev_s': '0.005546599728965504', 'cpu_variance_s2': '3.076476855336021e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T19:52:40Z', 'dyn_line_events': '3', 'dyn_py_calls': '3', 'dyn_max_call_depth': '2', 'dyn_peak_alloc_bytes': '5624', 'dyn_alloc_bytes_pos': '234', 'dyn_alloc_count_pos': '3', 'dyn_rss_peak_bytes': '94441472'}
|
APPS_51598
|
APPS
|
Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).
The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.
Example 1:
Input: s = "011101"
Output: 5
Explanation:
All possible ways of splitting s into two non-empty substrings are:
left = "0" and right = "11101", score = 1 + 4 = 5
left = "01" and right = "1101", score = 1 + 3 = 4
left = "011" and right = "101", score = 1 + 2 = 3
left = "0111" and right = "01", score = 1 + 1 = 2
left = "01110" and right = "1", score = 2 + 1 = 3
Example 2:
Input: s = "00111"
Output: 5
Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5
Example 3:
Input: s = "1111"
Output: 3
Constraints:
2 <= s.length <= 500
The string s consists of characters '0' and '1' only.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = "class Solution:\n def maxScore(self, s: str) -> int:\n list_score = []\n for i in range(1,len(s)):\n score = 0\n for j in s[:i]:\n if j == '0':\n score += 1\n for j in s[i:]:\n if j == '1':\n score += 1\n list_score.append(score)\n \n return max(list_score)\n"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'maxScore'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,502 |
memory_bytes
|
{'question_id': '2534', 'solution_index': '11', 'qid_solution': '2534,11', 'num_inputs': '1', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '2', 'runs_succeeded': '2', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '6', 'static_max_nesting': '4', 'static_loop_count': '3', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.031148387', 'wall_median_s': '0.0372662995', 'wall_mean_s': '0.0372662995', 'wall_p90_s': '0.043384212', 'wall_max_s': '0.043384212', 'wall_stddev_s': '0.0061179125', 'wall_variance_s2': '3.742885335765625e-05', 'cpu_min_s': '0.030718', 'cpu_median_s': '0.0368444995', 'cpu_mean_s': '0.0368444995', 'cpu_p90_s': '0.042970999', 'cpu_max_s': '0.042970999', 'cpu_stddev_s': '0.0061264995', 'cpu_variance_s2': '3.753399612350025e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T10:24:20Z', 'dyn_line_events': '173', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5502', 'dyn_alloc_bytes_pos': '290', 'dyn_alloc_count_pos': '2', 'dyn_rss_peak_bytes': '65073152'}
|
APPS_78280
|
APPS
|
You've just recently been hired to calculate scores for a Dart Board game!
Scoring specifications:
* 0 points - radius above 10
* 5 points - radius between 5 and 10 inclusive
* 10 points - radius less than 5
**If all radii are less than 5, award 100 BONUS POINTS!**
Write a function that accepts an array of radii (can be integers and/or floats), and returns a total score using the above specification.
An empty array should return 0.
## Examples:
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'def score_throws(radii):\n return 5*sum((r<=10)+(r<5) for r in radii)+(100 if len(radii) and all(r<5 for r in radii) else 0)'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'score_throws'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,634 |
memory_bytes
|
{'question_id': '3789', 'solution_index': '3', 'qid_solution': '3789,3', 'num_inputs': '10', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '20', 'runs_succeeded': '20', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '2', 'static_max_nesting': '1', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '2', 'wall_min_s': '0.030859553', 'wall_median_s': '0.0426355055', 'wall_mean_s': '0.03881662935', 'wall_p90_s': '0.043919131', 'wall_max_s': '0.044007289', 'wall_stddev_s': '0.005822210559096195', 'wall_variance_s2': '3.389813579445123e-05', 'cpu_min_s': '0.030337999', 'cpu_median_s': '0.0422234995', 'cpu_mean_s': '0.03836609945', 'cpu_p90_s': '0.043499999', 'cpu_max_s': '0.043588', 'cpu_stddev_s': '0.005827501163990466', 'cpu_variance_s2': '3.395976981631024e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T18:23:09Z', 'dyn_line_events': '7', 'dyn_py_calls': '8', 'dyn_max_call_depth': '2', 'dyn_peak_alloc_bytes': '5634', 'dyn_alloc_bytes_pos': '294', 'dyn_alloc_count_pos': '4', 'dyn_rss_peak_bytes': '94441472'}
|
APPS_71197
|
APPS
|
Create a function that will return ```true``` if the input is in the following date time format ```01-09-2016 01:20``` and ```false``` if it is not.
This Kata has been inspired by the Regular Expressions chapter from the book Eloquent JavaScript.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = "from re import match\n\n\ndef date_checker(date):\n return bool(match(r'\\d{2}-\\d{2}-\\d{4}\\s\\d{2}:\\d{2}', date))\n"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'date_checker'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 37,557 |
memory_bytes
|
{'question_id': '3466', 'solution_index': '0', 'qid_solution': '3466,0', 'num_inputs': '10', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '20', 'runs_succeeded': '20', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '1', 'static_max_nesting': '1', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.030779501', 'wall_median_s': '0.0420202145', 'wall_mean_s': '0.03845033875', 'wall_p90_s': '0.043993514', 'wall_max_s': '0.045022095', 'wall_stddev_s': '0.005743665501801379', 'wall_variance_s2': '3.298969339658329e-05', 'cpu_min_s': '0.030354', 'cpu_median_s': '0.0415865', 'cpu_mean_s': '0.03801644945', 'cpu_p90_s': '0.043564999', 'cpu_max_s': '0.044578999', 'cpu_stddev_s': '0.0057273966475350074', 'cpu_variance_s2': '3.2803072358195245e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T15:46:47Z', 'dyn_line_events': '1', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '37557', 'dyn_alloc_bytes_pos': '60', 'dyn_alloc_count_pos': '1', 'dyn_rss_peak_bytes': '94441472'}
|
APPS_44456
|
APPS
|
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems.
There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly q_{i} items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the q_{i} items in the cart.
Maxim now needs to buy n items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well.
Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.
-----Input-----
The first line contains integer m (1 ≤ m ≤ 10^5) — the number of discount types. The second line contains m integers: q_1, q_2, ..., q_{m} (1 ≤ q_{i} ≤ 10^5).
The third line contains integer n (1 ≤ n ≤ 10^5) — the number of items Maxim needs. The fourth line contains n integers: a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^4) — the items' prices.
The numbers in the lines are separated by single spaces.
-----Output-----
In a single line print a single integer — the answer to the problem.
-----Examples-----
Input
1
2
4
50 50 100 100
Output
200
Input
2
2 3
5
50 50 50 50 50
Output
150
Input
1
1
7
1 1 1 1 1 1 1
Output
3
-----Note-----
In the first sample Maxim needs to buy two items that cost 100 and get a discount for two free items that cost 50. In that case, Maxim is going to pay 200.
In the second sample the best strategy for Maxim is to buy 3 items and get 2 items for free using the discount. In that case, Maxim is going to pay 150.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
ns = {"__name__": "__main__"}
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'def main():\n input()\n q = min(list(map(int, input().split())))\n input()\n aa = sorted(map(int, input().split()), reverse=True)\n print(sum(aa) - sum(aa[q::q + 2]) - sum(aa[q + 1::q + 2]))\n\n\ndef __starting_point():\n main()\n\n__starting_point()'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
```
| 13,967 |
memory_bytes
|
{'question_id': '2080', 'solution_index': '4', 'qid_solution': '2080,4', 'num_inputs': '13', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '26', 'runs_succeeded': '26', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '1', 'static_max_nesting': '1', 'static_loop_count': '0', 'static_recursion': 'True', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.030576756', 'wall_median_s': '0.042025148', 'wall_mean_s': '0.040446675038461534', 'wall_p90_s': '0.043960671', 'wall_max_s': '0.044314212', 'wall_stddev_s': '0.004357479405393378', 'wall_variance_s2': '1.8987626768427424e-05', 'cpu_min_s': '0.030162', 'cpu_median_s': '0.041610999', 'cpu_mean_s': '0.040020268653846156', 'cpu_p90_s': '0.043480999', 'cpu_max_s': '0.043858999', 'cpu_stddev_s': '0.004356839931998473', 'cpu_variance_s2': '1.8982054193056454e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T01:49:08Z', 'dyn_line_events': '9', 'dyn_py_calls': '3', 'dyn_max_call_depth': '3', 'dyn_peak_alloc_bytes': '13967', 'dyn_alloc_bytes_pos': '1206', 'dyn_alloc_count_pos': '11', 'dyn_rss_peak_bytes': '45297664'}
|
APPS_78145
|
APPS
|
Clock shows 'h' hours, 'm' minutes and 's' seconds after midnight.
Your task is to make 'Past' function which returns time converted to milliseconds.
## Example:
```python
past(0, 1, 1) == 61000
```
Input constraints: `0 <= h <= 23`, `0 <= m <= 59`, `0 <= s <= 59`
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'def past(h, m, s):\n time = (h*3600) + (m*60) + s\n time = time * 1000\n return time'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'past'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,400 |
memory_bytes
|
{'question_id': '3779', 'solution_index': '57', 'qid_solution': '3779,57', 'num_inputs': '5', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '10', 'runs_succeeded': '10', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '1', 'static_max_nesting': '1', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.030784039', 'wall_median_s': '0.0424779515', 'wall_mean_s': '0.040128122', 'wall_p90_s': '0.042973227', 'wall_max_s': '0.043262916', 'wall_stddev_s': '0.004547449317309056', 'wall_variance_s2': '2.0679295293494602e-05', 'cpu_min_s': '0.030377999', 'cpu_median_s': '0.0420649995', 'cpu_mean_s': '0.0397105994', 'cpu_p90_s': '0.042537', 'cpu_max_s': '0.042856999', 'cpu_stddev_s': '0.004547495631522941', 'cpu_variance_s2': '2.0679716518720234e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T18:20:29Z', 'dyn_line_events': '3', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5400', 'dyn_alloc_bytes_pos': '76', 'dyn_alloc_count_pos': '2', 'dyn_rss_peak_bytes': '94441472'}
|
APPS_7597
|
APPS
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'class Solution:\n def lenLongestFibSubseq(self, A: List[int]) -> int:\n n = len(A)\n if n < 3:\n return 0\n dp = [[2 for j in range(n)] for i in range(n)]\n ans = 2\n hmap = {A[0]:0, A[1]:1}\n for i in range(2, n):\n for j in range(1, i):\n pos = hmap.get(A[i]-A[j], -1)\n if pos >= 0 and pos < j:\n dp[i][j] = max(dp[i][j], dp[j][pos]+1)\n ans = max(ans, dp[i][j])\n hmap[A[i]] = i\n return ans if ans > 2 else 0'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'lenLongestFibSubseq'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 7,200 |
memory_bytes
|
{'question_id': '0222', 'solution_index': '28', 'qid_solution': '0222,28', 'num_inputs': '1', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '2', 'runs_succeeded': '2', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '6', 'static_max_nesting': '4', 'static_loop_count': '2', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '2', 'wall_min_s': '0.043226438', 'wall_median_s': '0.043590744', 'wall_mean_s': '0.043590744', 'wall_p90_s': '0.04395505', 'wall_max_s': '0.04395505', 'wall_stddev_s': '0.000364306', 'wall_variance_s2': '1.32718861636e-07', 'cpu_min_s': '0.042742999', 'cpu_median_s': '0.0431169995', 'cpu_mean_s': '0.0431169995', 'cpu_p90_s': '0.043491', 'cpu_max_s': '0.043491', 'cpu_stddev_s': '0.0003740005', 'cpu_variance_s2': '1.3987637400025e-07', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-14T21:52:08Z', 'dyn_line_events': '193', 'dyn_py_calls': '10', 'dyn_max_call_depth': '3', 'dyn_peak_alloc_bytes': '7200', 'dyn_alloc_bytes_pos': '1220', 'dyn_alloc_count_pos': '14', 'dyn_rss_peak_bytes': '18878464'}
|
APPS_57362
|
APPS
|
A carpet shop sells carpets in different varieties. Each carpet can come in a different roll width and can have a different price per square meter.
Write a function `cost_of_carpet` which calculates the cost (rounded to 2 decimal places) of carpeting a room, following these constraints:
* The carpeting has to be done in one unique piece. If not possible, retrun `"error"`.
* The shop sells any length of a roll of carpets, but always with a full width.
* The cost has to be minimal.
* The length of the room passed as argument can sometimes be shorter than its width (because we define these relatively to the position of the door in the room).
* A length or width equal to zero is considered invalid, return `"error"` if it occurs.
INPUTS:
`room_width`, `room_length`, `roll_width`, `roll_cost` as floats.
OUTPUT:
`"error"` or the minimal cost of the room carpeting, rounded to two decimal places.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'def cost_of_carpet(l, w, r, c):\n if l==0 or w==0 or l>r and w>r : \n return "error"\n return round( (min(l,w) if l<=r and w<=r else max(l,w) ) * r * c , 2)\n'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'cost_of_carpet'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,514 |
memory_bytes
|
{'question_id': '2896', 'solution_index': '5', 'qid_solution': '2896,5', 'num_inputs': '8', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '16', 'runs_succeeded': '16', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '3', 'static_max_nesting': '2', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.030982857', 'wall_median_s': '0.042966435', 'wall_mean_s': '0.0403976439375', 'wall_p90_s': '0.043871923', 'wall_max_s': '0.04495083', 'wall_stddev_s': '0.005169781277078974', 'wall_variance_s2': '2.6726638452836305e-05', 'cpu_min_s': '0.030566', 'cpu_median_s': '0.0424944995', 'cpu_mean_s': '0.0399573745', 'cpu_p90_s': '0.043462', 'cpu_max_s': '0.044485', 'cpu_stddev_s': '0.0051620949108864955', 'cpu_variance_s2': '2.664722386900025e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T11:51:14Z', 'dyn_line_events': '2', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5514', 'dyn_alloc_bytes_pos': '238', 'dyn_alloc_count_pos': '2', 'dyn_rss_peak_bytes': '65073152'}
|
APPS_47947
|
APPS
|
Snuke loves constructing integer sequences.
There are N piles of stones, numbered 1 through N.
The pile numbered i consists of a_i stones.
Snuke will construct an integer sequence s of length Σa_i, as follows:
- Among the piles with the largest number of stones remaining, let x be the index of the pile with the smallest index. Append x to the end of s.
- Select a pile with one or more stones remaining, and remove a stone from that pile.
- If there is a pile with one or more stones remaining, go back to step 1. Otherwise, terminate the process.
We are interested in the lexicographically smallest sequence that can be constructed. For each of the integers 1,2,3,...,N, how many times does it occur in the lexicographically smallest sequence?
-----Constraints-----
- 1 ≤ N ≤ 10^{5}
- 1 ≤ a_i ≤ 10^{9}
-----Input-----
The input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N}
-----Output-----
Print N lines. The i-th line should contain the number of the occurrences of the integer i in the lexicographically smallest sequence that can be constructed.
-----Sample Input-----
2
1 2
-----Sample Output-----
2
1
The lexicographically smallest sequence is constructed as follows:
- Since the pile with the largest number of stones remaining is pile 2, append 2 to the end of s. Then, remove a stone from pile 2.
- Since the piles with the largest number of stones remaining are pile 1 and 2, append 1 to the end of s (we take the smallest index). Then, remove a stone from pile 2.
- Since the pile with the largest number of stones remaining is pile 1, append 1 to the end of s. Then, remove a stone from pile 1.
The resulting sequence is (2,1,1). In this sequence, 1 occurs twice, and 2 occurs once.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
ns = {"__name__": "__main__"}
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'n = int(input())\na = list(map(int,input().split()))\nl = [0]\nind = [-1]\nfor i in range(n):\n if a[i] > l[-1]:\n l.append(a[i])\n ind.append(i)\nc1 = [0]*(len(l)+1)\nc2 = [0]*(len(l)+1)\nc1[0] = n\na.sort()\nnow = 0\nfor i in a:\n while now < len(l) and l[now] <= i:\n now += 1\n c1[now] -= 1\n c2[now-1] += i-l[now-1]\nans = [0]*n\nfor i in range(1,len(l)):\n c1[i] += c1[i-1]\n count = (l[i]-l[i-1])*c1[i]+c2[i-1]\n ans[ind[i]] = count\n\nfor i in ans:\n print(i)\n'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
```
| 13,637 |
memory_bytes
|
{'question_id': '2326', 'solution_index': '82', 'qid_solution': '2326,82', 'num_inputs': '2', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '4', 'runs_succeeded': '4', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '7', 'static_max_nesting': '2', 'static_loop_count': '5', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.031856522', 'wall_median_s': '0.043289465', 'wall_mean_s': '0.04061784575', 'wall_p90_s': '0.044035931', 'wall_max_s': '0.044035931', 'wall_stddev_s': '0.0050675242701706605', 'wall_variance_s2': '2.5679802228768688e-05', 'cpu_min_s': '0.031452999', 'cpu_median_s': '0.0428819995', 'cpu_mean_s': '0.0400722495', 'cpu_p90_s': '0.043072', 'cpu_max_s': '0.043072', 'cpu_stddev_s': '0.0049769318952794855', 'cpu_variance_s2': '2.476985109025025e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T03:06:15Z', 'dyn_line_events': '48', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '13637', 'dyn_alloc_bytes_pos': '1868', 'dyn_alloc_count_pos': '20', 'dyn_rss_peak_bytes': '45297664'}
|
APPS_96844
|
APPS
|
Lucy loves to travel. Luckily she is a renowned computer scientist and gets to travel to international conferences using her department's budget.
Each year, Society for Exciting Computer Science Research (SECSR) organizes several conferences around the world. Lucy always picks one conference from that list that is hosted in a city she hasn't been to before, and if that leaves her with more than one option, she picks the conference that she thinks would be most relevant for her field of research.
Write a function `conferencePicker` that takes in two arguments:
- `citiesVisited`, a list of cities that Lucy has visited before, given as an array of strings.
- `citiesOffered`, a list of cities that will host SECSR conferences this year, given as an array of strings. `citiesOffered` will already be ordered in terms of the relevance of the conferences for Lucy's research (from the most to the least relevant).
The function should return the city that Lucy should visit, as a string.
Also note:
- You should allow for the possibility that Lucy hasn't visited any city before.
- SECSR organizes at least two conferences each year.
- If all of the offered conferences are hosted in cities that Lucy has visited before, the function should return `'No worthwhile conferences this year!'` (`Nothing` in Haskell)
Example:
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = "def conference_picker(cities_visited, cities_offered):\n for city in cities_offered:\n if city not in cities_visited: return city\n return 'No worthwhile conferences this year!' if len(cities_visited) > 0 else cities_offered[0]"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'conference_picker'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,346 |
memory_bytes
|
{'question_id': '4664', 'solution_index': '17', 'qid_solution': '4664,17', 'num_inputs': '10', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '20', 'runs_succeeded': '20', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '4', 'static_max_nesting': '3', 'static_loop_count': '1', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.031062206', 'wall_median_s': '0.0433288565', 'wall_mean_s': '0.04115352075', 'wall_p90_s': '0.043965399', 'wall_max_s': '0.047998181', 'wall_stddev_s': '0.004965753283813613', 'wall_variance_s2': '2.465870567570569e-05', 'cpu_min_s': '0.030645999', 'cpu_median_s': '0.0429095', 'cpu_mean_s': '0.04073024965', 'cpu_p90_s': '0.043555', 'cpu_max_s': '0.047544', 'cpu_stddev_s': '0.004971580974214866', 'cpu_variance_s2': '2.471661738317523e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-16T00:07:22Z', 'dyn_line_events': '2', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5346', 'dyn_alloc_bytes_pos': '86', 'dyn_alloc_count_pos': '1', 'dyn_rss_peak_bytes': '94441472'}
|
APPS_20121
|
APPS
|
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.
Mouse starts at node 1 and goes first, Cat starts at node 2 and goes second, and there is a Hole at node 0.
During each player's turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in graph[1].
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in 3 ways:
If ever the Cat occupies the same node as the Mouse, the Cat wins.
If ever the Mouse reaches the Hole, the Mouse wins.
If ever a position is repeated (ie. the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
Given a graph, and assuming both players play optimally, return 1 if the game is won by Mouse, 2 if the game is won by Cat, and 0 if the game is a draw.
Example 1:
Input: [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
Output: 0
Explanation:
4---3---1
| |
2---5
\ /
0
Note:
3 <= graph.length <= 50
It is guaranteed that graph[1] is non-empty.
It is guaranteed that graph[2] contains a non-zero element.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'from collections import deque, defaultdict\n\n\nclass Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n n = len(graph)\n DRAW, MOUSE, CAT = 0, 1, 2\n \n def parents(m, c, t):\n if t == MOUSE:\n return [(m, x, CAT) for x in graph[c] if x != 0]\n return [(x, c, MOUSE) for x in graph[m]]\n \n color = defaultdict(int)\n for t in MOUSE, CAT:\n for x in range(n):\n color[0, x, t] = MOUSE\n if x != 0:\n color[x, x, t] = CAT\n \n degree = {}\n for m in range(n):\n for c in range(n):\n degree[m, c, MOUSE] = len(parents(m, c, CAT))\n degree[m, c, CAT] = len(parents(m, c, MOUSE))\n\n q = deque()\n for k, v in color.items():\n q.append((*k, v))\n \n while q:\n m, c, t, winner = q.popleft()\n for m2, c2, t2 in parents(m, c, t):\n if color[m2, c2, t2] != DRAW:\n continue\n \n if t2 == winner:\n color[m2, c2, t2] = winner\n q.append((m2, c2, t2, winner))\n else:\n degree[m2, c2, t2] -= 1\n if degree[m2, c2, t2] == 0:\n color[m2, c2, t2] = winner\n q.append((m2, c2, t2, winner))\n \n return color[1, 2, 1]'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'catMouseGame'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 30,730 |
memory_bytes
|
{'question_id': '0416', 'solution_index': '24', 'qid_solution': '0416,24', 'num_inputs': '1', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '2', 'runs_succeeded': '2', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '13', 'static_max_nesting': '5', 'static_loop_count': '7', 'static_recursion': 'True', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '2', 'wall_min_s': '0.043238822', 'wall_median_s': '0.043607827', 'wall_mean_s': '0.043607827', 'wall_p90_s': '0.043976832', 'wall_max_s': '0.043976832', 'wall_stddev_s': '0.000369005', 'wall_variance_s2': '1.36164690025e-07', 'cpu_min_s': '0.042835999', 'cpu_median_s': '0.0432059995', 'cpu_mean_s': '0.0432059995', 'cpu_p90_s': '0.043576', 'cpu_max_s': '0.043576', 'cpu_stddev_s': '0.0003700005', 'cpu_variance_s2': '1.3690037000025e-07', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-14T22:37:57Z', 'dyn_line_events': '2044', 'dyn_py_calls': '399', 'dyn_max_call_depth': '3', 'dyn_peak_alloc_bytes': '30730', 'dyn_alloc_bytes_pos': '16702', 'dyn_alloc_count_pos': '245', 'dyn_rss_peak_bytes': '27267072'}
|
APPS_59556
|
APPS
|
## Your Job
Find the sum of all multiples of `n` below `m`
## Keep in Mind
* `n` and `m` are natural numbers (positive integers)
* `m` is **excluded** from the multiples
## Examples
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = "def sum_mul(n, m):\n return sum(range(n,m,n)) if 0<n<m else 'INVALID' if n*m<=0 else 0 "
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'sum_mul'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,412 |
memory_bytes
|
{'question_id': '2995', 'solution_index': '63', 'qid_solution': '2995,63', 'num_inputs': '11', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '22', 'runs_succeeded': '22', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '3', 'static_max_nesting': '1', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.030768969', 'wall_median_s': '0.041876248', 'wall_mean_s': '0.03936000127272727', 'wall_p90_s': '0.043963183', 'wall_max_s': '0.044206063', 'wall_stddev_s': '0.005292402628509605', 'wall_variance_s2': '2.8009525582255376e-05', 'cpu_min_s': '0.030347', 'cpu_median_s': '0.0414369995', 'cpu_mean_s': '0.03893031772727273', 'cpu_p90_s': '0.043573', 'cpu_max_s': '0.04369', 'cpu_stddev_s': '0.005297027348313118', 'cpu_variance_s2': '2.805849872877711e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T12:26:48Z', 'dyn_line_events': '1', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5412', 'dyn_alloc_bytes_pos': '152', 'dyn_alloc_count_pos': '2', 'dyn_rss_peak_bytes': '65073152'}
|
APPS_1355
|
APPS
|
Alexandra has an even-length array $a$, consisting of $0$s and $1$s. The elements of the array are enumerated from $1$ to $n$. She wants to remove at most $\frac{n}{2}$ elements (where $n$ — length of array) in the way that alternating sum of the array will be equal $0$ (i.e. $a_1 - a_2 + a_3 - a_4 + \dotsc = 0$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.
For example, if she has $a = [1, 0, 1, 0, 0, 0]$ and she removes $2$nd and $4$th elements, $a$ will become equal $[1, 1, 0, 0]$ and its alternating sum is $1 - 1 + 0 - 0 = 0$.
Help her!
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^3$). Description of the test cases follows.
The first line of each test case contains a single integer $n$ ($2 \le n \le 10^3$, $n$ is even) — length of the array.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 1$) — elements of the array.
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^3$.
-----Output-----
For each test case, firstly, print $k$ ($\frac{n}{2} \leq k \leq n$) — number of elements that will remain after removing in the order they appear in $a$. Then, print this $k$ numbers. Note that you should print the numbers themselves, not their indices.
We can show that an answer always exists. If there are several answers, you can output any of them.
-----Example-----
Input
4
2
1 0
2
0 0
4
0 1 1 1
4
1 1 0 0
Output
1
0
1
0
2
1 1
4
1 1 0 0
-----Note-----
In the first and second cases, alternating sum of the array, obviously, equals $0$.
In the third case, alternating sum of the array equals $1 - 1 = 0$.
In the fourth case, alternating sum already equals $1 - 1 + 0 - 0 = 0$, so we don't have to remove anything.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
ns = {"__name__": "__main__"}
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'for _ in range(int(input())):\n n=int(input())\n a=list(map(int,input().split()))\n if a.count(0)>=n//2:\n print(n//2)\n print(*[0]*(n//2))\n else:\n if (n//2)%2==0:\n print(n//2)\n print(*[1]*(n//2))\n else:\n print(n//2+1)\n print(*[1]*(n//2+1))\n'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
```
| 13,185 |
memory_bytes
|
{'question_id': '0086', 'solution_index': '12', 'qid_solution': '0086,12', 'num_inputs': '1', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '2', 'runs_succeeded': '2', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '4', 'static_max_nesting': '3', 'static_loop_count': '1', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.03028343', 'wall_median_s': '0.0365676735', 'wall_mean_s': '0.0365676735', 'wall_p90_s': '0.042851917', 'wall_max_s': '0.042851917', 'wall_stddev_s': '0.0062842435', 'wall_variance_s2': '3.949171636729225e-05', 'cpu_min_s': '0.029872', 'cpu_median_s': '0.0361599995', 'cpu_mean_s': '0.0361599995', 'cpu_p90_s': '0.042447999', 'cpu_max_s': '0.042447999', 'cpu_stddev_s': '0.0062879995', 'cpu_variance_s2': '3.953893771200025e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-14T21:28:52Z', 'dyn_line_events': '26', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '13185', 'dyn_alloc_bytes_pos': '1346', 'dyn_alloc_count_pos': '17', 'dyn_rss_peak_bytes': '17829888'}
|
APPS_62569
|
APPS
|
A variation of determining leap years, assuming only integers are used and years can be negative and positive.
Write a function which will return the days in the year and the year entered in a string. For example 2000, entered as an integer, will return as a string 2000 has 366 days
There are a few assumptions we will accept the year 0, even though there is no year 0 in the Gregorian Calendar.
Also the basic rule for validating a leap year are as follows
Most years that can be divided evenly by 4 are leap years.
Exception: Century years are NOT leap years UNLESS they can be evenly divided by 400.
So the years 0, -64 and 2016 will return 366 days.
Whilst 1974, -10 and 666 will return 365 days.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = "def year_days(year):\n if year%100==0:\n if year%400==0: return f'{year} has 366 days'\n else: return f'{year} has 365 days'\n else:\n return f'{year} has 366 days' if year %4 ==0 else f'{year} has 365 days'"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'year_days'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,419 |
memory_bytes
|
{'question_id': '3114', 'solution_index': '92', 'qid_solution': '3114,92', 'num_inputs': '10', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '20', 'runs_succeeded': '20', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '4', 'static_max_nesting': '3', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.030317854', 'wall_median_s': '0.0428061035', 'wall_mean_s': '0.04153092335', 'wall_p90_s': '0.043983523', 'wall_max_s': '0.044316214', 'wall_stddev_s': '0.0037688320025152655', 'wall_variance_s2': '1.4204094663183228e-05', 'cpu_min_s': '0.030048', 'cpu_median_s': '0.0423635', 'cpu_mean_s': '0.0411738496', 'cpu_p90_s': '0.043625', 'cpu_max_s': '0.043950999', 'cpu_stddev_s': '0.003782083823341339', 'cpu_variance_s2': '1.4304158046780238e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T13:17:09Z', 'dyn_line_events': '2', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5419', 'dyn_alloc_bytes_pos': '159', 'dyn_alloc_count_pos': '2', 'dyn_rss_peak_bytes': '65073152'}
|
APPS_40861
|
APPS
|
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.
-----Output:-----
For each test case, output as the pattern.
-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$
-----Sample Input:-----
5
1
2
3
4
5
-----Sample Output:-----
1
1
32
1
32
654
1
32
654
10987
1
32
654
10987
1514131211
-----EXPLANATION:-----
No need, else pattern can be decode easily.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
ns = {"__name__": "__main__"}
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 't=int(input())\r\nfor i in range(t):\r\n k=int(input())\r\n m=0\r\n for j in range(1,k+1):\r\n m=m+j\r\n n=m\r\n for l in range(1,j+1):\r\n print(n,end="")\r\n n=n-1\r\n print()\r\n \r\n \r\n \r\n '
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
```
| 12,981 |
memory_bytes
|
{'question_id': '1530', 'solution_index': '16', 'qid_solution': '1530,16', 'num_inputs': '1', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '2', 'runs_succeeded': '2', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '4', 'static_max_nesting': '3', 'static_loop_count': '3', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.039328031', 'wall_median_s': '0.0411395285', 'wall_mean_s': '0.0411395285', 'wall_p90_s': '0.042951026', 'wall_max_s': '0.042951026', 'wall_stddev_s': '0.0018114975', 'wall_variance_s2': '3.28152319250625e-06', 'cpu_min_s': '0.039132', 'cpu_median_s': '0.0409195', 'cpu_mean_s': '0.0409195', 'cpu_p90_s': '0.042707', 'cpu_max_s': '0.042707', 'cpu_stddev_s': '0.0017875', 'cpu_variance_s2': '3.19515625e-06', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T00:24:19Z', 'dyn_line_events': '202', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '12981', 'dyn_alloc_bytes_pos': '1508', 'dyn_alloc_count_pos': '20', 'dyn_rss_peak_bytes': '27267072'}
|
APPS_61358
|
APPS
|
Your start-up's BA has told marketing that your website has a large audience in Scandinavia and surrounding countries. Marketing thinks it would be great to welcome visitors to the site in their own language. Luckily you already use an API that detects the user's location, so this is an easy win.
### The Task
- Think of a way to store the languages as a database (eg an object). The languages are listed below so you can copy and paste!
- Write a 'welcome' function that takes a parameter 'language' (always a string), and returns a greeting - if you have it in your database. It should default to English if the language is not in the database, or in the event of an invalid input.
### The Database
```python
'english': 'Welcome',
'czech': 'Vitejte',
'danish': 'Velkomst',
'dutch': 'Welkom',
'estonian': 'Tere tulemast',
'finnish': 'Tervetuloa',
'flemish': 'Welgekomen',
'french': 'Bienvenue',
'german': 'Willkommen',
'irish': 'Failte',
'italian': 'Benvenuto',
'latvian': 'Gaidits',
'lithuanian': 'Laukiamas',
'polish': 'Witamy',
'spanish': 'Bienvenido',
'swedish': 'Valkommen',
'welsh': 'Croeso'
```
``` java
english: "Welcome",
czech: "Vitejte",
danish: "Velkomst",
dutch: "Welkom",
estonian: "Tere tulemast",
finnish: "Tervetuloa",
flemish: "Welgekomen",
french: "Bienvenue",
german: "Willkommen",
irish: "Failte",
italian: "Benvenuto",
latvian: "Gaidits",
lithuanian: "Laukiamas",
polish: "Witamy",
spanish: "Bienvenido",
swedish: "Valkommen",
welsh: "Croeso"
```
Possible invalid inputs include:
~~~~
IP_ADDRESS_INVALID - not a valid ipv4 or ipv6 ip address
IP_ADDRESS_NOT_FOUND - ip address not in the database
IP_ADDRESS_REQUIRED - no ip address was supplied
~~~~
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = "def greet(language):\n if language == 'english':\n return ('Welcome')\n elif language == 'czech':\n return ('Vitejte')\n elif language == 'danish':\n return ('Velkomst')\n elif language == 'dutch':\n return ('Welkom')\n elif language == 'estonian':\n return ('Tere tulemast')\n elif language == 'finnish':\n return ('Tervetuloa')\n elif language == 'fllemish':\n return ('Welgekomen')\n elif language == 'french':\n return ('Bienvenue')\n elif language == 'german':\n return ('Willkommen')\n elif language == 'italian':\n return ('Benvenuto')\n elif language == 'latvian':\n return ('Gaidits')\n elif language == 'lithuanian':\n return ('Laukiamas')\n elif language == 'polish':\n return ('Witamy')\n elif language == 'spanish':\n return ('Bienvenido')\n elif language == 'swedish':\n return ('Valkommen')\n elif language == 'welsh':\n return ('Croeso')\n else:\n return ('Welcome')"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'greet'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,522 |
memory_bytes
|
{'question_id': '3069', 'solution_index': '28', 'qid_solution': '3069,28', 'num_inputs': '5', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '10', 'runs_succeeded': '10', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '17', 'static_max_nesting': '17', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.030879781', 'wall_median_s': '0.0423204535', 'wall_mean_s': '0.039155349799999996', 'wall_p90_s': '0.04325436', 'wall_max_s': '0.043816256', 'wall_stddev_s': '0.005337822017453706', 'wall_variance_s2': '2.8492343890013553e-05', 'cpu_min_s': '0.030450999', 'cpu_median_s': '0.0418429995', 'cpu_mean_s': '0.0387173993', 'cpu_p90_s': '0.042839999', 'cpu_max_s': '0.043372999', 'cpu_stddev_s': '0.0053408761417168445', 'cpu_variance_s2': '2.852495796116021e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T13:01:02Z', 'dyn_line_events': '2', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5522', 'dyn_alloc_bytes_pos': '262', 'dyn_alloc_count_pos': '1', 'dyn_rss_peak_bytes': '65073152'}
|
APPS_23700
|
APPS
|
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.
Example 1:
Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
Example 3:
Input: coins = [1], amount = 0
Output: 0
Example 4:
Input: coins = [1], amount = 1
Output: 1
Example 5:
Input: coins = [1], amount = 2
Output: 2
Constraints:
1 <= coins.length <= 12
1 <= coins[i] <= 231 - 1
0 <= amount <= 104
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'import numpy as np\nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n maximum = amount + 1\n dp = np.full((maximum), maximum)\n dp[0] = 0\n for i in range(1, maximum):\n for j in coins:\n if j <= i:\n dp[i] = min(dp[i], dp[i - j] + 1)\n if dp[amount] > amount:\n return -1\n return dp[amount]'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'coinChange'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,930 |
memory_bytes
|
{'question_id': '0457', 'solution_index': '482', 'qid_solution': '0457,482', 'num_inputs': '1', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '2', 'runs_succeeded': '2', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '5', 'static_max_nesting': '4', 'static_loop_count': '2', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'True', 'static_comp_count': '0', 'wall_min_s': '0.195714742', 'wall_median_s': '0.196684617', 'wall_mean_s': '0.196684617', 'wall_p90_s': '0.197654492', 'wall_max_s': '0.197654492', 'wall_stddev_s': '0.000969875', 'wall_variance_s2': '9.40657515625e-07', 'cpu_min_s': '3.024625999', 'cpu_median_s': '3.026054499', 'cpu_mean_s': '3.026054499', 'cpu_p90_s': '3.027482999', 'cpu_max_s': '3.027482999', 'cpu_stddev_s': '0.0014285', 'cpu_variance_s2': '2.04061225e-06', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-14T22:51:00Z', 'dyn_line_events': '122', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5930', 'dyn_alloc_bytes_pos': '322', 'dyn_alloc_count_pos': '3', 'dyn_rss_peak_bytes': '27267072'}
|
APPS_83482
|
APPS
|
```if-not:rust
Your task is to write a function `toLeetSpeak` that converts a regular english sentence to Leetspeak.
```
```if:rust
Your task is to write a function `to_leet_speak` that converts a regular english sentence to Leetspeak.
```
More about LeetSpeak You can read at wiki -> https://en.wikipedia.org/wiki/Leet
Consider only uppercase letters (no lowercase letters, no numbers) and spaces.
For example:
```if-not:rust
~~~
toLeetSpeak("LEET") returns "1337"
~~~
```
```if:rust
~~~
to_leet_speak("LEET") returns "1337"
~~~
```
In this kata we use a simple LeetSpeak dialect. Use this alphabet:
```
{
A : '@',
B : '8',
C : '(',
D : 'D',
E : '3',
F : 'F',
G : '6',
H : '#',
I : '!',
J : 'J',
K : 'K',
L : '1',
M : 'M',
N : 'N',
O : '0',
P : 'P',
Q : 'Q',
R : 'R',
S : '$',
T : '7',
U : 'U',
V : 'V',
W : 'W',
X : 'X',
Y : 'Y',
Z : '2'
}
```
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = "alphabet = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n}\n\ndef to_leet_speak(str):\n new_string = ''\n for char in str:\n new_string += alphabet[char] if char != ' ' else ' '\n return new_string\n"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'to_leet_speak'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,381 |
memory_bytes
|
{'question_id': '4047', 'solution_index': '39', 'qid_solution': '4047,39', 'num_inputs': '5', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '10', 'runs_succeeded': '10', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '3', 'static_max_nesting': '2', 'static_loop_count': '1', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.031007652', 'wall_median_s': '0.043376686', 'wall_mean_s': '0.0410448258', 'wall_p90_s': '0.044103811', 'wall_max_s': '0.044602357', 'wall_stddev_s': '0.004876652874941783', 'wall_variance_s2': '2.3781743262677962e-05', 'cpu_min_s': '0.030554999', 'cpu_median_s': '0.0429539995', 'cpu_mean_s': '0.0406102995', 'cpu_p90_s': '0.043668999', 'cpu_max_s': '0.044116', 'cpu_stddev_s': '0.004870501685606961', 'cpu_variance_s2': '2.372178666950025e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T19:43:27Z', 'dyn_line_events': '11', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5381', 'dyn_alloc_bytes_pos': '121', 'dyn_alloc_count_pos': '2', 'dyn_rss_peak_bytes': '94441472'}
|
APPS_63267
|
APPS
|
Write a function that removes every lone 9 that is inbetween 7s.
```python
seven_ate9('79712312') => '7712312'
seven_ate9('79797') => '777'
```
Input: String
Output: String
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = "def seven_ate9(str_):\n res = ''\n for i,x in enumerate(str_):\n if x!='9' or i==0 or i==len(str_)-1:\n res+=f'{x}'\n else:\n if str_[i-1]!='7' or str_[i+1]!='7':\n res+=f'{x}'\n return res\n"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'seven_ate9'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,532 |
memory_bytes
|
{'question_id': '3142', 'solution_index': '68', 'qid_solution': '3142,68', 'num_inputs': '10', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '20', 'runs_succeeded': '20', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '4', 'static_max_nesting': '4', 'static_loop_count': '1', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.030729013', 'wall_median_s': '0.043363436', 'wall_mean_s': '0.042317521049999994', 'wall_p90_s': '0.045161968', 'wall_max_s': '0.047520834', 'wall_stddev_s': '0.0038699082006770327', 'wall_variance_s2': '1.497618948166735e-05', 'cpu_min_s': '0.030271999', 'cpu_median_s': '0.0428664995', 'cpu_mean_s': '0.041821699450000006', 'cpu_p90_s': '0.044693', 'cpu_max_s': '0.047033', 'cpu_stddev_s': '0.0038605739898841776', 'cpu_variance_s2': '1.490403153137024e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T13:28:16Z', 'dyn_line_events': '58', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5532', 'dyn_alloc_bytes_pos': '328', 'dyn_alloc_count_pos': '3', 'dyn_rss_peak_bytes': '65073152'}
|
APPS_5261
|
APPS
|
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'class Solution:\n def trap(self, height):\n """\n :type height: List[int]\n :rtype: int\n """\n \n length = len(height)\n if(length == 0):\n return 0\n maxLeft = [0] * length\n maxRight = [0] * length\n result = 0\n maxLeft[0] = height[0]\n maxRight[length - 1] = height[length - 1]\n for i in range(1,length):\n maxLeft[i] = max(maxLeft[i - 1], height[i])\n for i in reversed(list(range(0, length - 1))):\n maxRight[i] = max(maxRight[i + 1], height[i])\n for i in range(length):\n result += min(maxLeft[i], maxRight[i]) - height[i]\n return result\n \n \n \n \n'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'trap'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,950 |
memory_bytes
|
{'question_id': '0182', 'solution_index': '10', 'qid_solution': '0182,10', 'num_inputs': '1', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '2', 'runs_succeeded': '2', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '5', 'static_max_nesting': '2', 'static_loop_count': '3', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.041008149', 'wall_median_s': '0.042313451', 'wall_mean_s': '0.042313451', 'wall_p90_s': '0.043618753', 'wall_max_s': '0.043618753', 'wall_stddev_s': '0.001305302', 'wall_variance_s2': '1.703813311204e-06', 'cpu_min_s': '0.040566999', 'cpu_median_s': '0.0418974995', 'cpu_mean_s': '0.0418974995', 'cpu_p90_s': '0.043228', 'cpu_max_s': '0.043228', 'cpu_stddev_s': '0.0013305005', 'cpu_variance_s2': '1.77023158050025e-06', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-14T21:43:19Z', 'dyn_line_events': '79', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5950', 'dyn_alloc_bytes_pos': '746', 'dyn_alloc_count_pos': '5', 'dyn_rss_peak_bytes': '17829888'}
|
APPS_92896
|
APPS
|
All of the animals are having a feast! Each animal is bringing one dish. There is just one rule: the dish must start and end with the same letters as the animal's name. For example, the great blue heron is bringing garlic naan and the chickadee is bringing chocolate cake.
Write a function `feast` that takes the animal's name and dish as arguments and returns true or false to indicate whether the beast is allowed to bring the dish to the feast.
Assume that `beast` and `dish` are always lowercase strings, and that each has at least two letters. `beast` and `dish` may contain hyphens and spaces, but these will not appear at the beginning or end of the string. They will not contain numerals.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
def _disabled_input(*args, **kwargs):
raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input
ns = {"__name__": "__judge__"} # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = 'def feast(beast, dish):\n #if beast[0]==dish[0] and beast[-1]==dish[-1]:\n # return True\n #else:\n # return False\n #return beast[0]==dish[0] and beast[-1]==dish[-1]\n return beast.startswith(dish[0]) and beast.endswith(dish[-1])'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
_target = None
_fn_name = 'feast'
if _fn_name:
if "Solution" in ns:
try:
_obj = ns["Solution"]()
if hasattr(_obj, _fn_name):
_target = getattr(_obj, _fn_name)
except Exception:
_target = None
if _target is None and _fn_name in ns and callable(ns[_fn_name]):
_target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
_cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
_user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
if len(_user_funcs) == 1:
_target = _user_funcs[0]
if _target is None:
raise RuntimeError(f"Could not resolve callable '{_fn_name}'")
_raw = sys.stdin.read().strip()
if _raw:
_parsed = json.loads(_raw)
if isinstance(_parsed, dict):
_kwargs = _parsed.get("kwargs", {})
_args = _parsed.get("args", [])
else:
_args, _kwargs = _parsed, {}
else:
_args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
_args = [_args]
_res = _target(*_args, **_kwargs)
try:
sys.stdout.write(repr(_res) + "\n")
except Exception:
pass
```
| 5,370 |
memory_bytes
|
{'question_id': '4464', 'solution_index': '83', 'qid_solution': '4464,83', 'num_inputs': '11', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '22', 'runs_succeeded': '22', 'runs_timed_out': '0', 'runs_failed': '0', 'static_cc_total': '1', 'static_max_nesting': '1', 'static_loop_count': '0', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '0.030759814', 'wall_median_s': '0.042777081', 'wall_mean_s': '0.041049276090909095', 'wall_p90_s': '0.043435105', 'wall_max_s': '0.043523172', 'wall_stddev_s': '0.004012484713819333', 'wall_variance_s2': '1.610003357863381e-05', 'cpu_min_s': '0.030292999', 'cpu_median_s': '0.042352499', 'cpu_mean_s': '0.04061722686363637', 'cpu_p90_s': '0.043011', 'cpu_max_s': '0.043081999', 'cpu_stddev_s': '0.004019877303542149', 'cpu_variance_s2': '1.6159413535533296e-05', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T22:55:55Z', 'dyn_line_events': '1', 'dyn_py_calls': '1', 'dyn_max_call_depth': '1', 'dyn_peak_alloc_bytes': '5370', 'dyn_alloc_bytes_pos': '158', 'dyn_alloc_count_pos': '2', 'dyn_rss_peak_bytes': '94441472'}
|
APPS_43337
|
APPS
|
You are provided with an input containing a number. Implement a solution to find the largest sum of consecutive increasing digits , and present the output with the largest sum and the positon of start and end of the consecutive digits.
Example :
Input :> 8789651
Output :> 24:2-4
where 24 is the largest sum and 2-4 is start and end of the consecutive increasing digits.
```python
USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
import resource as _res
except Exception:
_res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
from typing import *
except Exception:
pass
try:
sys.setrecursionlimit(1_000_000)
except Exception:
pass
try:
import site as _site
try:
_sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
for _p in _sys_sites:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
try:
_usp = _site.getusersitepackages()
if isinstance(_usp, str):
_usp = [_usp]
for _p in _usp:
if _p and _p not in sys.path:
sys.path.append(_p)
except Exception:
pass
except Exception:
pass
ns = {"__name__": "__main__"}
for _k, _v in list(globals().items()):
if not _k.startswith("_"):
ns[_k] = _v
_CODE = '# cook your dish here\np=input().strip()\nr=[]\nfor i in range(len(p)):\n s=int(p[i])\n k=0\n for j in range(i,len(p)-1):\n if p[j+1]>p[j]:\n s=s+int(p[j+1])\n k+=1\n else:\n break\n r.append([i+1,i+k+1,s]) \nfor i in range(len(r)):\n for j in range(i+1,len(r)):\n if r[i][2]>r[j][2]:\n c=r[j]\n r[j]=r[i]\n r[i]=c\nprint("{}:{}-{}".format(r[-1][2],r[-1][0],r[-1][1]))'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)
```
| null |
memory_bytes
|
{'question_id': '1682', 'solution_index': '7', 'qid_solution': '1682,7', 'num_inputs': '1', 'repeats_per_input': '2', 'warmup_per_input': '1', 'timeout_s': '10.0', 'runs_attempted': '2', 'runs_succeeded': '0', 'runs_timed_out': '0', 'runs_failed': '2', 'static_cc_total': '7', 'static_max_nesting': '3', 'static_loop_count': '4', 'static_recursion': 'False', 'static_uses_heapq': 'False', 'static_uses_numpy': 'False', 'static_comp_count': '0', 'wall_min_s': '', 'wall_median_s': '', 'wall_mean_s': '', 'wall_p90_s': '', 'wall_max_s': '', 'wall_stddev_s': '', 'wall_variance_s2': '', 'cpu_min_s': '', 'cpu_median_s': '', 'cpu_mean_s': '', 'cpu_p90_s': '', 'cpu_max_s': '', 'cpu_stddev_s': '', 'cpu_variance_s2': '', 'python': '3.11.11', 'hostname': 'f3f34a848498', 'timestamp_utc': '2025-09-15T01:07:35Z', 'dyn_line_events': '', 'dyn_py_calls': '', 'dyn_max_call_depth': '', 'dyn_peak_alloc_bytes': '', 'dyn_alloc_bytes_pos': '', 'dyn_alloc_count_pos': '', 'dyn_rss_peak_bytes': ''}
|
Code-Regression
A unified regression dataset collated from three sources (APPS, KBSS, CDSS) along with our own custom profiling for training and evaluating regression models that map code strings to a target metric.
This is part of a larger research paper on regression-language models for code.
Link for Graph-Regression dataset: https://huggingface.co/datasets/akhauriyash/GraphArch-Regression
Link for Base Gemma-Adapted RLM model: https://huggingface.co/akhauriyash/RLM-GemmaS-Code-v0
Schema
- identifier (string): Source key for the example, e.g.
APPS_0
,KBSS_1
,CDSS_42
. - space (string): Logical dataset split/source (
APPS
,KBSS
, orCDSS
). - input (string): The input string (
shortest_onnx
). - target_metric (string): Always
val_accuracy
. - val_accuracy (number | null): The regression target.
- metric_type (string): Auxiliary metric family for this row:
memory_bytes
for APPS and CDSSlatency_ms
for KBSS
- metadata (string): A Python-dict-like string with source-specific information:
- APPS:
problem_metainformation
cast to string. - KBSS:
{'stddev_ms': <value>}
. - CDSS: subset of fields
{s_id, p_id, u_id, date, language, original_language, filename_ext, status, cpu_time, memory, code_size}
.
- APPS:
This dataset has 7502559 rows:
- APPS: 98932
- CDSS (CodeNets): 7391012
- KBSS (Triton Kernels): 12615
Tip: turn
metadata
back into a dict with:
from ast import literal_eval meta = literal_eval(row["metadata"])
How to load with 🤗 Datasets
from datasets import load_dataset
ds = load_dataset("akhauriyash/Code-Regression")
Testing Code-Regression with a basic Gemma RLM model
Use the code below as reference for evaluating a basic RegressLM model ( better, more models to come! :) )
import torch
import numpy as np
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
from scipy.stats import spearmanr
from tqdm import tqdm
REPO_ID = "akhauriyash/RLM-GemmaS-Code-v0"
DATASET = "akhauriyash/Code-Regression"
dataset = load_dataset(DATASET, split="train")
tok = AutoTokenizer.from_pretrained(REPO_ID, trust_remote_code=True)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = AutoModelForSeq2SeqLM.from_pretrained(REPO_ID, trust_remote_code=True).to(device).eval()
MAX_ITEMS, BATCH_SIZE, spaces, results = 512, 16, ["KBSS", "CDSS", "APPS"], {}
language = None # Specify language for CDSS, e.g. "python"
n_out_tokens = getattr(model.config, "num_tokens_per_obj", 8) * getattr(model.config, "max_num_objs", 1)
n_out_tokens = model.config.num_tokens_per_obj * model.config.max_num_objs
for SPACE in spaces:
inputs, targets = [], []
for row in tqdm(dataset, desc=f"Processing {SPACE} till {MAX_ITEMS} items"):
if row.get("space") == SPACE and "input" in row and "target" in row:
try:
lang = eval(row['metadata'])['language'] if SPACE == "CDSS" else None
if SPACE != "CDSS" or language is None or lang == language:
targets.append(float(row["target"]))
if SPACE == "CDSS":
inputs.append(f"# {SPACE}\n# Language: {lang}\n{row['input']}")
else:
inputs.append(f"{SPACE}\n{row['input']}")
except: continue
if len(inputs) >= MAX_ITEMS: break
preds = []
for i in tqdm(range(0, len(inputs), BATCH_SIZE)):
enc = tok(inputs[i:i+BATCH_SIZE], return_tensors="pt", truncation=True, padding=True, max_length=2048).to(device)
batch_preds = []
for _ in range(8):
out = model.generate(**enc, max_new_tokens=n_out_tokens, min_new_tokens=n_out_tokens, do_sample=True, top_p=0.95, temperature=1.0)
decoded = [tok.token_ids_to_floats(seq.tolist()) for seq in out]
decoded = [d[0] if isinstance(d, list) and d else float("nan") for d in decoded]
batch_preds.append(decoded)
preds.extend(torch.tensor(batch_preds).median(dim=0).values.tolist())
spear, _ = spearmanr(np.array(targets), np.array(preds))
results[SPACE] = spear; print(f"Spearman ρ for {SPACE}: {spear:.3f}")
print("Spearman ρ | KBSS | CDSS | APPS")
print(f"{REPO_ID} | " + " | ".join(f"{results[s]:.3f}" for s in spaces))
We got the following results when testing on a random subset of the Code-Regression dataset.
Model ID | KBSS | CDSS | APPS
akhauriyash/RegressLM-gemma-s-RLM-table3 | 0.527 | 0.787 | 0.926
Credits
This dataset was collated from several sources, along with our own latency and memory profiling. We thank the authors for their efforts.
APPS: Hendrycks, D., Basart, S., Kadavath, S., Mazeika, M., Arora, A., Guo, E., Burns, C., Puranik, S., He, H., Song, D., & Steinhardt, J. (2021). Measuring Coding Challenge Competence With APPS. NeurIPS.
CDSS (CodeNet): Puri, R., Kung, D. S., Janssen, G., Zhang, W., Domeniconi, G., Zolotov, V., Dolby, J., Chen, J., Choudhury, M., Decker, L., & others. (2021). Codenet: A large-scale ai for code dataset for learning a diversity of coding tasks.
KBSS (KernelBook): Paliskara, S., & Saroufim, M. (2025). KernelBook. https://huggingface.co/datasets/GPUMODE/KernelBook
Citations
If you found this dataset useful for your research, please cite the original sources above as well as:
@article{akhauri2025regressionlanguagemodelscode,
title={Regression Language Models for Code},
author={Yash Akhauri and Xingyou Song and Arissa Wongpanich and Bryan Lewandowski and Mohamed S. Abdelfattah},
journal={arXiv preprint arXiv:2509.26476},
year={2025}
}
@article{akhauri2025performance,
title={Performance Prediction for Large Systems via Text-to-Text Regression},
author={Akhauri, Yash and Lewandowski, Bryan and Lin, Cheng-Hsi and Reyes, Adrian N and Forbes, Grant C and Wongpanich, Arissa and Yang, Bangding and Abdelfattah, Mohamed S and Perel, Sagi and Song, Xingyou},
journal={arXiv preprint arXiv:2506.21718},
year={2025}
}
- Downloads last month
- 59