Write a function get_digits that returns the list of digits present in the given number.
>>> get_digits(1234)
[1, 2, 3, 4]
# your code here
def get_digits(number):
return [int(d) for d in str(number)]
# try it
get_digits(1234)
# sum of digits
sum(get_digits(1234))
Notice that strings can be used like a list. Iterating over a string goes over the characters of the string.
Write a function barchart that takes a list of numbers and prints them as a barchart.
>>> barchart([2, 5, 4, 3])
|==
|======
|====
|===
Hint:
>>> print("=" * 3)
===
# your code here
def barchart(numbers):
for n in numbers:
print("|" + "=" * n)
# try it
barchart([2, 5, 4, 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.
# your code here
def getext(filename):
return filename.split(".")[-1]
# try it
getext("a.py")
getext("a.tar.gz")
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.
%%file ten.txt
1234567890
%%file filesize.py
# your code here
import sys
import os.path
filename = sys.argv[1]
print(os.path.getsize(filename))
# try it
!python filesize.py ten.txt
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
%%file sum.py
# your code here
import sys
args = sys.argv[1:]
numbers = [int(a) for a in args]
print(sum(numbers))
# try it
!python sum.py 1 2 3
!python sum.py 1 2 3 4 5
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]]
# your code here
def group(values, size):
return [values[start:start+size] for start in range(0, len(values), size)]
# try it
group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
group([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)