Assignment 03

Solutions to Assignment 03.

Vector Add

write a function vector_add to add two vectors.

>>> vector_add([1, 2, 3, 4], [10, 20, 30, 40])
[11, 22, 33, 44]
>>> sum(vector_add([1, 2, 3, 4], [10, 20, 30, 40]))
110

Solution

def vector_add(v1, v2):
    return [a+b for a, b in zip(v1, v2)]

Group

Write a function group that take a list of values and splits 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]]

Solution


def group(values, n):
    return [values[i:i+n] for i in range(0, len(values), n)]

Longest Argument

Write a program longest_argument.py that takes a one or more words as command-line arguments and prints the longest word.

$ python longest_argument.py joy of programming
programming

$ python longest_argument.py this too shall pass
shall

Hint: You can use list slicing to get all the arguments. For example sys.argv[1:] will give you all arguments other than the program name.

Solution

import sys
args = sys.argv[1:]
print(max(args, key=len))

Paste

Write a program paste.py that takes two files as command-line arguments and contacenates the corresponding lines in those two files with a tab character and prints it.

For example, of the first file files/a.txt has the following contents:

A
B
C
D

and the second file files/b.txt has the following:

1
2
3
4

The output should be:

$ python paste.py files/a.txt files/b.txt
A       1
B       2
C       3
D       4

Note that the first line is "A\t1".

For simplicity, assume that both the files have exactly same number of lines.

Hint:

You can use the strip method on a string to remove the new line character.

>>> "a\n".strip("\n")
"a"

Solution

import sys

f1 = sys.argv[1]
f2 = sys.argv[2]

for left, right in zip(open(f1), open(f2)):
    left = left.strip("\n")
    right = right.strip("\n")
    print(f"{left}\t{right}")

Center Align

Write a program center_align.py to center align all lines in the given file.

$ cat poem.txt
There was an Old Man with a beard
Who said, "It is just as I feared!
Two Owls and a Hen,
Four Larks and a Wren,
Have all built their nests in my beard!"

$ python center_align.py poem.txt
   There was an Old Man with a beard
   Who said, "It is just as I feared!
          Two Owls and a Hen,
         Four Larks and a Wren,
Have all built their nests in my beard!"

Hint:

>>> "hello".center(7)
" hello "
>>> "hello".center(9)
"  hello  "

The built-in function max can take a list of numbers and return the maximum value out of them.

>>> max([1, 5, 2, 7, 4])
7

Solution

import sys
filename = sys.argv[1]
lines = open(filename).readlines()
if lines:
    n = max(len(line.strip()) for line in lines)

    for line in lines:
        print(line.strip().center(n))