From 311f02937235cdc56050fd0409887473f3558c53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Kn=C3=BCttel?= Date: Wed, 31 Oct 2018 14:08:44 +0100 Subject: [PATCH] Added exercise 8 --- ex_08.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 ex_08.py diff --git a/ex_08.py b/ex_08.py new file mode 100644 index 0000000..8b3e801 --- /dev/null +++ b/ex_08.py @@ -0,0 +1,38 @@ +#!/usr/bin/python3 + +from itertools import count +import random + +from util.io import readvalue + +def peter_coin_series(randf = random.randint): + result = 0 + + for k in count(1): + if(randf(0, 1) < 0.5): + return (result, k) + result += 2**k + + + +if( __name__ == "__main__"): + + def positive_int(s): + i = int(s) + if(i <= 0): + raise ValueError("{} is negative".format(i)) + return i + + print("I am going to toss a coin many times.\n" + "You are going to win 2**k if no head appears afer k throws.\n") + + bet = readvalue("How many ducats do you want to bet? ", positive_int) + result, throws = peter_coin_series() + + win = bet - result + + if(win < 0): + print("Bad, A head came out on throw #{}. You lost {} ducats.".format(throws, -win)) + else: + print("You won {} ducats.".format(win)) +