task_id
stringlengths 4
6
| category
stringclasses 8
values | prompt
stringlengths 152
1.03k
| canonical_solution
stringlengths 18
1.32k
| test
stringlengths 135
1.21k
| entry_point
stringlengths 2
37
|
|---|---|---|---|---|---|
EN/0
|
文化
|
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/1
|
文化
|
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/2
|
文化
|
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/3
|
文化
|
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/4
|
文化
|
def check_season(seasons: list, target: str) -> str:
"""
Determines whether the given season is included in the given list.
argument:
seasons (list): list of seasons (e.g. ['Spring', 'Summer', 'Autumn', 'Winter'])
target (str): Season to judge (e.g. 'summer')
Return value:
str: Returns "含まれている" if the season is included, otherwise returns "含まれていない"
Usage example:
>>> check_season(['春', '夏', '秋', '冬'], '夏')
'含まれている'
>>> check_season(['春', '秋'], '夏')
'含まれていない'
>>> check_season([], '冬')
'含まれていない'
>>> check_season(['夏'], '夏')
'含まれている'
"""
|
if target in seasons:
return '含まれている'
return '含まれていない'
|
def check(candidate):
assert candidate(['春', '夏', '秋', '冬'], '夏') == '含まれている'
assert candidate(['春', '秋'], '秋') == '含まれている'
assert candidate(['夏'], '夏') == '含まれている'
assert candidate(['春', '秋'], '夏') == '含まれていない'
assert candidate(['冬'], '秋') == '含まれていない'
assert candidate(['あ', 'い', 'う', 'え', 'お'], '秋') == '含まれていない'
assert candidate(['夏'], '冬') == '含まれていない'
|
check_season
|
EN/5
|
文化
|
def count_particles(text: str) -> int:
"""
Create a function that counts the number of occurrences of particles (``ga'', ``no'', ``ha'', ``wo'', and ``ni'') in Japanese sentences.
argument:
text (str): Japanese text
Return value:
int: Number of particle occurrences
Usage example:
>>> count_particles("私は学校に行きます。")
2
"""
|
particles = ['が', 'の', 'は', 'を', 'に']
count = 0
for particle in particles:
count += text.count(particle)
return count
|
def check(candidate):
assert candidate("私は学校に行きます。") == 2
assert candidate("今日の天気は良いです。") == 2
assert candidate("AIは世界を変える。") == 2
assert candidate("がががののははをを") == 9
assert candidate("これは助詞が含まれていません。") == 2
|
count_particles
|
EN/6
|
文化
|
from typing import List, Dict
def count_emoji_occurrences(text: str, emoji_list: List[str]) -> Dict[str, int]:
"""
Counts the number of occurrences of an emoji in the given text, based on the specified list of emoji.
argument:
text (str): input text
emoji_list (List[str]): List of emojis to count
Return value:
Dict[str, int]: Dictionary indicating the number of occurrences of each emoji
Usage example:
>>> count_emoji_occurrences("🍎🍏🍎🍇🍉🍉🍎", ["🍎", "🍉", "🍇"])
{'🍎': 3, '🍉': 2, '🍇': 1}
>>> count_emoji_occurrences("🎉🎉🎉🎂🎂🎂🎂", ["🎉", "🎂", "🎈"])
{'🎉': 3, '🎂': 4, '🎈': 0}
>>> count_emoji_occurrences("🌟✨💫🌟🌟✨", ["🌟", "✨", "💫"])
{'🌟': 3, '✨': 2, '💫': 1}
"""
|
emoji_counts = {emoji: 0 for emoji in emoji_list} # 指定された絵文字をすべて0で初期化
for char in text:
if char in emoji_counts:
emoji_counts[char] += 1
return emoji_counts
|
def check(candidate):
assert candidate("🍎🍏🍎🍇🍉🍉🍎", ["🍎", "🍉", "🍇"]) == {'🍎': 3, '🍉': 2, '🍇': 1}
assert candidate("🎉🎉🎉🎂🎂🎂🎂", ["🎉", "🎂", "🎈"]) == {'🎉': 3, '🎂': 4, '🎈': 0}
assert candidate("🌟✨💫🌟🌟✨", ["🌟", "✨", "💫"]) == {'🌟': 3, '✨': 2, '💫': 1}
assert candidate("", ["🎉", "🎂", "🎈"]) == {'🎉': 0, '🎂': 0, '🎈': 0}
assert candidate("🍎🍏🍎🍇🍉🍉🍎", ["🍎", "🍏", "🍇", "🍉", "🍌"]) == {'🍎': 3, '🍏': 1, '🍇': 1, '🍉': 2, '🍌': 0}
assert candidate("🎂🎂🎂🎂🎂", ["🎉", "🎂", "🎈"]) == {'🎉': 0, '🎂': 5, '🎈': 0}
assert candidate("🍎🍎🍎", ["🍎"]) == {'🍎': 3}
assert candidate("🍕🍕🍔🍔🍟🍟", ["🍕", "🍔", "🍟", "🌭"]) == {'🍕': 2, '🍔': 2, '🍟': 2, '🌭': 0}
assert candidate("🍣🍣🍣🍣", ["🍣", "🍚", "🍛"]) == {'🍣': 4, '🍚': 0, '🍛': 0}
assert candidate("💖💖💖💖💖", ["💖", "💗", "💕"]) == {'💖': 5, '💗': 0, '💕': 0}
|
count_emoji_occurrences
|
EN/7
|
文化
|
from typing import List
def parse_taiko_rhythm(rhythm_string: str) -> List[int]:
"""
Parses the string representing the Japanese drum rhythm, converts each rhythm symbol to the corresponding number of beats, and returns it as a list.
The Japanese drum rhythm consists of the following symbols:
- 'ドン': 4 beats
- 'ドコ': 2 beats
- 'ツク': 1 beat
input:
rhythm_string (str): A string of characters delimited by spaces that represents the rhythm of Japanese drums
output:
List[int]: List of each rhythm symbol converted to the corresponding number of beats
Usage example:
>>> parse_taiko_rhythm('ドン ドコ ツク ドコ ドン')
[4, 2, 1, 2, 4]
>>> parse_taiko_rhythm('ドコ ドコ ドン ツク ツク ドン')
[2, 2, 4, 1, 1, 4]
"""
|
# リズム記号と拍数の対応辞書
note_durations = {
'ドン': 4,
'ドコ': 2,
'ツク': 1
}
# 入力文字列を空白で分割し、対応する拍数をリストにする
beats = [note_durations[note] for note in rhythm_string.split()]
return beats
|
def check(candidate):
assert candidate('ドン ドコ ツク ドコ ドン') == [4, 2, 1, 2, 4]
assert candidate('ドコ ドコ ドン ツク ツク ドン') == [2, 2, 4, 1, 1, 4]
assert candidate('ドン ドン ドン') == [4, 4, 4]
assert candidate('ツク ツク ツク ツク') == [1, 1, 1, 1]
assert candidate('ドコ ドン') == [2, 4]
assert candidate('ドン') == [4]
|
parse_taiko_rhythm
|
EN/8
|
文化
|
def count_dango(s: str) -> int:
"""
Count the dango "o" contained in the string s.
argument:
s (str): string to check
Return value:
int: number of dumplings
Execution example:
>>> count_dango("oo-oo-oo-o-")
7
>>> count_dango("oo-o-o-oo-")
6
>>> count_dango("o-o-o-o-o-")
5
"""
|
return s.count('o')
|
def check(candidate):
assert candidate("oo-oo-oo-o-") == 7
assert candidate("oo-o-o-oo-") == 6
assert candidate("o-o-o-o-o-") == 5
assert candidate("ooo-ooo-o-") == 7
assert candidate("o-oo-o-o-") == 5
|
count_dango
|
EN/9
|
文化
|
import re
def is_haiku(haiku: str) -> bool:
"""
Determines whether the given string is in 5-7-5 haiku form.
Note:
Inputs other than hiragana do not need to be considered.
Also, one hiragana character is counted as one sound.
argument:
haiku (str): Hiragana string separated by spaces for each phrase
Return value:
bool: True if 5-7-5 format, False otherwise
"""
|
parts = haiku.split()
if len(parts) != 3:
return False
syllable_count = [len(re.findall(r'[ぁ-ん]', part)) for part in parts]
return syllable_count == [5, 7, 5]
|
def check(candidate):
assert candidate("はるかぜや どこかへとんだ ふうせんが") == True
assert candidate("ふるいけや かわずとびこむ みずのおと") == True
assert candidate("しずけさや いわにしみいる せみのこえ") == True
assert candidate("なつくさや つわものどもが ゆめのあと") == True
assert candidate("ふるいけ かわず みず") == False
assert candidate("はる かぜや どこ かへとん だふうせ んが") == False
assert candidate("あいうえお あいうえおあい あいうえお") == True
assert candidate("しずけさや いわにしみいる せみの声") == False
assert candidate("こんにちは 世界 どうも") == False
assert candidate("あきのよる") == False
assert candidate("ふるいけや かわずとびこむ みずのおとほげ") == False
|
is_haiku
|
EN/10
|
文化
|
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/11
|
文化
|
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/12
|
文化
|
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/13
|
文化
|
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/14
|
文化
|
def weight_needed_for_sumo(height: int, current_weight: int) -> tuple:
"""
From your height and current weight, calculate the amount of weight gain needed to reach the average BMI of a sumo wrestler.
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/15
|
文化
|
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/16
|
文化
|
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/17
|
文化
|
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/18
|
文化
|
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/19
|
文化
|
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/20
|
文化
|
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/21
|
文化
|
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/22
|
文化
|
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/23
|
文化
|
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/24
|
文化
|
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/25
|
文化
|
from typing import List
def are_all_kites_high_enough(heights: List[float], threshold: float) -> bool:
"""
Determine whether the height of all kites is greater than or equal to a threshold.
argument:
heights (List[float]): Current height of each kite (m)
threshold (float): Threshold for flying a kite (m)
Return value:
bool: True if the height of all kites is greater than or equal to the threshold, otherwise False
Execution example:
>>> are_all_kites_high_enough([10.0, 12.5, 9.0], 5.0)
True
>>> are_all_kites_high_enough([3.0, 6.0, 2.0], 5.0)
False
"""
|
return all(height >= threshold for height in heights)
|
def check(candidate):
assert candidate([10.0, 12.5, 9.0], 5.0) == True
assert candidate([3.0, 6.0, 2.0], 5.0) == False
assert candidate([7.0, 8.0, 9.0], 6.0) == True
assert candidate([3.0, 5.0], 5.0) == False
assert candidate([10.0, 10.5, 11.0], 10.0) == True
|
are_all_kites_high_enough
|
EN/26
|
文化
|
from typing import List
def karaoke_score_with_grade(target: List[int], actual: List[int]) -> str:
"""
Calculates the pitch accuracy score in karaoke and assigns grades.
Compare the ideal pitch list (target) and the pitch list for singing (actual),
Returns a score according to the proportion of matching pitches.
Judgment criteria:
- S: 90% or more
- A: 80% or more but less than 90%
- B: 70% or more but less than 80%
- C: 60% or more but less than 70%
- D: Less than 60%
argument:
target (List[int]): ideal pitch list
actual (List[int]): pitch list when singing
Return value:
str: Grade based on pitch matching rate (e.g. "Score: 85.0%, Grade: A")
"""
|
# 一致している音程の数をカウント
match_count = sum(1 for t, a in zip(target, actual) if t == a)
# スコアをパーセンテージで計算
score_percentage = (match_count / len(target)) * 100
# 成績を判定
if score_percentage >= 90:
grade = "S"
elif score_percentage >= 80:
grade = "A"
elif score_percentage >= 70:
grade = "B"
elif score_percentage >= 60:
grade = "C"
else:
grade = "D"
return grade
|
def check(candidate):
assert candidate([60, 62, 64, 65, 67], [60, 62, 64, 65, 67]) == "S"
assert candidate([60, 62, 64, 65, 67], [60, 62, 63, 65, 67]) == "A"
assert candidate([60, 62, 64, 65, 67, 68, 69], [60, 61, 64, 64, 67, 68, 69]) == "B"
assert candidate([60, 62, 64, 65, 67], [60, 61, 64, 65, 66]) == "C"
assert candidate([60, 62, 64, 65, 67], [61, 61, 63, 64, 66]) == "D"
|
karaoke_score_with_grade
|
EN/27
|
文化
|
def translate_thank_you(language_code):
"""
Translate "ありがとう" by specifying the language code.
Args:
language_code (str): ISO 639-1 language code
(Example: "ja", "en", "ru", "fr", "ko", "es", "de", "it", "zh", "ar")
Returns:
str: Translation of "ありがとう" into the specified language.
"""
|
translations = {
"ja": "ありがとう", # 日本語
"en": "Thank you", # 英語
"ru": "Спасибо", # ロシア語
"fr": "Merci", # フランス語
"ko": "감사합니다", # 韓国語
"es": "Gracias", # スペイン語
"de": "Danke", # ドイツ語
"it": "Grazie", # イタリア語
"zh": "谢谢", # 中国語
"ar": "شكرا", # アラビア語
}
return translations.get(language_code)
|
def check(candidate):
assert candidate("ja") == "ありがとう"
assert candidate("en") == "Thank you"
assert candidate("es") == "Gracias"
assert candidate("fr") == "Merci"
assert candidate("de") == "Danke"
assert candidate("it") == "Grazie"
assert candidate("zh") == "谢谢"
assert candidate("ko") == "감사합니다"
assert candidate("ar") == "شكرا"
assert candidate("ru") == "Спасибо"
|
translate_thank_you
|
EN/28
|
文化
|
def check_ichiju_sansai(menu):
"""
Determine whether the menu satisfies the format of one soup and three dishes.
argument:
menu (dict): menu
{"汁物": list of str, "主菜": list of str, "副菜": list of str}
Return:
bool: True if it satisfies the format of one soup and three dishes, otherwise False
>>> check_ichiju_sansai({"汁物": ["味噌汁"], "主菜": ["焼き魚"], "副菜": ["おひたし", "漬物"]})
True
>>> check_ichiju_sansai({"汁物": ["味噌汁"], "主菜": ["焼き魚"], "副菜": ["おひたし"]})
False
"""
|
if set(menu.keys()) != {"汁物", "主菜", "副菜"}:
return False
if len(menu["汁物"]) == 1 and len(menu["主菜"]) == 1 and len(menu["副菜"]) == 2:
return True
return False
|
def check(candidate):
assert candidate({"汁物": ["味噌汁"], "主菜": ["焼き魚"], "副菜": ["おひたし", "漬物"]}) == True
assert candidate({"汁物": ["豚汁"], "主菜": ["煮物"], "副菜": ["おひたし", "ポテトサラダ"]}) == True
assert candidate({"汁物": ["味噌汁"], "主菜": ["焼き魚"], "副菜": ["おひたし"]}) == False
assert candidate({"汁物": ["味噌汁"], "主菜": ["焼き魚"]}) == False
assert candidate({"汁物": [], "主菜": ["焼き魚"], "副菜": ["おひたし", "漬物"]}) == False
|
check_ichiju_sansai
|
EN/29
|
文化
|
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/30
|
文化
|
def calculate_congestion_rate(max_capacity: int, current_passengers: int) -> float:
"""
Calculate the congestion rate of the train.
Arguments:
max_capacity (int): Train capacity (maximum capacity)
current_passengers (int): Number of passengers currently on board
Return:
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/31
|
風習
|
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/32
|
風習
|
def calculate_remaining_bill(total_bill: int, boss_bills: list, other_members_count: int) -> int:
"""
A function that splits the 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/33
|
風習
|
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/34
|
風習
|
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/35
|
風習
|
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/36
|
風習
|
def is_correct_hinamatsuri_order(dolls: list) -> bool:
"""
Given the correct order of the dolls for Hinamatsuri, create a function to determine whether the input order is correct.
Argument:
- dolls (list): the order of the dolls
Return:
- bool: True if correct, False if incorrect
Example:
>>> is_correct_hinamatsuri_order(["お内裏様", "お雛様", "三人官女", "五人囃子", "随身", "仕丁"])
True
>>> is_correct_hinamatsuri_order(["お雛様", "お内裏様", "三人官女", "五人囃子", "仕丁", "随身"])
False
"""
|
correct_order = ["お内裏様", "お雛様", "三人官女", "五人囃子", "随身", "仕丁"]
return dolls == correct_order
|
def check(candidate):
assert candidate(["お内裏様", "お雛様", "三人官女", "五人囃子", "随身", "仕丁"]) == True
assert candidate(["お雛様", "お内裏様", "三人官女", "五人囃子", "仕丁", "随身"]) == False
assert candidate(["お雛様", "お内裏様", "三人官女", "五人囃子", "随身", "仕丁"]) == False
assert candidate(["お内裏様", "お雛様", "随身", "三人官女", "五人囃子", "仕丁"]) == False
assert candidate(["仕丁", "お内裏様", "三人官女", "五人囃子", "お雛様", "随身"]) == False
|
is_correct_hinamatsuri_order
|
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
|
風習
|
def is_keigo(text: str) -> bool:
"""
A function that determines whether the input sentence is honorific language (ending in "ます" or "です").
argument:
text (str): Japanese text
Return value:
bool: Returns True if the sentence is honorific (ending with "ます" or "です"), otherwise returns false.
Usage example:
>>> is_keigo("私は学校に行きます。")
True
>>> is_keigo("今日はいい天気だね。")
False
>>> is_keigo("お手伝いさせていただきます。")
True
"""
|
if text.endswith('ます。') or text.endswith('です。'):
return True
return False
|
def check(candidate):
assert candidate("私は学校に行きます。") == True
assert candidate("今日はいい天気だね。") == False
assert candidate("お手伝いさせていただきます。") == True
assert candidate("昨日の天気は悪かった。") == False
assert candidate("今日は天気がいいです。") == True
assert candidate("彼は走るのが早い。") == False
assert candidate("AIは進化しています。") == True
assert candidate("すごいね!") == False
|
is_keigo
|
EN/39
|
風習
|
def count_hashi_pair(s: str) -> int:
"""
Counts the number of chopsticks (two chopsticks make a set) in the string s.
Args.
s (str): string
Return.
int: Number of chopsticks
Ex.
>>> count_hashi_pair(""||-|-|||-"")
3
"""
|
count = s.count("|")
return count // 2
|
def check(candidate):
assert candidate("||-|-|||-") == 3
assert candidate("|||-|-|") == 2
assert candidate("-|---|") == 1
assert candidate("|-||-|") == 2
assert candidate("|||||") == 2
|
count_hashi_pair
|
EN/40
|
風習
|
from typing import List
def calculate_total_beans(ages: List[int]) -> int:
"""
Calculate the number of beans that the whole family will eat.
Assume that each family member eats as many beans as their age.
argument:
ages (List[int]): List of ages of each family member.
Return value:
int: Number of beans eaten by the whole family (sum of ages).
Usage example:
>>> calculate_total_beans([10, 15, 20])
45
>>> calculate_total_beans([5, 8, 13])
26
"""
|
return sum(ages)
|
def check(candidate):
assert candidate([10, 15, 20]) == 45
assert candidate([5, 8, 13]) == 26
assert candidate([1, 2, 3, 4]) == 10
assert candidate([30, 25, 15]) == 70
assert candidate([7, 6, 5, 4]) == 22
|
calculate_total_beans
|
EN/41
|
風習
|
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/42
|
風習
|
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/43
|
風習
|
def convert_to_japanese_time(hour: int, minute: int) -> str:
"""
A function that converts the time (hour, minute) in 24-hour notation to Japanese notation for AM/PM.
argument:
hour (int): Time in 24-hour notation (0 <= hour < 24)
minute (int): minute (0 <= minute < 60)
Return value:
str: Japanese notation for AM/PM hours (e.g. "10:30 AM", "2:15 PM")
"""
|
if 0 <= hour < 12: # 午前
meridian = "午前"
display_hour = hour if hour != 0 else 0 # 0時はそのまま0時
else: # 午後
meridian = "午後"
display_hour = hour - 12 if hour != 12 else 12 # 12時はそのまま12時
return f"{meridian}{display_hour}時{minute}分"
|
def check(candidate):
assert candidate(0, 0) == '午前0時0分'
assert candidate(0, 15) == '午前0時15分'
assert candidate(11, 59) == '午前11時59分'
assert candidate(12, 0) == '午後12時0分'
assert candidate(12, 30) == '午後12時30分'
assert candidate(23, 59) == '午後11時59分'
assert candidate(14, 30) == '午後2時30分'
assert candidate(1, 1) == '午前1時1分'
assert candidate(13, 45) == '午後1時45分'
assert candidate(11, 0) == '午前11時0分'
assert candidate(18, 15) == '午後6時15分'
assert candidate(21, 30) == '午後9時30分'
|
convert_to_japanese_time
|
EN/44
|
風習
|
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/45
|
風習
|
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/46
|
風習
|
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/47
|
風習
|
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/48
|
風習
|
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/49
|
風習
|
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/50
|
風習
|
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/51
|
風習
|
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/52
|
風習
|
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/53
|
風習
|
from datetime import datetime
def generate_work_message(start_time: str, end_time: str) -> str:
"""
A function that generates a message after work based on the start and end times.
Arguments:
start_time (str): Start time of work (HH:MM format)
end_time (str): End time of work (HH:MM format)
Return value:
str: message after work
Example:
>>> generate_work_message("09:00", "18:00")
'お疲れ様でした。ゆっくり休んでください。'
>>> generate_work_message("09:00", "16:30")
'お疲れ様でした。明日もがんばりましょう。'
"""
|
start = datetime.strptime(start_time, "%H:%M")
end = datetime.strptime(end_time, "%H:%M")
work_duration = (end - start).seconds / 3600 # 勤務時間(時間単位)
if work_duration >= 8:
return "お疲れ様でした。ゆっくり休んでください。"
else:
return "お疲れ様でした。明日もがんばりましょう。"
|
def check(candidate):
assert candidate("09:00", "18:00") == "お疲れ様でした。ゆっくり休んでください。"
assert candidate("09:00", "16:30") == "お疲れ様でした。明日もがんばりましょう。"
assert candidate("08:00", "16:00") == "お疲れ様でした。ゆっくり休んでください。"
assert candidate("10:00", "15:00") == "お疲れ様でした。明日もがんばりましょう。"
assert candidate("11:00", "19:00") == "お疲れ様でした。ゆっくり休んでください。"
|
generate_work_message
|
EN/54
|
風習
|
from datetime import datetime, timedelta
def calculate_bedtime(wake_up_time: str, sleep_duration: str) -> str:
"""
Calculates the time you should go to bed to get the desired amount of sleep.
Arguments:
- wake_up_time (str): Time you want to wake up in the morning (e.g. ‘07:30’)
- sleep_duration (str): sleep duration (e.g. “8:00”, “7:30”)
Return value:
- time to go to bed (e.g. “23:30”, “10:30”)
"""
|
wake_up_time_obj = datetime.strptime(wake_up_time, "%H:%M")
sleep_hours, sleep_minutes = map(int, sleep_duration.split(':'))
sleep_duration_obj = timedelta(hours=sleep_hours, minutes=sleep_minutes)
bed_time_obj = wake_up_time_obj - sleep_duration_obj
return bed_time_obj.strftime("%H:%M")
|
def check(candidate):
assert candidate("07:30", "8:00") == "23:30"
assert candidate("07:30", "8:30") == "23:00"
assert candidate("18:00", "7:30") == "10:30"
assert candidate("18:15", "7:30") == "10:45"
assert candidate("09:00", "7:00") == "02:00"
assert candidate("10:00", "7:00") == "03:00"
assert candidate("22:00", "6:30") == "15:30"
assert candidate("06:00", "7:00") == "23:00"
|
calculate_bedtime
|
EN/55
|
風習
|
def can_all_family_wait(times, num_people):
"""
A function to determine whether the Aoki family can all wait in line at a restaurant.
The waiting time is (number of people until they enter the restaurant) * 30 minutes.
Arguments:
- times (list): List of acceptable waiting times (in minutes) for all members of the Aoki family.
- num_people (int): Number of people until they enter the restaurant.
Return value:
- bool: True if all family members are waiting in line, False if even one person is not waiting in line.
"""
|
wait_time = num_people * 30
for time in times:
if time < wait_time:
return False
return True
|
def check(candidate):
assert candidate([60, 90, 120], 1) == True
assert candidate([60, 90, 120], 2) == True
assert candidate([60, 90, 120], 3) == False
assert candidate([60, 90, 120], 4) == False
assert candidate([120, 120, 120], 4) == True
assert candidate([120, 150, 150], 4) == True
assert candidate([60, 120, 150], 4) == False
|
can_all_family_wait
|
EN/56
|
風習
|
def evaluate_score(score: int) -> str:
"""
Grades will be evaluated based on the points given.
Performance evaluation criteria:
- 80 points or more: "良"
- 60 points or more but less than 80 points: "可"
- Less than 60 points: "不可"
argument:
score (int): Input score (0-100)
Return value:
str: Evaluated grade ("良", "可", "不可")
Usage example:
>>> evaluate_score(85)
'良'
>>> evaluate_score(75)
'可'
>>> evaluate_score(45)
'不可'
"""
|
if score >= 80:
return "良"
elif score >= 60:
return "可"
else:
return "不可"
|
def check(candidate):
assert candidate(85) == "良"
assert candidate(75) == "可"
assert candidate(45) == "不可"
assert candidate(60) == "可"
assert candidate(80) == "良"
assert candidate(59) == "不可"
assert candidate(100) == "良"
assert candidate(0) == "不可"
|
evaluate_score
|
EN/57
|
日本地理
|
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/58
|
日本地理
|
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/59
|
日本地理
|
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/60
|
日本地理
|
def get_region(prefecture: str) -> str:
"""
Accepts a Japanese prefecture name as input and returns the corresponding region name.
If a prefecture that does not exist is entered, "Unknown" is returned.
>>> get_region('北海道')
'北海道地方'
>>> get_region('秋田県')
'東北地方'
"""
|
regions = {
"北海道地方": ["北海道"],
"東北地方": ["青森県", "岩手県", "宮城県", "秋田県", "山形県", "福島県"],
"関東地方": ["茨城県", "栃木県", "群馬県", "埼玉県", "千葉県", "東京都", "神奈川県"],
"中部地方": ["新潟県", "富山県", "石川県", "福井県", "山梨県", "長野県", "岐阜県", "静岡県", "愛知県"],
"近畿地方": ["三重県", "滋賀県", "京都府", "大阪府", "兵庫県", "奈良県", "和歌山県"],
"中国地方": ["鳥取県", "島根県", "岡山県", "広島県", "山口県"],
"四国地方": ["徳島県", "香川県", "愛媛県", "高知県"],
"九州地方": ["福岡県", "佐賀県", "長崎県", "熊本県", "大分県", "宮崎県", "鹿児島県", "沖縄県"],
}
for region, prefectures in regions.items():
if prefecture in prefectures:
return region
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("鳥取県") == "中国地方"
assert candidate("香川県") == "四国地方"
assert candidate("福岡県") == "九州地方"
assert candidate("長崎県") == "九州地方"
assert candidate("不存在県") == "不明"
|
get_region
|
EN/61
|
日本地理
|
def is_in_tokyo(ward: str) -> bool:
"""
A function that determines whether it is in Tokyo's 23 wards.
argument:
ward (str): Ward name to be judged.
Return value:
bool: True if the argument is the name of Tokyo's 23 wards, False otherwise.
example:
>>> is_in_tokyo("新宿区")
True
>>> is_in_tokyo("横浜市")
False
"""
|
tokyo_23_wards = {
"千代田区", "中央区", "港区", "新宿区", "文京区", "台東区", "墨田区", "江東区",
"品川区", "目黒区", "大田区", "世田谷区", "渋谷区", "中野区", "杉並区",
"豊島区", "北区", "荒川区", "板橋区", "練馬区", "足立区", "葛飾区", "江戸川区"
}
return ward in tokyo_23_wards
|
def check(candidate):
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
assert candidate("富士市") == False
|
is_in_tokyo
|
EN/62
|
日本地理
|
def get_hottest_location(temperature_data):
"""
Given city and temperature data, returns the city with the highest temperature.
argument:
temperature_data (dict): Dictionary of cities and their temperature data.
Return value:
str: Name of the city with the highest temperature.
Execution example:
>>> temperature_data = {"新宿区": 35.5, "大阪市": 34.0, "福岡市": 36.2}
>>> get_hottest_location(temperature_data)
'福岡市'
"""
|
return max(temperature_data, key=lambda location: temperature_data[location])
|
def check(candidate):
assert candidate({"新宿区": 35.5, "大阪市": 34.0, "福岡市": 36.2}) == "福岡市"
assert candidate({"横浜市": 29.8, "京都市": 33.1, "神戸市": 32.7}) == "京都市"
assert candidate({"仙台市": 25.3, "長野市": 24.1, "高松市": 26.0}) == "高松市"
assert candidate({"金沢市": 31.2}) == "金沢市"
assert candidate({"富山市": -5.0, "秋田市": -3.2, "盛岡市": -7.1}) == "秋田市"
|
get_hottest_location
|
EN/63
|
日本地理
|
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/64
|
日本地理
|
def is_tokaido_shinkansen_nobori(stations: list) -> str:
"""
Determines whether the specified station on the Tokaido Shinkansen is an '上り' (東京-bound) or '下り' (新大阪-bound) station.
This function takes a list of stations, which consists of different stations for the departure and arrival stations.
It returns '上り' if the station is an up station on the Tokaido Shinkansen, '下り' if it is a down station, and '判定不可' if it is not possible to determine.
使用例:
>>> is_tokaido_shinkansen_nobori(["新大阪", "東京"])
'上り'
>>> is_tokaido_shinkansen_nobori(["東京", "新大阪"])
'下り'
>>> is_tokaido_shinkansen_nobori(["北海道", "沖縄"])
'判定不可'
"""
|
tokaido_shinkansen_stations = [
"東京", "品川", "新横浜", "小田原", "熱海", "三島", "新富士", "静岡", "掛川", "浜松",
"豊橋", "三河安城", "名古屋", "岐阜羽島", "米原", "京都", "新大阪"
]
start_station, end_station = stations[0], stations[1]
if start_station not in tokaido_shinkansen_stations or end_station not in tokaido_shinkansen_stations:
return "判定不可"
else:
start_index = tokaido_shinkansen_stations.index(start_station)
end_index = tokaido_shinkansen_stations.index(end_station)
return "上り" if start_index > end_index else "下り"
|
def check(candidate):
assert candidate(["新大阪", "東京"]) == "上り"
assert candidate(["東京", "新大阪"]) == "下り"
assert candidate(["名古屋", "東京"]) == "上り"
assert candidate(["静岡", "名古屋"]) == "下り"
assert candidate(["京都", "新大阪"]) == "下り"
assert candidate(["品川", "新横浜"]) == "下り"
assert candidate(["掛川", "豊橋"]) == "下り"
assert candidate(["豊橋", "静岡"]) == "上り"
assert candidate(["北海道", "沖縄"]) == "判定不可"
assert candidate(["東京", "沖縄"]) == "判定不可"
|
is_tokaido_shinkansen_nobori
|
EN/65
|
日本地理
|
def is_japan_three_views(place: str) -> bool:
"""
Determine whether the specified place name is one of the three most scenic places in Japan.
>>> is_japan_three_views(""松島"")
True
>>> is_japan_three_views(""天橋立"")
True
>>> is_japan_three_views(""宮島"")
True
>>> is_japan_three_views(""富士山"")
False
"""
|
japan_three_views = {"松島", "天橋立", "宮島"}
return place in japan_three_views
|
def check(candidate):
assert candidate("松島") == True
assert candidate("天橋立") == True
assert candidate("宮島") == True
assert candidate("富士山") == False
assert candidate("東京タワー") == False
assert candidate("琵琶湖") == False
assert candidate("屋久島") == False
assert candidate("沖縄") == False
|
is_japan_three_views
|
EN/66
|
日本地理
|
def is_prefectural_capital(city: str) -> bool:
"""
Determines whether the specified city is the capital of the prefecture.
Argument:
city (str): City name
Return:
bool: True if the capital of the prefecture, False otherwise
Ex:
>>> is_prefectural_capital("東京")
True
>>> is_prefectural_capital("渋谷")
False
"""
|
prefectural_capitals = {
"札幌", "青森", "盛岡", "仙台", "秋田", "山形", "福島", "水戸", "宇都宮", "前橋",
"さいたま", "千葉", "東京", "横浜", "新潟", "富山", "金沢", "福井", "甲府", "長野",
"岐阜", "静岡", "名古屋", "津", "大津", "京都", "大阪", "神戸", "奈良", "和歌山",
"鳥取", "松江", "岡山", "広島", "山口", "徳島", "高松", "松山", "高知", "福岡",
"佐賀", "長崎", "熊本", "大分", "宮崎", "鹿児島", "那覇"
}
return city in prefectural_capitals
|
def check(candidate):
assert candidate("東京") == True
assert candidate("渋谷") == False
assert candidate("北海道") == False
assert candidate("札幌") == True
assert candidate("津") == True
assert candidate("大津") == True
assert candidate("高松") == True
assert candidate("埼玉") == False
assert candidate("神奈川") == False
assert candidate("沖縄") == False
|
is_prefectural_capital
|
EN/67
|
文化
|
def check_olympic_year(year: int) -> bool:
"""
A function that checks whether it 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/68
|
文化
|
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/69
|
文化
|
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/70
|
日本語処理
|
def convert_to_manyo_gana(text: str) -> str:
"""
A function that converts a given string to Manyogana.
Convert each Hiragana character to its Manyogana counterpart. Here, we will perform a temporary and simple conversion.
For example, 「あ」is「安」、「い」is「以」、「う」is「宇」.
argument:
text (str): String containing hiragana.
Return value:
str: String converted to Manyogana.
Usage example:
使用例:
>>> convert_to_manyo_gana("あいう")
'安以宇'
"""
|
hira_to_manyo = {
'あ': '安', 'い': '以', 'う': '宇', 'え': '衣', 'お': '於',
'か': '加', 'き': '幾', 'く': '久', 'け': '計', 'こ': '己',
'さ': '左', 'し': '之', 'す': '須', 'せ': '世', 'そ': '曽',
'た': '多', 'ち': '知', 'つ': '川', 'て': '天', 'と': '止',
'な': '奈', 'に': '仁', 'ぬ': '奴', 'ね': '祢', 'の': '乃',
'は': '波', 'ひ': '比', 'ふ': '布', 'へ': '部', 'ほ': '保',
'ま': '末', 'み': '美', 'む': '武', 'め': '女', 'も': '毛',
'や': '也', 'ゆ': '由', 'よ': '与',
'ら': '良', 'り': '利', 'る': '留', 'れ': '礼', 'ろ': '呂',
'わ': '和', 'ゐ': '為', 'ゑ': '恵', 'を': '遠',
'ん': '無'
}
result = []
for char in text:
result.append(hira_to_manyo.get(char))
return ''.join(result)
|
def check(candidate):
assert candidate("あいう") == '安以宇'
assert candidate("かきくけこ") == '加幾久計己'
assert candidate("さしすせそ") == '左之須世曽'
assert candidate("たちつてと") == '多知川天止'
assert candidate("なにぬねの") == '奈仁奴祢乃'
assert candidate("はひふへほ") == '波比布部保'
assert candidate("まみむめも") == '末美武女毛'
assert candidate("やゆよ") == '也由与'
assert candidate("らりるれろ") == '良利留礼呂'
assert candidate("わゐゑをん") == '和為恵遠無'
|
convert_to_manyo_gana
|
EN/71
|
風習
|
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/72
|
日本語処理
|
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/73
|
日本語処理
|
def next_katakana(char: str) -> str:
"""
A function that returns the character following the specified character in a katakana table.
If the specified character is the last character ('ン'), it will return to the first character ('a').
argument:
char (str): 1 character katakana
Return value:
str: next katakana character
Usage example:
>>> next_katakana("ア")
'イ'
>>> next_katakana("ン")
'ア'
>>> next_katakana("カ")
'キ'
>>> next_katakana("ヲ")
'ン'
"""
|
katakana_list = ['ア', 'イ', 'ウ', 'エ', 'オ',
'カ', 'キ', 'ク', 'ケ', 'コ',
'サ', 'シ', 'ス', 'セ', 'ソ',
'タ', 'チ', 'ツ', 'テ', 'ト',
'ナ', 'ニ', 'ヌ', 'ネ', 'ノ',
'ハ', 'ヒ', 'フ', 'ヘ', 'ホ',
'マ', 'ミ', 'ム', 'メ', 'モ',
'ヤ', 'ユ', 'ヨ',
'ラ', 'リ', 'ル', 'レ', 'ロ',
'ワ', 'ヲ', 'ン']
index = katakana_list.index(char)
next_index = (index + 1) % len(katakana_list) # 最後の文字の次は最初の文字
return katakana_list[next_index]
|
def check(candidate):
assert candidate("ア") == 'イ'
assert candidate("カ") == 'キ'
assert candidate("ヲ") == 'ン'
assert candidate("ン") == 'ア'
assert candidate("ソ") == 'タ'
assert candidate("ヨ") == 'ラ'
assert candidate("ン") == 'ア'
assert candidate("ホ") == 'マ'
assert candidate("ワ") == 'ヲ'
|
next_katakana
|
EN/74
|
日本語処理
|
def replace_katakana(s, replacement):
"""
Replaces katakana characters in the given string s with the specified string replacement.
argument:
s (str): Target string.
replacement (str): String used for replacement.
Return value:
str: String resulting from replacing katakana.
Execution example:
>>> replace_katakana("カタカナとひらがな", "*")
'**とひらがな'
"""
|
return "".join(replacement if "ァ" <= char <= "ン" or char == "ヴ" else char for char in s)
|
def check(candidate):
assert candidate("カタカナとひらがな", "*") == "****とひらがな"
assert candidate("カタカナ", "!") == "!!!!"
assert candidate("ひらがなと漢字", "?") == "ひらがなと漢字"
assert candidate("漢字とカタカナ", "#") == "漢字と####"
assert candidate("あアイいうウえエオお", "+") == "あ++いう+え++お"
|
replace_katakana
|
EN/75
|
日本語処理
|
def calculate_katakana_percentage(text: str) -> float:
"""
A function that calculates the percentage of katakana in a text.
Arguments:
text (str): Japanese text
Return value:
float: Percentage of katakana (to one decimal place)
Example:
>>> calculate_katakana_percentage("コンピュータ")
100.0
>>> calculate_katakana_percentage("カタカナとひらがな")
44.4
"""
|
if len(text) == 0:
return 0.0
total_chars = len(text)
katakana_count = sum(1 for char in text if '\u30a0' <= char <= '\u30ff')
percentage = (katakana_count / total_chars) * 100
return round(percentage, 1)
|
def check(candidate):
assert candidate("コンピュータ") == 100.0
assert candidate("カタカナとひらがな") == 44.4
assert candidate("カタカナと漢字") == 57.1
assert candidate("あア阿んン") == 40.0
assert candidate("カタカナトひらがなト漢字") == 50.0
assert candidate("漢字のみ") == 0.0
|
calculate_katakana_percentage
|
EN/76
|
日本語処理
|
def convert_katakana_to_halfwidth(text: str) -> str:
"""
You are given a text (text) composed of hiragana and katakana syllabary characters.
Create a function that converts all katakana characters in the text to half-width characters.
Rules:
- Keep hiragana and already half-width katakana characters unchanged
Example:
>>> convert_katakana_to_halfwidth("あいうえおアイウエオ")
'あいうえおアイウエオ'
>>> convert_katakana_to_halfwidth("ワヲンわをん")
'ワヲンわをん'
"""
|
fullwidth = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン"
halfwidth = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン"
return text.translate(str.maketrans(fullwidth, halfwidth))
|
def check(candidate):
assert candidate("あいうえおアイウエオ") == "あいうえおアイウエオ"
assert candidate("ワヲンわをん") == "ワヲンわをん"
assert candidate("カタカナ ひらがな") == "カタカナ ひらがな"
assert candidate("アイウエオ アイウエオ") == "アイウエオ アイウエオ"
assert candidate("ワヲン ワヲン") == "ワヲン ワヲン"
assert candidate("アイウエオ") == "アイウエオ"
assert candidate("ワヲン") == "ワヲン"
assert candidate("ひらがなのみ") == "ひらがなのみ"
assert candidate("アいウえオ") == "アいウえオ"
assert candidate("カキクケコかきくけこ") == "カキクケコかきくけこ"
|
convert_katakana_to_halfwidth
|
EN/77
|
日本語処理
|
def is_two_char_shiritori_valid_katakana(words: list) -> bool:
"""
A function that determines whether or not the rules for two-character shiritori using katakana are satisfied.
Returns True if the two-character shiritori is valid, and False otherwise.
Rules:
- The “last two characters” of each word must be an exact match for the “first two characters” of the next word.
- It is assumed that the input consists entirely of katakana.
Example:
>>> is_two_char_shiritori_valid_katakana(["シリトリ", "トリクチ", "クチバシ", "バショ"])
True
>>> is_two_char_shiritori_valid_katakana(["タヌキ", "キツネ", "ネコ", "コイヌ"])
False
"""
|
for i in range(len(words) - 1):
if len(words[i]) < 2 or len(words[i + 1]) < 2:
return False
if words[i][-2:] != words[i + 1][:2]:
return False
return True
|
def check(candidate):
assert candidate(["シリトリ", "トリクチ", "クチバシ", "バショ"]) == True
assert candidate(["トマト", "マトリョーシカ", "シカイ", "カイガラ"]) == True
assert candidate(["キツツキ", "ツキアカリ", "カリモノ", "モノオキ"]) == True
assert candidate(["タヌキ", "キツネ", "ネコ", "コイヌ"]) == False
assert candidate(["ネコ", "コタツ", "ツミキ", "キノコ"]) == False
assert candidate(["シリトリ", "トリクチ", "クチビル", "ビルド"]) == True
assert candidate(["カタカナ", "ナマエ", "エアコン"]) == False
|
is_two_char_shiritori_valid_katakana
|
EN/78
|
日本語処理
|
def katakana_to_romaji(name: str) -> str:
"""
This function takes the furigana for the name ‘name’ and converts it to full-width capital letters.
Ex:
>>> katakana_to_romaji("タナカ")
'TANAKA'
"""
|
katakana_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',
'ガ': 'GA', 'ギ': 'GI', 'グ': 'GU', 'ゲ': 'GE', 'ゴ': 'GO',
'ザ': 'ZA', 'ジ': 'JI', 'ズ': 'ZU', 'ゼ': 'ZE', 'ゾ': 'ZO',
'ダ': 'DA', 'ヂ': 'JI', 'ヅ': 'ZU', 'デ': 'DE', 'ド': 'DO',
'バ': 'BA', 'ビ': 'BI', 'ブ': 'BU', 'ベ': 'BE', 'ボ': 'BO',
'パ': 'PA', 'ピ': 'PI', 'プ': 'PU', 'ペ': 'PE', 'ポ': 'PO',
'ァ': 'a', 'ィ': 'i', 'ゥ': 'u', 'ェ': 'e', 'ォ': 'o',
'ャ': 'ya', 'ュ': 'yu', 'ョ': 'yo',
'ッ': 'tsu', 'ー': ''
}
romaji = ''
for char in name:
romaji += katakana_map.get(char, '')
return romaji
|
def check(candidate):
assert candidate("アオキ") == "AOKI"
assert candidate("カネコ") == "KANEKO"
assert candidate("スズキ") == "SUZUKI"
assert candidate("タナカ") == "TANAKA"
assert candidate("ニシダ") == "NISHIDA"
assert candidate("フジモト") == "FUJIMOTO"
assert candidate("ミウラ") == "MIURA"
assert candidate("ヤノ") == "YANO"
assert candidate("ワタナベ") == "WATANABE"
|
katakana_to_romaji
|
EN/79
|
日本語処理
|
def encode_shift(s: str):
return "".join([chr(((ord(ch) + 5 - ord("a")) % 26) + ord("a")) for ch in s])
def decode_shift(s: str):
"""
This function takes a string encoded with the encode_shift function as an argument and returns the decoded string.
"""
|
return "".join([chr(((ord(ch) - ord("a") - 5) % 26) + ord("a")) for ch in s])
|
from random import randint, choice
import string
import copy
def check(candidate):
letters = string.ascii_lowercase
for _ in range(50):
str = ''.join(choice(letters) for i in range(randint(10, 20)))
encoded_str = encode_shift(str)
assert candidate(copy.deepcopy(encoded_str)) == str
|
decode_shift
|
EN/80
|
日本語処理
|
from collections import Counter
def most_frequent_katakana(text: str) -> str:
"""
A function that returns the most frequent katakana character in a string.
It ignores hiragana and kanji characters in the string and only counts katakana.
Arguments:
text (str): A string containing hiragana, katakana and kanji
Return value:
str: Most frequent katakana (if there is a tie, the first katakana that appears)
"""
|
katakana = [ch for ch in text if 'ア' <= ch <= 'ン']
if not katakana:
return ""
counter = Counter(katakana)
most_frequent = counter.most_common(1)[0][0]
return most_frequent
|
def check(candidate):
assert candidate("ひらがな") == ""
assert candidate("カタカナ") == "カ"
assert candidate("漢字") == ""
assert candidate("アアイアイウアイウエアイウエオ") == "ア"
assert candidate("アイイウウエエオ") == "イ"
assert candidate("ひらがなやカタカナや漢字を含む") == "カ"
assert candidate("ヒラガナヤ片仮名ヤカンジヲフクム") == "ヤ"
|
most_frequent_katakana
|
EN/81
|
日本語処理
|
def determine_winner(names: list) -> str:
"""
In a game involving 佐藤, 鈴木, and 高橋, calculate the score for each player from the given list of names,
and return the player with the highest score.
Calculation method for score:
- Total number of katakana + (total number of unique katakana * 10) - (total number of non-katakana * 2)
Arguments:
names (list): List of player names (strings containing katakana, hiragana and kanji)
Return value:
str: Name of the player with the highest score
Example:
>>> determine_winner(['アイウエオ', 'アアアアアア', 'あアいイウエオ'])
'佐藤'
"""
|
katakana = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン"
def calculate_score(name: str) -> int:
""" 名前から得点を計算する """
count_katakana = sum(1 for char in name if char in katakana) # 片仮名の総数
unique_katakana = len(set(char for char in name if char in katakana)) # 重複なしの片仮名の総数
non_katakana_count = sum(1 for char in name if char not in katakana) # 片仮名以外の総数
score = count_katakana + unique_katakana * 10 - non_katakana_count * 2
return score
# それぞれのプレイヤーの点数を計算
scores = [calculate_score(name) for name in names]
# 最も高い点数を取ったプレイヤーを選択
max_score = max(scores)
winner_index = scores.index(max_score)
return ["佐藤", "鈴木", "高橋"][winner_index]
|
def check(candidate):
assert candidate(['アイウエオ', 'アアアアアア', 'あアいイウエオ']) == '佐藤'
assert candidate(['アアウウオオ', 'アイウエオ', 'アアアアアア']) == '鈴木'
assert candidate(['アイウエオ', 'アアアアアア', 'アイウエオアイウエオ']) == '高橋'
|
determine_winner
|
EN/82
|
日本語処理
|
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/83
|
日本語処理
|
def extract_hiragana(text: str) -> str:
"""
A function that extracts and returns only hiragana from a string `text`.
argument:
text (str): input string
Return value:
str: String with only hiragana extracted
Example:
>>> extract_hiragana("こんにちは。")
'こんにちは'
>>> extract_hiragana("今日はいい天気ですね。")
'はいいですね'
"""
|
return ''.join(char for char in text if 'ぁ' <= char <= 'ん')
|
def check(candidate):
assert candidate("") == ''
assert candidate("こんにちは。") == 'こんにちは'
assert candidate("今日はいい天気ですね。") == 'はいいですね'
assert candidate("こんにちは。今日はいい天気ですね。") == 'こんにちははいいですね'
assert candidate("ひらがなカタカナ漢字") == 'ひらがな'
assert candidate("ひらがな、Hiragana、hiragana") == 'ひらがな'
|
extract_hiragana
|
EN/84
|
日本語処理
|
from typing import List
def all_prefixes(string: str) -> List[str]:
"""
Returns a list of all prefixes, from shortest to longest, for the string given as an argument.
However, it is assumed that all character strings are in hiragana.
example:
>>> all_prefixes('Aiu')
['A', 'Ai', 'Aiu']
"""
|
result = []
for i in range(len(string)):
result.append(string[:i+1])
return result
|
def check(candidate):
assert candidate('') == []
assert candidate('あいうえお') == ['あ', 'あい', 'あいう', 'あいうえ', 'あいうえお']
assert candidate('ひらがな') == ['ひ', 'ひら', 'ひらが', 'ひらがな']
|
all_prefixes
|
EN/85
|
日本語処理
|
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/86
|
日本語処理
|
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/87
|
日本語処理
|
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
|
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 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/90
|
日本語処理
|
def is_valid_reverse_shiritori(words: list) -> bool:
"""
A function that determines whether a list of hiragana satisfies the reverse shiritori rules.
Gyaku-shiritori places the first letter of the previous word at the end of the next word.
argument:
words (list): list of hiragana words
Return value:
bool: True if the reverse rules are met, False if not
Usage example:
>>> is_valid_reverse_shiritori(["りんご", "ちり", "しゃち", "かし"])
True
>>> is_valid_reverse_shiritori(["りんご", "ごりら", "らっぱ", "ぱせり"])
False
"""
|
for i in range(1, len(words)):
if words[i-1][0] != words[i][-1]:
return False
return True
|
def check(candidate):
assert candidate(["りんご", "ちり", "しゃち", "かし"]) == True
assert candidate(["ごりら", "りんご", "くり", "きく", "かき"]) == True
assert candidate(["らっぱ", "さら", "ささ", "せんさ"]) == True
assert candidate(["りんご", "ごりら", "らっぱ", "ぱせり"]) == False
assert candidate(["ごりら", "らっこ", "こども", "もも"]) == False
|
is_valid_reverse_shiritori
|
EN/91
|
日本語処理
|
def hiragana_ascii_sum(s: str) -> int:
"""Takes a string of hiragana as an argument and returns the sum of the ASCII codes (Unicode code points) for hiragana characters only."""
|
total_sum = 0
for char in s:
if 'ぁ' <= char <= 'ん':
total_sum += ord(char)
return total_sum
|
def check(candidate):
assert candidate("あい") == 24710
assert candidate("さしすせそ") == 61885
assert candidate("あかさたな") == 61867
assert candidate("あabcい") == 24710
assert candidate("12345あい") == 24710
assert candidate("わをん") == 37300
|
hiragana_ascii_sum
|
EN/92
|
日本語処理
|
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/93
|
日本語処理
|
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/94
|
日本語処理
|
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/95
|
日本語処理
|
def sort_japanese_characters(text: str) -> str:
"""
A function that receives a string, sorts and combines hiragana, katakana, kanji, and alphabets.
argument:
text (str): input string
Return value:
str: string of characters arranged in hiragana, katakana, kanji, alphabetical order
Usage example:
>>> sort_japanese_characters("ひらがな")
'がなひら'
>>> sort_japanese_characters("ひらがなカタカナ漢字Alphabet")
'がなひらカカタナ字漢Aabehlpt'
"""
|
hiragana = sorted([char for char in text if 'ぁ' <= char <= 'ん'])
katakana = sorted([char for char in text if 'ァ' <= char <= 'ヶ'])
kanji = sorted([char for char in text if '一' <= char <= '龯'])
alphabet = sorted([char for char in text if 'A' <= char <= 'Z' or 'a' <= char <= 'z'])
return ''.join(hiragana + katakana + kanji + alphabet)
|
def check(candidate):
assert candidate("ひらがな") == "がなひら"
assert candidate("カタカナ") == "カカタナ"
assert candidate("漢字") == "字漢"
assert candidate("Alphabet") == "Aabehlpt"
assert candidate("ひらがなカタカナ漢字Alphabet") == "がなひらカカタナ字漢Aabehlpt"
|
sort_japanese_characters
|
EN/96
|
日本語処理
|
def solve(s):
"""
A string s is given.
If s[i] is hiragana or katakana, convert that character (hiragana to katakana, katakana to hiragana).
If it contains other characters, leave it as is.
If the string does not contain any hiragana or katakana characters, reverse the entire string.
The function returns a string of results.
example:
>>> solve("1234")
'4321'
>>> solve("あい")
'アイ'
>>> solve("#あ@イ")
'#ア@い'
"""
|
flg = 0
idx = 0
new_str = list(s)
for i in s:
if 'ぁ' <= i <= 'ん': # ひらがなをカタカナに変換
new_str[idx] = chr(ord(i) - ord('ぁ') + ord('ァ'))
flg = 1
elif 'ァ' <= i <= 'ン': # カタカナをひらがなに変換
new_str[idx] = chr(ord(i) - ord('ァ') + ord('ぁ'))
flg = 1
idx += 1
s = "".join(new_str)
if flg == 0:
return s[::-1]
return s
|
def check(candidate):
# 簡単なケースをチェック
assert candidate("あい") == "アイ"
assert candidate("1234") == "4321"
assert candidate("アカ") == "あか"
assert candidate("#あ@イ") == "#ア@い"
assert candidate("#あいウエ^45") == "#アイうえ^45"
assert candidate("#6@2") == "2@6#"
# 境界ケースをチェック
assert candidate("#$あ^カ") == "#$ア^か"
assert candidate("#あああ") == "#アアア"
assert candidate("かきくけこ") == "カキクケコ"
assert candidate("アイウエオ") == "あいうえお"
assert candidate("123456") == "654321"
|
solve
|
EN/97
|
日本語処理
|
def count_sentences(text: str) -> int:
"""
A function that counts how many Japanese sentences there are.
Sentences are defined to be separated by one of "。", "!", or "?".
argument:
text (str): input Japanese text
Return value:
int: number of sentences
Usage example:
>>> count_sentences("")
0
>>> count_sentences("おはようございます。")
1
>>> count_sentences("今日はいい天気ですね。明日も晴れるといいですね!")
2
"""
|
if not text:
return 0
sentences = [sentence for sentence in text.split('。') if sentence] # 「。」で分割
temp_sentences = []
for sentence in sentences:
temp_sentences.extend([s for s in sentence.split('!') if s]) # 「!」でさらに分割
final_sentences = []
for sentence in temp_sentences:
final_sentences.extend([s for s in sentence.split('?') if s]) # 「?」でさらに分割
return len(final_sentences)
|
def check(candidate):
assert candidate("") == 0
assert candidate("おはようございます。") == 1
assert candidate("今日はいい天気ですね。明日も晴れるといいですね!") == 2
assert candidate("おはよう!今日は何から始めようか?") == 2
assert candidate("おはようございます。今日はいい天気ですね!明日の天気はいかがでしょうか?") == 3
|
count_sentences
|
EN/98
|
日本語処理
|
def count_onsen_symbols(text: str) -> int:
"""
Counts and returns the number of hot spring symbols "♨️" from the input string.
Args:
text (str): input string
Returns:
int: Number of hot spring symbols “♨️”
"""
|
return text.count('♨️')
|
def check(candidate):
assert candidate("♨️") == 1
assert candidate("♨️♨️♨️♨️♨️") == 5
assert candidate("♨️あ♨️い♨️う♨️え♨️お♨️") == 6
assert candidate("♨️温泉に入りましょう♨️") == 2
|
count_onsen_symbols
|
EN/99
|
日本語処理
|
def check_katakana_hiragana_match(katakana: str, hiragana: str) -> bool:
"""
A function that checks whether katakana and hiragana match.
Arguments:
katakana (str): katakana string
hiragana (str): hiragana string
Return value:
bool: True if katakana and hiragana match, False otherwise
"""
|
def katakana_to_hiragana(katakana: str) -> str:
katakana_map = {
'ア': 'あ', 'イ': 'い', 'ウ': 'う', 'エ': 'え', 'オ': 'お',
'カ': 'か', 'キ': 'き', 'ク': 'く', 'ケ': 'け', 'コ': 'こ',
'サ': 'さ', 'シ': 'し', 'ス': 'す', 'セ': 'せ', 'ソ': 'そ',
'タ': 'た', 'チ': 'ち', 'ツ': 'つ', 'テ': 'て', 'ト': 'と',
'ナ': 'な', 'ニ': 'に', 'ヌ': 'ぬ', 'ネ': 'ね', 'ノ': 'の',
'ハ': 'は', 'ヒ': 'ひ', 'フ': 'ふ', 'ヘ': 'へ', 'ホ': 'ほ',
'マ': 'ま', 'ミ': 'み', 'ム': 'む', 'メ': 'め', 'モ': 'も',
'ヤ': 'や', 'ユ': 'ゆ', 'ヨ': 'よ',
'ラ': 'ら', 'リ': 'り', 'ル': 'る', 'レ': 'れ', 'ロ': 'ろ',
'ワ': 'わ', 'ヲ': 'を', 'ン': 'ん',
'ガ': 'が', 'ギ': 'ぎ', 'グ': 'ぐ', 'ゲ': 'げ', 'ゴ': 'ご',
'ザ': 'ざ', 'ジ': 'じ', 'ズ': 'ず', 'ゼ': 'ぜ', 'ゾ': 'ぞ',
'ダ': 'だ', 'ヂ': 'ぢ', 'ヅ': 'づ', 'デ': 'で', 'ド': 'ど',
'バ': 'ば', 'ビ': 'び', 'ブ': 'ぶ', 'ベ': 'べ', 'ボ': 'ぼ',
'パ': 'ぱ', 'ピ': 'ぴ', 'プ': 'ぷ', 'ペ': 'ぺ', 'ポ': 'ぽ',
'ァ': 'ぁ', 'ィ': 'ぃ', 'ゥ': 'ぅ', 'ェ': 'ぇ', 'ォ': 'ぉ',
'ャ': 'ゃ', 'ュ': 'ゅ', 'ョ': 'ょ',
'ッ': 'っ', 'ー': 'ー'
}
hiragana = ''.join([katakana_map.get(char, '') for char in katakana])
return hiragana
converted_hiragana = katakana_to_hiragana(katakana)
return converted_hiragana == hiragana
|
def check(candidate):
assert candidate("タナカ", "たなか") == True
assert candidate("スズキ", "すずき") == True
assert candidate("カッパ", "かっぱ") == True
assert candidate("タカハシ", "たかはし") == True
assert candidate("タナカ", "なかた") == False
assert candidate("サトウ", "すずき") == False
assert candidate("ガッコウ", "かっぱ") == False
assert candidate("タカハシ", "はしもと") == False
|
check_katakana_hiragana_match
|
End of preview. Expand
in Data Studio
SakuraEval
Dataset Description
SakuraEval is a Japan-specific code generation benchmark dataset. It is designed independently and does not rely on translation from English benchmarks such as HumanEval or JHumanEval.
Dataset Structure
from datasets import load_dataset
load_dataset("kogi-jwu/sakuraeval", "ja")
DatasetDict({
test: Dataset({
features: ['task_id', 'category', 'prompt', 'canonical_solution', 'test', 'entry_point'],
num_rows: 164
})
})
Data Fields
- task_id: Identifier for the data sample.
- category: Task category.
- prompt: Input for the model, including the function header and docstring that describes the task.
- canonical_solution: Solution to the problem presented in the prompt.
- test: Function(s) to test the generated code for correctness.
- entry_point: Entry point function to begin testing.
Category Breakdown
| Category | Number of Tasks |
|---|---|
| 文化(Culture) | 34 |
| 風習(Customs) | 27 |
| 日本地理(Japanese Geography) | 10 |
| 公民・法律(Law and Civics) | 11 |
| 数学・科学(Math and Science) | 21 |
| 単位変換(Unit Conversion) | 11 |
| 日本語処理(Japanese Language) | 43 |
| その他(Other) | 7 |
Languages
The dataset contains coding problems in 2 natural languages: English and Japanese.
- Downloads last month
- 7