Assignment 01

Solutions to Assignment 01.

Mean

Write a function mean to compute the arthematic mean of a list of numbers.

The arthemetic mean of N numbers is computed by adding all the N numbers and dividing the total by N.

The function takes the list of numbers as argument and returns the mean.

>>> mean([1, 2, 3, 4, 5])
3.0

Solution

def mean(numbers):
    return sum(numbers)/len(numbers)

Discussion

The solution is quite straight-forward. We use the built-in function sum to compute the total and divide it by the number of numbers, which is computed using the built-in function len.

def mean(numbers):
    return sum(numbers) / len(numbers)

You could also write that in multiple lines, if you find that more comfortable.

def mean(numbers):
    total = sum(numbers)
    n = len(numbers)
    return total / n

Product

Write a function product to compute the product of a list of numbers.

>>> product([1, 2, 3, 4])
24
>>> product([10, 2, 50])
1000

Solution

def product(numbers):
    result = 1
    for n in numbers:
        result *= n
    return result

Digit Count

Write a function digit_count that takes a number and a digit as argument and returns the number of times the digit is present in that number.

>>> digit_count(1231, 1)
2
>>> digit_count(1231, 3)
1
>>> digit_count(1231, 9)
0

Hint

>>> "mathematics".count("mat")
2

Solution

def digit_count(number, digit):
    return str(number).count(str(digit))

Discussion

Both the arguments, the number and the digit, are integers. As shown in the hint, we could use the count method, but that works only on strings. So, we need to convert both the number and digit into strings.

def digit_count(number, digit):
    return str(number).count(str(digit))

If that feels complicated to follow, you could simiplify it a bit by splitting that code into multiple lines.

def digit_count(number, digit):
    s1 = str(number)
    s2 = str(digit)
    return s1.count(s2)

Make Header

Write a program header.py that takes a word as command-line argument and prints it as header as shown below with the word converted to upper case.

$ python header.py python
======
PYTHON
======

$ python header.py python-foundation-course
========================
PYTHON-FOUNDATION-COURSE
========================

Hint:

>>> name = 'python'
>>> name.upper()
'PYTHON'

Solution

import sys

word = sys.argv[1].upper()
n = len(word)
print("=" * n)
print(word)
print("=" * n)

Text in a Box

Write a program box.py that takes word as a command-line argument and prints the word in a box as shown below.

$ python box.py python
+--------+
| python |
+--------+

Please note that there should be exactly one space on either side of the text in the box.

Solution

import sys

word = sys.argv[1]

n = len(word) + 2
line = "-" * n
header = f"+{line}+"

print(header)
print(f"| {word} |")
print(header)