Practice Problems for Day 2

Problem 2.1

Write a function get_digits that returns the list of digits present in the given number.

>>> get_digits(1234)
[1, 2, 3, 4]
In [1]:
# your code here

def get_digits(number):
    return [int(d) for d in str(number)]
In [2]:
# try it
get_digits(1234)
Out[2]:
[1, 2, 3, 4]
In [3]:
# sum of digits
sum(get_digits(1234))
Out[3]:
10

Notice that strings can be used like a list. Iterating over a string goes over the characters of the string.

In [ ]:
 

Problem 2.2

Write a function barchart that takes a list of numbers and prints them as a barchart.

>>> barchart([2, 5, 4, 3])
|==
|======
|====
|===

Hint:

>>> print("=" * 3)
===
In [4]:
# your code here

def barchart(numbers):
    for n in numbers:
        print("|" + "=" * n)
In [5]:
# try it
barchart([2, 5, 4, 3])
|==
|=====
|====
|===
In [ ]:
 
In [ ]:
 

Problem 2.3

Write a function getext to get the extension of given filename.

>>> getext("a.py")
'py'
>>> getext("a.tar.gz")
'gz'

Assume that the filename will always have an extension.

In [6]:
# your code here

def getext(filename):
    return filename.split(".")[-1]
In [7]:
# try it
getext("a.py")
Out[7]:
'py'
In [8]:
getext("a.tar.gz")
Out[8]:
'gz'
In [ ]:
 
In [ ]:
 
In [ ]:
 

Problem 2.4

Write a program filesize.py that takes path to a file as argument and prints size of that file.

$ python filesize.py ten.txt
10

Hint: use os.path.getsize

Use the following sample input file for testing.

In [2]:
%%file ten.txt
1234567890
Overwriting ten.txt
In [13]:
%%file filesize.py
# your code here
import sys
import os.path
filename = sys.argv[1]
print(os.path.getsize(filename))
Overwriting filesize.py
In [14]:
# try it
!python filesize.py ten.txt
10
In [ ]:
 
In [ ]:
 

Problem 2.5

Write a program sum.py that takes multiple numbers as command-line arguments and prints their sum.

$ python sum.py 1 2 3
6
$ python sum.py 1 2 3 4 5
15
In [15]:
%%file sum.py
# your code here
import sys
args = sys.argv[1:]
numbers = [int(a) for a in args]
print(sum(numbers))
Writing sum.py
In [16]:
# try it
!python sum.py 1 2 3
6
In [17]:
!python sum.py 1 2 3 4 5
15
In [ ]:
 
In [ ]:
 

Problem 2.6

Write a function group(values, size) that take a list of values and size as arguments and splits the list into smaller lists of given size.

>>> group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> group([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)
[[1, 2, 3, 4], [5, 6, 7, 8], [9]]
In [18]:
# your code here
def group(values, size):
    return [values[start:start+size] for start in range(0, len(values), size)]
In [19]:
# try it
group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
Out[19]:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [20]:
group([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)
Out[20]:
[[1, 2, 3, 4], [5, 6, 7, 8], [9]]
In [ ]: