Esempio n. 1
0
def calc_sphere_volume():
    """Ask for the input required for calculating a sphere's volume and print the result."""
    r = ask_float("Sphere radius: ")
    result = sphere_volume(r)
    print("The sphere's volume is: {0:.3f}".format(result))
    print("Formula: 4/3*pi*r**3")
    utils.get_input("PRESS ENTER TO CONTINUE")
Esempio n. 2
0
    def place_bets(self):
        """Place bets for a turn of roulette.

        The user is continually asked to provide raw bet input until a valid string is given. It
        is possible to provide more than one bet. To do this, the bets should be joined with a
        semicolon character (see the example). The resulting list of bets is set as an attribute
        for the roulette player.

        Example::

            >>> player = RoulettePlayer('John', 100, 2000)
            >>> player.bets
            []
            >>> player.place_bets()
            Place your bet(s): 100,red;200,odd
            Insufficient credits, maximum allowed: 100
            Try again: 50,red;50,odd
            >>> for bet in player.bets:
            ...     print(bet)
            ...
            - Bet of 50 credits in position 'red':
                Pays out 50 credits if won.
                Odds for winning this bet are 18 against 20.
            - Bet of 50 credits in position 'odd':
                Pays out 50 credits if won.
                Odds for winning this bet are 18 against 20.
        """
        self.bets = validate_bets(utils.get_input("Place your bet(s): "), self)
        while self.bets is None:
            self.bets = validate_bets(utils.get_input("Try again: "), self)
Esempio n. 3
0
def calc_sphere_surface_area():
    """Ask for the input required for calculating a sphere's surface area and print the result."""
    r = ask_float("Sphere radius: ")
    result = sphere_surface_area(r)
    print("The sphere's surface area is: {0:.3f}".format(result))
    print("Formula: 4*pi*r**2")
    utils.get_input("PRESS ENTER TO CONTINUE")
Esempio n. 4
0
def calc_cube_volume():
    """Ask for the input required for calculating a cube's volume and print the result."""
    z = ask_float("Cube edge length: ")
    result = cube_volume(z)
    print("The cube's volume is: {0:.3f}".format(result))
    print("Formula: z**3")
    utils.get_input("PRESS ENTER TO CONTINUE")
Esempio n. 5
0
def calc_cube_surface_area():
    """Ask for the input required for calculating a cube's surface area and print the result."""
    z = ask_float("Cube edge length: ")
    result = cube_surface_area(z)
    print("The cube's surface area is: {0:.3f}".format(result))
    print("Formula: 6*z**2")
    utils.get_input("PRESS ENTER TO CONTINUE")
Esempio n. 6
0
def run():
    """Execute the challenges.028e module."""
    # Ask user input.
    nelems = int(utils.get_input("Amount of elements in list: "))
    llim = int(utils.get_input("Lower element limit: "))
    ulim = int(utils.get_input("Upper element limit: "))
    plist = utils.get_input("Print the list (y/n)? ").lower()[0]

    # Generate the random list with a single duplicate element.
    if llim > ulim:
        llim, ulim = ulim, llim
    if nelems > ulim - llim + 1:
        nelems = ulim - llim + 1
    x = list(range(llim, ulim + 1))
    random.shuffle(x)
    x = x[:nelems - 1] + x[nelems - 2:nelems - 1]
    random.shuffle(x)
    if plist == 'y':
        print("Randomly generated list:")
        print(x)

    # Find and print the duplicate element.
    index = lt.first_duplicate(x)
    item = x[index]
    print("The duplicate element in the list is: {}".format(item))
Esempio n. 7
0
    def remove_broke_players(self):
        """Remove all broke players from the list of players.

        When a player is broke, there is no point in keeping him in the game. This method removes
        all broke players from the list of players.

        Example::

            >>> roulette = Roulette.new(nplayers=1, table='input/032e_ascii_roulette_table.txt')
            Enter information for player 1:
            New player name: John
            Starting credits for John: 0
            Goal for John: 100
            >>> len(roulette.players)
            1
            >>> roulette.remove_broke_players()
            Sorry John, but you are broke. You're out!
            >>> len(roulette.players)
            0
        """
        players_new = []
        for player in self.players:
            if player.credits > 0:
                players_new.append(player)
            else:
                utils.get_input(
                    "Sorry {}, but you are broke. You're out!".format(
                        player.name))
        self.players = players_new
Esempio n. 8
0
def run():
    """Execute the challenges.011e module."""
    year = int(utils.get_input("Year (1583 - ...) > "))
    month = int(utils.get_input("Month (1 - 12) > "))
    ndays = dd.ndays_in_month(month, year)
    day = int(utils.get_input("Day (1 - {}) > ".format(ndays)))
    date = dd.Date(year, month, day)
    print("{} is a {}.".format(date, date.weekday(h=True)))
Esempio n. 9
0
def run():
    """Execute the challenges.023e module."""
    x = list(range(int(utils.get_input("Length of list: "))))
    f = float(utils.get_input("Split fraction: "))
    x1, x2 = lt.split_list(x, f=f)
    print("Original list: {}".format(x))
    print("Split part 1: {}".format(x1))
    print("Split part 2: {}".format(x2))
Esempio n. 10
0
def run():
    """Execute the challenges.031e module."""
    nr1 = utils.get_input('First base 26 number (A - Z): ').upper()
    nr2 = utils.get_input('Second base 26 number (A - Z): ').upper()
    nr1 = ei.EnhancedInt([map_ltrs2nrs[char] for char in nr1], 26)
    nr2 = ei.EnhancedInt([map_ltrs2nrs[char] for char in nr2], 26)
    result = ''.join([map_nrs2ltrs[digit] for digit in (nr1 * nr2).digits])
    print("Multiplication of both numbers: {}".format(result))
Esempio n. 11
0
def run():
    """Execute the challenges.007e module."""
    # Settings for the strange 'Reddit' Morse code convention that was pulled out of
    # someone's ass for this challenge.
    ls = ' '  ## Spacing between letters in a Morse sequence.
    ws = ' / '  ## Spacing between words in a Morse sequence.
    charmap = {
        'A': '.-',
        'B': '-...',
        'C': '-.-.',
        'D': '-..',
        'E': '.',
        'F': '..-.',
        'G': '--.',
        'H': '....',
        'I': '..',
        'J': '.---',
        'K': '-.-',
        'L': '.-..',
        'M': '--',
        'N': '-.',
        'O': '---',
        'P': '.--.',
        'Q': '--.-',
        'R': '.-.',
        'S': '...',
        'T': '-',
        'U': '..-',
        'V': '...-',
        'W': '.--',
        'X': '-..-',
        'Y': '-.--',
        'Z': '--..',
    }
    beepmap = {
        ' ': Beep(pitch=200, btime=200, stime=250),
        '/': Beep(pitch=200, btime=200, stime=250),
        '.': Beep(pitch=400, btime=200, stime=250),
        '-': Beep(pitch=400, btime=600, stime=650),
    }
    morse_reddit = MorseConvention(ls, ws, charmap, beepmap)

    # Decode the challenge sequence.
    sequence = (
        ".... . .-.. .-.. --- / -.. .- .. .-.. -.-- / .--. .-. --- --. .-. .- -- -- . .-. /"
        " --. --- --- -.. / .-.. ..- -.-. -.- / --- -. / - .... . / -.-. .... .- .-.. .-.. "
        ". -. --. . ... / - --- -.. .- -.--")
    msg = morse_reddit.decode(sequence)
    print("\nChallenge Morse sequence:\n{}".format(sequence))
    print("decodes to:\n{}\n".format(msg))

    # Ask for a message to encode and whether or not to beep it.
    msg = utils.get_input("Message to encode? > ").upper()
    sequence = morse_reddit.encode(msg)
    print("Resulting Morse sequence:\n{}\n".format(sequence))
    if utils.get_input("Beep this (y/n)? ").lower()[0] == 'y':
        morse_reddit.beep(sequence)
Esempio n. 12
0
def run():
    """Execute the challenges.013e module."""
    year = int(utils.get_input("Year (1583 - ...) > "))
    month = int(utils.get_input("Month (1 - 12) > "))
    ndays = dd.ndays_in_month(month, year)
    day = int(utils.get_input("Day (1 - {}) > ".format(ndays)))
    date = dd.Date(year, month, day)
    cumulday = date.cumulative_day_of_year()
    print("{} is day number {} of the year {}.".format(date, cumulday,
                                                       date.year))
Esempio n. 13
0
def run():
    """Execute the challenges.045e module."""
    x = int(utils.get_input("Amount of tiles along the width > "))
    y = int(utils.get_input("Amount of tiles along the height > "))
    tx = int(utils.get_input("Tile character width > "))
    ty = int(utils.get_input("Tile character height > "))
    chars = utils.get_input(
        "Tile characters (separated with space) > ").split()
    grid = aa.CheckeredGrid(x, y, tx, ty, chars)
    print(grid)
Esempio n. 14
0
def run():
    """Execute the challenges.049e module."""
    ndoors = int(utils.get_input("How many doors are there > "))
    nruns = int(utils.get_input("How many simulations do you want to run > "))
    results = [simulate_monty_hall(ndoors) for run in range(nruns)]
    counts = lt.count_items(results)
    print("When switching, the player wins {} times out of {}.".format(
        counts[True], nruns))
    print("When not switching, the player wins {} times out of {}.".format(
        counts[False], nruns))
Esempio n. 15
0
def run():
    """Execute the challenges.004e module."""
    # Ask for input.
    np = int(utils.get_input("Amount of passwords > "))
    lp = int(utils.get_input("Password length > "))

    # Generate the passwords.
    pwds = [password.random_password(l=lp) for ii in range(np)]
    print("===PASSWORDS===")
    print('\n'.join(
        ["{}. {}".format(pi + 1, pwd) for pi, pwd in enumerate(pwds)]))
    print("=" * 15)
Esempio n. 16
0
def run():
    """Execute the challenges.001e module."""
    # Ask for input.
    name = utils.get_input("Name? > ")
    age = utils.get_input("Age? > ")
    reddit_username = utils.get_input("Reddit Username? > ")

    # Create PersonalInfo object, print and write to file.
    pi = user.User(name=name, age=age, reddit_username=reddit_username)
    print(pi)
    outputfile_fn = os.path.join(cfg.output_dir, '001e_example_output.txt')
    pi.write(outputfile_fn)
    print("Note: Data has been appended to file '{}'".format(outputfile_fn))
Esempio n. 17
0
    def evaluate_bets(self):
        """Evaluate each player's bet(s) and update credits accordingly.

        Each bet of all players is evaluated. If the game's winning number is in the bet's list of
        winning numbers, the bet's payout is added to the respective player's credits. If the number
        is not in the list, the value of the bet is subtracted from the respective player's credits.

        Example::

            >>> b1 = RouletteBet('50,red')
            >>> b2 = RouletteBet('50,black')
            >>> p1 = RoulettePlayer('John', 100, 2000)
            >>> p1.bets = [b1]
            >>> p2 = RoulettePlayer('Jane', 100, 2000)
            >>> p2.bets = [b2]
            >>> roulette = Roulette([p1, p2], 'input/032e_ascii_roulette_table.txt')
            >>> roulette.winning_number = 'r1'
            >>> roulette.evaluate_bets()

            John, let's see how you did...
            Your bet of 50 credits in position 'red' is won! You gain 50 credits.
            John, that was it for you. You now have 150 credits.

            Jane, let's see how you did...
            Your bet of 50 credits in position 'black' is lost... You lose 50 credits.
            Jane, that was it for you. You now have 50 credits.

            All bets have been evaluated!
        """
        for player in self.players:
            utils.get_input("\n{}, let's see how you did...".format(
                player.name))
            for bet in player.bets:
                msg = "Your bet of {} credits in position '{}' is ".format(
                    bet.value(),
                    bet.position(),
                )
                print(msg, end='')
                if self.winning_number in bet.winning_numbers():
                    utils.get_input("won! You gain {} credits.".format(
                        bet.payout()))
                    player.credits += bet.payout()
                else:
                    utils.get_input("lost... You lose {} credits.".format(
                        bet.value()))
                    player.credits -= bet.value()
            msg = "{}, that was it for you. You now have {} credits."
            utils.get_input(msg.format(player.name, player.credits))
        utils.get_input("\nAll bets have been evaluated!")
Esempio n. 18
0
def run():
    """Execute the challenges.003e module."""
    # Ask for input
    msg = utils.get_input("Message to encode > ")
    n = int(utils.get_input("Amount of right shift > "))

    # Play with the input
    print("Original message: " + msg)
    msg_encoded = caesar(msg, n)
    print("Encoded message: " + msg_encoded)
    msg_decoded = caesar(msg_encoded, n, dir='decode')
    print("Decoded encoded message: " + msg_decoded)
    options = caesar_brute_force(msg_encoded)
    print("Brute-force-decoded encoded message:")
    print('\n'.join(options))
Esempio n. 19
0
def run():
    """Execute the challenges.050e module."""
    ncases = int(utils.get_input("Amount of cases: "))
    cases = []
    for icase in range(ncases):
        credit = int(utils.get_input("Credit for case {}: ".format(icase + 1)))
        prices_raw = utils.get_input("Item prices for case {}: ".format(icase +
                                                                        1))
        prices = [int(price_raw) for price_raw in prices_raw.split()]
        cases.append((prices, credit))
    results = [lt.first_sum_pair(pr, cr) for pr, cr in cases]
    [
        print("Case #{}: {} {}".format(icase + 1, *result))
        for icase, result in enumerate(results)
    ]
Esempio n. 20
0
def calc_pi(func, pi_exp='3.141592653589793238462643383279'):
    """Calculate pi up to a desired precision with the provided function and compare with expected.

    The user is asked for the desired precision of the calculation of pi. Pi is then calculated
    up to that precision using the provided function, and the result is compared with the expected
    value.

    :param Callable func: the function with which pi should be calculated
    :param str pi_exp: the expected value of pi (default '3.141592653589793238462643383279')
    """
    prec_exp = len(pi_exp) - 2
    prec_calc = int(
        utils.get_input("Desired precision for calculation of pi: "))
    pi_calc = str(func(prec_calc))
    print("\nCalculation of pi up to {} digits:\n    {}".format(
        prec_calc, pi_calc))
    print("Pi calculated up to {} digits should be:\n    {}".format(
        prec_exp, pi_exp))
    if prec_calc <= prec_exp and pi_calc in pi_exp:
        print("The calculation appears to be correct!\n")
    elif prec_calc > prec_exp and pi_exp in pi_calc:
        msg = "The calculation appears to be correct (at least for the first {} digits)!\n"
        print(msg.format(prec_exp))
    else:
        print("The calculation appears to be incorrect!\n")
Esempio n. 21
0
def run():
    """Execute the challenges.036e module."""
    n = int(utils.get_input("How many lockers are there? > "))
    lockers = locker_problem2(n)
    open_lockers = [l + 1 for l, s in enumerate(lockers) if s]
    msg = "After toggling, there are {} open lockers.\nThese are their numbers:\n{}"
    print(msg.format(len(open_lockers), open_lockers))
Esempio n. 22
0
def run():
    """Execute the challenges.020e module."""
    limit = int(utils.get_input("Find all prime numbers up to and including: "))
    primes = sieve_of_eratosthenes(limit)
    end = {True: '\n', False: ', '}
    for i, prime in enumerate(primes):
        print(str(prime).rjust(4), end=end[(i+1)%13==0 or (i+1)==len(primes)])
    def ask_valid_item(tm):
        """Repeatedly ask for an item from a text menu until a valid item ID is received.

        :param TextMenu tm: the text menu from which an item should be selected
        :return: ID of the selected text menu item
        :rtype: str

        Example::

            >>> tm = TextMenu('Menu', [
            ...     TextMenuItem('1', 'action', 'Menu Item 1'),
            ... ])
            >>> TextMenuEngine.ask_valid_item(tm)
            === Menu ===
            1. Menu Item 1
            Choose menu item > 2
            That is not a valid menu item, please try again!
            Choose menu item > 1
            '1'
        """
        print(tm)
        while True:
            id = utils.get_input('Choose menu item > ')
            if tm.is_valid_id(id):
                return id
            else:
                print("That is not a valid menu item, please try again!")
Esempio n. 24
0
def run():
    """Execute the challenges.015e module."""
    # Get user input.
    textinfn = utils.get_input("Input file? > ")
    a = utils.get_input("Desired alignment ('<', '>', '^')? > ")
    textoutfn = utils.get_input("Output file? > ")

    # Read, align and write.
    textinfp = os.path.join(cfg.input_dir, textinfn)
    textoutfp = os.path.join(cfg.output_dir, textoutfn)
    with open(textinfp, 'r') as textinfil:
        text = estr.EnhancedString(textinfil.read())
    text.align(a)
    with open(textoutfp, 'w') as textoutfil:
        textoutfil.write(str(text))
    print("Note: Data has been written to file '{}'.".format(textoutfp))
Esempio n. 25
0
def run():
    """Execute the challenges.035e module."""
    nr = int(utils.get_input("Enter number: "))
    nlevels = math.floor(inverse_sum_of_range(nr))
    maxnr = sum_of_range(nlevels)
    char_len = len(str(maxnr)) + 1
    chars = ['{1:<{0}}'.format(char_len, n) for n in range(1, maxnr + 1)]
    print(aa.TextTriangle(char=chars, nlevels=nlevels, o='v'))
Esempio n. 26
0
def run():
    """Execute the challenges.037e module."""
    fil_fn = utils.get_input("Provide input file name > ")
    fil_fp = os.path.join(cfg.input_dir, fil_fn)
    with open(fil_fp, 'r') as fil:
        text = es.EnhancedString(fil.read())
    print("Amount of lines in file: {}".format(text.nlines))
    print("Amount of words in file: {}".format(text.nwords))
Esempio n. 27
0
def run():
    """Execute the challenges.046e module."""
    while True:
        nr = utils.get_input("Give me a number ('q' to quit) > ").lower()
        if nr == 'q':
            break
        nr = int(nr)
        print(ei.EnhancedInt(nr).convert(2), ';', population_count(nr))
Esempio n. 28
0
def run():
    """Execute the challenges.021e module."""
    number = utils.get_input("Number: ")
    number = {True: float, False: int}['.' in number](number)
    newnumber = next_permutation(number)
    if newnumber != number:
        print("Next higher permutation of this number: {}".format(newnumber))
    else:
        print("There is no next higher permutation for this number!")
Esempio n. 29
0
def run():
    """Execute the challenges.017e module."""
    nlevels = int(utils.get_input("Amount of triangle levels: "))
    triangle = aa.TextTriangle(rm=2, lm=0, add=0, nlevels=nlevels)
    print("\nNormal triangle:\n{}".format(triangle))
    triangle.o = 'v'
    print("\nReversed triangle:\n{}".format(triangle))
    triangle.a = '>'
    print("\nReversed triangle with right alignment:\n{}".format(triangle))
Esempio n. 30
0
    def spin_wheel(self):
        """Determine a new winning number.

        A random sample is taken from the list of numbers on the roulette wheel and set as
        the game's current winning number.

        Example::

            >>> roulette = Roulette.new(nplayers=0, table='input/032e_ascii_roulette_table.txt')
            >>> roulette.winning_number  ## Nothing is printed, there is no winning number yet.
            >>> roulette.spin_wheel()
            Press [ENTER] to spin the wheel!
            The winning number is: 'b24'
            >>> roulette.winning_number
            'b24'
        """
        utils.get_input("Press [ENTER] to spin the wheel!")
        self.winning_number = random.sample(rnrs, 1)[0]
        utils.get_input("The winning number is: '{}'".format(
            self.winning_number))