task_id
stringlengths 4
6
| prompt
stringlengths 152
1.04k
| canonical_solution
stringlengths 18
953
| test
stringlengths 135
1.8k
| entry_point
stringlengths 2
37
|
---|---|---|---|---|
en/0 | def calculate_tsubo(x: float, y: float) -> int:
"""
Calculates the size of the land with the specified length x meters and width y meters, and returns the number of tsubos.
The land size is returned as an integer.
1 tsubo = 3.30579 square meters
Args:
x (float): Vertical length of land (meters)
y (float): horizontal length of land (meters)
Returns:
int: Returns the land area in tsubo units.
Example:
>>> calculate_tsubo(10, 10)
30
>>> calculate_tsubo(5, 7)
10
"""
| area_square_meters = x * y
tsubo = area_square_meters / 3.30579
return int(tsubo)
| def check(candidate):
assert candidate(10.0, 10.0) == 30
assert candidate(5.5, 7.2) == 11
assert candidate(0.3, 10.0) == 0
assert candidate(10.0, 0.3) == 0
assert candidate(0.0, 0.0) == 0
assert candidate(100.0, 100.0) == 3024
assert candidate(5.5, 5.5) == 9
assert candidate(3.14, 3.14) == 2
| calculate_tsubo |
en/1 | def calculate_tax_included_price(amount: int) -> int:
"""
Calculate the tax-included amount by adding consumption tax to the total amount at the time of takeout.
The consumption tax rate is calculated at 8%, rounded off, and returned as an integer.
argument:
amount (int): Total amount for takeout (excluding tax)
Return value:
int: Tax-included amount including consumption tax (rounded off)
Usage example:
>>> calculate_tax_included_price(1000)
1080
>>> calculate_tax_included_price(500)
540
>>> calculate_tax_included_price(1234)
1333
"""
| tax_rate = 0.08
tax_included_price = amount * (1 + tax_rate)
return round(tax_included_price)
| def check(candidate):
assert candidate(1000) == 1080
assert candidate(500) == 540
assert candidate(1234) == 1333
assert candidate(0) == 0
assert candidate(1) == 1
assert candidate(2500) == 2700
assert candidate(999) == 1079
| calculate_tax_included_price |
en/2 | def tatami_to_square_meters(n: int) -> float:
"""
Convert the number of tatami mats to square meters and calculate to two decimal places.
Convert as 1 tatami = 1.62 square meters.
argument:
n (int): number of tatami mats
Return value:
float: square meter (2 decimal places)
Usage example:
>>> tatami_to_square_meters(1)
1.62
>>> tatami_to_square_meters(6)
9.72
>>> tatami_to_square_meters(10)
16.20
"""
| square_meters = n * 1.62
return round(square_meters, 2)
| def check(candidate):
assert candidate(1) == 1.62
assert candidate(2) == 3.24
assert candidate(3) == 4.86
assert candidate(6) == 9.72
assert candidate(6) == 9.72
assert candidate(9) == 14.58
assert candidate(10) == 16.20
assert candidate(15) == 24.30
assert candidate(20) == 32.40
| tatami_to_square_meters |
en/3 | def tokyo_dome_units(n: int) -> float:
"""
Calculates how many Tokyo Dome areas are covered by the given area `n` and returns it in two decimal places.
`n` is an integer value representing the area you want to calculate in square meters.
The area equivalent to one Tokyo Dome is approximately 46,755 square meters.
argument:
n (int): Area to be calculated (square meters)
Return value:
float: How many Tokyo Domes the area is equivalent to (up to 2 decimal places)
example:
>>> tokyo_dome_units(100000)
2.14
>>> tokyo_dome_units(50000)
1.07
>>> tokyo_dome_units(46755)
1.00
"""
| # 東京ドームの床面積(平方メートル)
tokyo_dome_area = 46755
# 東京ドーム何個分かを計算して、小数点以下2桁までの浮動小数点数で返す
units = n / tokyo_dome_area
return round(units, 2)
| def check(candidate):
assert candidate(100000) == 2.14
assert candidate(50000) == 1.07
assert candidate(46755) == 1.00
assert candidate(46755 * 2) == 2.00
assert candidate(46755 * 10) == 10.00
assert candidate(1000000) == 21.39
assert candidate(467550) == 10.00
| tokyo_dome_units |
en/4 | def judge_janken(a: str, b: str) -> str:
"""
Determines the result of rock, paper, scissors and returns the winner as "A" or "B", and in case of a tie, returns "引き分け".
It is based on the rule that "グー" beats "チョキ", "チョキ" beats "パー", and "パー" beats "グー".
argument:
a (str): Player A's hand ("グー", "チョキ", "パー")
b (str): Player B's hand ("グー", "チョキ", "パー")
Return value:
str: Returns the winner as "A" or "B", or "引き分け" in case of a tie.
Usage example:
>>> judge_janken("グー", "チョキ")
'A'
>>> judge_janken("パー", "チョキ")
'B'
>>> judge_janken("グー", "グー")
'引き分け'
"""
|
if a == b:
return "引き分け"
win_map = {
("グー", "チョキ"): "A",
("チョキ", "パー"): "A",
("パー", "グー"): "A",
("チョキ", "グー"): "B",
("パー", "チョキ"): "B",
("グー", "パー"): "B"
}
return win_map.get((a, b))
| def check(candidate):
assert candidate("グー", "チョキ") == "A"
assert candidate("パー", "チョキ") == "B"
assert candidate("チョキ", "グー") == "B"
assert candidate("グー", "パー") == "B"
assert candidate("チョキ", "パー") == "A"
assert candidate("パー", "グー") == "A"
assert candidate("グー", "グー") == "引き分け"
assert candidate("チョキ", "チョキ") == "引き分け"
assert candidate("パー", "パー") == "引き分け"
| judge_janken |
en/5 | def count_pencils(n: int) -> str:
"""
When counting pencils in Japanese, ``hon'' is added after the number as a particle. This particle is read differently depending on the ones place of the number.
If the ones place is "0, 1, 6, or 8", it is read as "ぽん", and if it is "3", it is read as "ぼん".
Other numbers such as "2, 4, 5, 7, and 9" are read as "ほん".
argument:
n (int): Number of pencils (positive integer less than or equal to 999)
Return value:
str: How to read the particle ``hon'' ('ほん', 'ぽん', or 'ぼん')
Usage example:
>>> count_pencils(1)
'ぽん'
>>> count_pencils(3)
'ぼん'
>>> count_pencils(7)
'ほん'
"""
| last_digit = n % 10
if last_digit in [2, 4, 5, 7, 9]:
return "ほん"
elif last_digit in [0, 1, 6, 8]:
return "ぽん"
elif last_digit == 3:
return "ぼん"
| def check(candidate):
assert candidate(6) == "ぽん"
assert candidate(8) == "ぽん"
assert candidate(10) == "ぽん"
assert candidate(21) == "ぽん"
assert candidate(3) == "ぼん"
assert candidate(13) == "ぼん"
assert candidate(4) == "ほん"
assert candidate(5) == "ほん"
assert candidate(7) == "ほん"
assert candidate(12) == "ほん"
assert candidate(99) == "ほん"
| count_pencils |
en/6 | def eto_from_year(year: int) -> str:
"""
Given a year in the Western calendar, find the zodiac sign for that year.
The zodiac signs repeat in order: the zodiac (子, 丑, 寅, 卯, 辰, 巳, 午, 未, 申, 酉, 戌, 亥).
>>> eto_from_year(2024)
'辰'
>>> eto_from_year(2023)
'卯'
>>> eto_from_year(2000)
'辰'
"""
| eto_cycle = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"]
index = (year - 4) % 12
return eto_cycle[index]
| def check(candidate):
assert candidate(2020) == "子"
assert candidate(2021) == "丑"
assert candidate(2022) == "寅"
assert candidate(2023) == "卯"
assert candidate(2024) == "辰"
assert candidate(2025) == "巳"
assert candidate(2026) == "午"
assert candidate(2027) == "未"
assert candidate(2028) == "申"
assert candidate(2029) == "酉"
assert candidate(2030) == "戌"
assert candidate(2031) == "亥"
assert candidate(2008) == "子"
assert candidate(1996) == "子"
assert candidate(1984) == "子"
| eto_from_year |
en/7 | def is_valid_postal_code(postal_code: str) -> bool:
"""
A function that determines whether a postal code is formatted correctly.
The correct format for a postal code is 123-4567, which meets the following conditions:
- It is a 7 digit number.
- A hyphen ('-') is between the third and fourth digits.
- There is a 3-digit number before the hyphen and a 4-digit number after it.
argument:
postal_code (str): Postal code string
Return value:
bool: True if the format is correct, False if it is not.
"""
| # 文字列の長さが8であり、4文字目に '-' があり、前3桁と後4桁が数字か確認
if len(postal_code) == 8 and postal_code[3] == '-':
# ハイフン前の部分とハイフン後の部分が数字かどうか確認
if postal_code[:3].isdigit() and postal_code[4:].isdigit():
return True
return False
| def check(candidate):
assert candidate("123-4567") == True
assert candidate("000-0000") == True
assert candidate("12-34567") == False
assert candidate("1234-567") == False
assert candidate("123-456") == False
assert candidate("1234567") == False
assert candidate("abc-defg") == False
| is_valid_postal_code |
en/8 | def convert_wareki_to_seireki(wareki: str) -> int:
"""
Converts the given Japanese calendar to the Western calendar. The Japanese calendar is limited to era names from ``明治'' to ``令和.''
The Japanese calendar is expressed as "令和3年" or "平成30年".
Argument:
wareki (str): Japanese calendar string
Return:
int: An integer representing the year in the Western calendar
Execution example:
>>> convert_wareki_to_seireki('令和3年')
2021
>>> convert_wareki_to_seireki('平成30年')
2018
>>> convert_wareki_to_seireki('昭和64年')
1989
>>> convert_wareki_to_seireki('平成元年')
1989
"""
| eras = {
"令和": 2019,
"平成": 1989,
"昭和": 1926,
"大正": 1912,
"明治": 1868
}
era_name = wareki[:2]
year_str = wareki[2:-1]
year = 1 if year_str == "元" else int(year_str)
return eras[era_name] + year - 1
| def check(candidate):
assert candidate('令和3年') == 2021
assert candidate('平成30年') == 2018
assert candidate('昭和64年') == 1989
assert candidate('平成元年') == 1989
assert candidate('大正元年') == 1912
assert candidate('明治45年') == 1912
assert candidate('令和元年') == 2019
assert candidate('昭和1年') == 1926
assert candidate('明治1年') == 1868 | convert_wareki_to_seireki |
en/9 | def is_shichi_go_san_age(birth_year: int, current_year: int) -> bool:
"""
Given the year of birth and the current year, determine whether that age is eligible for Shichi-Go-San.
Since Shichi-Go-San is celebrated in the years when people are 3, 5, or 7 years old, it returns True if it is applicable, and False otherwise.
argument:
birth_year (int): Year of birth (Western calendar)
current_year (int): Current year (Western calendar)
Return value:
bool: True if the target age of Shichi-Go-San, otherwise False
Execution example:
>>> is_shichi_go_san_age(2020, 2023)
True # 3 years old
>>> is_shichi_go_san_age(2018, 2023)
True # 5 years old
>>> is_shichi_go_san_age(2016, 2023)
True # 7 years old
>>> is_shichi_go_san_age(2017, 2023)
False
>>> is_shichi_go_san_age(2020, 2024)
False
"""
| age = current_year - birth_year
return age in {3, 5, 7}
| def check(candidate):
assert candidate(2020, 2023) == True
assert candidate(2018, 2023) == True
assert candidate(2016, 2023) == True
assert candidate(2017, 2023) == False
assert candidate(2020, 2024) == False
assert candidate(2015, 2023) == False
assert candidate(2021, 2023) == False
| is_shichi_go_san_age |
en/10 | def solve_tsurukame(total_animals: int, total_legs: int) -> tuple:
"""
A function that solves Tsurukame arithmetic. Calculate the number of each from the total of the crane and turtle and the total of the legs.
Use the fact that cranes have two legs and turtles have four legs to solve this problem.
For example, if the number of cranes is x and the number of turtles is y, the following formula holds.
1. x + y = total_animals (total number of cranes and turtles is given)
2. 2x + 4y = total_legs (given the sum of the legs of the crane and turtle)
Transform this simultaneous equation to first find the number of turtles, y, and then find the number of cranes, x, by subtracting the number of turtles from the total number.
argument:
total_animals (int): Total number of cranes and turtles
total_legs (int): total number of legs
Return value:
tuple: (number of cranes, number of turtles)
Usage example:
>>> solve_tsurukame(10, 28)
(6, 4)
"""
| y = (total_legs - 2 * total_animals) // 2
x = total_animals - y
return x, y
| def check(candidate):
# 基本的なテストケース
assert candidate(10, 28) == (6, 4)
assert candidate(8, 24) == (4, 4)
assert candidate(5, 14) == (3, 2)
# 鶴と亀が全て鶴または全て亀の場合
assert candidate(10, 20) == (10, 0)
assert candidate(5, 20) == (0, 5)
# エッジケース: 鶴と亀が1匹ずつ
assert candidate(2, 6) == (1, 1)
| solve_tsurukame |
en/11 | def get_emergency_service(text: str) -> int:
"""
If the input string matches the service name of an emergency number, returns that number.
Corresponding service name:
- 消防・救急: 119
- 警察: 110
- 天気予報: 177
- 災害用伝言ダイヤル: 171
- 海上保安庁: 118
- 消費者ホットライン: 188
argument:
text (str): Service name corresponding to the emergency number.
Return value:
int: Corresponding emergency phone number (integer).
Execution example:
>>> extract_emergency_number_from_key("消防・救急")
119
>>> extract_emergency_number_from_key("警察")
110
>>> extract_emergency_number_from_key("天気予報")
177
"""
| emergency_services = {
"消防・救急": 119,
"警察": 110,
"天気予報": 177,
"災害用伝言ダイヤル": 171,
"海上保安庁": 118,
"消費者ホットライン": 188
}
return emergency_services.get(text)
| def check(candidate):
assert candidate("消防・救急") == 119
assert candidate("警察") == 110
assert candidate("天気予報") == 177
assert candidate("災害用伝言ダイヤル") == 171
assert candidate("海上保安庁") == 118
assert candidate("消費者ホットライン") == 188
| get_emergency_service |
en/12 | def missing_positions(player_positions):
"""
Check the baseball positions and identify the missing positions.
argument:
player_positions (list): List of positions the player is in (in Kanji).
Return value:
list: List of missing positions.
Execution example:
>>> positions = ["投手", "捕手", "一塁手", "二塁手", "三塁手", "遊撃手"]
>>> missing_positions(positions)
['中堅手', '左翼手', '右翼手']
>>> positions = ["投手", "捕手", "中堅手", "左翼手", "右翼手"]
>>> missing_positions(positions)
['一塁手', '二塁手', '三塁手', '遊撃手']
"""
| required_positions = {
"投手",
"捕手",
"一塁手",
"二塁手",
"三塁手",
"遊撃手",
"中堅手",
"左翼手",
"右翼手"
}
current_positions = set(player_positions)
missing = required_positions - current_positions
return list(missing)
| def check(candidate):
assert set(candidate(["投手", "捕手", "一塁手", "二塁手", "三塁手", "遊撃手"])) == {"中堅手", "左翼手", "右翼手"}
assert set(candidate(["投手", "捕手", "一塁手", "二塁手", "三塁手", "遊撃手", "中堅手"])) == {"左翼手", "右翼手"}
assert set(candidate([])) == {"投手", "捕手", "一塁手", "二塁手", "三塁手", "遊撃手", "中堅手", "左翼手", "右翼手"}
assert set(candidate(["投手", "捕手", "中堅手"])) == {"一塁手", "二塁手", "三塁手", "遊撃手", "左翼手", "右翼手"}
| missing_positions |
en/13 | def calculate_salt_solution_concentration(salt: float, water: float) -> float:
"""
Calculate the concentration of saline solution.
Concentration = (weight of salt / (weight of salt + weight of water)) * 100
argument:
salt (float): weight of salt (g)
water (float): weight of water (g)
Return value:
float: Concentration of saline solution (%)
Usage example:
>>> calculate_salt_solution_concentration(10, 90)
10.0
>>> calculate_salt_solution_concentration(15, 85)
15.0
"""
| if salt + water == 0:
return 0.0
concentration = (salt / (salt + water)) * 100
return concentration
| def check(candidate):
assert candidate(10, 90) == 10.0
assert candidate(15, 85) == 15.0
assert candidate(50, 50) == 50.0
assert candidate(30, 70) == 30.0
| calculate_salt_solution_concentration |
en/14 | def corrections_needed(lyrics: str) -> int:
"""
Compare the given lyrics with the lyrics of Japan's national anthem "Kimigayo".
Calculate the number of edits required to correct mistakes.
Lyrics comparison is performed using character strings that do not include spaces.
argument:
lyrics (str): Lyrics entered by the user
Return value:
int: Number of times required for insertion/replacement/deletion and correction
Execution example:
>>> corrections_needed("君が代は千代に八千代に細石の巌となりて苔のむすまで")
0
>>> corrections_needed("君が代は千代に八千代に細石の巌となりて苔のむすまだ")
1
"""
| correct_lyrics = "君が代は千代に八千代に細石の巌となりて苔のむすまで"
lyrics = lyrics.replace(" ", "")
len_lyrics, len_correct = len(lyrics), len(correct_lyrics)
dp = [[0] * (len_correct + 1) for _ in range(len_lyrics + 1)]
for i in range(len_lyrics + 1):
dp[i][0] = i
for j in range(len_correct + 1):
dp[0][j] = j
for i in range(1, len_lyrics + 1):
for j in range(1, len_correct + 1):
if lyrics[i - 1] == correct_lyrics[j - 1]:
cost = 0
else:
cost = 1
dp[i][j] = min(
dp[i - 1][j] + 1,
dp[i][j - 1] + 1,
dp[i - 1][j - 1] + cost
)
return dp[len_lyrics][len_correct]
| def check(candidate):
assert candidate("君が代は千代に八千代に細石の巌となりて苔のむすまで") == 0
assert candidate("君が代は千代に八千代に細石の巌となりて苔のむすまだ") == 1
assert candidate("君が代は千代に百千代に細石の巌となりて苔のむすまで") == 1
assert candidate("君が代は千代に八千代に細石の巌となり苔のむすまで") == 1
assert candidate("君が代は千代に八千代に細石の巌となりて苔のむすま") == 1
assert candidate("君が代千代に八千代に細石の巌となりて苔のむすまでだよ") == 3
assert candidate("君が代は千代に八千代に細石の巌となり苔のむすま") == 2
| corrections_needed |
en/15 | def get_condiment_by_hiragana(hiragana: str) -> str:
"""
Returns the seasoning that corresponds to the hiragana in the input line.
argument:
hiragana (str): Hiragana for the line (``さ'', ``し', ``す'', ``せ'', ``そ'')
Return value:
str: Compatible seasonings ("砂糖", "塩", "酢", "醤油", "miso")
Usage example:
>>> get_condiment_by_hiragana("さ")
'砂糖'
>>> get_condiment_by_hiragana("し")
'塩'
>>> get_condiment_by_hiragana("す")
'酢'
>>> get_condiment_by_hiragana("せ")
'醤油'
>>> get_condiment_by_hiragana("そ")
'味噌'
"""
| condiments = {
"さ": "砂糖",
"し": "塩",
"す": "酢",
"せ": "醤油",
"そ": "味噌"
}
return condiments.get(hiragana)
| def check(candidate):
assert candidate("さ") == "砂糖"
assert candidate("し") == "塩"
assert candidate("す") == "酢"
assert candidate("せ") == "醤油"
assert candidate("そ") == "味噌"
| get_condiment_by_hiragana |
en/16 | def classify_bow(angle: int) -> str:
"""
Based on the angle of the bow, the type of bow ('会釈', '普通礼', '最敬礼') is determined.
argument:
angle (int): angle of bow (integer)
Return value:
str: type of bow ('会釈', '普通礼', '最敬礼', or '無効な角度')
Execution example:
>>> classify_bow(15)
'会釈'
>>> classify_bow(30)
'普通礼'
>>> classify_bow(45)
'最敬礼'
>>> classify_bow(20)
'無効な角度'
"""
| if angle == 15:
return "会釈"
elif angle == 30:
return "普通礼"
elif angle == 45:
return "最敬礼"
else:
return "無効な角度"
| def check(candidate):
assert candidate(15) == "会釈"
assert candidate(30) == "普通礼"
assert candidate(45) == "最敬礼"
assert candidate(20) == "無効な角度"
assert candidate(0) == "無効な角度"
assert candidate(60) == "無効な角度"
| classify_bow |
en/17 | def tatami_area(num_tatami: int, tatami_type: str) -> float:
"""
Calculate the area of the room from the number of tatami mats and the type of tatami mats. The type of tatami is designated as ``江戸間'' or ``京間''.
- 江戸間: 1.76 square meters (approximately 1.76 square meters)
- 京間: 1.82 square meters (approximately 1.82 square meters)
argument:
num_tatami (int): Number of tatami
tatami_type (str): Tatami type. Either '江戸間' or '京間'.
Return value:
float: area of the room (square meters)
Execution example:
>>> tatami_area(6, "江戸間")
10.56
>>> tatami_area(6, "京間")
10.92
"""
| tatami_sizes = {
"江戸間": 1.76,
"京間": 1.82
}
return round(num_tatami * tatami_sizes[tatami_type], 2)
| def check(candidate):
assert candidate(6, "江戸間") == 10.56
assert candidate(6, "京間") == 10.92
assert candidate(1, "江戸間") == 1.76
assert candidate(1, "京間") == 1.82
assert candidate(10, "江戸間") == 17.6
assert candidate(10, "京間") == 18.2
| tatami_area |
en/18 | def compare_fortunes(last_year: str, this_year: str) -> str:
"""
Compare last year's fortune with this year's fortune and decide whether this year's fortune is better, worse, or unchanged than last year.
Omikuji ranks are evaluated in the following order (left is best):
大吉 > 中吉 > 小吉 > 吉 > 末吉 > 凶 > 大凶
Argument:
last_year (str): Last year's omikuji result
this_year (str): This year's fortune results
Return value:
str: Message indicating whether this year is 良い, 悪い, or 変化なし than last year
Example:
>>> compare_fortunes("吉", "大吉")
'良い'
>>> compare_fortunes("大吉", "小吉")
'悪い'
>>> compare_fortunes("中吉", "中吉")
'変化なし'
"""
| fortune_ranks = {
"大吉": 1,
"中吉": 2,
"小吉": 3,
"吉": 4,
"末吉": 5,
"凶": 6,
"大凶": 7
}
last_rank = fortune_ranks.get(last_year, float('inf'))
this_rank = fortune_ranks.get(this_year, float('inf'))
if this_rank < last_rank:
return '良い'
elif this_rank > last_rank:
return '悪い'
else:
return '変化なし'
| def check(candidate):
assert candidate("吉", "大吉") == '良い'
assert candidate("大吉", "小吉") == '悪い'
assert candidate("中吉", "中吉") == '変化なし'
assert candidate("凶", "吉") == '良い'
assert candidate("大凶", "大吉") == '良い'
assert candidate("大吉", "大凶") == '悪い'
assert candidate("末吉", "末吉") == '変化なし'
assert candidate("小吉", "中吉") == '良い'
assert candidate("小吉", "凶") == '悪い'
assert candidate("中吉", "小吉") == '悪い'
assert candidate("大吉", "大吉") == '変化なし'
| compare_fortunes |
en/19 | def judo_match_winner(A: dict, B: dict) -> str:
"""
Determine the winner or loser of a judo match.
argument:
A (dict): Player A's score and foul information
- "一本" (int): Number of one
- "技あり" (int): number of wazaari
- "指導" (int): number of teachings
B (dict): Player B's score and foul information
- "一本" (int): Number of one
- "技あり" (int): number of wazaari
- "指導" (int): number of teachings
Return value:
str: string representing the winner ("A", "B", "extension")
Execution example:
>>> judo_match_winner({"一本": 1, "技あり": 0, "指導": 0},
{"一本": 0, "技あり": 1, "指導": 0})
'A'
>>> judo_match_winner({"一本": 0, "技あり": 2, "指導": 1},
{"一本": 0, "技あり": 1, "指導": 0})
'A'
>>> judo_match_winner({"一本": 0, "技あり": 0, "指導": 3},
{"一本": 0, "技あり": 0, "指導": 3})
'延長'
"""
| # 1. 一本勝ちの判定
if A["一本"] > B["一本"]:
return "A"
elif A["一本"] < B["一本"]:
return "B"
# 2. 技ありの判定(2つで一本と同等)
if A["技あり"] >= 2:
return "A"
if B["技あり"] >= 2:
return "B"
if A["技あり"] > B["技あり"]:
return "A"
if A["技あり"] < B["技あり"]:
return "B"
# 3. 指導による敗北(指導3つで敗北)
if A["指導"] >= 3 and B["指導"] < 3:
return "B"
if B["指導"] >= 3 and A["指導"] < 3:
return "A"
# 4. 引き分け(延長)
return "延長"
| def check(candidate):
# 一本勝ちの例
assert candidate({"一本": 1, "技あり": 0, "指導": 0},
{"一本": 0, "技あり": 0, "指導": 0}) == "A"
assert candidate({"一本": 0, "技あり": 0, "指導": 0},
{"一本": 1, "技あり": 0, "指導": 0}) == "B"
# 技ありの判定
assert candidate({"一本": 0, "技あり": 2, "指導": 1},
{"一本": 0, "技あり": 1, "指導": 0}) == "A"
assert candidate({"一本": 0, "技あり": 1, "指導": 0},
{"一本": 0, "技あり": 2, "指導": 0}) == "B"
# 指導による勝敗
assert candidate({"一本": 0, "技あり": 0, "指導": 3},
{"一本": 0, "技あり": 0, "指導": 2}) == "B"
assert candidate({"一本": 0, "技あり": 0, "指導": 2},
{"一本": 0, "技あり": 0, "指導": 3}) == "A"
# 引き分け(延長)
assert candidate({"一本": 0, "技あり": 0, "指導": 3},
{"一本": 0, "技あり": 0, "指導": 3}) == "延長"
assert candidate({"一本": 0, "技あり": 1, "指導": 1},
{"一本": 0, "技あり": 1, "指導": 1}) == "延長"
| judo_match_winner |
en/20 | def compare_to_tokyo_tower(height: int) -> str:
"""
Compare the height of Tokyo Tower (333m) and the input height,
Determine if they are higher, lower, or the same height.
argument:
height (int): Height to compare (unit: meters)
Return:
str: Is the input height "高い", "低い", or "同じ"
Usage example:
>>> compare_to_tokyo_tower(400)
'高い'
>>> compare_to_tokyo_tower(333)
'同じ'
>>> compare_to_tokyo_tower(100)
'低い'
"""
| TOKYO_TOWER_HEIGHT = 333 # 東京タワーの高さ(単位: メートル)
if height > TOKYO_TOWER_HEIGHT:
return "高い"
elif height < TOKYO_TOWER_HEIGHT:
return "低い"
else:
return "同じ"
| def check(candidate):
assert candidate(400) == "高い"
assert candidate(333) == "同じ"
assert candidate(100) == "低い"
assert candidate(500) == "高い"
assert candidate(0) == "低い"
| compare_to_tokyo_tower |
en/21 | def is_valid_mynumber_format(mynumber: str) -> bool:
"""
Determine whether the My Number format is correct.
My Number is a 12-digit number that is unique to each person.
argument:
mynumber (str): My number (string format)
Return value:
bool: True if the format is correct, False otherwise
example:
>>> is_valid_mynumber_format("123456789012")
True
>>> is_valid_mynumber_format("12345678ABCD")
False
>>> is_valid_mynumber_format("12345678901")
False
"""
| return mynumber.isdigit() and len(mynumber) == 12 | def check(candidate):
assert candidate("123456789012") == True
assert candidate("135790246810") == True
assert candidate("12345678901") == False
assert candidate("1234567890123") == False
assert candidate("ABCDEFGGIJKL") == False
| is_valid_mynumber_format |
en/22 | def can_vote(birthday: str, today: str) -> bool:
"""
A program to determine voting age (18 years or older).
argument:
birthday (str): Date of birth ("YYYY年MM月DD日").
today (str): Current date ("YYYY年MM月DD日").
Return value:
bool: True if you have the right to vote, False otherwise.
Execution example:
>>> can_vote("2000年01月01日", "2008年01月01日")
False
>>> can_vote("2000年01月01日", "2020年01月01日")
True
"""
| # 生年月日と現在の日付を分割し、整数に変換
birth_year, birth_month, birth_day = map(int, birthday.replace("年", "-").replace("月", "-").replace("日", "").split("-"))
today_year, today_month, today_day = map(int, today.replace("年", "-").replace("月", "-").replace("日", "").split("-"))
# 年齢を計算
age = today_year - birth_year
if (today_month, today_day) < (birth_month, birth_day):
age -= 1 # 誕生日が来ていない場合は年齢を1引く
# 18歳以上かどうかを判定
return age >= 18
| def check(candidate):
assert candidate("2000年01月01日", "2008年01月01日") == False
assert candidate("2000年01月01日", "2020年01月01日") == True
assert candidate("2002年12月31日", "2021年12月31日") == True
assert candidate("2005年07月01日", "2023年06月30日") == False
assert candidate("2005年07月01日", "2023年07月01日") == True
| can_vote |
en/23 | def get_rokuyou(days: int) -> str:
"""
Assuming that today's Rokuyo is "先勝", returns the Rokuyo from the specified number of days later.
argument:
days (int): Number of days since today
Return value:
str: Rokuyo (any of "先勝", "友引", "先負", "仏滅", "大安", "赤口")
"""
| rokuyou_names = ["先勝", "友引", "先負", "仏滅", "大安", "赤口"]
index = days % 6
return rokuyou_names[index]
| def check(candidate):
assert candidate(0) == "先勝"
assert candidate(1) == "友引"
assert candidate(2) == "先負"
assert candidate(3) == "仏滅"
assert candidate(4) == "大安"
assert candidate(5) == "赤口"
assert candidate(6) == "先勝"
assert candidate(7) == "友引"
assert candidate(30) == "先勝"
assert candidate(365) == "赤口"
| get_rokuyou |
en/24 | import re
def normalize_postal_code(postal_code: str) -> str:
"""
A function that unifies the notation of postal codes.
・Delete extra white space
・Convert full-width numbers and full-width symbols (such as "-") to half-width
- Place the hyphen in the postal code in the correct position (e.g. '1234567' → '123-4567')
argument:
postal_code (str): Postal code string
Return value:
str: Normalized postal code
example:
>>> normalize_postal_code("〒1234567")
'123-4567'
>>> normalize_postal_code("1234567")
'123-4567'
"""
| postal_code = re.sub(r'\s+|〒', '', postal_code)
full_width_to_half_width = str.maketrans(
'0123456789-',
'0123456789-'
)
postal_code = postal_code.translate(full_width_to_half_width)
postal_code = re.sub(r'(\d{3})(\d{4})', r'\1-\2', postal_code)
return postal_code
| def check(candidate):
assert candidate("123-4567") == '123-4567'
assert candidate("1234567") == '123-4567'
assert candidate(" 123 4567 ") == '123-4567'
assert candidate("〒1234567") == '123-4567'
assert candidate("123 4567") == '123-4567'
assert candidate("123-4567") == '123-4567'
assert candidate("123-4567") == '123-4567'
| normalize_postal_code |
en/25 | def identify_nanakusa(name: str) -> bool:
"""
Returns True if the given name `name` applies to the seven spring herbs, otherwise returns False.
The seven herbs of spring are "せり", "なずな", "ごぎょう", "はこべら", "ほとけのざ", "すずな" or "すずしろ".
argument:
- name (str): Hiragana name
Return value:
- bool: True/False
Example:
>>> identify_nanakusa("せり")
True
>>> identify_nanakusa("なずな")
True
>>> identify_nanakusa("さくら")
False
>>> identify_nanakusa("きく")
False
"""
| # 春の七草のリスト
nanakusa = {"せり", "なずな", "ごぎょう", "はこべら", "ほとけのざ", "すずな", "すずしろ"}
# 名前が七草に含まれるかどうかを判定
return name in nanakusa
| def check(candidate):
assert candidate("せり") == True
assert candidate("なずな") == True
assert candidate("ごぎょう") == True
assert candidate("はこべら") == True
assert candidate("ほとけのざ") == True
assert candidate("すずな") == True
assert candidate("すずしろ") == True
assert candidate("さくら") == False
assert candidate("きく") == False
assert candidate("たんぽぽ") == False
assert candidate("ほうれんそう") == False
| identify_nanakusa |
en/26 | import math
def calculate_fan(radius: int, angle: int, threshold: float) -> bool:
"""
If the area of the fan is greater than or equal to `threshold`, it is determined that the pattern looks beautiful.
Calculates the area of the fan and returns True if it looks good, False if it doesn't.
The area of the fan is calculated using the following formula:
Area = 0.5 * radius^2 * (radian value of angle)
argument:
radius (int): Radius of the fan (unit: cm, positive integer).
angle (int): The angle of the fan (unit: degrees, 0-360).
threshold (float): The area threshold (unit: square cm) for the pattern to look good.
Return value:
bool: True if the area is greater than or equal to the threshold, otherwise False.
example:
>>> calculate_fan(10, 180, 100)
True
>>> calculate_fan(10, 90, 100)
False
"""
| # 角度をラジアンに変換
angle_rad = math.radians(angle)
# 扇子の面積を計算
area = 0.5 * (radius ** 2) * angle_rad
# 面積が閾値以上か判定
return area >= threshold
| def check(candidate):
assert candidate(10, 180, 100) == True
assert candidate(10, 90, 100) == False
assert candidate(15, 120, 150) == True
assert candidate(5, 360, 150) == False
assert candidate(20, 360, 500) == True
assert candidate(1, 1, 0.01) == False | calculate_fan |
en/27 | def calculate_mission_success(skill: int, difficulty: int) -> int:
"""
Calculate the ninja's mission success rate.
The mission success rate can be calculated from the difference between the ninja's technical ability and the difficulty of the mission.
argument:
skill (int): Ninja's technical ability (1-100)
difficulty (int): Difficulty of the mission (1-100)
Return value:
int: Mission success rate (0-100)
"""
| return max(0, skill - difficulty) | def check(candidate):
assert candidate(80, 50) == 30
assert candidate(40, 60) == 0
assert candidate(100, 100) == 0
assert candidate(70, 50) == 20
assert candidate(50, 50) == 0
assert candidate(90, 30) == 60
assert candidate(30, 70) == 0
assert candidate(1, 100) == 0
assert candidate(100, 1) == 99 | calculate_mission_success |
en/28 | def weight_needed_for_sumo(height: int, current_weight: int) -> tuple:
"""
Calculate the amount of weight gain needed to reach the average BMI of a sumo wrestler from your height and current weight.
If the sumo wrestler's average BMI is 33, returns the target weight and required weight gain.
argument:
height (int): Height (cm)
current_weight (int): Current weight (kg)
Return value:
tuple: target weight and required weight gain (both integers)
example:
>>> weight_needed_for_sumo(180, 100)
(106, 6)
>>> weight_needed_for_sumo(175, 80)
(101, 21)
"""
| target_bmi = 33
height_m = height / 100
target_weight = target_bmi * (height_m ** 2)
weight_increase = target_weight - current_weight
target_weight = int(round(target_weight))
weight_increase = int(round(weight_increase))
return (target_weight, weight_increase)
| def check(candidate):
assert candidate(180, 100) == (107, 7)
assert candidate(175, 80) == (101, 21)
assert candidate(160, 60) == (84, 24)
assert candidate(200, 120) == (132, 12)
assert candidate(165, 75) == (90, 15)
assert candidate(150, 50) == (74, 24)
assert candidate(190, 90) == (119, 29)
assert candidate(185, 85) == (113, 28)
assert candidate(155, 65) == (79, 14)
assert candidate(178, 70) == (105, 35)
| weight_needed_for_sumo |
en/29 | def month_to_emoji(month: int) -> str:
"""
A function that accepts the month and returns the corresponding emoji.
"""
number_to_emoji = {
1: '🎍', 2: '👹', 3: '🎎', 4: '🌸', 5: '🎏', 6: '☔',
7: '🎋', 8: '🍉', 9: '🎑', 10: '🏃', 11: '🍁', 12: '🎄'
}
emoji = number_to_emoji.get(month, '')
return emoji
def create_monthly_message(month: int) -> str:
"""
A function that accepts the month and creates a corresponding message.
month_to_emoji gets the emoji for the month and returns it on both sides of the message.
>>> create_monthly_message(1)
'🎍今月は1月です🎍'
>>> create_monthly_message(12)
'🎄今月は12月です🎄'
"""
| emoji = month_to_emoji(month)
return f'{emoji}今月は{month}月です{emoji}'
| def check(candidate):
assert candidate(1) == '🎍今月は1月です🎍'
assert candidate(2) == '👹今月は2月です👹'
assert candidate(3) == '🎎今月は3月です🎎'
assert candidate(4) == '🌸今月は4月です🌸'
assert candidate(5) == '🎏今月は5月です🎏'
assert candidate(6) == '☔今月は6月です☔'
assert candidate(7) == '🎋今月は7月です🎋'
assert candidate(8) == '🍉今月は8月です🍉'
assert candidate(9) == '🎑今月は9月です🎑'
assert candidate(10) == '🏃今月は10月です🏃'
assert candidate(11) == '🍁今月は11月です🍁'
assert candidate(12) == '🎄今月は12月です🎄'
| create_monthly_message |
en/30 | def calculate_postcard_fee(fee: int, x: int) -> int:
"""
This is a function that calculates the price of postcards.
argument:
fee (int): Fee for one postcard (yen)
x (int): Number of postcards
Return value:
int: Total postcard fee (yen)
example:
>>> calculate_postcard_fee(63, 1)
63
>>> calculate_postcard_fee(63, 5)
315
"""
| return fee * x
| def check(candidate):
assert candidate(63, 1) == 63
assert candidate(63, 5) == 315
assert candidate(63, 10) == 630
assert candidate(70, 10) == 700
assert candidate(84, 2) == 168
assert candidate(84, 3) == 252
| calculate_postcard_fee |
en/31 | from typing import List
def sort_koinobori(sizes: List[int]) -> List[int]:
"""
Sort the carp streamer size list from largest to largest.
- sizes (List[int]): List of sizes (cm) of each carp streamer.
- Returns: A list of carp streamers sorted by size.
example:
>>> sort_koinobori([30, 50, 70, 20])
[70, 50, 30, 20]
>>> sort_koinobori([100, 200, 150])
[200, 150, 100]
"""
| return sorted(sizes, reverse=True)
| def check(candidate):
assert candidate([30, 50, 70, 20]) == [70, 50, 30, 20]
assert candidate([100, 200, 150]) == [200, 150, 100]
assert candidate([10, 10, 10]) == [10, 10, 10]
assert candidate([5, 3, 8, 1]) == [8, 5, 3, 1]
assert candidate([500, 100, 300, 200]) == [500, 300, 200, 100]
assert candidate([1]) == [1]
assert candidate([999, 1000, 888, 1000]) == [1000, 1000, 999, 888] | sort_koinobori |
en/32 | from typing import List
def determine_winner(red_scores: List[int], white_scores: List[int]) -> str:
"""
The winner of the 紅白歌合戦 will be determined.
Each group is given a score, and the team with the highest total score is the winning team.
Returns either "紅組", "白組", or "引き分け".
Example:
>>> determine_winner([10, 20, 30], [15, 25, 20])
'引き分け'
>>> determine_winner([50, 40, 60], [30, 20, 10])
'紅組'
>>> determine_winner([10, 20, 30], [40, 50, 60])
'白組'
"""
| red_total = sum(red_scores)
white_total = sum(white_scores)
if red_total > white_total:
return "紅組"
elif white_total > red_total:
return "白組"
else:
return "引き分け"
| def check(candidate):
assert candidate([10, 20, 30], [15, 25, 20]) == '引き分け'
assert candidate([50, 40, 60], [30, 20, 10]) == '紅組'
assert candidate([10, 20, 30], [40, 50, 60]) == '白組'
assert candidate([100, 200, 300], [100, 150, 200]) == '紅組'
assert candidate([0, 0, 0], [0, 0, 0]) == '引き分け'
assert candidate([999], [1000]) == '白組'
| determine_winner |
en/33 | from typing import List
def calculate_yamanote_distance(start: str, end: str, stations: List[str]) -> int:
"""
Given a list of stations on the Yamanote Line, a departure station, and an arrival station, calculate the number of stations from the departure station to the arrival station.
Since the Yamanote Line is a circular line, we consider two routes, one clockwise and one counterclockwise, and return the one with fewer stations.
- start (str): Name of departure station
- end (str): name of arrival station
- stations (List[str]): List of station names on the Yamanote Line (in order along the loop line)
- Return value: Shortest number of stations
"""
| start_index = stations.index(start)
end_index = stations.index(end)
clockwise_distance = (end_index - start_index) % len(stations)
counterclockwise_distance = (start_index - end_index) % len(stations)
return min(clockwise_distance, counterclockwise_distance)
| def check(candidate):
stations = ["東京", "有楽町", "新橋", "浜松町", "田町", "品川", "大崎", "五反田", "目黒", "恵比寿", "渋谷",
"原宿", "代々木", "新宿", "新大久保", "高田馬場", "目白", "池袋", "大塚", "巣鴨", "駒込", "田端",
"西日暮里", "日暮里", "鶯谷", "上野", "御徒町", "秋葉原", "神田"]
assert candidate("東京", "品川", stations) == 5
assert candidate("東京", "渋谷", stations) == 10
assert candidate("渋谷", "東京", stations) == 10
assert candidate("恵比寿", "目黒", stations) == 1
assert candidate("大塚", "上野", stations) == 7
assert candidate("秋葉原", "東京", stations) == 2
| calculate_yamanote_distance |
en/34 | def daruma_block(blocks: list, count: int) -> list:
"""
Daruma blocks are arranged in the order of blocks.
Drops the bottom block count times and returns the list of currently remaining Daruma blocks.
argument:
blocks (list): list of Daruma blocks
count (int): Number of drops
Return value:
list: Daruma's block list after dropping it
Example:
>>> daruma_block(['赤', '青', '緑', '黄'], 2)
['赤', '青']
>>> daruma_block(['赤', '青'], 1)
['赤']
"""
| return blocks[:-count] if count < len(blocks) else []
| def check(candidate):
assert candidate(['赤', '青', '緑', '黄'], 1) == ['赤', '青', '緑']
assert candidate(['赤', '青', '緑', '黄'], 2) == ['赤', '青']
assert candidate(['赤', '青', '緑', '黄'], 3) == ['赤']
assert candidate(['赤', '青', '緑', '黄'], 4) == []
assert candidate(['赤', '青'], 1) == ['赤']
| daruma_block |
en/35 | def ryugu_time_passed(days: int) -> int:
"""
Returns the number of days elapsed on earth based on the number of days spent in Ryugu Castle.
If you spend one day in Ryugu Castle, 365 days have passed on earth.
argument:
days (int): Number of days spent in Ryugujo
Return value:
int: Number of days on earth
Usage example:
>>> ryugu_time_passed(1)
365
>>> ryugu_time_passed(10)
3650
"""
| return int(days) * 365
| def check(candidate):
assert candidate(1) == 365
assert candidate(0) == 0
assert candidate(10) == 3650
assert candidate(100) == 36500
assert candidate(365) == 133225
assert candidate(2) == 730
assert candidate(50) == 18250
assert candidate(123) == 44895
| ryugu_time_passed |
en/36 | def check_kendo_gear(gear: list) -> str:
"""
A function that determines whether all Kendo armor is available.
argument:
gear (list): List of equipped armor
Return value:
str: '準備完了' or '準備不足'
Usage example:
>>> check_kendo_gear(['面', '小手', '胴', '垂'])
'準備完了'
>>> check_kendo_gear(['面', '小手', '垂'])
'準備不足'
"""
| required_gear = {'面', '小手', '胴', '垂'}
if required_gear.issubset(set(gear)):
return '準備完了'
else:
return '準備不足'
| def check(candidate):
assert candidate(['面', '小手', '胴', '垂']) == '準備完了'
assert candidate(['面', '小手', '垂']) == '準備不足'
assert candidate(['面', '小手']) == '準備不足'
assert candidate(['面', '面', '面', '面']) == '準備不足'
assert candidate(['面', '小手', '胴']) == '準備不足'
assert candidate([]) == '準備不足'
assert candidate(['小手', '胴', '垂', '面']) == '準備完了'
assert candidate(['面', '小手', '胴', '垂', 'サポーター']) == '準備完了'
assert candidate(['面', '垂', '小手', '胴', '足袋']) == '準備完了'
| check_kendo_gear |
en/37 | def get_ehou_direction(year: int) -> str:
"""
A function that receives the year in the Western calendar and returns the lucky direction (東北東, 南南東, 西南西, or 北北西) of that year.
argument:
year (int): year of the Western calendar
Return value:
str: Direction of lucky direction for the year
Usage example:
>>> get_ehou_direction(2024)
'東北東'
>>> get_ehou_direction(2025)
'北北西'
>>> get_ehou_direction(2026)
'西南西'
>>> get_ehou_direction(2027)
'南南東'
"""
| directions = ['東北東', '北北西', '西南西', '南南東']
return directions[year % 4]
| def check(candidate):
assert candidate(2020) == '東北東'
assert candidate(2021) == '北北西'
assert candidate(2022) == '西南西'
assert candidate(2023) == '南南東'
assert candidate(2024) == '東北東'
assert candidate(2025) == '北北西'
assert candidate(2026) == '西南西'
assert candidate(2027) == '南南東'
assert candidate(2028) == '東北東'
| get_ehou_direction |
en/38 | from collections import Counter
def rank_sushi_ingredients(orders: list) -> list:
"""
A function that returns popular sushi items from a sushi order list in order of ranking.
argument:
orders (list): List of ordered sushi items
Return value:
list: List of sushi toppings arranged in order of popularity
Usage example:
>>> rank_sushi_ingredients(["まぐろ", "サーモン", "まぐろ", "いくら", "サーモン", "まぐろ"])
['まぐろ', 'サーモン', 'いくら']
>>> rank_sushi_ingredients(["えび", "えび", "たまご", "いか", "いか", "いか"])
['いか', 'えび', 'たまご']
>>> rank_sushi_ingredients(["まぐろ", "まぐろ", "まぐろ"])
['まぐろ']
"""
| count = Counter(orders)
sorted_items = sorted(count.items(), key=lambda x: (-x[1], x[0]))
return [item[0] for item in sorted_items]
| def check(candidate):
# 基本的なテストケース
assert candidate(["まぐろ", "サーモン", "まぐろ", "いくら", "サーモン", "まぐろ"]) == ['まぐろ', 'サーモン', 'いくら']
assert candidate(["えび", "えび", "たまご", "いか", "いか", "いか"]) == ['いか', 'えび', 'たまご']
assert candidate(["まぐろ", "まぐろ", "まぐろ"]) == ['まぐろ']
assert candidate(["うに", "いくら", "いくら", "たこ", "たこ", "たこ", "サーモン", "サーモン", "サーモン"]) == ['たこ', 'サーモン', 'いくら', 'うに']
# 境界値テスト
assert candidate([]) == []
assert candidate(["まぐろ"]) == ["まぐろ"]
assert candidate(["まぐろ", "まぐろ", "まぐろ", "まぐろ", "まぐろ"]) == ["まぐろ"]
| rank_sushi_ingredients |
en/39 | def calculate_remaining_bill(total_bill: int, boss_bills: list, other_members_count: int) -> int:
"""
A function that distributes the amount of your bill.
argument:
total_bill (int): Total amount
boss_bills (list): List of amounts paid by the boss
other_members_count (int): Number of people other than the boss
Return value:
int: amount paid by each member
Usage example:
>>> calculate_remaining_bill(10000, [3000, 2000], 3)
1666
>>> calculate_remaining_bill(15000, [5000], 4)
2500
>>> calculate_remaining_bill(20000, [8000, 8000], 1)
4000
"""
| total_boss_payment = sum(boss_bills)
remaining_amount = total_bill - total_boss_payment
if remaining_amount <= 0:
return 0
remaining_per_member = remaining_amount // other_members_count
return remaining_per_member
| def check(candidate):
assert candidate(10000, [3000, 2000], 3) == 1666
assert candidate(15000, [5000], 4) == 2500
assert candidate(20000, [8000, 8000], 1) == 4000
assert candidate(10000, [10000], 3) == 0
assert candidate(10000, [11000], 3) == 0
assert candidate(1000000, [400000, 300000], 10) == 30000
assert candidate(1000000, [999999], 1) == 1
| calculate_remaining_bill |
en/40 | def recommend_least_crowded_train(train_crowdings: dict) -> str:
"""
A function that recommends the least crowded train based on the congestion level of each train.
argument:
train_crowdings (dict): Dictionary of {train name: crowding rate (0-100%)}
Return value:
str: name of the least crowded train
Usage example:
>>> recommend_least_crowded_train({"A train": 80, "B train": 60, "C train": 90})
'B train'
>>> recommend_least_crowded_train({"Yamanote Line": 95, "Keihin Tohoku Line": 85, "Chuo Line": 99})
'Keihin Tohoku Line'
"""
| return min(train_crowdings, key=lambda train: train_crowdings[train])
| def check(candidate):
assert candidate({"A列車": 80, "B列車": 60, "C列車": 90}) == 'B列車'
assert candidate({"山手線": 95, "京浜東北線": 85, "中央線": 99}) == '京浜東北線'
assert candidate({"A列車": 50, "B列車": 50, "C列車": 50}) == 'A列車'
assert candidate({"列車1": 0, "列車2": 100}) == '列車1'
assert candidate({"列車1": 0}) == '列車1'
assert candidate({"新幹線": 10, "特急": 20, "快速": 15}) == '新幹線'
assert candidate({"夜行列車": 100, "通勤快速": 99, "普通列車": 98}) == '普通列車'
assert candidate({"A": 100, "B": 100, "C": 100}) == 'A'
assert candidate({"急行": 70, "普通": 40, "特急": 90}) == '普通'
| recommend_least_crowded_train |
en/41 | def get_izumo_traditional_month_name(n: int) -> str:
"""
Returns the traditional month name of the Izumo region that corresponds to the current month.
In the Izumo region, October is called "神有月".
argument:
n (int): current month (1-12)
Return value:
str: Ancient month name in Izumo region
example:
>>> get_izumo_traditional_month_name(1)
'睦月'
>>> get_izumo_traditional_month_name(6)
'水無月'
>>> get_izumo_traditional_month_name(10)
'神有月'
"""
| month_names = [
"睦月", "如月", "弥生", "卯月", "皐月", "水無月",
"文月", "葉月", "長月", "神有月", "霜月", "師走"
]
return month_names[n - 1]
| def check(candidate):
assert candidate(1) == "睦月"
assert candidate(2) == "如月"
assert candidate(3) == "弥生"
assert candidate(4) == "卯月"
assert candidate(5) == "皐月"
assert candidate(6) == "水無月"
assert candidate(7) == "文月"
assert candidate(8) == "葉月"
assert candidate(9) == "長月"
assert candidate(10) == "神有月"
assert candidate(11) == "霜月"
assert candidate(10) == "神有月"
assert candidate(12) == "師走"
| get_izumo_traditional_month_name |
en/42 | def append_administrative_unit(prefecture: str) -> str:
"""
Returns the given prefecture name with the correct administrative unit ("都", "道", "府", "県").
argument:
prefecture (str): prefecture name without administrative unit
Return value:
str: Prefecture name with administrative unit
example:
>>> append_administrative_unit("東京")
'東京都'
>>> append_administrative_unit("北海道")
'北海道'
>>> append_administrative_unit("京都")
'京都府'
>>> append_administrative_unit("愛知")
'愛知県'
"""
| prefectures_with_special_units = {
"東京": "東京都",
"大阪": "大阪府",
"京都": "京都府",
"北海道": "北海道"
}
if prefecture in prefectures_with_special_units:
return prefectures_with_special_units[prefecture]
else:
return prefecture + "県"
| def check(candidate):
assert candidate("東京") == "東京都"
assert candidate("北海道") == "北海道"
assert candidate("大阪") == "大阪府"
assert candidate("京都") == "京都府"
assert candidate("埼玉") == "埼玉県"
assert candidate("神奈川") == "神奈川県"
assert candidate("愛知") == "愛知県"
assert candidate("新潟") == "新潟県"
assert candidate("兵庫") == "兵庫県"
assert candidate("福岡") == "福岡県"
assert candidate("沖縄") == "沖縄県"
| append_administrative_unit |
en/43 | import math
def days_to_complete(m: int, n: int) -> int:
"""
Calculate how many days it will take Takashi and Kiyoshi to finish their work together.
Round the result up to the nearest integer.
argument:
m (int): How many days would it take for Takashi to do it alone?
n (int): How many days would it take if Kiyoshi did it alone?
Return value:
int: Number of days it takes for two people to finish the job (rounded up to the nearest integer)
Usage example:
>>> days_to_complete(6, 3)
2
>>> days_to_complete(5, 5)
3
>>> days_to_complete(7, 4)
3
"""
| combined_rate = 1/m + 1/n
total_days = 1 / combined_rate
return math.ceil(total_days)
| def check(candidate):
assert candidate(6, 3) == 2
assert candidate(5, 5) == 3
assert candidate(7, 4) == 3
assert candidate(10, 2) == 2
assert candidate(8, 8) == 4
assert candidate(12, 6) == 4
assert candidate(9, 3) == 3
assert candidate(15, 5) == 4
| days_to_complete |
en/44 | import math
def days_to_meet(x: int, y: int) -> int:
"""
There is an older brother and a younger brother who fly back and forth across the 120 ri between Edo and Kyoto.
The older brother goes x miles a day, and the younger brother goes y miles a day.
Now, the older brother is heading towards Kyoto and the younger brother is heading towards Edo and Kyoto respectively.
We left at the same time. Calculate on what day the brothers will meet.
argument:
x (int): Distance traveled by my brother in a day (village)
y (int): Distance traveled by the younger brother in a day (village)
Return value:
int: number of days the siblings meet
Execution example:
>>> days_to_meet(14, 11)
5
>>> days_to_meet(10, 12)
6
"""
| total_distance = 120
combined_speed = x + y
return math.ceil(total_distance / combined_speed)
| def check(candidate):
assert candidate(14, 11) == 5
assert candidate(10, 12) == 6
assert candidate(20, 20) == 3
assert candidate(15, 15) == 4
assert candidate(25, 30) == 3
assert candidate(1, 1) == 60
assert candidate(10, 110) == 1
| days_to_meet |
en/45 | def find_number_of_thieves(m: int, r: int, c: int) -> int:
"""
If the thief takes m pieces each, there will be r pieces left over, and if he takes m-1 pieces each, there will be c pieces left over.
Calculate the number of thieves.
argument:
m (int): Number of silk items taken per person
r (int): Remaining reciprocal
c (int): missing counternumber
Return value:
int: number of thieves
Usage example:
>>> find_number_of_thieves(5, 3, 2)
-5
>>> find_number_of_thieves(4, 1, 3)
-4
>>> find_number_of_thieves(6, 0, 1)
-1
"""
| n = -(r + c)
return n
| def check(candidate):
assert candidate(5, 3, 2) == -5
assert candidate(4, 1, 3) == -4
assert candidate(6, 0, 1) == -1
assert candidate(10, 5, 7) == -12
assert candidate(3, 2, 2) == -4
| find_number_of_thieves |
en/46 | def total_bales_of_rice(n: int) -> int:
"""
Rice bales are stacked sideways in a cedar shape. Find the total number of rice bales.
argument:
n (int): Number of rice bags in the bottom row
Return value:
int: How many bales are there in total?
Execution example:
>>> total_bales_of_rice(3)
6
>>> total_bales_of_rice(5)
15
>>> total_bales_of_rice(1)
1
"""
| return n * (n + 1) // 2
| def check(candidate):
assert candidate(3) == 6
assert candidate(5) == 15
assert candidate(1) == 1
assert candidate(10) == 55
assert candidate(0) == 0
assert candidate(20) == 210
| total_bales_of_rice |
en/47 | def total_cries(n: int) -> int:
"""
If there are n crows, each crow crows n times, and they are in n pools, calculate how many crows they crow in total.
argument:
n (int): An integer representing the number of crows, number of uras, and number of crows per crow
Return value:
int: Total number of cries
Execution example:
>>> total_cries(1)
1
>>> total_cries(2)
8
>>> total_cries(3)
27
>>> total_cries(4)
64
"""
| return n ** 3
| def check(candidate):
assert candidate(1000) == 1000 ** 3
assert candidate(500) == 500 ** 3
assert candidate(1234) == 1234 ** 3
assert candidate(0) == 0 ** 3
assert candidate(1) == 1 ** 3
assert candidate(2500) == 2500 ** 3
assert candidate(999) == 999 ** 3
| total_cries |
en/48 | def min_coins(x: int) -> int:
"""
Calculate the minimum number of coins required to pay x yen.
The coins that can be used are 500 yen, 100 yen, 50 yen, 10 yen, 5 yen, and 1 yen.
argument:
x (int): amount to pay
Return value:
int: minimum number of coins
Execution example:
>>> min_coins(1)
1
>>> min_coins(567)
6
"""
| coins = [500, 100, 50, 10, 5, 1]
count = 0
for coin in coins:
count += x // coin
x %= coin
return count
| def check(candidate):
assert candidate(1) == 1
assert candidate(5) == 1
assert candidate(11) == 2
assert candidate(250) == 3
assert candidate(567) == 6
assert candidate(1000) == 2
assert candidate(1234) == 11
| min_coins |
en/49 | def count_ways(n: int) -> int:
"""
When you go up the n-step stairs at Yamadera, you go up one or two steps,
Calculate the number of ways to climb if you do not climb two steps in succession.
argument:
n (int): Number of stairs (positive integer)
Return value:
int: number of ways up the stairs
Execution example:
>>> count_ways(1)
1
>>> count_ways(2)
2
>>> count_ways(3)
3
"""
| if n == 1:
return 1
if n == 2:
return 2
dp = [0] * (n + 1)
dp[1] = 1
dp[2] = 2
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
| def check(candidate):
assert candidate(1) == 1
assert candidate(2) == 2
assert candidate(3) == 3
assert candidate(4) == 5
assert candidate(5) == 8
assert candidate(6) == 13
assert candidate(7) == 21
assert candidate(8) == 34
assert candidate(9) == 55
assert candidate(10) == 89
assert candidate(15) == 987
| count_ways |
en/50 | def is_japan_prefecture(prefecture):
"""
A function that determines whether a given prefecture name is a Japanese prefecture.
This function is based on a list of Japan's 47 prefectures (1 capital, 1 prefecture, 2 prefectures, 43 prefectures).
Checks whether the entered prefecture name is included in that list and returns the result.
Parameters:
prefecture (str): Prefecture name to be determined
Returns:
bool: True if the prefecture name is included in Japan, otherwise False
example:
>>> is_japan_prefecture('東京都')
True
>>> is_japan_prefecture('ニューヨーク')
False
"""
| japan_prefectures = [
'北海道', '青森県', '岩手県', '宮城県', '秋田県', '山形県', '福島県',
'茨城県', '栃木県', '群馬県', '埼玉県', '千葉県', '東京都', '神奈川県',
'新潟県', '富山県', '石川県', '福井県', '山梨県', '長野県',
'岐阜県', '静岡県', '愛知県', '三重県',
'滋賀県', '京都府', '大阪府', '兵庫県', '奈良県', '和歌山県',
'鳥取県', '島根県', '岡山県', '広島県', '山口県',
'徳島県', '香川県', '愛媛県', '高知県',
'福岡県', '佐賀県', '長崎県', '熊本県', '大分県', '宮崎県', '鹿児島県', '沖縄県'
]
return prefecture in japan_prefectures
| def check(candidate):
true_prefectures = [
'東京都', '大阪府', '北海道', '福岡県', '沖縄県', '青森県',
'岩手県', '宮城県', '秋田県', '山形県', '福島県', '茨城県',
'栃木県', '群馬県', '埼玉県', '千葉県', '神奈川県',
'新潟県', '富山県', '石川県', '福井県', '山梨県',
'長野県', '岐阜県', '静岡県', '愛知県', '三重県',
'滋賀県', '京都府', '兵庫県', '奈良県', '和歌山県',
'鳥取県', '島根県', '岡山県', '広島県', '山口県',
'徳島県', '香川県', '愛媛県', '高知県', '佐賀県',
'長崎県', '熊本県', '大分県', '宮崎県', '鹿児島県'
]
for prefecture in true_prefectures:
assert candidate(prefecture) == True
false_prefectures = ['ニューヨーク州', 'カリフォルニア州', '上海市', 'パリ', 'ロンドン', 'シンガポール', 'バンコク', 'シドニー']
for location in false_prefectures:
assert candidate(location) == False
| is_japan_prefecture |
en/51 | import math
def calculate_coin_change(N: int, bill: int) -> int:
"""
Calculates the amount of change that is generated when paying for an item worth N yen using the specified banknote.
argument:
N (int): Product price.
bill (int): The amount of banknotes to be used (e.g. 1000 yen, 5000 yen, 10000 yen, etc.).
Return value:
int: Amount of change (less than 1000 yen).
Usage example:
>>> calculate_coin_change(1200, 1000)
800
>>> calculate_coin_change(2500, 1000)
500
"""
| num_of_bills = math.ceil(N / bill)
total_paid = num_of_bills * bill
change = total_paid - N
coin_change = change % 1000
return coin_change
| def check(candidate):
assert candidate(1200, 1000) == 800
assert candidate(2500, 1000) == 500
assert candidate(3000, 1000) == 0
assert candidate(4500, 2000) == 500
assert candidate(9999, 5000) == 1
assert candidate(1000, 1000) == 0
assert candidate(1, 10000) == 999
assert candidate(1500, 2000) == 500
| calculate_coin_change |
en/52 | import math
def lcm(a, b):
"""Function to find the least common multiple of two integers"""
return a * b // math.gcd(a, b)
def find_next_fireworks_time(N: int, periods: list) -> int:
"""
A function that calculates the next time all fireworks will go off at the same time.
Parameters:
N (int): Number of fireworks
periods (list): List of firing periods for each fireworks
Return value:
int: Time when all fireworks will be launched at the same time
"""
| result = periods[0]
for i in range(1, N):
result = lcm(result, periods[i])
return result
| def check(candidate):
assert candidate(3, [3, 5, 7]) == 105
assert candidate(2, [4, 6]) == 12
assert candidate(4, [2, 3, 4, 5]) == 60
assert candidate(5, [1, 1, 1, 1, 1]) == 1
assert candidate(3, [10, 20, 30]) == 60
assert candidate(2, [6, 8]) == 24
assert candidate(3, [11, 13, 17]) == 2431
assert candidate(1, [9]) == 9
assert candidate(3, [15, 25, 35]) == 525
| find_next_fireworks_time |
en/53 | import math
def can_measure_water(X: int, Y: int, Z: int) -> bool:
"""
A function that determines whether bucket A has a capacity of X liters, bucket B has a capacity of Y liters, and can measure Z liters of water.
argument:
X (int): Capacity of bucket A
Y (int): Capacity of bucket B
Z (int): amount of water you want to measure
Return value:
bool: True if Z liters can be measured, False if not.
Usage example:
>>> can_measure_water(3, 5, 4)
True
>>> can_measure_water(2, 6, 5)
False
>>> can_measure_water(1, 2, 3)
True
"""
| # ZがXとYを合わせた容量を超える場合は測定不能
if Z > X + Y:
return False
# ZリットルがXリットルとYリットルの最大公約数で割り切れるか確認
return Z % math.gcd(X, Y) == 0
| def check(candidate):
assert candidate(3, 5, 4) == True
assert candidate(2, 6, 5) == False
assert candidate(1, 2, 3) == True
assert candidate(8, 12, 20) == True
assert candidate(8, 12, 25) == False
assert candidate(7, 5, 3) == True
assert candidate(7, 5, 0) == True
assert candidate(7, 5, 12) == True
assert candidate(7, 5, 13) == False
| can_measure_water |
en/54 | def check_olympic_year(year: int) -> bool:
"""
A function that checks whether the year is the year in which the Olympics were held in Japan.
argument:
year (int): year to check
Return value:
bool: True if the year the Olympics were held in Japan, False otherwise.
Usage example:
>>> check_olympic_year(1964)
True
>>> check_olympic_year(2000)
False
>>> check_olympic_year(2021)
True
"""
| olympic_years = {1964, 1972, 1998, 2021}
return year in olympic_years
| def check(candidate):
assert candidate(1964) == True
assert candidate(1972) == True
assert candidate(1998) == True
assert candidate(2021) == True
assert candidate(2000) == False
assert candidate(2016) == False
assert candidate(2024) == False
| check_olympic_year |
en/55 | def is_seven_gods(god_name: str) -> bool:
"""
Returns True if it is the name of the Seven Lucky Gods.
>>> is_seven_gods("恵比寿")
True
>>> is_seven_gods("大黒天")
True
>>> is_seven_gods("阿弥陀如来")
False
"""
| seven_gods = ["恵比寿", "大黒天", "毘沙門天", "弁財天", "福禄寿", "寿老人", "布袋"]
return god_name in seven_gods
| def check(candidate):
assert candidate("恵比寿") == True
assert candidate("大黒天") == True
assert candidate("毘沙門天") == True
assert candidate("弁財天") == True
assert candidate("福禄寿") == True
assert candidate("寿老人") == True
assert candidate("布袋") == True
assert candidate("阿弥陀如来") == False
assert candidate("釈迦") == False
assert candidate("観音") == False
assert candidate("不動明王") == False
| is_seven_gods |
en/56 | def next_pigeon_clock_time(current_hour: int, interval: int) -> int:
"""
Calculate the next time the cuckoo clock will ring.
argument:
current_hour (int): current time (0 <= current_hour < 24)
interval (int): Ringing interval (0 <= interval < 24)
Return value:
int: next time to ring (0 <= int < 24)
Execution example:
>>> next_pigeon_clock_time(14, 3)
17
>>> next_pigeon_clock_time(23, 1)
0
>>> next_pigeon_clock_time(22, 5)
3
>>> next_pigeon_clock_time(0, 24)
0
>>> next_pigeon_clock_time(12, 12)
0
"""
| next_hour = (current_hour + interval) % 24
return next_hour
| def check(candidate):
assert candidate(14, 3) == 17
assert candidate(23, 1) == 0
assert candidate(22, 5) == 3
assert candidate(0, 24) == 0
assert candidate(12, 12) == 0
assert candidate(6, 18) == 0
assert candidate(15, 10) == 1
assert candidate(23, 25) == 0
assert candidate(0, 1) == 1
| next_pigeon_clock_time |
en/57 | def can_hanako_see_fireworks(A: int, B: int, C: int, D: int) -> bool:
"""
Determine whether Hanako can watch the fireworks display.
- A (int): Start date of the fireworks display (number of days from today, afternoon).
- B (int): End date of the fireworks display (number of days from today, afternoon).
- C (int): Hanako's arrival date (number of days from today, morning).
- D (int): The day Hanako leaves (number of days from today, morning).
>>> can_hanako_see_fireworks(2, 4, 1, 3)
True
>>> can_hanako_see_fireworks(2, 4, 0, 2)
False
>>> can_hanako_see_fireworks(1, 5, 3, 6)
True
"""
| return C <= B and D > A | def check(candidate):
assert candidate(2, 4, 1, 3) == True
assert candidate(1, 5, 3, 6) == True
assert candidate(2, 4, 0, 5) == True
assert candidate(2, 4, 0, 2) == False
assert candidate(3, 5, 0, 3) == False
assert candidate(1, 2, 3, 4) == False
assert candidate(2, 3, 4, 5) == False
| can_hanako_see_fireworks |
en/58 | import datetime
def get_tokyo_seijinshiki_date(year: int) -> str:
"""
Finds the coming-of-age ceremony date in Tokyo for the specified year.
argument:
year (int): year
Return value:
str: Date of coming-of-age ceremony (YYYY-MM-DD format)
Usage example:
>>> get_tokyo_seijinshiki_date(2024)
'2024-01-08'
"""
| # 指定された年の1月1日を取得
first_january = datetime.date(year, 1, 1)
# 第1月曜日を計算
first_monday = first_january + datetime.timedelta(days=(7 - first_january.weekday()) % 7)
# 第2月曜日を計算
seijin_shiki_date = first_monday + datetime.timedelta(days=7)
return seijin_shiki_date.strftime('%Y-%m-%d')
| def check(candidate):
assert candidate(2024) == "2024-01-08"
assert candidate(2023) == "2023-01-09"
assert candidate(2025) == "2025-01-13"
assert candidate(2022) == "2022-01-10"
assert candidate(2020) == "2020-01-13"
| get_tokyo_seijinshiki_date |
en/59 | def find_number_of_apples(n: int, price: int) -> int:
"""
Find the number of apples purchased if a total of n apples and oranges are purchased and the total price is price yen.
Apples cost 250 yen each, and oranges cost 120 yen each.
argument:
n (int): Total number of apples and oranges purchased
price (int): total price
Return value:
int: Number of apples purchased.
example:
>>> find_number_of_apples(2, 370)
1
>>> find_number_of_apples(1, 250)
1
"""
| for x in range(n + 1):
if 250 * x + 120 * (n - x) == price:
return x
return -1
| def check(candidate):
assert candidate(1, 250) == 1
assert candidate(1, 120) == 0
assert candidate(2, 370) == 1
assert candidate(5, 860) == 2
assert candidate(9, 1470) == 3
assert candidate(20, 3700) == 10
| find_number_of_apples |
en/60 | def mouse_population(n: int) -> int:
"""
In January, the parent mouse gave birth to 12 children, and the total number of children was 14.
From February onwards, every rat gives birth to 12 pups, so the number of rats each month is 13 times that of the previous month.
argument:
n (int): Month number (nth month)
Return value:
int: total number of rats in month n
Execution example:
>>> mouse_population(1)
14
>>> mouse_population(2)
98
>>> mouse_population(3)
686
>>> mouse_population(4)
4802
"""
| return 2*7**n
| def check(candidate):
assert candidate(1) == 14
assert candidate(2) == 98
assert candidate(3) == 686
assert candidate(4) == 4802
assert candidate(5) == 33614
assert candidate(6) == 235298
assert candidate(12) == 27682574402
| mouse_population |
en/61 | import datetime
def get_weekday(date: str) -> str:
"""
A function that returns the day of the week that corresponds to a given date.
argument:
date (str): date (yyyy-mm-dd format)
Return value:
str: Day of the week
Usage example:
>>> get_weekday("2024-01-01")
'月曜日'
>>> get_weekday("2024-02-14")
'水曜日'
"""
| dt = datetime.datetime.strptime(date, "%Y-%m-%d")
weekdays = ["月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日", "日曜日"]
return weekdays[dt.weekday()]
| def check(candidate):
assert candidate("2024-01-01") == "月曜日"
assert candidate("2024-01-02") == "火曜日"
assert candidate("2024-01-03") == "水曜日"
assert candidate("2024-01-04") == "木曜日"
assert candidate("2024-01-05") == "金曜日"
assert candidate("2024-01-06") == "土曜日"
assert candidate("2024-01-07") == "日曜日"
assert candidate("2024-02-14") == "水曜日"
assert candidate("2024-12-31") == "火曜日"
| get_weekday |
en/62 | def find_b_paper_size(width: int, height: int) -> str:
"""
Determines the size of paper with the given dimensions using JIS standard B version and returns it.
argument:
width (int): Paper width (mm)
height (int): Height of paper (mm)
Return value:
str: B version paper size (e.g. "B2")
"""
| b_width, b_height = 1030, 1456
for i in range(11):
if (width == b_width and height == b_height) or (width == b_height and height == b_width):
return f"B{i}"
b_width, b_height = b_height // 2, b_width
| def check(candidate):
assert candidate(1030, 1456) == "B0"
assert candidate(728, 1030) == "B1"
assert candidate(515, 728) == "B2"
assert candidate(364, 515) == "B3"
assert candidate(257, 364) == "B4"
assert candidate(182, 257) == "B5"
assert candidate(128, 182) == "B6"
assert candidate(91, 128) == "B7"
assert candidate(64, 91) == "B8"
assert candidate(45, 64) == "B9"
assert candidate(32, 45) == "B10"
assert candidate(1456, 1030) == "B0"
assert candidate(1030, 728) == "B1"
assert candidate(728, 515) == "B2" | find_b_paper_size |
en/63 | def sanmoku_winner(board: list) -> str:
"""
Determine the winner or loser of tic-tac-toe.
Tic-tac-toe is won when three Go pieces of the same color line up vertically, horizontally, or diagonally.
It is assumed that a given board always has a winner or loser.
argument:
board (list): A 5×5 board represented by a double list.
Each element is either "黒", "白", or an empty string ("").
Return value:
str: "黒" or "白" to represent the winner.
"""
| directions = [(0, 1), (1, 0), (1, 1), (1, -1)] # 横, 縦, 右下がり, 左下がり
n = len(board)
for row in range(n):
for col in range(n):
if board[row][col] in ("黒", "白"):
player = board[row][col]
for dr, dc in directions:
if all(
0 <= row + dr * i < n and
0 <= col + dc * i < n and
board[row + dr * i][col + dc * i] == player
for i in range(3)
):
return player
| def check(candidate):
# 横方向の勝利
board1 = [
["黒", "黒", "黒", "", ""],
["", "白", "", "", ""],
["", "", "", "白", ""],
["", "", "", "", ""],
["", "", "", "", ""]
]
assert candidate(board1) == "黒"
# 縦方向の勝利
board2 = [
["", "", "", "", ""],
["白", "黒", "", "", ""],
["白", "黒", "", "", ""],
["白", "黒", "", "", ""],
["", "", "", "", ""]
]
assert candidate(board2) == "白"
# 左下がり斜めの勝利
board3 = [
["", "", "", "", "白"],
["", "", "", "白", ""],
["", "", "白", "", ""],
["", "黒", "", "", ""],
["黒", "", "", "", ""]
]
assert candidate(board3) == "白"
# 終了時の盤面が複雑なケース(横方向)
board4 = [
["黒", "黒", "黒", "白", "白"],
["白", "白", "黒", "黒", "白"],
["白", "黒", "白", "黒", "黒"],
["黒", "白", "黒", "白", "白"],
["白", "黒", "白", "白", "黒"]
]
assert candidate(board4) == "黒"
# 終了時の盤面が複雑なケース(縦方向)
board6 = [
["白", "黒", "白", "黒", "白"],
["白", "黒", "白", "黒", "白"],
["白", "黒", "白", "黒", "白"],
["黒", "白", "黒", "白", "黒"],
["白", "黒", "白", "黒", "白"]
]
assert candidate(board6) == "白"
| sanmoku_winner |
en/64 | def goldfish_scooping_score(fish_weights: list, poi_strength: int) -> int:
"""
Calculate the goldfish scooping score.
Returns 0 if the sum of the weights exceeds the strength of the poi.
argument:
fish_weights (list of int): List of weights for each goldfish (e.g. [3, 2, 5])
poi_strength (int): Poi strength (e.g. 10)
Return value:
int: total score
Usage example:
>>> goldfish_scooping_score([3, 2, 5], 10)
10
>>> goldfish_scooping_score([3, 4, 6], 10)
0
>>> goldfish_scooping_score([2, 2, 2], 7)
6
"""
| total_weight = sum(fish_weights)
if total_weight > poi_strength:
return 0
return total_weight
| def check(candidate):
assert candidate([3, 2, 5], 10) == 10
assert candidate([2, 2, 2], 7) == 6
assert candidate([3, 4, 6], 10) == 0
assert candidate([4, 3, 3], 10) == 10
assert candidate([1, 1, 1], 3) == 3
assert candidate([], 10) == 0
| goldfish_scooping_score |
en/65 | def hanako_otoshidama(before_price: int, growth_percentage: int, saving_price: int, item_price: int):
"""
The New Year has arrived. Hanako receives her New Year's gift.
New Year's gift is the amount increased by `growth_percentage`% from the previous year's `before_price`.
Hanako should determine whether she can reach the amount of money she wants for the game `item_price` by combining her savings `saving_price` with this year's New Year's gift.
argument:
before_price (int): Amount of New Year's gift from the previous year
growth_percentage (int): Growth percentage value
saving_price (int): Saving amount
item_price (int): Price of the game you want
Return value:
str: If it can be achieved, it returns "購入可能", otherwise it returns "差額は{差額}円".
"""
| current_otoshidama = before_price * (100 + growth_percentage) // 100
total_money = current_otoshidama + saving_price
if total_money >= item_price:
return "購入可能"
else:
return f"差額は{item_price - total_money}円"
|
def check(candidate):
assert candidate(10000, 10, 5000, 16000) == "購入可能"
assert candidate(10000, 5, 3000, 15000) == "差額は1500円"
assert candidate(5000, 20, 2000, 10000) == "差額は2000円"
| hanako_otoshidama |
en/66 | import math
def calculate_folds(x: float) -> int:
"""
Calculate the number of folds of origami from the length of one side of a small square.
argument:
x (float): The length of one side of a small square.
Return value:
int: Number of times the origami was folded n.
"""
| n = math.log2(1 / x)
return int(n)
| def check(candidate):
assert candidate(0.5) == 1
assert candidate(0.25) == 2
assert candidate(0.125) == 3
assert candidate(0.0625) == 4
assert candidate(1) == 0
assert candidate(0.03125) == 5
assert candidate(0.015625) == 6
| calculate_folds |
en/67 | def calculate_and_check_caffeine(logs):
"""
A record of the drinks and caffeine consumed today will be provided.
Check whether your daily caffeine intake exceeds 400mg.
argument:
logs: A list of dictionaries that record the daily caffeine intake of drinks.
Each dictionary contains 'drink' (drink name) and 'caffeine_mg' (caffeine amount).
Return value:
'High' if your caffeine intake exceeds 400mg
'Low' if your caffeine intake is less than 400mg
"""
| recommended_limit = 400
total_caffeine = 0
for log in logs:
total_caffeine += log['caffeine_mg']
if total_caffeine > recommended_limit:
return "High"
else:
return "Low"
| def check(candidate):
logs1 = [
{'drink': 'コーヒー', 'caffeine_mg': 95},
{'drink': '紅茶', 'caffeine_mg': 40},
{'drink': 'ジュース', 'caffeine_mg': 10}
]
result1 = candidate(logs1)
assert result1 == "Low", f"Test 1 failed: {result1}"
logs2 = [
{'drink': 'コーヒー', 'caffeine_mg': 100},
{'drink': '紅茶', 'caffeine_mg': 100},
{'drink': 'エナジードリンク', 'caffeine_mg': 100}
]
result2 = candidate(logs2)
assert result2 == "Low", f"Test 2 failed: {result2}"
logs3 = [
{'drink': 'コーヒー', 'caffeine_mg': 200},
{'drink': '紅茶', 'caffeine_mg': 150},
{'drink': 'エナジードリンク', 'caffeine_mg': 100}
]
result3 = candidate(logs3)
assert result3 == "High", f"Test 3 failed: {result3}"
| calculate_and_check_caffeine |
en/68 | from typing import List
def find_best_seat_with_location(seats: List[int], current: int) -> int:
"""
Given a seating list and current location, Haruko searches for a seat without anyone sitting next to her.
argument:
seats (List[int]): Seat list (0: empty seats, 1: seated seats).
current (int): Haruko's current location (seat index).
Return value:
int: Index of the seat to which Haruko should move (starting at 0).
Returns current location if there is no need to move.
"""
| n = len(seats)
best_seat = current # 初期値は現在地
min_distance = float('inf') # 最小移動距離の初期化
for i in range(n):
if seats[i] == 0: # 空席を探す
# 隣が空いているか確認
left_empty = (i == 0 or seats[i - 1] == 0)
right_empty = (i == n - 1 or seats[i + 1] == 0)
if left_empty and right_empty:
distance = abs(current - i) # 現在地からの距離
if distance < min_distance: # より近い席を探す
min_distance = distance
best_seat = i
return best_seat | def check(candidate):
assert candidate([1, 0, 0, 1, 0, 0, 1], 2) == 2
assert candidate([1, 0, 1, 1, 0, 1, 0], 5) == 5
assert candidate([1, 1, 1, 1], 0) == 0
assert candidate([0, 0, 1, 0, 0], 2) == 0
assert candidate([1, 0, 0, 0, 1], 3) == 2
assert candidate([0, 0, 0, 0, 0], 2) == 2
assert candidate([1, 1, 0, 0, 1], 2) == 2
| find_best_seat_with_location |
en/69 | import math
def calculate_number_of_trees(r: float) -> int:
"""
If you want to plant trees around the perimeter of a circular lake with a radius of r meters, calculate the number of trees that can be planted every 3 meters.
argument:
r (float): radius of the lake (meters)
Return value:
int: Number of trees to be planted
Execution example:
>>> calculate_number_of_trees(10)
20
>>> calculate_number_of_trees(5)
10
"""
| circumference = 2 * math.pi * r
return int(circumference // 3)
| def check(candidate):
assert candidate(10) == 20
assert candidate(5) == 10
assert candidate(15) == 31
assert candidate(3) == 6
assert candidate(1) == 2
| calculate_number_of_trees |
en/70 | def min_cooking_time(ingredients):
"""
A function that calculates the minimum time to fry tempura using two pots.
argument:
ingredients (list): list of ingredients for frying time
Return value:
int: minimum frying time
Usage example:
>>> min_cooking_time([2, 3, 2, 1, 4])
7
"""
| # 食材の揚げ時間をソート(短い順)
ingredients.sort()
# 2つの鍋を使った最小時間を計算
time1 = 0 # 鍋1の時間
time2 = 0 # 鍋2の時間
for i in range(len(ingredients)):
if time1 <= time2:
time1 += ingredients[i] # 鍋1に食材を追加
else:
time2 += ingredients[i] # 鍋2に食材を追加
return max(time1, time2) # どちらか長い方の時間が全体の時間
| def check(candidate):
assert candidate([2, 3, 2, 1, 4]) == 7
assert candidate([3, 3, 3, 3]) == 6
assert candidate([5]) == 5
assert candidate([1, 2, 3, 4, 5, 6]) == 12
| min_cooking_time |
en/71 | def get_essay_by_author(author: str) -> str:
"""
A function that returns the three major essays related to a given author.
argument:
author (str): name of the author
Return value:
str: Titles of three major essays related to the author
"""
| essays = {
"清少納言": "枕草子",
"鴨長明": "方丈記",
"吉田兼好": "徒然草"
}
return essays.get(author)
| def check(candidate):
assert candidate("清少納言") == "枕草子"
assert candidate("鴨長明") == "方丈記"
assert candidate("吉田兼好") == "徒然草"
| get_essay_by_author |
en/72 | def calculate_restitution_coefficient(initial_velocity: float, final_velocity: float) -> float:
"""
Calculate the bounce coefficient of the Ohajiki.
argument:
initial_velocity (float): Velocity before collision.
final_velocity (float): Velocity after collision.
Return value:
float: bounce coefficient e (value in the range 0 to 1)
Usage example:
>>> calculate_restitution_coefficient(5.0, 3.0)
0.6
>>> calculate_restitution_coefficient(5.0, 0.0)
0.0
"""
| if initial_velocity == 0:
return 0.0
return final_velocity / initial_velocity
| def check(candidate):
assert candidate(5.0, 3.0) == 0.6
assert candidate(5.0, 0.0) == 0.0
assert candidate(10.0, 5.0) == 0.5
assert candidate(7.0, 7.0) == 1.0
| calculate_restitution_coefficient |
en/73 | def get_rainbow_color(wavelength: int) -> str:
"""
Determine the rainbow color that corresponds to the given wavelength.
argument:
wavelength (int): Wavelength of light in nanometers.
Return value:
str: Rainbow color corresponding to wavelength (string)
Usage example:
>>> get_rainbow_color(650)
'赤'
>>> get_rainbow_color(510)
'緑'
>>> get_rainbow_color(400)
'紫'
>>> get_rainbow_color(800)
None
"""
| if 620 <= wavelength <= 750:
return "赤"
elif 590 <= wavelength < 620:
return "橙"
elif 570 <= wavelength < 590:
return "黄"
elif 495 <= wavelength < 570:
return "緑"
elif 450 <= wavelength < 495:
return "青"
elif 430 <= wavelength < 450:
return "藍"
elif 380 <= wavelength < 430:
return "紫"
else:
return None
| def check(candidate):
assert candidate(650) == "赤"
assert candidate(610) == "橙"
assert candidate(575) == "黄"
assert candidate(510) == "緑"
assert candidate(480) == "青"
assert candidate(445) == "藍"
assert candidate(400) == "紫"
assert candidate(800) == None
| get_rainbow_color |
en/74 | from typing import List, Tuple
import math
def calculate_arrow_distance(speed: float, angle: float) -> float:
"""
Calculate the flight distance from the speed and angle at which the arrow was shot.
argument:
speed (float): initial speed of the arrow (m/s)
angle (float): Angle at which the arrow is shot (in degrees)
Return value:
float: Arrow flight distance (m) (2 decimal places)
Execution example:
>>> calculate_arrow_distance(50, 45)
255.10
>>>calculate_arrow_distance(30, 30)
79.85
"""
| g = 9.8 # 定数: 重力加速度(m/s^2)
angle_rad = math.radians(angle)
distance = (speed ** 2 * math.sin(2 * angle_rad)) / g
return round(distance, 2)
| def check(candidate):
assert candidate(50, 45) == 255.10
assert candidate(30, 30) == 79.53
assert candidate(40, 60) == 141.39
assert candidate(20, 15) == 20.41
assert candidate(100, 45) == 1020.41
| calculate_arrow_distance |
en/75 | def calculate_congestion_rate(max_capacity: int, current_passengers: int) -> float:
"""
Calculate the congestion rate of the train.
argument:
max_capacity (int): Train capacity (maximum capacity)
current_passengers (int): Number of passengers currently on board
Return value:
float: Crowding rate (%)
example:
>>> calculate_congestion_rate(100, 120)
120.0
>>> calculate_congestion_rate(100, 50)
50.0
"""
| return (current_passengers / max_capacity) * 100
| def check(candidate):
assert candidate(100, 120) == 120.0
assert candidate(100, 50) == 50.0
assert candidate(150, 150) == 100.0
assert candidate(200, 180) == 90.0
assert candidate(300, 450) == 150.0
| calculate_congestion_rate |
en/76 | def count_votes(votes: list) -> dict:
"""
Tally the voting results and calculate the number of votes for each candidate.
argument:
votes (list): List of voting results (list of candidate names)
Return value:
dict: a dictionary containing the number of votes each candidate received and the name of the winner
Usage example:
>>> votes = ["A", "B", "A", "C", "B", "A", "C", "B", "C", "C"]
>>> count_votes(votes)
{'A': 3, 'B': 3, 'C': 4, '勝者': 'C'}
"""
| # 投票結果を集計する辞書を作成
vote_count = {}
# 投票を集計
for vote in votes:
if vote in vote_count:
vote_count[vote] += 1
else:
vote_count[vote] = 1
# 勝者を決定(得票数が同じ場合は最初の候補者を勝者とする)
winner = max(vote_count, key=vote_count.get)
# 結果に勝者を追加
vote_count['勝者'] = winner
return vote_count
| def check(candidate):
assert candidate(["A", "B", "A", "C", "B", "A", "C", "B", "C", "C"]) == {'A': 3, 'B': 3, 'C': 4, '勝者': 'C'}
assert candidate(["A", "A", "A", "B", "B", "C"]) == {'A': 3, 'B': 2, 'C': 1, '勝者': 'A'}
assert candidate(["A", "B", "B", "C", "C", "C", "C"]) == {'A': 1, 'B': 2, 'C': 4, '勝者': 'C'}
assert candidate(["X", "Y", "Y", "X", "Z", "Z", "Z"]) == {'X': 2, 'Y': 2, 'Z': 3, '勝者': 'Z'}
| count_votes |
en/77 | def day_or_night(hour: int, solstice: str) -> str:
"""
Determines whether the specified time is daytime or nighttime. Consider sunrise and sunset depending on the season.
- hour (int): Time (integer from 0 to 23).
- solstice (str): One of "summer solstice", "winter solstice", "spring equinox", "autumn equinox".
- Return value: "day" or "night".
Sunrise/Sunset (hypothetical):
夏至: sunrise at 4 o'clock, sunset at 20 o'clock
冬至: Sunrise 7:00, Sunset 17:00
春分/秋分: Sunrise 6:00, Sunset 18:00
>>> day_or_night(5, "夏至")
'昼'
>>> day_or_night(21, "夏至")
'夜'
>>> day_or_night(6, "冬至")
'夜'
>>> day_or_night(12, "春分")
'昼'
>>> day_or_night(19, "秋分")
'夜'
"""
| if solstice not in ("夏至", "冬至", "春分", "秋分"):
raise ValueError("solsticeは'夏至', '冬至', '春分', '秋分'のいずれかを指定してください。")
# 季節ごとの日の出・日の入り時刻
if solstice == "夏至":
sunrise, sunset = 4, 20
elif solstice == "冬至":
sunrise, sunset = 7, 17
elif solstice in ("春分", "秋分"):
sunrise, sunset = 6, 18
# 昼間か夜間を判定
return "昼" if sunrise <= hour < sunset else "夜"
| def check(candidate):
assert candidate(4, "夏至") == "昼"
assert candidate(3, "夏至") == "夜"
assert candidate(12, "夏至") == "昼"
assert candidate(20, "夏至") == "夜"
assert candidate(21, "夏至") == "夜"
assert candidate(7, "冬至") == "昼"
assert candidate(6, "冬至") == "夜"
assert candidate(12, "冬至") == "昼"
assert candidate(17, "冬至") == "夜"
assert candidate(18, "冬至") == "夜"
assert candidate(6, "春分") == "昼"
assert candidate(5, "春分") == "夜"
assert candidate(12, "春分") == "昼"
assert candidate(18, "春分") == "夜"
assert candidate(19, "春分") == "夜"
assert candidate(6, "秋分") == "昼"
assert candidate(5, "秋分") == "夜"
assert candidate(12, "秋分") == "昼"
assert candidate(18, "秋分") == "夜"
assert candidate(19, "秋分") == "夜"
| day_or_night |
en/78 | def get_japanese_holiday(month: int) -> list:
"""
If you enter a month, it will return a list of Japanese holidays in that month.
argument:
month (int): month (1-12)
Return value:
list: list of applicable holidays
Usage example:
>>> get_japanese_holiday(1)
['New Year's Day', 'Coming-of-Age Day']
>>> get_japanese_holiday(11)
['Culture Day', 'Labor Thanksgiving Day']
"""
| holiday_dict = {
1: ['元日', '成人の日'], # 成人の日は1月の第2月曜日
2: ['建国記念の日'], # 2月11日
3: ['春分の日'], # 春分の日は年によって変動するが、3月20日頃
4: ['昭和の日'], # 4月29日
5: ['憲法記念日', 'みどりの日', 'こどもの日'], # 5月3日, 5月4日, 5月5日
6: [], # 6月は祝日なし
7: ['海の日'], # 海の日は7月の第3月曜日
8: ['山の日'], # 山の日は8月11日
9: ['敬老の日', '秋分の日'], # 敬老の日は9月の第3月曜日、秋分の日は9月23日頃
10: ['スポーツの日'], # 10月の第2月曜日
11: ['文化の日', '勤労感謝の日'], # 11月3日, 11月23日
12: [], # 12月は祝日なし
}
return holiday_dict.get(month, [])
| def check(candidate):
assert candidate(1) == ['元日', '成人の日'] # 1月
assert candidate(2) == ['建国記念の日'] # 2月
assert candidate(3) == ['春分の日'] # 3月
assert candidate(4) == ['昭和の日'] # 4月
assert candidate(5) == ['憲法記念日', 'みどりの日', 'こどもの日'] # 5月
assert candidate(7) == ['海の日'] # 7月
assert candidate(8) == ['山の日'] # 8月
assert candidate(9) == ['敬老の日', '秋分の日'] # 9月
assert candidate(10) == ['スポーツの日'] # 10月
assert candidate(11) == ['文化の日', '勤労感謝の日'] # 11月
assert candidate(6) == [] # 6月
assert candidate(12) == [] # 12月
| get_japanese_holiday |
en/79 | def check_yakudoshi(age: int, gender: str) -> str:
"""
Based on age and gender, it determines whether the age is in bad year, mae-yaku, or after-yaku.
argument:
age (int): Age to judge
gender (str): gender ('male' or 'female')
Return value:
str: One of the ”厄年”, ”前厄”, ”後厄”, or "厄年ではない"
Usage example:
>>> check_yakudoshi(25, '女性')
'前厄'
>>> check_yakudoshi(33, '女性')
'厄年'
>>> check_yakudoshi(37, '男性')
'後厄'
>>> check_yakudoshi(40, '男性')
'厄年ではない'
"""
|
male_yakudoshi = {
'前厄': [24, 40, 60],
'厄年': [25, 41, 61],
'後厄': [26, 42, 62]
}
female_yakudoshi = {
'前厄': [18, 32, 36],
'厄年': [19, 33, 37],
'後厄': [20, 34, 38]
}
if gender == '男性':
yakudoshi_dict = male_yakudoshi
elif gender == '女性':
yakudoshi_dict = female_yakudoshi
for yakutype, ages in yakudoshi_dict.items():
if age in ages:
return yakutype
return '厄年ではない'
| def check(candidate):
# 1. 男性のテスト
assert candidate(24, '男性') == '前厄' # 前厄
assert candidate(25, '男性') == '厄年' # 厄年
assert candidate(26, '男性') == '後厄' # 後厄
assert candidate(40, '男性') == '前厄' # 前厄
assert candidate(41, '男性') == '厄年' # 厄年
assert candidate(42, '男性') == '後厄' # 後厄
assert candidate(30, '男性') == '厄年ではない' # どの厄年にも該当しない
# 2. 女性のテスト
assert candidate(18, '女性') == '前厄' # 前厄
assert candidate(19, '女性') == '厄年' # 厄年
assert candidate(20, '女性') == '後厄' # 後厄
assert candidate(32, '女性') == '前厄' # 前厄
assert candidate(33, '女性') == '厄年' # 厄年
assert candidate(34, '女性') == '後厄' # 後厄
assert candidate(25, '女性') == '厄年ではない' # どの厄年にも該当しない
| check_yakudoshi |
en/80 | def binary_search_count(numbers, x):
"""
Hanako and Taro are enjoying a number guessing game.
Hanako creates a sequence of numbers arranged in ascending order and determines the secret number.
Taro guesses the secret number while performing a binary search.
Please calculate how many times Taro can guess the secret number.
argument:
numbers (list): a sequence of numbers arranged in ascending order
x (int): secret number
Return value:
count (int): Number of times it takes Taro to guess the secret number
example:
>>> binary_search_count([1, 3, 5, 7, 9], 5)
1
>>> binary_search_count([1, 3, 5, 7, 9], 7)
2
>>> binary_search_count([1, 3, 5, 7, 9], 2)
3
"""
| left, right = 0, len(numbers) - 1
count = 0
while left <= right:
count += 1
mid = (left + right) // 2
if numbers[mid] == x:
return count
elif numbers[mid] < x:
left = mid + 1
else:
right = mid - 1
return count
| def check(candidate):
assert candidate([1, 3, 5, 7, 9], 5) == 1
assert candidate([1, 3, 5, 7, 9], 7) == 2
assert candidate([1, 3, 5, 7, 9], 2) == 3
assert candidate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1) == 3
assert candidate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10) == 4
| binary_search_count |
en/81 | def calculate_rice_time(rice_type: str) -> int:
"""
A function that returns the soaking time (minutes) required to cook rice.
Minimum requirements:
- rice_type is one of "白米", "玄米", or "無洗米" .
- If any other rice_type is specified, -1 is returned.
rule:
- "白米" requires 30 minutes of soaking time.
- "玄米" requires soaking time of 360 minutes (6 hours).
- For "無洗米", soaking time is 0 minutes (not required).
argument:
rice_type (str): Type of rice
Return value:
int: Immersion time (minutes)
Usage example:
>>> calculate_rice_time("白米")
30
>>> calculate_rice_time("玄米")
360
>>> calculate_rice_time("無洗米")
0
>>> calculate_rice_time("もち米")
-1
"""
| if rice_type == "白米":
return 30
elif rice_type == "玄米":
return 360 # 6時間 = 360分
elif rice_type == "無洗米":
return 0
else:
return -1 # 不明なご飯の種類
| def check(candidate):
assert candidate("白米") == 30
assert candidate("玄米") == 360
assert candidate("無洗米") == 0
assert candidate("もち米") == -1
assert candidate("黒米") == -1
assert candidate("") == -1
assert candidate("WHITE") == -1
assert candidate("白") == -1
assert candidate("無洗") == -1
assert candidate("玄") == -1
| calculate_rice_time |
en/82 | def is_mobile_phone(number: str) -> bool:
"""
Determine whether the given phone number is a Japanese mobile phone number.
Japanese mobile phone numbers start like this:
-090
- 080
-070
argument:
number (str): 11-digit phone number (must start with 0)
Return value:
bool: Returns True if it is a mobile phone number, otherwise returns False.
Usage example:
>>> is_mobile_phone("09012345678")
True
>>> is_mobile_phone("08098765432")
True
>>> is_mobile_phone("07011112222")
True
>>> is_mobile_phone("0312345678")
False
>>> is_mobile_phone("0123456789")
False
"""
| if number.startswith("090") or number.startswith("080") or number.startswith("070"):
return True
return False
| def check(candidate):
# 使用例
assert candidate("09012345678") == True
assert candidate("08098765432") == True
assert candidate("07011112222") == True
assert candidate("0312345678") == False
assert candidate("0123456789") == False
# 日本の携帯電話番号形式
assert candidate("09012345678") == True
assert candidate("08098765432") == True
assert candidate("07055556666") == True
# 日本の携帯電話番号形式ではない
assert candidate("0312345678") == False
assert candidate("01201234567") == False
assert candidate("05012345678") == False
| is_mobile_phone |
en/83 | def hiragana_to_katakana(name: str) -> str:
"""
Converts the name entered in hiragana to katakana.
argument:
name (str): Full name entered in hiragana
Return value:
str: Full name converted to katakana
Usage example:
>>> hiragana_to_katakana('たなか たろう')
'タナカ タロウ'
>>> hiragana_to_katakana('さとう じろう')
'サトウ ジロウ'
>>> hiragana_to_katakana('やまだ はなこ')
'ヤマダ ハナコ'
"""
| hiragana = (
"ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞ"
"ただちぢつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽ"
"まみむめもゃやゅゆょよらりるれろゎわゐゑをんゔ"
)
katakana = (
"ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾ"
"タダチヂツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポ"
"マミムメモャヤュユョヨラリルレロヮワヰヱヲンヴ"
)
# ひらがなをカタカナに変換
return name.translate(str.maketrans(hiragana, katakana))
| def check(candidate):
# 基本的な使用例
assert candidate('たなか たろう') == 'タナカ タロウ'
assert candidate('さとう じろう') == 'サトウ ジロウ'
assert candidate('やまだ はなこ') == 'ヤマダ ハナコ'
# 様々なひらがな文字列
assert candidate('きむら みさき') == 'キムラ ミサキ'
assert candidate('こばやし まさひろ') == 'コバヤシ マサヒロ'
assert candidate('はしもと かいと') == 'ハシモト カイト'
assert candidate('まつもと さくら') == 'マツモト サクラ'
| hiragana_to_katakana |
en/84 | def contains_fullwidth_katakana(text: str) -> bool:
"""
Checks whether the given string contains full-width katakana characters.
Returns True if full-width katakana is included.
argument:
text (str): string to check
Return value:
bool: True if full-width katakana is included, False if not
Usage example:
>>> contains_fullwidth_katakana("カタカナ")
True
>>> contains_fullwidth_katakana("こんにちは")
False
>>> contains_fullwidth_katakana("Hello")
False
"""
| for char in text:
if '\u30A0' <= char <= '\u30FF':
return True
return False
| def check(candidate):
assert candidate("アイウエオ") == True
assert candidate("カキクケコ") == True
assert candidate("ハローワールド") == True
assert candidate("かたかな") == False
assert candidate("カタカナ") == True
assert candidate("片仮名") == False
assert candidate("KATAKANA") == False
assert candidate("katakana") == False
| contains_fullwidth_katakana |
en/85 | def number_to_kanji(number: int) -> str:
"""
This function converts the given number into Chinese numerals and returns it.
argument:
number (int): number (0 <= number <= 9999)
Return value:
str: Numeric value expressed in Chinese numerals
example:
>>> number_to_kanji(0)
'〇'
>>> number_to_kanji(21)
'二十一'
>>> number_to_kanji(105)
'百五'
>>> number_to_kanji(9999)
'九千九百九十九'
"""
| if number == 0:
return "〇"
kanji_digits = "〇一二三四五六七八九"
units = ["", "十", "百", "千"]
kanji = ""
digits = str(number)
length = len(digits)
for i, digit in enumerate(digits):
d = int(digit)
if d == 0:
continue
unit = units[length - i - 1]
if d == 1 and unit in ["十", "百", "千"] and i == 0:
kanji += unit
else:
kanji += kanji_digits[d] + unit
return kanji
| def check(candidate):
assert candidate(0) == "〇"
assert candidate(1) == "一"
assert candidate(10) == "十"
assert candidate(21) == "二十一"
assert candidate(105) == "百五"
assert candidate(1234) == "千二百三十四"
assert candidate(9999) == "九千九百九十九"
| number_to_kanji |
en/86 | def sum_of_kanji_numbers(S: str) -> int:
"""
A function that calculates the sum of the Chinese digits '1' to '9' in the string S.
argument:
S (str): A string containing the Chinese numerals '一二三四五六七八九'.
Return value:
int: Total number obtained by converting kanji numerals.
example
>>> sum_of_kanji_numbers(”一二三四五六七八九”)
45
"""
| kanji_to_number = {'一': 1, '二': 2, '三': 3, '四': 4, '五': 5,
'六': 6, '七': 7, '八': 8, '九': 9}
return sum(kanji_to_number[char] for char in S if char in kanji_to_number)
| def check(candidate):
assert candidate("一二三四五六七八九") == 45
assert candidate("三五七") == 15
assert candidate("一四七") == 12
assert candidate("二二二") == 6
assert candidate("九九") == 18
| sum_of_kanji_numbers |
en/87 | import re
def parse_date(date_str: str) -> tuple:
"""
Converts a date string in 'YYYY年MM月DD日' format to a tuple (year, month, day).
argument:
date_str (str): Date string in the format 'YYYYYYYYMMMMDDD'
Return value:
tuple: tuple of (year, month, day)
Usage example:
>>> parse_japanese_date('2024年11月20日')
(2024, 11, 20)
"""
| pattern = r'(\d{4})年(\d{2})月(\d{2})日'
match = re.match(pattern, date_str)
if match:
return tuple(map(int, match.groups()))
| def check(candidate):
assert candidate('2024年11月20日') == (2024, 11, 20)
assert candidate('2000年01月01日') == (2000, 1, 1)
assert candidate('1999年12月31日') == (1999, 12, 31)
| parse_date |
en/88 | from typing import List
def max_shiritori_chain(words: List[str]) -> int:
"""
Returns the chain number of how many times Shiritori lasts.
Rules:
- Match the last letter of the previous word with the first letter of the next word
- Ends if the same word appears or if the last letter of the word ends with "n"
argument:
words (List[str]): list of words
Return value:
int: longest shiritori chain number
Usage example:
>>> max_shiritori_chain(["ねこ", "こたつ", "つみき", "きつね", "ねずみ"])
5
>>> max_shiritori_chain(["りんご", "ごま", "まり", "いぬ", "ぬりえ", "えんぴつ"])
3
>>> max_shiritori_chain(["さくら", "らいおん", "んま", "まつり"])
1
"""
| if not words:
return 0
chain_count = 0
seen_words = set()
for i in range(len(words)):
word = words[i]
if word in seen_words or word[-1] == "ん":
break
seen_words.add(word)
if i > 0 and words[i - 1][-1] != word[0]:
break
chain_count += 1
return chain_count
| def check(candidate):
assert candidate(["ねこ", "こたつ", "つみき", "きつね", "ねずみ"]) == 5
assert candidate(["りんご", "ごま", "まり", "いぬ", "ぬりえ", "えんぴつ"]) == 3
assert candidate(["りんご", "ごま", "まり", "りんご"]) == 3
assert candidate(["さくら", "らっぱ", "ぱん", "んま", "まつり"]) == 2
assert candidate(["さくら", "らいおん", "んま", "まつり"]) == 1
assert candidate(["たぬき", "きつね", "ねずみ", "みみず", "ずるい"]) == 5 | max_shiritori_chain |
en/89 | def calculate(expression: str) -> int:
"""
Performs a calculation based on a kanji calculation formula and returns the result.
argument:
expression (str): Kanji calculation expression (e.g. "和 3 5")
Return value:
int: calculation result
Usage example:
>>> calculate("和 3 5")
8
>>> calculate("差 9 4")
5
>>> calculate("積 2 6")
12
>>> calculate("商 8 2")
4
"""
| # 文字列を分割して、演算の種類と数値を取得
parts = expression.split()
operator, a, b = parts[0], int(parts[1]), int(parts[2])
# 漢字に対応する計算を行う
if operator == "和":
return a + b
elif operator == "差":
return a - b
elif operator == "積":
return a * b
elif operator == "商":
return a // b # 0除算は入力側の責任で防ぐ前提
| def check(candidate):
assert candidate("和 3 5") == 8
assert candidate("差 9 4") == 5
assert candidate("積 2 6") == 12
assert candidate("商 8 2") == 4
assert candidate("商 7 3") == 2
assert candidate("差 0 5") == -5
assert candidate("和 0 0") == 0
assert candidate("積 5 0") == 0 | calculate |
en/90 | import re
from typing import List
def extract_numbers_from_text(text: str) -> List[int]:
"""
Extracts numbers from a given Japanese sentence and returns them as a list of integers.
argument:
text (str): Japanese text containing numbers.
Return value:
List[int]: List of extracted numbers.
Execution example:
>>> extract_numbers_from_text("今年の予算は500万円で、先月の売上は200万円でした。")
[500, 200]
>>> extract_numbers_from_text("お店には3つのリンゴがあり、4人のお客さんが来ました。")
[3, 4]
>>> extract_numbers_from_text("2023年は特別な年です。")
[2023]
>>> extract_numbers_from_text("文章に数値がありません。")
[]
"""
| numbers = re.findall(r'\d+', text)
return [int(num) for num in numbers]
| def check(candidate):
assert candidate("今年の予算は500万円で、先月の売上は200万円でした。") == [500, 200]
assert candidate("お店には3つのリンゴがあり、4人のお客さんが来ました。") == [3, 4]
assert candidate("今日は5月10日で、午後2時30分に始まります。") == [5, 10, 2, 30]
assert candidate("2023年は特別な年です。") == [2023]
assert candidate("10人の参加者と1000枚のチケットがあります。") == [10, 1000]
assert candidate("結果は3-2で勝利しました!") == [3, 2]
assert candidate("文章に数値がありません。") == []
| extract_numbers_from_text |
en/91 | def sort_in_japanese_order(words: list) -> list:
"""
Sorts the input word list in alphabetical order.
argument:
words (list): word list to be sorted
Return value:
list: list of words sorted alphabetically
Execution example:
>>> sort_in_japanese_order(["さくら", "あおい", "きく"])
['あおい', 'きく', 'さくら']
"""
| return sorted(words, key=lambda word: ''.join(chr(ord(c)) for c in word)) | def check(candidate):
assert candidate(["さくら", "あおい", "きく"]) == ["あおい", "きく", "さくら"]
assert candidate(["うみ", "えき", "あめ"]) == ["あめ", "うみ", "えき"]
assert candidate(["あさひ", "あかり", "あい"]) == ["あい", "あかり", "あさひ"]
assert candidate(["カタカナ", "ひらがな", "かんじ"]) == ["かんじ", "ひらがな", "カタカナ"]
assert candidate(["あい", "うた", "えのき"]) == ["あい", "うた", "えのき"]
assert candidate(["あかり"]) == ["あかり"]
| sort_in_japanese_order |
en/92 | def is_matching_iroha_song(text: str) -> bool:
"""
A function that determines whether the given string completely matches the Iroha song.
Ignore spaces and line breaks in the input string.
Full text of the Iroha song (check for matches, ignoring spaces and line breaks):
いろはにほへとちりぬるを
わかよたれそつねならむ
うゐのおくやまけふこえて
あさきゆめみしえひもせす
example:
>>> is_matching_iroha_song("いろはにほへと ちりぬるを わかよたれそ つねならむ うゐのおくやま けふこえて あさきゆめみし えひもせす")
True
>>> is_matching_iroha_song("いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしえひもせす")
True
"""
| iroha_song = "いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしえひもせす"
cleaned_text = ''.join(char for char in text if char not in ' \n')
return cleaned_text == iroha_song
| def check(candidate):
# いろは歌と完全に一致するケース
assert candidate("いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしえひもせす") == True
# 改行やスペースが含まれるが、いろは歌の順番が正しいケース
assert candidate("いろはにほへと ちりぬるを わかよたれそ つねならむ うゐのおくやま けふこえて あさきゆめみし えひもせす") == True
assert candidate("いろはにほへと\nちりぬるを\nわかよたれそ\nつねならむ\nうゐのおくやま\nけふこえて\nあさきゆめみし\nえひもせす") == True
assert candidate(" いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしえひもせす ") == True
# 1文字だけ異なるケース
assert candidate("いろはにほへとちりぬるをわかよたれそつねならむういのおくやまけふこえてあさきゆめみしえひもせす") == False
assert candidate("いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしえひもせ") == False
assert candidate("いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしえひもせすす") == False
# 途中で大きな変更があるケース
assert candidate("いろはにほへとちりぬるをわかよたれそあああむうゐのおくやまけふこえてあさきゆめみしえひもせす") == False
assert candidate("いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしえひもせす123") == False
# 完全に異なるケース
assert candidate("") == False
assert candidate("あいうえおかきくけこ") == False
assert candidate("いろはにほへとちりぬるを") == False
| is_matching_iroha_song |
en/93 | def validate_aiueo_poem(prefix: str, poem: list) -> bool:
"""
A function that determines whether each line of an essay begins with the specified prefix character string.
Args:
prefix (str): The first character string of the AIUEO composition (any character string).
poem (list): A list of Aiueo essays.
Returns:
bool: True if all lines are correct, False otherwise.
example:
>>> validate_aiueo_poem("あいうえお", ["あ: あさ", "い: いぬ", "う: うみ", "え: えび", "お: おかし"])
True
>>> validate_aiueo_poem("さしすせそ", ["さ: さくら", "し: しろ", "す: すいか", "せ: せみ", "そ: そら"])
True
>>> validate_aiueo_poem("あいうえお", ["あ: さくら", "い: いぬ", "う: うみ", "え: えび", "お: おかし"])
False
"""
| if len(prefix) != len(poem):
return False
for i, line in enumerate(poem):
if not line.startswith(f"{prefix[i]}: {prefix[i]}"):
return False
return True
| def check(candidate):
# 正しいあいうえお作文のチェック
assert candidate("あいうえお", ["あ: あさ", "い: いぬ", "う: うみ", "え: えび", "お: おかし"]) == True
assert candidate("さしすせそ", ["さ: さくら", "し: しろ", "す: すいか", "せ: せみ", "そ: そら"]) == True
assert candidate("たちつてと", ["た: たぬき", "ち: ちか", "つ: つき", "て: てがみ", "と: とけい"]) == True
# 誤ったあいうえお作文のチェック
assert candidate("あいうえお", ["あ: さくら", "い: いぬ", "う: うみ", "え: えび", "お: おかし"]) == False
assert candidate("かきくけこ", ["か: かわ", "き: きのこ", "く: くも", "け: けいこ", "こ: こねこ"]) == True
assert candidate("あいうえお", ["あ: あさ", "い: いぬ", "う: うみ", "え: えび", "お: おもち"]) == True
assert candidate("なにぬねの", ["な: なす", "に: にんじん", "ぬ: ぬの", "ね: ねこ", "の: ので"]) == True
# 境界ケースのチェック
assert candidate("あ", ["あ: あさ"]) == True
assert candidate("あ", ["あ: さくら"]) == False
assert candidate("あい", ["あ: あさ", "い: いぬ"]) == True
assert candidate("あい", ["あ: あさ", "い: いんこ"]) == True
assert candidate("あい", ["あ: いんこ", "い: いぬ"]) == False
# 異なる長さのチェック
assert candidate("あいうえお", ["あ: あさ", "い: いぬ", "う: うみ"]) == False
assert candidate("あいう", ["あ: あさ", "い: いぬ", "う: うみ", "え: えび", "お: おかし"]) == False | validate_aiueo_poem |
en/94 | def contains_major_river(text: str) -> bool:
"""
Determines whether text contains the name of one of Japan's three major rivers.
Japan's three major rivers are "信濃川", "利根川", and "石狩川".
argument:
text (str): Character string to be evaluated.
Return value:
bool: True if any of the three major rivers is included, False if not.
"""
| major_rivers = ["信濃川", "利根川", "石狩川"]
return any(river in text for river in major_rivers)
| def check(candidate):
assert candidate("昨日は信濃に行きました。") == False
assert candidate("利根の流域は広いですね。") == False
assert candidate("石狩地方は雪が多いです。") == False
assert candidate("信濃川は日本最長の川です。") == True
assert candidate("この地域では利根川が有名です。") == True
assert candidate("石狩川が流れる風景は美しい。") == True
assert candidate("日本には美しい川が多い。") == False
assert candidate("北海道には多くの川が流れています。") == False
| contains_major_river |
en/95 | def extract_repeated_words(words: list) -> list:
"""
A function that extracts only words in which the same string is repeated twice from a list of strings.
Args:
words (list): list of strings
Returns:
list: list containing only words that are repeated twice
example:
>>> extract_repeated_words(['いろいろ', 'たびたび', 'あかあお', 'abcabc', 'abcd', 'どきどき'])
['いろいろ', 'たびたび', 'abcabc', 'どきどき']
"""
| result = [word for word in words if len(word) % 2 == 0 and word[:len(word)//2] == word[len(word)//2:]]
return result
| def check(candidate):
assert candidate(['いろいろ', 'たびたび', 'あかあお', 'かきかき', 'どきどき', 'ひるひる', 'ねるねる']) == ['いろいろ', 'たびたび', 'かきかき', 'どきどき', 'ひるひる', 'ねるねる']
assert candidate(['あかあお', 'しろくろ', 'くろしろ', 'あおあお']) == ['あおあお']
assert candidate(['あいあい', 'いいうう', 'うえうえ', 'えおえお', 'かきかき']) == ['あいあい', 'うえうえ', 'えおえお', 'かきかき']
assert candidate(['あさあさ', 'ひるひる', 'よるよる', 'ばんばん']) == ['あさあさ', 'ひるひる', 'よるよる', 'ばんばん']
assert candidate(['ぴかぴか', 'ころころ', 'すべすべ', 'つやつや']) == ['ぴかぴか', 'ころころ', 'すべすべ', 'つやつや']
assert candidate(['ふわふわ', 'もこもこ', 'さらさら', 'つるつる', 'ごろごろ']) == ['ふわふわ', 'もこもこ', 'さらさら', 'つるつる', 'ごろごろ']
assert candidate(['くるくる', 'まるまる', 'ぐるぐる', 'てくてく']) == ['くるくる', 'まるまる', 'ぐるぐる', 'てくてく']
assert candidate(['はらはら', 'どきどき', 'わくわく', 'そわそわ', 'ひやひや']) == ['はらはら', 'どきどき', 'わくわく', 'そわそわ', 'ひやひや']
| extract_repeated_words |
en/96 | def get_hiragana(key: int, presses: int) -> str:
"""
Returns hiragana depending on the phone's key and number of presses.
argument:
key (int): Pressed key number (0-9).
presses (int): Number of key presses (1 or more).
Return value:
str: Corresponding Hiragana character.
"""
| key_map = {
1: ["あ", "い", "う", "え", "お"],
2: ["か", "き", "く", "け", "こ"],
3: ["さ", "し", "す", "せ", "そ"],
4: ["た", "ち", "つ", "て", "と"],
5: ["な", "に", "ぬ", "ね", "の"],
6: ["は", "ひ", "ふ", "へ", "ほ"],
7: ["ま", "み", "む", "め", "も"],
8: ["や", "ゆ", "よ"],
9: ["ら", "り", "る", "れ", "ろ"],
0: ["わ", "を", "ん"],
}
characters = key_map[key]
index = (presses - 1) % len(characters)
return characters[index]
| def check(candidate):
key_map = {
1: ["あ", "い", "う", "え", "お"],
2: ["か", "き", "く", "け", "こ"],
3: ["さ", "し", "す", "せ", "そ"],
4: ["た", "ち", "つ", "て", "と"],
5: ["な", "に", "ぬ", "ね", "の"],
6: ["は", "ひ", "ふ", "へ", "ほ"],
7: ["ま", "み", "む", "め", "も"],
8: ["や", "ゆ", "よ"],
9: ["ら", "り", "る", "れ", "ろ"],
0: ["わ", "を", "ん"],
}
for key, characters in key_map.items():
for presses in range(1, len(characters) * 2 + 1): # 各キーのリスト長の2倍までテスト
expected = characters[(presses - 1) % len(characters)]
result = get_hiragana(key, presses)
assert result == expected | get_hiragana |
en/97 | def romaji_to_hiragana(romaji: str) -> str:
"""
Convert Hepburn-style romaji to hiragana.
argument:
romaji (str): Romaji to be converted (50 sounds only)
Return value:
str: String converted to hiragana
Execution example:
>>> romaji_to_hiragana("konnichiha")
'こんにちは'
>>> romaji_to_hiragana("sushi")
'すし'
"""
| romaji_map = {
"a": "あ", "i": "い", "u": "う", "e": "え", "o": "お",
"ka": "か", "ki": "き", "ku": "く", "ke": "け", "ko": "こ",
"sa": "さ", "shi": "し", "su": "す", "se": "せ", "so": "そ",
"ta": "た", "chi": "ち", "tsu": "つ", "te": "て", "to": "と",
"na": "な", "ni": "に", "nu": "ぬ", "ne": "ね", "no": "の",
"ha": "は", "hi": "ひ", "fu": "ふ", "he": "へ", "ho": "ほ",
"ma": "ま", "mi": "み", "mu": "む", "me": "め", "mo": "も",
"ya": "や", "yu": "ゆ", "yo": "よ",
"ra": "ら", "ri": "り", "ru": "る", "re": "れ", "ro": "ろ",
"wa": "わ", "wo": "を", "n": "ん",
}
i = 0
result = []
while i < len(romaji):
for length in (3, 2, 1):
if romaji[i:i+length] in romaji_map:
result.append(romaji_map[romaji[i:i+length]])
i += length
break
else:
result.append(romaji[i])
i += 1
return ''.join(result)
| def check(candidate):
assert candidate("aiueo") == "あいうえお"
assert candidate("akasatana") == "あかさたな"
assert candidate("hamayarawa") == "はまやらわ"
assert candidate("konnichiha") == "こんにちは"
assert candidate("sushi") == "すし"
assert candidate("satsumaimo") == "さつまいも"
| romaji_to_hiragana |
en/98 | def classify_japanese_characters(text: str) -> dict:
"""
Classifies the input string into kanji, hiragana, katakana, and other characters and returns the number of each character.
argument:
text (str): string to process
Return value:
dict: Classification results for each character type (e.g. {'漢字': 3, 'ひらがな': 5, 'カタカナ': 2, 'その他': 4})
Execution example:
>>> classify_japanese_characters("今日は晴れです。")
{'漢字': 3, 'ひらがな': 4, 'カタカナ': 0, 'その他': 1}
"""
| result = {'漢字': 0, 'ひらがな': 0, 'カタカナ': 0, 'その他': 0}
for char in text:
if '\u4e00' <= char <= '\u9fff':
result['漢字'] += 1
elif '\u3040' <= char <= '\u309f':
result['ひらがな'] += 1
elif '\u30a0' <= char <= '\u30ff':
result['カタカナ'] += 1
else:
result['その他'] += 1
return result
| def check(candidate):
assert candidate("今日は晴れです。") == {'漢字': 3, 'ひらがな': 4, 'カタカナ': 0, 'その他': 1}
assert candidate("あいうえおアイウエオ") == {'漢字': 0, 'ひらがな': 5, 'カタカナ': 5, 'その他': 0}
assert candidate("体育の授業ではサッカーをやります。今日も元気一杯に頑張りましょう。") == {'漢字': 12, 'ひらがな': 15, 'カタカナ': 4, 'その他': 2}
assert candidate("ABC123!@#漢字ひらがなカタカナ") == {'漢字': 2, 'ひらがな': 4, 'カタカナ': 4, 'その他': 9}
| classify_japanese_characters |
en/99 | def can_create_henohenomoheji(text: str) -> bool:
"""
By rearranging the given string `text`, determine whether it is possible to create ``Henohenomoheji''.
Returns True if it can be created, False otherwise.
>>> can_create_heno_heno_moheji("へのへのもへじ")
True
>>> can_create_heno_heno_moheji("へへへののもじ")
True
>>> can_create_heno_heno_moheji("へのへのへのへ")
False
"""
| required_characters = {"へ": 3, "の": 2, "も": 1, "じ": 1}
for char, count in required_characters.items():
if text.count(char) < count:
return False
return True
| def check(candidate):
assert candidate("へのへのもへじ") == True
assert candidate("へへへののもじ") == True
assert candidate("へのへのへのへ") == False
assert candidate("へのへへもじの") == True
assert candidate("へへへもももじ") == False
assert candidate("はひふへほのほ") == False
| can_create_henohenomoheji |