2016年8月26日金曜日

開発環境

Pythonからはじめる数学入門 (Amit Saha (著)、黒川 利明 (翻訳)、オライリージャパン)の5章(集合と確率を操作する)、5.4(プログラミングチャレンジ)、問題5-3(お金がなくなるまで何回硬貨を投げられるか)を取り組んでみる。

問題5-3(お金がなくなるまで何回硬貨を投げられるか)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import random


def toss(amount):
    tosses = 0
    while True:
        tosses += 1
        t = random.randrange(2)
        if t == 0:
            amount += 1
            print('Heads! Current amount: {0}'.format(amount))
        else:
            amount -= 1.5
            print('Tails! Current amount: {0}'.format(amount))
        if amount <= 0:
            break

    print('Game over :( Current amount: {0} Coins tosses: {1}'.format(
        amount, tosses))

if __name__ == '__main__':
    amount = int(input('Enter your starting amount: '))
    toss(amount)

入出力結果(Terminal, IPython)

$ ./sample3.py
Enter your starting amount: 10
Heads! Current amount: 11
Tails! Current amount: 9.5
Tails! Current amount: 8.0
Heads! Current amount: 9.0
Heads! Current amount: 10.0
Tails! Current amount: 8.5
Heads! Current amount: 9.5
Tails! Current amount: 8.0
Heads! Current amount: 9.0
Tails! Current amount: 7.5
Heads! Current amount: 8.5
Heads! Current amount: 9.5
Tails! Current amount: 8.0
Tails! Current amount: 6.5
Tails! Current amount: 5.0
Heads! Current amount: 6.0
Heads! Current amount: 7.0
Tails! Current amount: 5.5
Heads! Current amount: 6.5
Tails! Current amount: 5.0
Heads! Current amount: 6.0
Heads! Current amount: 7.0
Heads! Current amount: 8.0
Heads! Current amount: 9.0
Tails! Current amount: 7.5
Heads! Current amount: 8.5
Heads! Current amount: 9.5
Tails! Current amount: 8.0
Tails! Current amount: 6.5
Heads! Current amount: 7.5
Heads! Current amount: 8.5
Tails! Current amount: 7.0
Tails! Current amount: 5.5
Heads! Current amount: 6.5
Heads! Current amount: 7.5
Tails! Current amount: 6.0
Heads! Current amount: 7.0
Tails! Current amount: 5.5
Tails! Current amount: 4.0
Tails! Current amount: 2.5
Tails! Current amount: 1.0
Tails! Current amount: -0.5
Game over :( Current amount: -0.5 Coins tosses: 42
$ ./sample3.py
Enter your starting amount: 10
Heads! Current amount: 11
Tails! Current amount: 9.5
Heads! Current amount: 10.5
Tails! Current amount: 9.0
Tails! Current amount: 7.5
Tails! Current amount: 6.0
Tails! Current amount: 4.5
Tails! Current amount: 3.0
Heads! Current amount: 4.0
Heads! Current amount: 5.0
Tails! Current amount: 3.5
Heads! Current amount: 4.5
Tails! Current amount: 3.0
Heads! Current amount: 4.0
Tails! Current amount: 2.5
Heads! Current amount: 3.5
Tails! Current amount: 2.0
Tails! Current amount: 0.5
Heads! Current amount: 1.5
Heads! Current amount: 2.5
Heads! Current amount: 3.5
Tails! Current amount: 2.0
Heads! Current amount: 3.0
Tails! Current amount: 1.5
Tails! Current amount: 0.0
Game over :( Current amount: 0.0 Coins tosses: 25
$

0 コメント:

コメントを投稿