Advanced Python — diagnostic exercise

Answer these questions using the environment of your choice. Examples are shown using the Jupyter environment.
  1. Use the time module's .ctime() function to display the current time in human-readable form.

    Example output

    Fri Dec 27 13:10:51 2019
    
    Preferably, put the code you need into a stand-alone file.

    Solution

    import time
    print(time.time())
    print(time.ctime())
    
  2. Write script (or statements in an interactive session) to input two numbers from the user, then calculate and display their ratio (divide the first by the second). Use a try - except block on the division, to trap any errors.

    Example output

    $ ./q-try-ratio.py
    first number? 12
    second number? 13
    12.000000 / 13.000000 equals 0.923077
    $ ./q-try-ratio.py
    first number? 12
    second number? 0
    Error:  float division by zero
    $ ./q-try-ratio.py
    first number? 0
    second number? 0
    Got exception -->float division by zero<--
    $ 
    

    Solution

    #!/usr/bin/env python3
    
    x = float(input('first number? '))
    y = float(input('second number? '))
    
    try:
        z = x / y
        print('{:f} / {:f} = {:f}'.format(x, y, z))
    except Exception as e:
        print('Got exception -->{}<--'.format(e))
    #--------
    
  3. Write a function named average3() that accepts three numbers, and returns their average.

    Then write a simple program that includes the function, uses it to calculate an average, and displays the result. The program can get three numbers from the user, or just "hardcode" three numbers, whichever you prefer. The point is to demonstrate the use of the function.

    Example usage and output

    answer = average3(17, -3.5, 8)
    print(answer)
    7.166666666666667
    

    Solution

    #!/usr/bin/env python3
    
    def average3(x, y, z):
        return (x + y + z) / 3
    #--------
    
    a = float(input('first number? '))
    b = float(input('second number? '))
    c = float(input('third number? '))
    
    avg = average3(a, b, c)
    print('Average of {}, {}, {} equals {}'.format(a,b,c, avg))
    
  4. Write a script (or an interactive session) that uses a loop to accept text strings from the keyboard and collect them into a list of strings. Stop when the user enters an empty text string; then print out the list.

    Example usage

    Next string?  hello, world
    Next string?  goodbye, earth
    Next string?  stop, I want to get off.
    Next string?  ... and blah blah blah...
    Next string?  
    
    ['hello, world', 'goodbye, earth', 'stop, I want to get off.', '... and blah blah blah...']
    

    Solution

  5. Write a function that accepts a list of text strings (such as the one from the previous question), and returns a dictionary of the characters in all the strings and how ofter they occur.

    Then write a simple program that includes the function and uses it. Display the resulting dictionary.

    Example usage and output

    cd = make_char_dict(result)
    print(cd)
    {'h': 5, 'e': 4, 'l': 6, 'o': 7, ',': 3, ' ': 11, 'w': 2, 'r': 2, 'd': 3, 'g': 2, 'b': 4, 'y': 1, 'a': 6, 't': 5, 's': 1, 'p': 1, 'I': 1, 'n': 2, 'f': 2, '.': 7}
    
    for c, v in cd.items():
        print(c, v)
    h 5
    e 4
    l 6
    o 7
    , 3
      11
    w 2
    r 2
    d 3
    g 2
    b 4
    y 1
    a 6
    t 5
    s 1
    p 1
    I 1
    n 2
    f 2
    . 7
    

    Solution

    #!/usr/bin/env python3
    
    def question1(strings):
       chars = {}
        for s in strings:
            for c in s:
                if c not in chars:
                    chars[c] = 0
                chars[c] += 1
    
        return chars
    #--------
    
  6. Write a program (or script) that accepts command-line arguments, then displays each of them in reverse order.

    Example run, in a shell

    $ python echo-cmdline.py a bc def ghij klmno pqrst uvwxyz
    uvwxyz
    pqrst
    klmno
    ghij
    def
    bc
    a
    echo-cmdline.py
    

    Solution

    #!/usr/bin/env python3
    #       Multiple solutions for command-line arguments question
    import sys
    
    
    # (1) use a loop - naive approach
    mylist = []
    for a in sys.argv:
        mylist.append(a)
    for i in range(len(mylist)-1, -1, -1):
        print(mylist[i])
    print('#----')
    
    
    # (2) list comprehension copy, reverse-index printing
    mylist = [ a for a in sys.argv ]
    for a in mylist[::-1] :
        print(a)
    print('#----')
    
    
    # (3) slicing operation copy, reverse-index printing
    mylist = sys.argv[:]
    for a in sys.argv[::-1] :
        print(a)
    print('#----')
    
    
    # (4) not a copy, just an "alias" name - not even needed
    mylist = sys.argv
    for a in sys.argv[::-1] :
        print(a)
    print('#----')