知っていることだけ

勉強していて役に立つ、理解の助けになるようなポイントを書いていきます。

python3 練習問題

10進数を2進数に変換して表示

実行結果

10進数> 1000
1000 = 1111101000

答え

print("10進数> ", end = '')
a = int(input())
print("{0} = {0:b}".format(a))

金額を入力して貨幣枚数に変換。

枚数が最小になる組み合わせを答える。二千円札を除く

実行結果

金額(円)> 48676
金額: 48676円
一万円札 = 4枚
五千円札 = 1枚
千円札 = 3枚
五百円札 = 1枚
百円札 = 1枚
五十円札 = 1枚
十円札 = 2枚
五円札 = 1枚
一円札 = 1枚

答え

print("金額(円)> ", end= "")
money = int(input())
print("金額: {}円".format(money))
strs = ["一万", "五千", "千", "五百", "百", "五十", "十", "五", "一"]
num = [10000, 5000, 1000, 500, 100, 50, 10, 5, 1]
for s, n in zip(strs, num):
    a = int(money / n)
    print("{}円札 = {}枚".format(s, a))
    money = money % n

うるう年の判定

  1. 年が400で割り切れるなら、うるう年
  2. それ以外で年が100で割り切れるならば、うるう年ではない
  3. それ以外で年が4で割り切れるならば、うるう年

実行結果

year> 2000
2000年はうるう年

答え

print("year> ", end = "")
year= int(input())
is_leap = False
if year % 400 == 0:
    is_leap = True
elif year % 100 == 0:
    is_leap = False
elif year % 4 == 0:
    is_leap = True
print("{}年は".format(year), end = "")
if is_leap:
    print("うるう年")
else:
    print("うるう年ではない")

じゃんけん

実行結果

例1

じゃんけん(0:グー, 1:チョキ, 2:パー)> 0
わたしはグー
あなたはグー
あいこ

例2

じゃんけん(0:グー, 1:チョキ, 2:パー)> 1
わたしはグー
あなたはチョキ
あなたの負け

答え

from random import randint
def say(x):
    ans = ""
    if x == 0:
        ans = "グー"
    elif x == 1:
        ans = "チョキ"
    else:
        ans = "パー"
    return ans

me = -1
while me < 0 or me > 2:
    print("じゃんけん(0:グー, 1:チョキ, 2:パー)> ", end = "")
    me = int(input())
enemy = randint(0,2)
print("わたしは"+ say(enemy))
print("あなたは"+ say(me))
a = (me - enemy ) % 3
if a == 0:
    print("あいこ")
elif a == 1:
    print("あなたの負け")
else:
    print("あなたの勝ち")

3つの数を昇順に並べ替える

実行結果

num[0]> 10
num[1]> 41
num[2]> 12
[10, 12, 41]

答え

num = []
for i in range(3):
    print("num[{}]> ".format(i), end = "")
    num.append(int(input()))
num.sort()
print(num)