Python

【無料】Pythonのプログラミング問題集を50問の答え

前回のプログラミング問題集50問の解答を示します。

初級編

  1. 変数aに5を代入し、変数bに10を代入して、abの合計を出力してください。
a = 5
b = 10
print(a + b)  # 出力: 15

2.リスト[1, 2, 3, 4, 5]のすべての要素を表示してください。

my_list = [1, 2, 3, 4, 5]
for item in my_list:
    print(item)

3.文字列"Hello, World!"を逆順に表示してください。

s = "Hello, World!"
print(s[::-1])  # 出力: !dlroW ,olleH

4.整数のリスト[1, 2, 3, 4, 5]の合計を求めてください。

my_list = [1, 2, 3, 4, 5]
print(sum(my_list))  # 出力: 15

5.文字列"Python"の各文字を一行ずつ表示してください。

s = "Python"
for char in s:
    print(char)

6.変数xに数値を入力し、その数値が正の数か負の数かを判定してください。

x = int(input("Enter a number: "))
if x > 0:
    print("Positive")
elif x < 0:
    print("Negative")
else:
    print("Zero")

7.リスト[1, 2, 3, 4, 5]の最大値を求めてください。

my_list = [1, 2, 3, 4, 5]
print(max(my_list))  # 出力: 5

8.リスト[1, 2, 3, 4, 5]の最小値を求めてください。

my_list = [1, 2, 3, 4, 5]
print(min(my_list))  # 出力: 1

9.1から10までの数値を表示してください(ループを使用)。

for i in range(1, 11):
    print(i)

10.1から10までの偶数を表示してください(ループを使用)。

for i in range(2, 11, 2):
    print(i)

中級編

  1. 与えられた文字列が回文かどうかを判定する関数を作成してください。
def is_palindrome(s):
    return s == s[::-1]

print(is_palindrome("madam"))  # 出力: True
print(is_palindrome("hello"))  # 出力: False

12. 1から100までの数値のうち、3の倍数であり5の倍数でもある数値を表示してください。

for i in range(1, 101):
    if i % 3 == 0 and i % 5 == 0:
        print(i)

13. a = [1, 2, 3]b = [4, 5, 6]を結合して新しいリストcを作成してください。

a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)  # 出力: [1, 2, 3, 4, 5, 6]

14. 与えられたリストの要素がすべて整数かどうかを判定する関数を作成してください。

def all_integers(lst):
    return all(isinstance(x, int) for x in lst)

print(all_integers([1, 2, 3]))  # 出力: True
print(all_integers([1, 2, '3']))  # 出力: False

15. リスト[1, 2, 3, 4, 5]を昇順にソートしてください。

my_list = [5, 3, 1, 4, 2]
my_list.sort()
print(my_list)  # 出力: [1, 2, 3, 4, 5]

16. 辞書{'name': 'Alice', 'age': 25, 'city': 'New York'}のすべてのキーを表示してください。

my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
for key in my_dict.keys():
    print(key)

17. 辞書{'name': 'Alice', 'age': 25, 'city': 'New York'}のすべての値を表示してください。

my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
for value in my_dict.values():
    print(value)

18. 0から9までの整数を含むリストを作成し、そのリストをシャッフルしてください。

import random

my_list = list(range(10))
random.shuffle(my_list)
print(my_list)

19. リスト[1, 2, 3, 4, 5]のすべての要素を2倍にするリストを作成してください。

my_list = [1, 2, 3, 4, 5]
doubled_list = [x * 2 for x in my_list]
print(doubled_list)  # 出力: [2, 4, 6, 8, 10]

20. 文字列"The quick brown fox jumps over the lazy dog"に含まれる単語の数を数えてください。

s = "The quick brown fox jumps over the lazy dog"
word_count = len(s.split())
print(word_count)  # 出力: 9

応用編

  1. 2つのリスト[1, 2, 3][4, 5, 6]の要素ごとの積を計算する関数を作成してください。
def elementwise_product(lst1, lst2):
    return [a * b for a, b in zip(lst1, lst2)]

print(elementwise_product([1, 2, 3], [4, 5, 6]))  # 出力: [4, 10, 18]

22. リスト内包表記を使用して、1から20までの数値のうち偶数のみを含むリストを作成してください。

even_numbers = [x for x in range(1, 21) if x % 2 == 0]
print(even_numbers)  # 出力: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

23. 与えられた文字列の各単語の最初の文字を大文字に変換する関数を作成してください。

def capitalize_words(s):
    return ' '.join(word.capitalize() for word in s.split())

print(capitalize_words("hello world"))  # 出力: Hello World

24. 文字列"abracadabra"に含まれるすべての母音をカウントしてください。

s = "abracadabra"
vowels = 'aeiou'
count = sum(1 for char in s if char in vowels)
print(count)  # 出力: 5

25. リスト[1, 2, 3, 4, 5]のすべての要素の積を計算してください。

from functools import reduce
import operator

my_list = [1, 2, 3, 4, 5]
product = reduce(operator.mul, my_list, 1)
print(product)  # 出力: 120

26. 2つの辞書をマージする関数を作成してください。

def merge_dicts(dict1, dict2):
    merged_dict = dict1.copy()
    merged_dict.update(dict2)
    return merged_dict

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
print(merge_dicts(dict1, dict2))  # 出力: {'a': 1, 'b': 3, 'c': 4}

27. 与えられたリストに重複する要素があるかどうかを判定する関数を作成してください。

def has_duplicates(lst):
    return len(lst) != len(set(lst))

print(has_duplicates([1, 2, 3, 4]))  # 出力: False
print(has_duplicates([1, 2, 2, 3, 4]))  # 出力: True

28. 与えられたリストの要素を逆順にする関数を作成してください(組み込みのreverseメソッドを使用しないこと)。

def reverse_list(lst):
    return lst[::-1]

print(reverse_list([1, 2, 3, 4, 5]))  # 出力: [5, 4, 3, 2, 1]

29. タプル(1, 2, 3, 4, 5)の各要素を2倍にする関数を作成してください。

def double_tuple_elements(tpl):
    return tuple(x * 2 for x in tpl)

print(double_tuple_elements((1, 2, 3, 4, 5)))  # 出力: (2, 4, 6, 8, 10)

30. 0から1までの乱数を生成して表示してください。

import random

print(random.random())

上級編

  1. フィボナッチ数列のn番目の要素を求める関数を作成してください。
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

print(fibonacci(10))  # 出力: 55

32. 与えられたリストのすべての組み合わせを生成する関数を作成してください。

from itertools import combinations

def all_combinations(lst):
    result = []
    for r in range(len(lst) + 1):
        result.extend(combinations(lst, r))
    return result

print(list(all_combinations([1, 2, 3])))  
# 出力: [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

33. クラスを使用して、長方形の面積と周囲を計算するプログラムを作成してください。

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)

rect = Rectangle(4, 5)
print(rect.area())  # 出力: 20
print(rect.perimeter())  # 出力: 18

34. リスト[1, 2, 3, 4, 5]のすべての部分リストを生成する関数を作成してください。

def all_sublists(lst):
    sublists = [[]]
    for i in range(len(lst) + 1):
        for j in range(i):
            sublists.append(lst[j: i])
    return sublists

print(all_sublists([1, 2, 3]))  
# 出力: [[], [1], [1, 2], [2], [1, 2, 3], [2, 3], [3]]

35. 2つの文字列がアナグラムかどうかを判定する関数を作成してください。

def are_anagrams(str1, str2):
    return sorted(str1) == sorted(str2)

print(are_anagrams("listen", "silent"))  # 出力: True
print(are_anagrams("hello", "world"))  # 出力: False

36. 与えられたリストの要素がすべてユニークであるかどうかを判定する関数を作成してください。

def all_unique(lst):
    return len(lst) == len(set(lst))

print(all_unique([1, 2, 3, 4]))  # 出力: True
print(all_unique([1, 2, 2, 3, 4]))  # 出力: False

37. 2つのリストの共通の要素を含むリストを作成してください。

def common_elements(lst1, lst2):
    return list(set(lst1) & set(lst2))

print(common_elements([1, 2, 3], [2, 3, 4]))  # 出力: [2, 3]

38. 2つのリストの要素を交互にマージする関数を作成してください。

def alternate_merge(lst1, lst2):
    return [val for pair in zip(lst1, lst2) for val in pair]

print(alternate_merge([1, 2, 3], [4, 5, 6]))  # 出力: [1, 4, 2, 5, 3, 6]

39. 与えられた数値が素数かどうかを判定する関数を作成してください。

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

print(is_prime(7))  # 出力: True
print(is_prime(4))  # 出力: False

40. リスト内包表記を使用して、与えられたリストのすべての要素を文字列に変換するリストを作成してください。

my_list = [1, 2, 3, 4, 5]
str_list = [str(x) for x in my_list]
print(str_list)  # 出力: ['1', '2', '3', '4', '5']

プロジェクトベース

  1. 簡単な電卓プログラムを作成してください(加算、減算、乗算、除算機能を含む)。
def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        return "Cannot divide by zero"
    return x / y

print("Select operation:")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = input("Enter choice(1/2/3/4): ")

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
    print(add(num1, num2))
elif choice == '2':
    print(subtract(num1, num2))
elif choice == '3':
    print(multiply(num1, num2))
elif choice == '4':
    print(divide(num1, num2))
else:
    print("Invalid input")

42. 簡単なToDoリストアプリを作成してください(タスクの追加、削除、表示機能を含む)。

todo_list = []

def add_task(task):
    todo_list.append(task)

def remove_task(task):
    if task in todo_list:
        todo_list.remove(task)

def display_tasks():
    print("ToDo List:")
    for task in todo_list:
        print(task)

while True:
    print("\n1. Add task\n2. Remove task\n3. Display tasks\n4. Exit")
    choice = int(input("Enter your choice: "))

    if choice == 1:
        task = input("Enter task: ")
        add_task(task)
    elif choice == 2:
        task = input("Enter task to remove: ")
        remove_task(task)
    elif choice == 3:
        display_tasks()
    elif choice == 4:
        break
    else:
        print("Invalid choice")

43. ユーザーからの入力を受け取り、その入力が回文かどうかを判定するプログラムを作成してください。

def is_palindrome(s):
    return s == s[::-1]

user_input = input("Enter a string: ")
if is_palindrome(user_input):
    print("The string is a palindrome.")
else:
    print("The string is not a palindrome.")

44. 簡単な連絡先管理アプリを作成してください(連絡先の追加、削除、表示機能を含む)。

contacts = {}

def add_contact(name, number):
    contacts[name] = number

def remove_contact(name):
    if name in contacts:
        del contacts[name]

def display_contacts():
    print("Contacts List:")
    for name, number in contacts.items():
        print(f"{name}: {number}")

while True:
    print("\n1. Add contact\n2. Remove contact\n3. Display contacts\n4. Exit")
    choice = int(input("Enter your choice: "))

    if choice == 1:
        name = input("Enter name: ")
        number = input("Enter number: ")
        add_contact(name, number)
    elif choice == 2:
        name = input("Enter name to remove: ")
        remove_contact(name)
    elif choice == 3:
        display_contacts()
    elif choice == 4:
        break
    else:
        print("Invalid choice")

45. 与えられたリストの要素をソートするプログラムを作成してください(バブルソートを使用)。

def bubble_sort(lst):
    n = len(lst)
    for i in range(n):
        for j in range(0, n-i-1):
            if lst[j] > lst[j+1]:
                lst[j], lst[j+1] = lst[j+1], lst[j]
    return lst

my_list = [64, 34, 25, 12, 22, 11, 90]
sorted_list = bubble_sort(my_list)
print(sorted_list)  # 出力: [11, 12, 22, 25, 34, 64, 90]

46. 簡単なメモ帳アプリを作成してください(メモの追加、削除、表示機能を含む)。

notes = []

def add_note(note):
    notes.append(note)

def remove_note(note):
    if note in notes:
        notes.remove(note)

def display_notes():
    print("Notes List:")
    for note in notes:
        print(note)

while True:
    print("\n1. Add note\n2. Remove note\n3. Display notes\n4. Exit")
    choice = int(input("Enter your choice: "))

    if choice == 1:
        note = input("Enter note: ")
        add_note(note)
    elif choice == 2:
        note = input("Enter note to remove: ")
        remove_note(note)
    elif choice == 3:
        display_notes()
    elif choice == 4:
        break
    else:
        print("Invalid choice")

47. 与えられた文字列から英単語の頻度をカウントするプログラムを作成してください。

from collections import Counter

def word_count(s):
    words = s.split()
    return Counter(words)

s = "the quick brown fox jumps over the lazy dog the quick brown fox"
print(word_count(s))
# 出力: Counter({'the': 3, 'quick': 2, 'brown': 2, 'fox': 2, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1})

48. 簡単なカウントダウンタイマーを作成してください(時間を設定してカウントダウンを表示)。

import time

def countdown(seconds):
    while seconds:
        mins, secs = divmod(seconds, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)
        print(timer, end="\r")
        time.sleep(1)
        seconds -= 1

    print("Time's up!")

countdown_time = int(input("Enter the time in seconds: "))
countdown(countdown_time)

49. 簡単な数当てゲームを作成してください(ユーザーが数を予想して当てるまで続ける)。

import random

def guess_number():
    number = random.randint(1, 100)
    guess = None

    while guess != number:
        guess = int(input("Guess the number (1-100): "))
        if guess < number:
            print("Too low!")
        elif guess > number:
            print("Too high!")
        else:
            print("Congratulations! You guessed the number.")

guess_number()

50. 簡単なファイル読み書きプログラムを作成してください(ファイルにテキストを書き込み、読み込んで表示)。

def write_to_file(filename, content):
    with open(filename, 'w') as file:
        file.write(content)

def read_from_file(filename):
    with open(filename, 'r') as file:
        return file.read()

filename = 'example.txt'
content = "Hello, world!"
write_to_file(filename, content)
print(read_from_file(filename))
# 出力: Hello, world!

これで50問のプログラミング問題の解答が揃いました。これらの問題に取り組むことで、Pythonの基本的なスキルを向上させることができます。

スポンサーリンク

-Python