- 10000までの数値で、5または6で割り切れるが両方で割り切れない数を探索する関数
def find_special_numbers():
result = []
for num in range(1, 10001):
if (num % 5 == 0 or num % 6 == 0) and num % 30 != 0:
result.append(num)
print(*result, sep=' ')
find_special_numbers()
- リストの偶数インデックスにある要素の合計を計算するメソッドを実装
data_list = eval(input("リストを入力してください:"))
def sum_even_indices(input_list):
total = 0
for idx in range(0, len(input_list), 2):
total += input_list[idx]
return total
print(f"偶数インデックス要素の合計:{sum_even_indices(data_list)}")
- ファイルパスからディレクトリ、ファイル名、拡張子を分離する処理
full_path = input("完全なファイルパスを入力してください:")
separator = "\\" if "\\" in full_path else "/"
directory = full_path[:full_path.rfind(separator) + 1]
filename_with_ext = full_path[full_path.rfind(separator) + 1:]
extension = filename_with_ext[filename_with_ext.rfind(".") + 1:] if "." in filename_with_ext else ""
print(f"ディレクトリ:{directory}")
print(f"ファイル名:{filename_with_ext}")
print(f"拡張子:{extension}")
- 指定された区切り文字で文字列を分割して改行表示する関数
def split_and_display(delimiter, text):
segments = text.split(delimiter)
for segment in segments:
print(segment)
if __name__ == '__main__':
input_text = input('区切り文字を含む文字列を入力してください:')
split_char = input('区切り文字を入力してください:')
split_and_display(split_char, input_text)
- 文字列リストの各要素から空白文字を除去するプログラム
string_array = eval(input("文字列のリストを入力してください:"))
cleaned_array = []
for item in string_array:
cleaned_array.append(item.replace(" ", ""))
print(f"元のリスト:{string_array}")
print(f"空白除去後:{cleaned_array}")
- 2人が入力した好きなゲーム名が一致するか判定する処理
player1_game = input('プレイヤー1の好きなゲーム名を入力:')
player2_game = input('プレイヤー2の好きなゲーム名を入力:')
if player1_game.strip().lower() == player2_game.strip().lower():
print('同じゲームが好きですね!')
else:
print('異なるゲームが好きですね')
- 大文字小文字を区別せずにゲーム名を比較する改善版
def compare_games(game_a, game_b):
return game_a.strip().lower() == game_b.strip().lower()
game1 = input('プレイヤー1の好きなゲーム名:')
game2 = input('プレイヤー2の好きなゲーム名:')
if compare_games(game1, game2):
print('同じゲームが好きです')
else:
print('違うゲームが好きです')
- 日付フォーマットを「YYYY/MM/DD」から「YYYY年-M月-D日」に変換
def convert_date_format(date_str):
parts = date_str.split('/')
if len(parts) == 3:
year, month, day = parts
return f"{year}年-{int(month)}月-{int(day)}日"
return "無効な日付形式"
if __name__ == '__main__':
input_date = input('「年/月/日」形式で日付を入力:')
print(convert_date_format(input_date))
- 入力文字列の文字をソートし、逆順にも表示するプログラム
input_string = input("文字列を入力してください:")
char_list = list(input_string)
char_list.sort()
sorted_asc = ''.join(char_list)
sorted_desc = sorted_asc[::-1]
print(f"昇順:{sorted_asc}")
print(f"降順:{sorted_desc}")
- 英文の単語順序を逆にして出力する関数
def reverse_words(sentence):
words = sentence.split()
words.reverse()
return ' '.join(words)
if __name__ == '__main__':
english_sentence = input('英文を入力してください:')
print(f'逆順:{reverse_words(english_sentence)}')
- URLからドメイン名とパラメータを抽出する処理
url = 'https://example.com?username=testuser&password=secret123'
parsed_url = url.split('?')
domain_part = parsed_url[0]
params_part = parsed_url[1] if len(parsed_url) > 1 else ''
domain = domain_part.split('//')[1] if '//' in domain_part else domain_part.split('/')[0]
if params_part:
param_pairs = params_part.split('&')
for pair in param_pairs:
key, value = pair.split('=')
if key == 'username':
username = value
break
print(f'ドメイン:{domain}')
print(f'ユーザー名:{username}')
- 書籍タイトルの長さを調整し、著者名を追加する処理
book_titles = [
"プログラミング入門",
"データ構造とアルゴリズム",
"機械学習の基礎",
"Web開発完全ガイドブック",
"人工知能とは何か",
"Pythonデータサイエンスハンドブック"
]
authors = {
"プログラミング入門": "田中太郎",
"データ構造とアルゴリズム": "山田花子",
"機械学習の基礎": "佐藤次郎",
"Web開発完全ガイドブック": "鈴木三郎",
"人工知能とは何か": "高橋四郎",
"Pythonデータサイエンスハンドブック": "伊藤五郎"
}
processed_titles = []
for title in book_titles:
if len(title) > 10:
processed = title[:7] + "...|" + authors[title]
else:
processed = title + "|" + authors[title]
processed_titles.append(processed)
print(processed_titles)
- 文字列内の特定の文字列の出現位置をすべて検索する関数
def find_all_occurrences(text, search_str):
positions = []
start = 0
while True:
found_pos = text.find(search_str, start)
if found_pos == -1:
break
positions.append(found_pos)
start = found_pos + len(search_str)
return positions
test_text = "これは面白いですね、本当に面白いですよね、面白い!"
search_word = "面白い"
print(f"見つかった位置:{find_all_occurrences(test_text, search_word)}")
- テキスト内の特定の単語を検閲語に置き換える処理
def censor_text(input_text, target_word):
if target_word in input_text:
censored = '*' * len(target_word)
return input_text.replace(target_word, censored)
return input_text
user_input = input("文章を入力してください:")
forbidden = input("禁止語を入力してください:")
print(f"検閲後:{censor_text(user_input, forbidden)}")
- 回文( palindrome )かどうかを判定する関数
def is_palindrome(text):
normalized = text.lower()
return normalized == normalized[::-1]
check_text = input("文字列を入力してください:")
if is_palindrome(check_text):
print("これは回文です")
else:
print("これは回文ではありません")