Python Forum
Convert a list of integers to strings?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert a list of integers to strings?
#3
Hm, I like the coin change code, because it's short.
But it is not so flexible. Putting them in functions,
let you split the tasks:
  • User input and validation
  • Calculation
  • Printing the results

Here an example with a list which contains tuples.
With a dict, the solutions looks much nicer and
since 3.6 dicts keeps the order.
With Python <= 3.5 you get different results.
Since Python 3.7 it's a language feature, that Python
should keep the order of dicts. Before the keys were scrambled.
You have to know this, otherwise you'll wonder about different
order in results.

Here my example with some comments:

# Constants
N = 'note'
C = 'coin'
# CASH is using the Constants N and C
# by the way, it's not really a constant
# you can still change the content,
# but by convention UPPER_CASE_NAME
# should act as a not changing object
# using UPPER_CASE_NAME in you code means:
# Never change the content or value

CASH = [
    (500, N), (200, N), (100, N), (50, N),
    (20, N), (10, N), (5, N), (2, C), (1, C),
    ]


# or use a dict to look up the kind
# CASH = {500: N, 200: N, 1: C}
# note_or_coin = CASH[500]
# in this case the function change must be refactored to
# use the CASH dict
# iterating over CASH will only get the keys like 500, 200, 1
# using the method items() on the dict, gives you key and values back
# for amount, kind in CASH.items():
#     print('The amount is', amount, 'and it is a', kind)


def ask():
    """
    Function to ask the user for price and paid, which
    return the price and paid as integer.

    Input validation is implemeted by principle:
    don't ask for permission ask for forgiveness

    The int function does exactly knows how to convert
    a string into an integer. If the function raises a
    ValueError, then the input was not an integer.

    It's easier to catch the error instead of programming
    an own function to check if the user-input was valid.

    With floating point numbers, it's more complex.
    So parsing float from a string, should be done in
    the same way.

    Everytime if you get data from a untrusted source (the User)
    you have to validate the input. Otherwise your program is very
    fragile.
    """
    while True:
        price = input('What is the price for the food? ')
        try:
            price = int(price)
        except ValueError:
            print(f'{price} is not an integer.')
            # error, go back to start
            continue
        paid = input('How much did you pay for it? ')
        try:
            paid = int(paid)
        except ValueError:
            print(f'{paid} is not an integer.')
            # error, go back to the start
            continue
        # NO error
        # here is a special case
        # what to do if the user enters a higher value for
        # price as paid
        # With your code you get 0 back
        # preventing this
        if price > paid:
            print("You don't have enough money")
            # asking again for input
            continue
        return price, paid


def change():
    """
    Function to ask the user for price and paid, which
    calculates the change in notes and coins.

    The function returns a list with tuples.
    Each tuple has the value and kind (note/coin)
    """
    price, paid = ask()
    change = paid - price
    change_returned = []
    for value, kind in CASH:  # <- CASH is a list with tuples
    # for each iteration, the tuple is unpacked into
    # value and kind
        while change >= value:
            change_returned.append(??) # <- your task
            # hint, use a tuple
            change = change - value
    return change_returned # <- This here should contain all what you need
    # the values and the kind (note/coin)
    # [(value, kind), (value, kind), ...]


# the while loop could also be a function.
# then you have:
# function to ask the user for input
# function to calculate the result
# function to print the output

while True:
    # The program main loop.
    result = change() # <- get the result
    # generator expression in a function call
    # sum does not have a key argument like, min max, sorted
    total = sum(value for value, kind in result)
    print(f'You get {total} € back')
    for value, kind in result:
        print(??)
        # you can use format-strings
        # or the format method to
        # print a more descriptive text
As you can see, I did not made the last function.
Very important is to understand the break and continue statement in for-loops/while-loops. With this you can control the loop.
Catch exceptions for input validation. Then compare if paid is bigger or equal to price.
Repeat the question (continue), if an Exception happens or the condition was not given. I hope I did not solved your complete homework.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: Convert a list of integers to strings? - by DeaD_EyE - Nov-15-2019, 09:51 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Removing all strings in a list that are of x length Bruizeh 5 6,623 Aug-27-2021, 03:11 AM
Last Post: naughtyCat
  How to convert every even number in a list to odd? Bruizeh 4 5,587 Aug-27-2021, 03:04 AM
Last Post: naughtyCat
  list of strings to list of float undoredo 3 4,151 Feb-19-2020, 08:51 AM
Last Post: undoredo
  how to convert list into string Shevach 3 3,407 May-14-2019, 09:51 AM
Last Post: perfringo
  please Help. TypeError: list indices must be integers, not str skamaaa01 1 4,955 Feb-04-2018, 12:33 PM
Last Post: Gribouillis
  List of Strings Problem jge047 3 4,450 Dec-19-2017, 04:06 AM
Last Post: dwiga
  Strings inside other strings - substrings OmarSinno 2 4,512 Oct-06-2017, 09:58 AM
Last Post: gruntfutuk
  create a 20 digit string, and cast to a list then add all the digits as integers nikhilkumar 2 7,311 Jul-19-2017, 04:53 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020