Open7
【python】問題演習

今まで解いた基礎問題・複合問題を掲載
あとでやること
- GitHubへアップする
- プログラミングの基礎力や土台作りとしていい練習になるので、記事を書く
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def get_even_numbers(numbers):
result = []
for number in numbers:
if number % 2 ==0:
result.append(number)
return result
print(get_even_numbers(numbers))
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def get_even_numbers(numbers):
return [number for number in numbers if number % 2 == 0]
print(get_even_numbers(numbers))
numbers = [3, 7, 1, 9, 2, 8]
def find_max_number(numbers):
max_so_far = numbers[0] # 最初の数を覚えておく
for number in numbers:
if number > max_so_far:
max_so_far = number
return max_so_far
print(find_max_number(numbers))
numbers = [2, 5, 3, 8, 1]
def calculate_sum(numbers):
total = 0
for number in numbers:
total += number
return total
print(calculate_sum(numbers))
words = ["apple", "banana", "cherry", "date"]
def count_long_words(words):
count = 0 # ← 個数を数えるので、数字で初期化
for word in words:
if len(word) >= 5: # ← 5文字以上なので >= 5
count += 1 # ← 見つけたら1つずつ増やす
return count # ← 個数を返す
print(count_long_words(words))
# 文中の単語数を数える
# 期待する出力: 3
sentence = "Hello World Python"
def count_words(sentence):
words = sentence.split(" ")
count = len(words)
return count
print(count_words(sentence))
# 各数字を2倍にしたリストを返す
# 期待する出力: [2, 4, 6, 8, 10]
numbers = [1, 2, 3, 4, 5]
def double_numbers(numbers):
result = []
for number in numbers:
result.append(number*2)
return result
print(double_numbers(numbers))
# 偶数だけを取り出して、それを2倍にしたリストを返す
# 期待する出力: [4, 8, 12, 16, 20]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def get_even_and_double(numbers):
result = []
for number in numbers:
if number % 2 == 0:
result.append(number * 2)
return result
print(get_even_and_double(numbers))
# 母音(a, e, i, o, u)の個数を数える(大文字小文字は区別しない)
# 期待する出力: 5 (o, a, i, o, a)
text = "Python Programming"
vowels = ["a", "i", "u", "e", "o"]
def count_vowels(text):
count = 0
words = text.lower().split()
for vowel in vowels:
if words == vowel:
count += 1
return count
print(count_vowels(text))
word = "Python Programming"
word.lower().split()
text = "Python Programming"
vowels = ["a", "i", "u", "e", "o"]
def count_vowels(text):
count = 0
text_lower = text.lower() # 小文字化
for letter in text_lower: # 一文字ずつ
if letter in vowels: # その文字が母音リストにあるか
count += 1
return count
print(count_vowels(text))
# 5で終わる数字だけを抜き出す
# 期待する出力: [25, 45, 15]
numbers = [10, 25, 30, 45, 50, 15]
def find_numbers_ending_with_5(numbers):
result = []
for number in numbers:
word = str(number)
print(word)
print(type(word))
if word[-1] == "5":
result.append(int(word))
return result
print(find_numbers_ending_with_5(numbers))
# 文字数ごとにグループ分けした辞書を返す
# 期待する出力: {5: ["apple", "cherry"], 6: ["banana"], 4: ["date"], 10: ["elderberry"]}
words = ["apple", "banana", "cherry", "date", "elderberry"]
def group_by_length(words):
result = {}
for word in words:
word_length = len(word) # 文字数
# その文字数のキーがまだない場合、空リストを作る
if word_length not in result:
result[word_length] = []
# その文字数のリストに単語を追加
result[word_length].append(word)
return result
print(group_by_length(words))
# 全ての学生の名前だけを取り出してリストで返す
# 期待する出力: ["田中", "佐藤", "鈴木", "高橋"]
students = [
{"name": "田中", "score": 85},
{"name": "佐藤", "score": 92},
{"name": "鈴木", "score": 78},
{"name": "高橋", "score": 88}
]
def get_student_names(students):
all_students_name = []
for student_info in students:
all_students_name.append(student_info["name"])
return all_students_name
print(get_student_names(students))
# 各商品の売上(価格×数量)を計算して、全体の売上合計を返す
# 期待する出力: 365000 (240000 + 20000 + 25000 + 60000)
sales_data = [
{"product": "ノートPC", "price": 80000, "quantity": 3},
{"product": "マウス", "price": 2000, "quantity": 10},
{"product": "キーボード", "price": 5000, "quantity": 5},
{"product": "モニター", "price": 30000, "quantity": 2}
]
def calculate_total_sales(sales_data):
product_price = []
product_quantity = []
for product_info in sales_data:
product_price.append(product_info["price"])
product_quantity.append(product_info["quantity"])
print(product_price)
print(product_quantity)
for price, quantity in zip(product_price, product_quantity):
one_product_price = price * quantity
return one_product_price
print(calculate_total_sales(sales_data))
# 各商品の売上(価格×数量)を計算して、全体の売上合計を返す
# 期待する出力: 365000 (240000 + 20000 + 25000 + 60000)
sales_data = [
{"product": "ノートPC", "price": 80000, "quantity": 3},
{"product": "マウス", "price": 2000, "quantity": 10},
{"product": "キーボード", "price": 5000, "quantity": 5},
{"product": "モニター", "price": 30000, "quantity": 2}
]
def calculate_total_sales(sales_data):
total = 0 # 合計を入れる変数
for product_info in sales_data:
# 1つの商品の売上を計算
price = product_info["price"]
quantity = product_info["quantity"]
one_product_sales = price * quantity
# 全体の合計に追加
total += one_product_sales
return total
print(calculate_total_sales(sales_data))
# 30度以上の気温の日数を数える
# 期待する出力: 2 (30と35が30度以上)
temperatures = [25, 30, 18, 35, 22, 28]
def find_hot_days(temperatures):
number_of_name = 0
for tempetarure in temperatures:
if tempetarure >= 30:
number_of_name += 1
return number_of_name
print(find_hot_days(temperatures))
# 各科目の平均点を計算した辞書を返す
# 期待する出力: {"数学": 85.0, "英語": 87.33..., "理科": 87.66...}
grades = {"数学": [85, 92, 78], "英語": [88, 79, 95], "理科": [90, 85, 88]}
def calculate_subject_averages(grades):
average_score = {}
for subject, scores in grades.items():
# scoresは点数のリスト:[85, 92, 78]
average = sum(scores) / len(scores)
# 辞書に科目名をキー、平均を値として追加
average_score[subject] = average
return average_score
print(calculate_subject_averages(grades))
# 2桁の数字(10以上99以下)の個数を数える
# 期待する出力: 6 (12, 23, 45, 19, 34, 99がないので実際は5個)
# 訂正:期待する出力: 5
numbers = [12, 7, 23, 45, 8, 19, 34]
def count_two_digit_numbers(numbers):
count_number = 0
for number in numbers:
if 10 <= number <=99:
count_number += 1
return count_number
print(count_two_digit_numbers(numbers))
# 指定された果物の在庫を指定された数量分減らす
# もしその果物が在庫にない場合は"商品なし"を返す
# 期待する動作: update_inventory(inventory, "りんご", 10) → りんごが40個になる
inventory = {"りんご": 50, "バナナ": 30, "オレンジ": 20, "ぶどう": 15}
def update_inventory(inventory, fruit, quantity):
if fruit in inventory:
inventory[fruit] -= quantity
elif fruit in inventory <= 0:
print("商品なし")
return inventory
print(update_inventory(inventory, "りんご", 10))
print(inventory) # 確認用
def update_inventory(inventory, fruit, quantity):
if fruit in inventory: # 果物が存在する場合
inventory[fruit] -= quantity
return inventory # 更新後の辞書を返す
else: # 果物が存在しない場合
return "商品なし" # メッセージを返す
# 存在する果物
print(update_inventory(inventory, "りんご", 10)) # 更新された辞書
print(update_inventory(inventory, "メロン", 5)) # "商品なし"
def update_inventory(inventory, fruit, quantity):
if fruit in inventory: # 果物が存在する場合
inventory[fruit] -= quantity
return inventory # 更新後の辞書を返す
else: # 果物が存在しない場合
return "商品なし" # メッセージを返す
# 存在する果物
print(update_inventory(inventory, "りんご", 10)) # 更新された辞書
print(update_inventory(inventory, "メロン", 5)) # "商品なし"
def update_inventory(inventory, fruit, quantity):
if fruit not in inventory:
return "商品なし"
# 在庫不足チェック
if inventory[fruit] < quantity:
return f"{fruit}の在庫不足です。現在の在庫: {inventory[fruit]}個"
# 在庫更新
inventory[fruit] -= quantity
return inventory
# 指定された科目で一番点数が高い学生の名前を返す
# 例: find_top_student_in_subject(students_scores, "数学") → "佐藤"
students_scores = {
"田中": {"数学": 85, "英語": 78, "理科": 92},
"伊藤": {"数学": 90, "英語": 85, "理科": 88},
"佐々木": {"数学": 75, "英語": 90, "理科": 80}
}
def find_top_student_in_subject(students_scores, subject):
max_score = 0
top_student = ""
for student_name in students_scores:
score = students_scores[student_name][subject]
if score > max_score:
max_score = score
top_student = student_name
return top_student
print(find_top_student_in_subject(students_scores, "英語"))
# 在庫がある商品名のリストを返す(stock > 0)
# 期待する出力: ["laptop", "mouse"]
products = {
"laptop": {"price": 80000, "stock": 5},
"mouse": {"price": 2000, "stock": 20},
"keyboard": {"price": 5000, "stock": 0}
}
def get_available_products(products):
products_in_stock = []
for product in products:
print(product)
stock = products[product]["stock"]
if stock > 0:
products_in_stock.append(stock)
return products_in_stock
print(get_available_products(products))
# 20歳以上の人数を数える
# 期待する出力: 3
ages = {"太郎": 25, "花子": 30, "次郎": 18, "美香": 22}
def count_adults(ages):
count_20_age_people = 0
for age in ages:
people_20_ages = ages[age]
if people_20_ages >= 20:
count_20_age_people += 1
return count_20_age_people
print(count_adults(ages))
# カテゴリごとの売上合計を辞書で返す
# 期待する出力: {"電子機器": 82000, "家具": 40000}
sales = [
{"product": "ノートPC", "category": "電子機器", "amount": 80000},
{"product": "マウス", "category": "電子機器", "amount": 2000},
{"product": "デスク", "category": "家具", "amount": 15000},
{"product": "チェア", "category": "家具", "amount": 25000}
]
def calculate_category_total(sales):
sales_amount = {}
for sale in sales:
category = sale["category"]
amount = sale["amount"]
# カテゴリがまだ辞書にない場合は0で初期化
if category not in sales_amount:
sales_amount[category] = 0
# そのカテゴリの合計に金額を加算
sales_amount[category] += amount
return sales_amount
print(calculate_category_total(sales))
# 部署ごとの平均給与を計算して辞書で返す
# 期待する出力: {"営業": 375000.0, "開発": 490000.0}
employees = [
{"name": "田中", "department": "営業", "salary": 400000},
{"name": "佐藤", "department": "開発", "salary": 500000},
{"name": "鈴木", "department": "営業", "salary": 350000},
{"name": "高橋", "department": "開発", "salary": 480000}
]
def get_department_average_salary(employees):
average_salary = {}
for employee in employees:
print(employee)
department = employee["department"]
print(department)
salary = employee["salary"]
print(salary)
if department not in average_salary:
average_salary[department] = 0
print(average_salary)
print(len(department))
average_salary[department] += salary
print(len(department))
average_salary[department] = average_salary[department] / len(department)
return average_salary
print(get_department_average_salary(employees))
# 部署ごとの平均給与を計算して辞書で返す
# 期待する出力: {"営業": 375000.0, "開発": 490000.0}
employees = [
{"name": "田中", "department": "営業", "salary": 400000},
{"name": "佐藤", "department": "開発", "salary": 500000},
{"name": "鈴木", "department": "営業", "salary": 350000},
{"name": "高橋", "department": "開発", "salary": 480000},
]
def get_department_average_salary(employees):
department_data = {}
for employee in employees:
department = employee["department"]
salary = employee["salary"]
if department not in department_data:
department_data[department] = {"total": 0, "count": 0}
print(department_data)
department_data[department]["total"] += salary
department_data[department]["count"] += 1
# 平均を計算
result = {}
for dept, data in department_data.items():
print(dept, data)
result[dept] = data["total"] / data["count"]
return result
print(get_department_average_salary(employees))
# 指定されたカテゴリで最も安い本のタイトルを返す
# 例: find_cheapest_in_category(books, "料理") → "料理の基本"
books = [
{"title": "Python入門", "price": 2800, "category": "プログラミング"},
{"title": "データ分析", "price": 3200, "category": "プログラミング"},
{"title": "料理の基本", "price": 1500, "category": "料理"},
{"title": "お菓子作り", "price": 1800, "category": "料理"}
]
def find_cheapest_in_category(books, target_category):
cheapest_price = float("inf") # 無限大で初期化(どんな価格より大きい)
cheapest_title = ""
print(cheapest_price)
print(type(cheapest_price))
for book in books:
# 指定されたカテゴリの本かチェック
if book["category"] == target_category:
# 現在の最安価格より安いかチェック
if book["price"] < cheapest_price:
cheapest_price = book["price"]
print(cheapest_price)
cheapest_title = book["title"]
print(cheapest_title)
return cheapest_title
print(find_cheapest_in_category(books, "プログラミング"))
# 指定された閾値以上の点数の個数を返す
scores = [85, 92, 78, 96, 73, 88, 90]
def count_high_scores(scores, threshold):
high_score = []
for score in scores:
print(score)
if score >= threshold:
high_score.append(score)
return high_score
print(count_high_scores(scores, 85)) # 5個 (85, 92, 96, 88, 90)
print(count_high_scores(scores, 90)) # 3個 (92, 96, 90)
# 指定された文字数の単語の個数を返す
text = "Hello World Python Programming"
def count_words_with_length(text, target_length):
count_words = 0
words = text.split(" ")
for word in words:
if len(word) == target_length:
count_words += 1
return count_words
print(count_words_with_length(text, 5)) # 2個 ("Hello", "World")
print(count_words_with_length(text, 6)) # 1個 ("Python")
# 指定された範囲内(min_val以上、max_val以下)の数字をリストで返す
# 例: find_numbers_in_range(numbers, 10, 20) → [12, 15, 19]
numbers = [12, 7, 23, 4, 15, 8, 19]
def find_numbers_in_range(numbers, min_val, max_val):
range_number = []
for number in numbers:
if min_val <= number <= max_val:
range_number.append(number)
return range_number
print(find_numbers_in_range(numbers, 10, 20))
print(find_numbers_in_range(numbers, 5, 10)) # [7, 8]
# 重複を除いた学生名のリストを返す(順序は最初に出現した順)
# 期待する出力: ["田中", "佐藤", "鈴木", "高橋", "山田"]
students = ["田中", "佐藤", "鈴木", "田中", "高橋", "佐藤", "山田"]
def remove_duplicates(students):
without_duplicates_student_list = []
for student in students:
if student not in without_duplicates_student_list:
without_duplicates_student_list.append(student)
return without_duplicates_student_list
print(remove_duplicates(students))
# 各単語の出現回数を辞書で返す
# 期待する出力: {"python": 2, "programming": 1, "is": 2, "fun": 1, "and": 1, "powerful": 1}
text = "python programming is fun and python is powerful"
def count_word_frequency(text):
word_count = {}
count = 0
words = text.split(" ")
for word in words:
print(word)
if word == word_count[word]:
count += 1
word_count = {word: count}
print(word_count)
return word_count
print(count_word_frequency(text))
text = "python programming is fun and python is powerful"
def count_word_frequency(text):
word_count = {}
words = text.split(" ")
for word in words:
# その単語が辞書にあるかチェック
if word in word_count:
word_count[word] += 1 # 既存の値に1を加算
else:
word_count[word] = 1 # 新しい単語は1で初期化
return word_count
print(count_word_frequency(text))
# 偶数と奇数を分けて辞書で返す
# 期待する出力: {"even": [2, 4, 6, 8, 10], "odd": [1, 3, 5, 7, 9]}
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def separate_even_odd(numbers):
even_and_odd = {}
even_and_odd["even"] = []
even_and_odd["odd"] = []
for number in numbers:
print(number)
if number % 2 == 0:
even_and_odd["even"].append(number)
else:
even_and_odd["odd"].append(number)
return even_and_odd
print(separate_even_odd(numbers))
# 各カテゴリで最も高い商品の情報を辞書で返す
# 期待する出力: {"electronics": {"name": "商品C", "price": 1500}, "books": {"name": "商品B", "price": 500}}
product_data = [
{"name": "商品A", "category": "electronics", "price": 1000},
{"name": "商品B", "category": "books", "price": 500},
{"name": "商品C", "category": "electronics", "price": 1500},
{"name": "商品D", "category": "books", "price": 300}
]
def get_most_expensive_by_category(product_data):
highest_product_info = {}
highest_product_info["name"] = []
highest_product_info["price"] = []
for data in product_data:
category = data["category"]
price = data["price"]
name = data["name"]
if category not in highest_product_info:
highest_product_info[category] =
print(highest_product_info)
print(get_most_expensive_by_category(product_data))

# 部署ごとの平均給与を計算して辞書で返す
# 期待する出力: {"営業": 375000.0, "開発": 490000.0}
employees = [
{"name": "田中", "department": "営業", "salary": 400000},
{"name": "佐藤", "department": "開発", "salary": 500000},
{"name": "鈴木", "department": "営業", "salary": 350000},
{"name": "高橋", "department": "開発", "salary": 480000},
]
def get_department_average_salary(employees):
department_data = {}
for employee in employees:
department = employee["department"]
salary = employee["salary"]
if department not in department_data:
print(department)
department_data[department] = {"total": 0, "count": 0}
print(department_data)
department_data[department]["total"] += salary
department_data[department]["count"] += 1
# 平均を計算
result = {}
for dept, data in department_data.items():
print(dept, data)
result[dept] = data["total"] / data["count"]
return result
print(get_department_average_salary(employees))
# 各カテゴリで最も高い商品の情報を辞書で返す
# 期待する出力: {"electronics": {"name": "商品C", "price": 1500}, "books": {"name": "商品B", "price": 500}}
data = [
{"name": "商品A", "category": "electronics", "price": 1000},
{"name": "商品B", "category": "books", "price": 500},
{"name": "商品C", "category": "electronics", "price": 1500},
{"name": "商品D", "category": "books", "price": 300},
]
def get_most_expensive_by_category(data):
result = {}
for product in data:
print(product)
category = product["category"]
print(category)
if category not in result:
result[category] = product
print(result)
else:
if product["price"] > result[category]["price"]:
result[category] = product
print(result)
# 必要な情報だけを抽出して返す
final_result = {}
for category, product in result.items():
final_result[category] = {"name": product["name"], "price": product["price"]}
print(final_result)
return final_result
print(get_most_expensive_by_category(data))
# 正数と負数を分けて辞書で返す(0は除外)
# 期待する出力: {"positive": [1, 3, 5, 7], "negative": [-2, -4, -6, -8]}
numbers = [1, -2, 3, -4, 5, -6, 7, -8]
def separate_positive_negative(numbers):
integer = {}
integer["positive"] = []
integer["negative"] = []
for number in numbers:
if number >= 0:
integer["positive"].append(number)
else:
integer["negative"].append(number)
return integer
print(separate_positive_negative(numbers))
# 成績の統計情報を辞書で返す(最高点、最低点、平均点、合格者数(80点以上))
# 期待する出力: {"max": 95, "min": 73, "average": 86.0, "passed": 5}
grades = [85, 92, 78, 88, 95, 73, 90, 87]
def get_grade_statistics(grades):
grades_info = {}
# 最大点
grades_info["max"] = []
# 最低点
grades_info["min"] = []
# 平均点
grades_info["average"] = []
# 合格者数
grades_info["passed"] = []
#
grades_info["total"] = []
for grade in grades:
print(grade)
grades_info["total"] += grade
if grade >= 80:
grades_info["average"].append(len(grade))
grades_info["max"].append(max(grades))
grades_info["min"].append(min(grades))
grades_info["total"] += grade
grades_info["count"] += 1
# 平均値
for dept, data in grades.items():
grades_info[dept] = data["total"] / data["count"]
print(get_grade_statistics(grades))
def get_grade_statistics(grades):
result = {}
# 最高点を見つける
result["max"] = max(grades)
# 最低点を見つける
result["min"] = min(grades)
# 平均点を計算
result["average"] = sum(grades) / len(grades)
# 合格者数(80点以上)を数える
passed_count = 0
for grade in grades:
if grade >= 80:
passed_count += 1
result["passed"] = passed_count
return result
temperatures = [22, 25, 18, 30, 27, 19, 24]
def count_comfortable_days(temperatures):
# 快適な気温(20度以上25度以下)の日数を返す
# 期待する出力: 4
print(count_comfortable_days(temperatures))
# 快適な気温(20度以上25度以下)の日数を返す
# 期待する出力: 4
temperatures = [22, 25, 18, 30, 27, 19, 24]
def count_comfortable_days(temperatures):
count = 0
for temperature in temperatures:
if 20 <= temperature <= 25:
count += 1
return count
print(count_comfortable_days(temperatures))
# 指定された文字で始まる単語の個数を返す
# 例: count_words_starting_with(words, "a") → 3
words = ["apple", "banana", "apricot", "blueberry", "avocado"]
def count_words_starting_with(words, letter):
count = 0
for word in words:
if word[0] == letter:
count += 1
return count
print(count_words_starting_with(words, "a"))
print(count_words_starting_with(words, "b"))
# 最も長い文(文字数が多い)の内容を返す
# 期待する出力: "This is another example of a sentence with multiple words in it."
sentences = [
"This is a short sentence.",
"This sentence is a bit longer than the previous one.",
"Short.",
"This is another example of a sentence with multiple words in it."
]
def find_longest_sentence(sentences):
longest_sentences = ""
sentence_number = []
for sentence in sentences:
number = len(sentence)
sentence_number.append(number)
print(sentence_number)
print(max(sentence_number))
if max(sentence_number):
longest_sentences = sentence
return longest_sentences
print(find_longest_sentence(sentences))

# 最も長い文(文字数が多い)の内容を返す
# 期待する出力: "This is another example of a sentence with multiple words in it."
sentences = [
"This is a short sentence.",
"This sentence is a bit longer than the previous one.",
"Short.",
"This is another example of a sentence with multiple words in it.",
]
def find_longest_sentence(sentences):
longest_sentence = ""
max_length = 0
for sentence in sentences:
current_length = len(sentence)
if current_length > max_length:
max_length = current_length
longest_sentence = sentence
return longest_sentence
print(find_longest_sentence(sentences))
# 2番目に大きい数を返す
# 期待する出力: 8
numbers = [3, 7, 2, 9, 1, 8, 5]
def find_second_largest(numbers):
result = sorted(numbers)[-2]
print(result)
print(find_second_largest(numbers))
# 重複を除いた名前のリストを返す(順序は保持)
# 期待する出力: ["Alice", "Bob", "Charlie", "David", "Eve"]
names = ["Alice", "Bob", "Charlie", "Alice", "David", "Bob", "Eve"]
def get_unique_names(names):
new_names = []
for name in names:
current_name = name
if name == current_name:
new_names.append(name)
return new_names
print(get_unique_names(names))
def get_unique_names(names):
unique_names = []
for name in names:
if name not in unique_names: # まだリストにない場合のみ
unique_names.append(name)
return unique_names
print(get_unique_names(names))
# 全ての価格に割引率を適用した新しいリストを返す
# discount_rate は 0.1 = 10%割引を意味する
# 例: apply_discount(prices, 0.1) → [90.0, 225.0, 72.0, 135.0, 270.0, 81.0]
prices = [100, 250, 80, 150, 300, 90]
def apply_discount(prices, discount_rate):
discount_prices = []
for price in prices:
discount_price = price * (1 - discount_rate)
discount_prices.append(discount_price)
return discount_prices
print(apply_discount(prices, 0.1))
# 指定された都市に住む人の名前のリストを返す
# 例: filter_by_city(data, "東京") → ["田中", "鈴木"]
data = [
{"name": "田中", "age": 25, "city": "東京"},
{"name": "佐藤", "age": 30, "city": "大阪"},
{"name": "鈴木", "age": 35, "city": "東京"},
{"name": "高橋", "age": 28, "city": "名古屋"}
]
def filter_by_city(data, target_city):
names = []
for one_data in data:
print(one_data)
target_city = one_data["city"]
print(target_city)
name = one_data["name"]
new_data= {target_city: name}
print(new_data)
print(new_data[target_city])
return names
print(filter_by_city(data, "東京"))
print(filter_by_city(data, "大阪"))
def filter_by_city(data, target_city):
result = []
for person in data:
if person["city"] == target_city:
result.append(person["name"])
return result
# 各科目の合計点を辞書で返す
# 期待する出力: {"数学": 245, "英語": 265, "理科": 245}
scores = {"数学": [80, 75, 90], "英語": [85, 88, 92], "理科": [78, 82, 85]}
def calculate_subject_totals(scores):
for score in scores:
print(score)
print(scores)
total = sum(scores[score])
print(total)
scores[score] = total
print(scores)
return scores
print(calculate_subject_totals(scores))
# 買い物リストの総額を計算する(各商品の quantity × price の合計)
# 期待する出力: 1400 (500 + 450 + 400)
shopping_list = [
{"item": "りんご", "quantity": 5, "price": 100},
{"item": "バナナ", "quantity": 3, "price": 150},
{"item": "オレンジ", "quantity": 2, "price": 200}
]
def calculate_total_cost(shopping_list):
for one_list in shopping_list:
quantity = one_list["quantity"]
print(quantity)
price = one_list["price"]
print(price)
item = one_list["item"]
print(item)
total_price = quantity * price
return total_price
print(calculate_total_cost(shopping_list))
# 履修科目数ごとの学生数をカウントする
# 期待する出力: {3: 1, 2: 1, 4: 1} (3科目:1人、2科目:1人、4科目:1人)
students = [
{"name": "田中", "subjects": ["数学", "英語", "理科"]},
{"name": "佐藤", "subjects": ["数学", "国語"]},
{"name": "鈴木", "subjects": ["英語", "理科", "社会", "国語"]}
]
def count_students_by_subject_count(students):
courses_students = {}
count = 0
for student in students:
name = student["name"]
subject = student["subjects"]
subjects = len(subject)
if name not in courses_students:
courses_students[subjects] = name
return courses_students
print(count_students_by_subject_count(students))
students = [
{"name": "田中", "subjects": ["数学", "英語", "理科"]},
{"name": "佐藤", "subjects": ["数学", "国語"]},
{"name": "鈴木", "subjects": ["英語", "理科", "社会", "国語"]},
]
def count_students_by_subject_count(students):
result = {}
for student in students:
subject_count = len(student["subjects"]) # 科目数を計算
if subject_count not in result:
result[subject_count] = 0 # 初期化
result[subject_count] += 1 # カウントを増やす
return result
print(count_students_by_subject_count(students))
# 午後の気温が最も高い日を返す
# 期待する出力: "火"
temperatures = [
{"day": "月", "morning": 18, "afternoon": 25},
{"day": "火", "morning": 20, "afternoon": 28},
{"day": "水", "morning": 16, "afternoon": 22}
]
def find_hottest_afternoon(temperatures):
result = max(temperatures, key=lambda temperature: temperature["afternoon"])
high_temp_day = result['day']
return high_temp_day
print(find_hottest_afternoon(temperatures))
temperatures = [
{"day": "月", "morning": 18, "afternoon": 25},
{"day": "火", "morning": 20, "afternoon": 28},
{"day": "水", "morning": 16, "afternoon": 22},
]
def find_hottest_afternoon(temperatures):
hottest_day = ""
max_temp = 0
for day_data in temperatures:
afternoon_temp = day_data["afternoon"]
if afternoon_temp > max_temp:
max_temp = afternoon_temp
hottest_day = day_data["day"]
return hottest_day
print(find_hottest_afternoon(temperatures))
# 予算内で購入可能かつ在庫がある商品の名前のリストを返す
products = [
{"name": "商品A", "price": 800, "in_stock": True},
{"name": "商品B", "price": 1200, "in_stock": False},
{"name": "商品C", "price": 600, "in_stock": True},
{"name": "商品D", "price": 1500, "in_stock": True},
{"name": "商品E", "price": 400, "in_stock": False}
]
def get_affordable_available_products(products, budget):
result = []
for product in products:
price = product["price"]
in_stock = product["in_stock"]
if price <= budget and in_stock == True:
result.append(product["name"])
return result
print(get_affordable_available_products(products, 1000)) # ["商品A", "商品C"]
print(get_affordable_available_products(products, 500)) # ["商品C"]
# 予算内で購入可能かつ在庫がある商品の名前のリストを返す
products = [
{"name": "商品A", "price": 800, "in_stock": True},
{"name": "商品B", "price": 1200, "in_stock": False},
{"name": "商品C", "price": 600, "in_stock": True},
{"name": "商品D", "price": 1500, "in_stock": True},
{"name": "商品E", "price": 400, "in_stock": False},
]
def get_affordable_available_products(products, budget):
result = []
for product in products:
price = product["price"]
in_stock = product["in_stock"]
if price <= budget and in_stock == True:
result.append(product["name"])
return result
print(get_affordable_available_products(products, 1000)) # ["商品A", "商品C"]
print(get_affordable_available_products(products, 500)) # ["商品C"]
# 在庫の総価値を計算する(quantity × price の合計、在庫0は除外)
# 期待する出力: 12400 (50×100 + 30×80 + 25×200)
inventory = {
"apple": {"quantity": 50, "price": 100},
"banana": {"quantity": 30, "price": 80},
"orange": {"quantity": 0, "price": 120},
"grape": {"quantity": 25, "price": 200}
}
def get_total_inventory_value(inventory):
total_amount = 0
for stock in inventory.values():
quantity = stock["quantity"]
price = stock["price"]
if quantity > 0:
total = quantity * price
total_amount += total
return total_amount
print(get_total_inventory_value(inventory))
# 勤続年数3年以上の社員を部署別にグループ化して返す
# 期待する出力: {"営業": ["田中"], "開発": ["佐藤", "高橋"], "総務": ["山田"]}
employees = [
{"name": "田中", "department": "営業", "years": 3, "salary": 400000},
{"name": "佐藤", "department": "開発", "years": 5, "salary": 500000},
{"name": "鈴木", "department": "営業", "years": 2, "salary": 350000},
{"name": "高橋", "department": "開発", "years": 7, "salary": 600000},
{"name": "山田", "department": "総務", "years": 4, "salary": 450000}
]
def get_senior_employees_by_department(employees):
result= {}
names = []
for employee in employees:
name = employee["name"]
department = employee["department"]
years = employee["years"]
if name not in names:
names.append(name)
print(names)
if years >= 3:
result[department] = name
return result
print(get_senior_employees_by_department(employees))

employees = [
{"name": "田中", "department": "営業", "years": 3, "salary": 400000},
{"name": "佐藤", "department": "開発", "years": 5, "salary": 500000},
{"name": "鈴木", "department": "営業", "years": 2, "salary": 350000},
{"name": "高橋", "department": "開発", "years": 7, "salary": 600000},
{"name": "山田", "department": "総務", "years": 4, "salary": 450000},
]
def get_senior_employees_by_department(employees):
result = {}
for employee in employees:
name = employee["name"]
department = employee["department"]
years = employee["years"]
# 勤続年数3年以上の場合のみ処理
if years >= 3:
# その部署がまだ辞書にない場合は空リストを作成
if department not in result:
result[department] = []
# その部署のリストに名前を追加
result[department].append(name)
return result
print(get_senior_employees_by_department(employees))
# 指定された単語が出現する位置(インデックス)のリストを返
text = "Hello world this is a test hello world"
def find_word_positions(text, target_word):
target = []
text_list = text.split(" ")
for i, element in enumerate(text_list):
if element == target_word:
target.append(i)
return target
print(find_word_positions(text, "world")) # [1, 7]
print(find_word_positions(text, "hello")) # [0, 6]
# 2回以上出現する数字の個数を返す
# 期待する出力: 3 (2, 3, 4が重複している)
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
def count_duplicates(numbers):
# 各数字の出現回数をカウント
count_dict = {}
for number in numbers:
if number not in count_dict:
count_dict[number] = 0
count_dict[number] += 1
# 2回以上出現する数字の個数をカウント
duplicate_count = 0
for number, count in count_dict.items():
if count >= 2:
duplicate_count += 1
return duplicate_count
print(count_duplicates(numbers))
# 成績の最高点と最低点の差を返す
# 期待する出力: 22 (95 - 73)
grades = [85, 92, 78, 88, 95, 73, 90, 87, 82]
def get_grade_range(grades):
highest_score = max(grades)
lowest_score = min(grades)
between_high_and_low = highest_score - lowest_score
return between_high_and_low
print(get_grade_range(grades))
# 単語を最初の文字でグループ化して辞書で返す
# 期待する出力: {"c": ["cat"], "d": ["dog"], "e": ["elephant"], "a": ["ant"], "b": ["bear"]}
words = ["cat", "dog", "elephant", "ant", "bear"]
def group_by_first_letter(words):
result = {}
for word in words:
first_word = word[0]
result[first_word] = word
return result
print(group_by_first_letter(words))
words = ["cat", "dog", "elephant", "ant", "bear"]
def group_by_first_letter(words):
result = {}
for word in words:
first_letter = word[0]
if first_letter not in result:
result[first_letter] = [] # 空のリストを作成
result[first_letter].append(word) # リストに追加
return result
print(group_by_first_letter(words))
# 指定された価格範囲内の商品価格のリストを返す
# 例: filter_price_range(prices, 100, 150) → [120, 150, 110]
prices = [120, 85, 200, 95, 150, 75, 180, 110]
def filter_price_range(prices, min_price, max_price):
price_within_range = []
for price in prices:
if min_price <= price <= max_price:
price_within_range.append(price)
return price_within_range
print(filter_price_range(prices, 100, 150))
# 各学生の平均点を計算して新しい辞書項目として追加
# 期待する出力: 各辞書に "average" キーが追加される
# 例: {"name": "田中", "math": 85, "english": 78, "science": 92, "average": 85.0}
students = [
{"name": "田中", "math": 85, "english": 78, "science": 92},
{"name": "佐藤", "math": 90, "english": 85, "science": 88},
{"name": "鈴木", "math": 75, "english": 90, "science": 80},
]
def calculate_averages(students):
for student in students:
math = student["math"]
english = student["english"]
science = student["science"]
average = (math + english + science) / 3
student["average"] = average
print(student)
return students
print(calculate_averages(students))
# 各月の利益(売上 - 経費)を計算し、新しいキー "profit" として追加
# さらに、全体の利益合計も計算して返す
# 戻り値: (更新されたリスト, 利益合計)
sales_data = [
{"month": "1月", "revenue": 1000000, "expenses": 600000},
{"month": "2月", "revenue": 1200000, "expenses": 700000},
{"month": "3月", "revenue": 900000, "expenses": 550000},
{"month": "4月", "revenue": 1100000, "expenses": 650000},
]
def calculate_monthly_profit(sales_data):
total_profit = 0
for sale_data in sales_data:
revenue = sale_data["revenue"]
expenses = sale_data["expenses"]
profit = revenue - expenses
sale_data["profit"] = profit
total_profit += profit
return sales_data, total_profit
updated_data, total = calculate_monthly_profit(sales_data)
print("更新されたデータ:", updated_data)
print("利益合計:", total)
# 以下の情報を含む辞書を返す:
# - 各カテゴリの商品数
# - 在庫がある商品の総価値(price × stock の合計)
# - 在庫切れ商品の名前のリスト
products = [
{"name": "商品A", "category": "electronics", "price": 1000, "stock": 5},
{"name": "商品B", "category": "books", "price": 500, "stock": 0},
{"name": "商品C", "category": "electronics", "price": 1500, "stock": 3},
{"name": "商品D", "category": "books", "price": 800, "stock": 2},
{"name": "商品E", "category": "clothing", "price": 2000, "stock": 1},
]
def analyze_inventory(products):
result = {
"category_counts": {},
"total_inventory_value": 0,
"out_of_stock": []
}
category_counts = {}
total_value = 0
out_of_stock = []
for product in products:
name = product["name"]
category = product["category"]
price = product["price"]
stock = product["stock"]
if stock == 0:
out_of_stock.append(name)
elif stock >= 1:
total_inventory_value = price * stock
total_value += total_inventory_value
result["category_counts"] = category_counts
result["total_inventory_value"] = total_value
result["out_of_stock"] = out_of_stock
return result
print(analyze_inventory(products))
# 以下の情報を含む辞書を返す:
# - 各カテゴリの商品数
# - 在庫がある商品の総価値(price × stock の合計)
# - 在庫切れ商品の名前のリスト
products = [
{"name": "商品A", "category": "electronics", "price": 1000, "stock": 5},
{"name": "商品B", "category": "books", "price": 500, "stock": 0},
{"name": "商品C", "category": "electronics", "price": 1500, "stock": 3},
{"name": "商品D", "category": "books", "price": 800, "stock": 2},
{"name": "商品E", "category": "clothing", "price": 2000, "stock": 1},
]
def analyze_inventory(products):
result = {"category_counts": {}, "total_inventory_value": 0, "out_of_stock": []}
for product in products:
category = product["category"]
price = product["price"]
stock = product["stock"]
name = product["name"]
# カテゴリをカウント
if category not in result["category_counts"]:
result["category_counts"][category] = 0
result["category_counts"][category] += 1
# 在庫チェック
if stock == 0:
result["out_of_stock"].append(name)
else:
result["total_inventory_value"] += price * stock
return result
print(analyze_inventory(products))
# 各顧客の注文回数と総購入金額を計算
# 期待する出力: {"田中": {"count": 2, "total": 3700}, "佐藤": {"count": 1, "total": 800}, "鈴木": {"count": 1, "total": 600}}
orders = [
{"customer": "田中", "items": ["商品A", "商品B"], "total": 1500},
{"customer": "佐藤", "items": ["商品C"], "total": 800},
{"customer": "田中", "items": ["商品D", "商品E", "商品F"], "total": 2200},
{"customer": "鈴木", "items": ["商品A"], "total": 600}
]
def analyze_customer_orders(orders):
result = {}
count_and_total = {"count": 0, "total": 0}
for order in orders:
customer = order["customer"]
total = order["total"]
if customer not in result:
result[customer] = count_and_total
count_and_total["count"] = 0
count_and_total["count"] += 1
count_and_total["total"] += total
return result
print(analyze_customer_orders(orders))

orders = [
{"customer": "田中", "items": ["商品A", "商品B"], "total": 1500},
{"customer": "佐藤", "items": ["商品C"], "total": 800},
{"customer": "田中", "items": ["商品D", "商品E", "商品F"], "total": 2200},
{"customer": "鈴木", "items": ["商品A"], "total": 600},
]
def analyze_customer_orders(orders):
result = {}
for order in orders:
customer = order["customer"]
total = order["total"]
if customer not in result:
# 各顧客ごとに新しい辞書を作成
result[customer] = {"count": 0, "total": 0}
# その顧客の値を更新
result[customer]["count"] += 1
result[customer]["total"] += total
return result
print(analyze_customer_orders(orders))
# 初期残高から全取引を処理して最終残高を返す
# deposit(預金)は残高を増やし、withdrawal(引出し)は残高を減らす
# 期待する出力: 1800 (0 + 1000 - 300 + 500 - 200 + 800)
transactions = [
{"type": "deposit", "amount": 1000},
{"type": "withdrawal", "amount": 300},
{"type": "deposit", "amount": 500},
{"type": "withdrawal", "amount": 200},
{"type": "deposit", "amount": 800}
]
def calculate_balance(transactions, initial_balance=0):
for transaction in transactions:
type_money = transaction["type"]
amount = transaction["amount"]
if type_money == "deposit":
initial_balance += amount
else :
initial_balance -= amount
return initial_balance
print(calculate_balance(transactions))
print(calculate_balance(transactions, 500)) # 初期残高500の場合: 2300
# 最も給与が高い社員の情報を返す
# 期待する出力: {"name": "高橋", "department": "開発", "salary": 600000, "years": 7}
employees = [
{"name": "田中", "department": "営業", "salary": 400000, "years": 3},
{"name": "佐藤", "department": "開発", "salary": 500000, "years": 5},
{"name": "鈴木", "department": "営業", "salary": 350000, "years": 2},
{"name": "高橋", "department": "開発", "salary": 600000, "years": 7},
{"name": "山田", "department": "総務", "salary": 450000, "years": 4}
]
def find_highest_paid_employee(employees):
result = {}
max_salary = 0
for employee in employees:
salary = employee["salary"]
if salary >= max_salary:
max_salary = salary
result = employee
return result
print(find_highest_paid_employee(employees))
# ページ数で書籍を分類する
# 短い(200未満), 普通(200以上300未満), 長い(300以上)
# 期待する出力: {"短い": [本のタイトルのリスト], "普通": [...], "長い": [...]}
books = [
{"title": "Python入門", "author": "田中", "pages": 200, "genre": "技術書"},
{"title": "データ分析", "author": "佐藤", "pages": 350, "genre": "技術書"},
{"title": "小説A", "author": "鈴木", "pages": 180, "genre": "小説"},
{"title": "料理本", "author": "高橋", "pages": 120, "genre": "実用書"},
{"title": "小説B", "author": "山田", "pages": 220, "genre": "小説"}
]
def categorize_books_by_length(books):
result = {}
for book in books:
title = book["title"]
pages = book["pages"]
if pages < 200:
short = []
short.append(title)
result["短い"] = short
elif 200 <= pages < 300:
middle = []
middle.append(title)
result["普通"] = middle
elif pages >= 300:
long = []
long.append(title)
result["長い"] = long
return result
print(categorize_books_by_length(books))
books = [
{"title": "Python入門", "author": "田中", "pages": 200, "genre": "技術書"},
{"title": "データ分析", "author": "佐藤", "pages": 350, "genre": "技術書"},
{"title": "小説A", "author": "鈴木", "pages": 180, "genre": "小説"},
{"title": "料理本", "author": "高橋", "pages": 120, "genre": "実用書"},
{"title": "小説B", "author": "山田", "pages": 220, "genre": "小説"},
]
def categorize_books_by_length(books):
result = {}
for book in books:
title = book["title"]
pages = book["pages"]
if pages < 200:
category = "短い"
elif 200 <= pages < 300:
category = "普通"
else:
category = "長い"
if category not in result:
result[category] = []
result[category].append(title)
return result
print(categorize_books_by_length(books))
# 快適な天候の都市を見つける
# 条件: 気温が20-28度、湿度が70%未満、天候が晴れ
# 期待する出力: ["東京"]
weather_data = [
{"city": "東京", "temperature": 25, "humidity": 60, "condition": "晴れ"},
{"city": "大阪", "temperature": 28, "humidity": 70, "condition": "曇り"},
{"city": "名古屋", "temperature": 22, "humidity": 55, "condition": "雨"},
{"city": "福岡", "temperature": 30, "humidity": 80, "condition": "晴れ"},
{"city": "札幌", "temperature": 18, "humidity": 50, "condition": "晴れ"}
]
def find_pleasant_weather_cities(weather_data):
cities = []
for data in weather_data:
temperature = data["temperature"]
humidity = data["humidity"]
condition = data["condition"]
if 20 <= temperature <= 28 and humidity < 70 and condition == "晴れ":
cities.append(data["city"])
return cities
print(find_pleasant_weather_cities(weather_data))
# 在庫状況のサマリーを返す
# - 各カテゴリの商品数
# - 在庫がある商品の平均価格
# - 在庫切れ商品数
# 戻り値例: {"categories": {"electronics": 2, "books": 2, "clothing": 1}, "avg_price": 114.0, "out_of_stock": 1}
inventory = [
{"product": "商品A", "price": 100, "stock": 5, "category": "electronics"},
{"product": "商品B", "price": 200, "stock": 0, "category": "books"},
{"product": "商品C", "price": 150, "stock": 3, "category": "electronics"},
{"product": "商品D", "price": 80, "stock": 10, "category": "clothing"},
{"product": "商品E", "price": 120, "stock": 2, "category": "books"}
]
def get_inventory_summary(inventory):
result = {}
for info in inventory:
price = info["price"]
stock = info["stock"]
category = info["category"]
if category not in result:
result["categories"] = {category: 0}
result["categories"][category] += 1
result.update()
# if stock == 0:
# result["out_of_stock"] += 1
# else:
# total = price * stock
# average = total / len()
return result
print(get_inventory_summary(inventory))
inventory = [
{"product": "商品A", "price": 100, "stock": 5, "category": "electronics"},
{"product": "商品B", "price": 200, "stock": 0, "category": "books"},
{"product": "商品C", "price": 150, "stock": 3, "category": "electronics"},
{"product": "商品D", "price": 80, "stock": 10, "category": "clothing"},
{"product": "商品E", "price": 120, "stock": 2, "category": "books"},
]
def get_inventory_summary(inventory):
result = {"categories": {}, "avg_price": 0, "out_of_stock": 0}
in_stock_prices = [] # 在庫ありの商品価格を記録
for item in inventory:
category = item["category"]
price = item["price"]
stock = item["stock"]
# 1. カテゴリ別商品数
if category not in result["categories"]:
result["categories"][category] = 0
result["categories"][category] += 1
# 2. 在庫切れ商品数
if stock == 0:
result["out_of_stock"] += 1
else:
# 3. 在庫ありの商品価格を記録
in_stock_prices.append(price)
# 平均価格計算
if in_stock_prices:
result["avg_price"] = sum(in_stock_prices) / len(in_stock_prices)
return result
print(get_inventory_summary(inventory))
# 平均点が最も高い学生の名前を返す
# 期待する出力: "鈴木"
students = [
{"name": "田中", "scores": [80, 85, 90]},
{"name": "佐藤", "scores": [70, 75, 80]},
{"name": "鈴木", "scores": [90, 95, 85]}
]
def find_top_student(students):
average_top_name = ""
max_average_score = 0
for student in students:
name = student["name"]
scores = student["scores"]
average_score = sum(scores) / len(scores)
if average_score > max_average_score:
max_average_score = average_score
average_top_name = name
return average_top_name
print(find_top_student(students))
# 各顧客の注文統計を返す
# - 注文回数
# - 完了した注文回数
# - 注文した商品の総数
# 期待する出力: {"田中": {"total": 2, "completed": 2, "items": 3}, "佐藤": {...}, "鈴木": {...}}
orders = [
{"id": 1, "customer": "田中", "items": ["商品A", "商品B"], "status": "completed"},
{"id": 2, "customer": "佐藤", "items": ["商品C"], "status": "pending"},
{"id": 3, "customer": "田中", "items": ["商品D"], "status": "completed"},
{"id": 4, "customer": "鈴木", "items": ["商品A", "商品E"], "status": "cancelled"},
{"id": 5, "customer": "佐藤", "items": ["商品F"], "status": "completed"}
]
def get_customer_order_stats(orders):
result = {}
for order in orders:
items = order["items"]
customer = order["customer"]
status = order["status"]
if customer not in result:
result[customer] = {"total": 0, "completed": 0, "items": 0}
if status == "completed":
result[customer]["completed"] += 1
result[customer]["total"] += 1
result[customer]["items"] += len(items)
return result
print(get_customer_order_stats(orders))
# 各カテゴリで評価平均が最も高い商品を返す
# 期待する出力: {"electronics": "商品C", "books": "商品B"}
products = [
{"name": "商品A", "category": "electronics", "price": 1000, "ratings": [4, 5, 3, 4, 5]},
{"name": "商品B", "category": "books", "price": 500, "ratings": [3, 3, 4, 2, 3]},
{"name": "商品C", "category": "electronics", "price": 1500, "ratings": [5, 4, 5, 5, 4]},
{"name": "商品D", "category": "books", "price": 800, "ratings": [2, 3, 2, 1, 2]}
]
def find_best_product_by_category(products):
result = {}
top_average_rating = 0
for product in products:
name = product["name"]
category = product["category"]
ratings = product["ratings"]
average_rating = sum(ratings) / len(ratings)
if average_rating > top_average_rating:
top_average_rating = average_rating
result[category] = name
if category not in result:
result[category] = name
return result
print(find_best_product_by_category(products))
def find_best_product_by_category(products):
result = {}
category_best = {} # カテゴリごとの最高評価を記録
for product in products:
name = product["name"]
category = product["category"]
ratings = product["ratings"]
average_rating = sum(ratings) / len(ratings)
# そのカテゴリが初回出現 or より高い評価の場合
if category not in category_best or average_rating > category_best[category]:
category_best[category] = average_rating
result[category] = name
return result
# 日付ごとの売上合計と取引件数を計算
# 売上 = quantity × unit_price
# 期待する出力: {"2024-01-15": {"total": 4400, "count": 2}, "2024-01-16": {"total": 3500, "count": 2}, "2024-01-17": {"total": 1000, "count": 1}}
sales_records = [
{"date": "2024-01-15", "salesperson": "田中", "product": "商品A", "quantity": 2, "unit_price": 1000},
{"date": "2024-01-16", "salesperson": "佐藤", "product": "商品B", "quantity": 1, "unit_price": 1500},
{"date": "2024-01-15", "salesperson": "田中", "product": "商品C", "quantity": 3, "unit_price": 800},
{"date": "2024-01-17", "salesperson": "鈴木", "product": "商品A", "quantity": 1, "unit_price": 1000},
{"date": "2024-01-16", "salesperson": "佐藤", "product": "商品A", "quantity": 2, "unit_price": 1000}
]
def calculate_daily_sales_summary(sales_records):
result = {}
for sales_record in sales_records:
date = sales_record["date"]
quantity = sales_record["quantity"]
unit_price = sales_record["unit_price"]
if date not in result:
result[date] = {"total": 0, "count": 0}
sales = quantity * unit_price
result[date]["total"] += sales
result[date]["count"] += 1
return result
print(calculate_daily_sales_summary(sales_records))
# 各担当者の未完了高優先度タスク数を返す
# 期待する出力: {"田中": 1, "佐藤": 0, "鈴木": 0}
tasks = [
{"id": 1, "title": "タスクA", "priority": "high", "completed": True, "assigned_to": "田中"},
{"id": 2, "title": "タスクB", "priority": "medium", "completed": False, "assigned_to": "佐藤"},
{"id": 3, "title": "タスクC", "priority": "high", "completed": False, "assigned_to": "田中"},
{"id": 4, "title": "タスクD", "priority": "low", "completed": True, "assigned_to": "鈴木"},
{"id": 5, "title": "タスクE", "priority": "medium", "completed": False, "assigned_to": "佐藤"}
]
def get_task_statistics(tasks):
result = {}
for task in tasks:
priority = task["priority"]
assigned_to = task["assigned_to"]
completed = task["completed"]
if assigned_to not in result and priority == "high" and completed == False:
result[assigned_to] = 0 + 1
return result
print(get_task_statistics(tasks))
tasks = [
{"id": 1, "title": "タスクA", "priority": "high", "completed": True, "assigned_to": "田中"},
{"id": 2, "title": "タスクB", "priority": "medium", "completed": False, "assigned_to": "佐藤"},
{"id": 3, "title": "タスクC", "priority": "high", "completed": False, "assigned_to": "田中"},
{"id": 4, "title": "タスクD", "priority": "low", "completed": True, "assigned_to": "鈴木"},
{"id": 5, "title": "タスクE", "priority": "medium", "completed": False, "assigned_to": "佐藤"}
]
def get_task_statistics(tasks):
result = {}
for task in tasks:
priority = task["priority"]
assigned_to = task["assigned_to"]
completed = task["completed"]
# 担当者が初回出現の場合は0で初期化
if assigned_to not in result:
result[assigned_to] = 0
# 高優先度かつ未完了の場合にカウント
if priority == "high" and completed == False:
result[assigned_to] += 1
return result
print(get_task_statistics(tasks))
# 同じ部屋で時間が重複している会議のペアを見つける
from datetime import datetime
events = [
{"name": "会議A", "start": "09:00", "end": "10:30", "room": "会議室1"},
{"name": "会議B", "start": "10:00", "end": "11:00", "room": "会議室2"},
{"name": "会議C", "start": "11:00", "end": "12:00", "room": "会議室1"},
{"name": "会議D", "start": "10:30", "end": "12:30", "room": "会議室1"},
]
# 時刻文字列をtime オブジェクトに変換
start_time = datetime.strptime("09:00", "%H:%M").time()
end_time = datetime.strptime("10:30", "%H:%M").time()
# 分に変換する関数
def time_to_minutes(time_str):
hours, minutes = map(int, time_str.split(":"))
return hours * 60 + minutes
def find_room_conflicts(events):
def time_to_minutes(time_str):
hours, minutes = map(int, time_str.split(":"))
return hours * 60 + minutes
def times_overlap(start1, end1, start2, end2):
return not (end1 <= start2 or start2 >= end1)
conflicts = []
for i in range(len(events)):
for j in range(i + 1, len(events)):
event1 = events[i]
event2 = events[j]
# 同じ部屋かチェック
if event1["room"] == event2["room"]:
start1 = time_to_minutes(event1["start"])
end1 = time_to_minutes(event1["end"])
start2 = time_to_minutes(event2["start"])
end2 = time_to_minutes(event2["end"])
if times_overlap(start1, end1, start2, end2):
conflicts.append((event1["name"], event2["name"]))
return conflicts
print(find_room_conflicts(events))
# 部活別の学生数をカウント
# 期待する出力: {"テニス部": 2, "バスケ部": 1, "サッカー部": 1}
students = [
{"name": "田中", "age": 20, "grade": 85, "club": "テニス部"},
{"name": "佐藤", "age": 19, "grade": 92, "club": "バスケ部"},
{"name": "鈴木", "age": 21, "grade": 78, "club": "テニス部"},
{"name": "高橋", "age": 20, "grade": 88, "club": "サッカー部"}
]
def count_students_by_club(students):
result = {}
for student in students:
club = student["club"]
if club not in result:
result[club] = 0
result[club] += 1
return result
print(count_students_by_club(students))

# 各商品の割引後価格を計算してリストで返す
# 期待する出力: [900, 1600, 1500, 680]
products = [
{"name": "商品A", "price": 1000, "discount": 10}, # 10%割引
{"name": "商品B", "price": 2000, "discount": 20}, # 20%割引
{"name": "商品C", "price": 1500, "discount": 0}, # 割引なし
{"name": "商品D", "price": 800, "discount": 15} # 15%割引
]
def calculate_discounted_prices(products):
result = []
for product in products:
price = product["price"]
discount = product["discount"]
discount_price = price * (1 - discount / 100)
result.append(discount_price)
return result
print(calculate_discounted_prices(products))
# 部署別の給与総額を計算
# 期待する出力: {"営業": 750000, "開発": 1100000}
employees = [
{"name": "田中", "salary": 400000, "department": "営業"},
{"name": "佐藤", "salary": 500000, "department": "開発"},
{"name": "鈴木", "salary": 350000, "department": "営業"},
{"name": "高橋", "salary": 600000, "department": "開発"}
]
def calculate_department_budgets(employees):
result = {}
for employee in employees:
salary = employee["salary"]
department = employee["department"]
if department not in result:
result[department] = 0
result[department] += salary
return result
print(calculate_department_budgets(employees))
# 顧客別の完了注文の売上合計を計算
# 期待する出力: {"田中": 2300, "佐藤": 1800}
orders = [
{"customer": "田中", "amount": 1500, "status": "completed"},
{"customer": "佐藤", "amount": 2000, "status": "pending"},
{"customer": "田中", "amount": 800, "status": "completed"},
{"customer": "鈴木", "amount": 1200, "status": "cancelled"},
{"customer": "佐藤", "amount": 1800, "status": "completed"}
]
def calculate_completed_revenue_by_customer(orders):
result = {}
for order in orders:
customer = order["customer"]
amount = order["amount"]
status = order["status"]
if status == "completed":
if customer not in result:
result[customer] = 0
result[customer] += amount
return result
print(calculate_completed_revenue_by_customer(orders))
# 指定された評価以上の映画タイトルのリストを返す
# 例: find_high_rated_movies(movies, 4.0) → ["映画A", "映画C"]
movies = [
{"title": "映画A", "genre": "アクション", "rating": 4.2, "year": 2020},
{"title": "映画B", "genre": "コメディ", "rating": 3.8, "year": 2019},
{"title": "映画C", "genre": "アクション", "rating": 4.6, "year": 2021},
{"title": "映画D", "genre": "ドラマ", "rating": 3.9, "year": 2020}
]
def find_high_rated_movies(movies, min_rating):
result = []
for movie in movies:
title = movie["title"]
rating = movie["rating"]
if rating >= min_rating:
result.append(title)
return result
print(find_high_rated_movies(movies, 4.0))
# カテゴリ別の在庫総額(price × quantity の合計)を計算
# 期待する出力: {"果物": 1140, "野菜": 1170}
items = [
{"name": "りんご", "price": 100, "quantity": 5, "category": "果物"},
{"name": "みかん", "price": 80, "quantity": 8, "category": "果物"},
{"name": "キャベツ", "price": 150, "quantity": 3, "category": "野菜"},
{"name": "にんじん", "price": 120, "quantity": 6, "category": "野菜"}
]
def calculate_category_totals(items):
result = {}
for item in items:
category = item["category"]
price = item["price"]
quantity = item["quantity"]
if category not in result:
result[category] = 0
total = price * quantity
result[category] += total
return result
print(calculate_category_totals(items))
# 指定された科目で指定された点数以上の学生名のリストを返す
students = [
{"name": "田中", "math": 85, "english": 78, "science": 92},
{"name": "佐藤", "math": 90, "english": 85, "science": 88},
{"name": "鈴木", "math": 75, "english": 90, "science": 80},
{"name": "高橋", "math": 88, "english": 82, "science": 85}
]
def find_students_above_average(students, subject, threshold):
result = []
for student in students:
name = student["name"]
if student[subject] >= threshold:
result.append(name)
return result
print(find_students_above_average(students, "math", 85)) # ["田中", "佐藤", "高橋"]
print(find_students_above_average(students, "english", 85)) # ["佐藤", "鈴木"]
# 指定された商品の売上が最も高い月を返す
sales = [
{"month": "1月", "product_a": 100, "product_b": 150, "product_c": 80},
{"month": "2月", "product_a": 120, "product_b": 140, "product_c": 90},
{"month": "3月", "product_a": 110, "product_b": 160, "product_c": 85}
]
def find_best_month_for_product(sales, product):
result = ""
max_sales = 0
for sale in sales:
month = sale["month"]
current_sales = sale[product]
if current_sales > max_sales:
max_sales = current_sales
result = month
return result
print(find_best_month_for_product(sales, "product_b")) # "3月"
print(find_best_month_for_product(sales, "product_a")) # "2月"
# 以下の情報を含む辞書を返す:
# - 職種別の人数
# - 職種別の平均給与
# 期待する出力: {"counts": {"manager": 2, "engineer": 2, "designer": 1},
# "avg_salaries": {"manager": 475000.0, "engineer": 390000.0, "designer": 420000.0}}
employees = [
{"name": "田中", "position": "manager", "salary": 500000, "years": 5},
{"name": "佐藤", "position": "engineer", "salary": 400000, "years": 3},
{"name": "鈴木", "position": "manager", "salary": 450000, "years": 2},
{"name": "高橋", "position": "engineer", "salary": 380000, "years": 1},
{"name": "山田", "position": "designer", "salary": 420000, "years": 4}
]
def analyze_employee_data(employees):
result = {}
occupations = {}
average = {}
for employee in employees:
position = employee["position"]
salary = employee["salary"]
if position not in occupations:
occupations[position] = 0
occupations[position] += 1
print(occupations)
if position not in average:
average[position] = 0
average[position] += salary
result["count"] = occupations
result["avg_salaries"] = average
return result
print(analyze_employee_data(employees))
def analyze_employee_data(employees):
result = {}
counts = {}
salary_totals = {}
# 1. データ収集フェーズ
for employee in employees:
position = employee["position"]
salary = employee["salary"]
# 人数カウント
if position not in counts:
counts[position] = 0
counts[position] += 1
# 給与合計
if position not in salary_totals:
salary_totals[position] = 0
salary_totals[position] += salary
# 2. 平均計算フェーズ
avg_salaries = {}
for position in counts:
avg_salaries[position] = salary_totals[position] / counts[position]
result["counts"] = counts
result["avg_salaries"] = avg_salaries
return result

# 指定された最低価格以上で、指定されたページ数以下の本のタイトルリストを返す
books = [
{"title": "Python入門", "author": "田中", "price": 2800, "pages": 300, "genre": "技術書"},
{"title": "データ分析", "author": "佐藤", "price": 3200, "pages": 450, "genre": "技術書"},
{"title": "小説A", "author": "鈴木", "price": 1200, "pages": 250, "genre": "小説"},
{"title": "料理本", "author": "高橋", "price": 1500, "pages": 180, "genre": "実用書"},
{"title": "小説B", "author": "山田", "price": 1000, "pages": 200, "genre": "小説"}
]
def find_books_by_criteria(books, min_price, max_pages):
result = []
for book in books:
title = book["title"]
price = book["price"]
pages = book["pages"]
if price >= min_price and pages <= max_pages:
result.append(title)
return result
print(find_books_by_criteria(books, 1500, 300)) # ["Python入門", "料理本", "小説B"]
print(find_books_by_criteria(books, 2000, 400)) # ["Python入門", "データ分析"]
# 在庫があるカテゴリ別商品名のリストを返す
# 期待する出力: {"electronics": ["商品A", "商品C"], "clothing": ["商品D"]}
products = [
{"name": "商品A", "category": "electronics", "price": 1000, "stock": 5},
{"name": "商品B", "category": "books", "price": 800, "stock": 0},
{"name": "商品C", "category": "electronics", "price": 1200, "stock": 3},
{"name": "商品D", "category": "clothing", "price": 600, "stock": 8}
]
def get_available_products_by_category(products):
result = {}
product_list = []
for product in products:
name = product["name"]
category = product["category"]
if category not in result:
product_list = []
product_list.append(name)
result[category] = product_list
return result
print(get_available_products_by_category(products))
def get_available_products_by_category(products):
result = {}
for product in products:
name = product["name"]
category = product["category"]
stock = product["stock"]
# 在庫がある場合のみ処理
if stock > 0:
# そのカテゴリが初回の場合は空リストを作成
if category not in result:
result[category] = []
# そのカテゴリのリストに商品名を追加
result[category].append(name)
return result
# 日付別のユニークな顧客数を返す
# 期待する出力: {"2024-01-15": 2, "2024-01-16": 2, "2024-01-17": 1}
orders = [
{"id": 1, "customer": "田中", "amount": 1500, "date": "2024-01-15"},
{"id": 2, "customer": "佐藤", "amount": 2000, "date": "2024-01-15"},
{"id": 3, "customer": "田中", "amount": 800, "date": "2024-01-16"},
{"id": 4, "customer": "鈴木", "amount": 1200, "date": "2024-01-16"},
{"id": 5, "customer": "佐藤", "amount": 1800, "date": "2024-01-17"}
]
def get_daily_customer_count(orders):
result = {}
for order in orders:
date = order["date"]
if date not in result:
result[date] = 0
result[date] += 1
return result
print(get_daily_customer_count(orders))
# 点数を範囲別に分類してカウント
# A(90以上), B(80-89), C(70-79), D(70未満)
# 期待する出力: {"A": 3, "B": 3, "C": 2, "D": 0}
scores = [85, 92, 78, 88, 95, 73, 90, 87]
def count_score_ranges(scores):
result = {"A": 0, "B": 0, "C": 0, "D": 0}
for score in scores:
if score >= 90:
result["A"] += 1
elif 80 <= score <= 89:
result["B"] += 1
elif 70 <= score <= 79:
result["C"] += 1
elif score < 70:
result["D"] += 1
return result
print(count_score_ranges(scores))
def count_score_ranges(scores):
ranges = [(90, "A"), (80, "B"), (70, "C"), (0, "D")]
result = {"A": 0, "B": 0, "C": 0, "D": 0}
for score in scores:
for min_score, grade in ranges:
if score >= min_score:
result[grade] += 1
break
return result
# 指定された最小在庫を下回る商品名のリストを返す
# 例: get_restock_needed(inventory, 7) → ["banana", "orange"]
inventory = [
{"item": "apple", "quantity": 10, "price": 100},
{"item": "banana", "quantity": 5, "price": 80},
{"item": "orange", "quantity": 0, "price": 120},
{"item": "grape", "quantity": 8, "price": 200}
]
def get_restock_needed(inventory, minimum_stock):
result = []
for product_info in inventory:
item = product_info["item"]
quantity = product_info["quantity"]
if quantity < minimum_stock:
result.append(item)
return result
print(get_restock_needed(inventory, 7))
# 送信者別のメッセージ数をカウント
# 期待する出力: {"田中": 2, "佐藤": 1, "鈴木": 1}
messages = [
{"sender": "田中", "content": "おはよう", "timestamp": "09:00"},
{"sender": "佐藤", "content": "お疲れ様", "timestamp": "17:30"},
{"sender": "田中", "content": "ありがとう", "timestamp": "18:00"},
{"sender": "鈴木", "content": "明日の会議", "timestamp": "20:00"}
]
def count_messages_per_sender(messages):
result = {}
for message in messages:
sender = message["sender"]
if sender not in result:
result[sender] = 0
result[sender] += 1
return result
print(count_messages_per_sender(messages))
# カテゴリ別の支出合計を計算
# 期待する出力: {"食費": 5500, "交通費": 1500, "娯楽費": 4000}
expenses = [
{"category": "食費", "amount": 3000, "date": "2024-01-15"},
{"category": "交通費", "amount": 1500, "date": "2024-01-15"},
{"category": "食費", "amount": 2500, "date": "2024-01-16"},
{"category": "娯楽費", "amount": 4000, "date": "2024-01-16"}
]
def get_total_by_category(expenses):
result = {}
for expense in expenses:
category = expense["category"]
amount = expense["amount"]
if category not in result:
result[category] = 0
result[category] += amount
return result
print(get_total_by_category(expenses))
# 指定された評価と最小レビュー数の両方を満たす商品名のリストを返す
# 例: find_popular_products(products, 4.0, 10) → ["商品A", "商品C"]
products = [
{"name": "商品A", "price": 1000, "rating": 4.2, "reviews": 15},
{"name": "商品B", "price": 800, "rating": 3.8, "reviews": 8},
{"name": "商品C", "price": 1200, "rating": 4.6, "reviews": 22},
{"name": "商品D", "price": 600, "rating": 3.5, "reviews": 5}
]
def find_popular_products(products, min_rating, min_reviews):
result = []
for product in products:
name = product["name"]
rating = product["rating"]
reviews = product["reviews"]
if rating >= min_rating and reviews >= min_reviews:
result.append(name)
return result
print(find_popular_products(products, 4.0, 10))
# 参加者数で分類(小: 10人未満、中: 10-20人、大: 20人超)
# 期待する出力: {"小": ["会議A", "会議C"], "中": ["会議B"], "大": ["研修D"]}
events = [
{"name": "会議A", "attendees": 5, "duration": 60, "room": "会議室1"},
{"name": "会議B", "attendees": 12, "duration": 90, "room": "会議室2"},
{"name": "会議C", "attendees": 8, "duration": 45, "room": "会議室1"},
{"name": "研修D", "attendees": 20, "duration": 120, "room": "研修室"}
]
def classify_events_by_size(events):
result = {}
for event in events:
name = event["name"]
attendee = event["attendees"]
if attendee >= 20:
name_list = []
name_list.append(name)
result["大"] = []
elif 10 <= attendee < 20:
name_list = []
name_list.append(name)
result["大"] = []
elif attendee < 10:
name_list = []
name_list.append(name)
result["大"] = []
return result
print(classify_events_by_size(events))
def classify_events_by_size(events):
result = {"小": [], "中": [], "大": []}
for event in events:
name = event["name"]
attendees = event["attendees"]
if attendees < 10:
result["小"].append(name)
elif 10 <= attendees <= 20:
result["中"].append(name)
else: # attendees > 20
result["大"].append(name)
return result
# 各学生の総得点と平均試行回数を計算
# 期待する出力: {"田中": {"total_score": 163, "avg_attempts": 1.5}, "佐藤": {...}, "鈴木": {...}}
quiz_results = [
{"student": "田中", "subject": "数学", "score": 85, "attempts": 2},
{"student": "田中", "subject": "英語", "score": 78, "attempts": 1},
{"student": "佐藤", "subject": "数学", "score": 92, "attempts": 1},
{"student": "佐藤", "subject": "英語", "score": 88, "attempts": 3},
{"student": "鈴木", "subject": "数学", "score": 76, "attempts": 2}
]
def get_student_performance(quiz_results):
result = {}
total_attempts = 0
for quiz_result in quiz_results:
student = quiz_result["student"]
score = quiz_result["score"]
attempts = quiz_result["attempts"]
if student not in result:
result[student] = {"total_score": 0, "avg_attempts": 0}
result[student]["total_score"] += score
total_attempts += attempts
result[student]["avg_attempts"] = total_attempts /
return result
print(get_student_performance(quiz_results))
def get_student_performance(quiz_results):
result = {}
# データ収集フェーズ
for quiz_result in quiz_results:
student = quiz_result["student"]
score = quiz_result["score"]
attempts = quiz_result["attempts"]
if student not in result:
result[student] = {
"total_score": 0,
"total_attempts": 0,
"subject_count": 0,
}
result[student]["total_score"] += score
result[student]["total_attempts"] += attempts
result[student]["subject_count"] += 1
# 平均計算フェーズ
for student in result:
avg_attempts = (
result[student]["total_attempts"] / result[student]["subject_count"]
)
result[student]["avg_attempts"] = avg_attempts
# 不要なデータを削除
del result[student]["total_attempts"]
del result[student]["subject_count"]
return result