Nurturing Session

Problem 1 Longest Line

%load_problem longest-line
Problem: Longest Line

Write a program longest_line.py to print the longest line from a file.

The program should take a filename as a command-line argument and print the longest line from it.

$ python longest_line.py files/five.txt
three

$ python longest_line.py files/zen-of-python.txt
There should be one-- and preferably only one --obvious way to do it.

$ python longest_line.py files/bumper-stickers.txt
The first 90 percent of the code accounts for the first 90 percent of the development time. The remaining 10 percent of the code accounts for the other 90 percent of the development time.

You can verify your solution using:

%verify_problem longest-line

%%file longest_line.py
# your code here


%%file five.txt
one
two
three
four
five
Overwriting five.txt
max(["one", "two", "three", "four", "five"]) # max by dictinary order
'two'
words  = ["one", "two", "three", "four", "five"]
max(words, key=len)
'three'
with open("five.txt") as f:
    print(max(f, key=len))
three

steps

  1. Take argument from commandline using sys/typer
  2. open the file using with statement
  3. make use of max function with len as key to find line with maximum length

Problem 2 Sum file

%load_problem sumfile
Problem: Sum File

Write a program sumfile.py that takes a filename as argument and prints sum of all numbers in the file. It is assumed that the file contains one number per line.

$ python sumfile.py files/ten.txt
55

You can verify your solution using:

%verify_problem sumfile

%%file sumfile.py
# your code here


%%file ten.txt
1
2
3
4
5
6
7
8
9
10
Writing ten.txt

steps

  1. Take filename/path from commandline argument using sys/typer
  2. open the file with with statement
  3. process line by converting into a number (int)
  4. if you wish you can convert your for loop into list comprehension

Problem 3 Invert Dictionary

%load_problem invertdict
Problem: Invert Dict

Write a function invertdict to interchange the keys and values in a dictionary.

The function should take a dictionary as an argument and return a new dictionary with keys and values interchanged. For simplicity, assume that the values in the dictionary are unique.

>>> invertdict({"x": 1, "y": 2, "z": 3})
{1: "x", 2: "y", 3: "z"}

You can verify your solution using:

%verify_problem invertdict

# your code here


{[1, 2, 3]: "a"}
TypeError: unhashable type: 'list'
{"a": 1, "b": 2, "c": 3}
{'a': 1, 'b': 2, 'c': 3}
x = [1, 2, 3]
d = {"a": x}
x.append(5)
d
{'a': [1, 2, 3, 5]}
d = {"x": 1, "y": 2, "z": 3}
for key in d:
    print(key, d[key])
x 1
y 2
z 3
for key,value in d.items():
    print(key, value)
x 1
y 2
z 3
words = ["one", "two", "three"]
numbers = [1 , 2, 3]

{ w:n for w, n in zip(words, numbers)}
{'one': 1, 'two': 2, 'three': 3}

steps

  1. make a function with name inverdict
  2. return a dictionary comprehension which will swap key, value

Problem 4 - Paste

%load_problem paste-cmd
Problem: 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"

You can verify your solution using:

%verify_problem paste-cmd

%%file paste.py
# your code here


%%file a.txt
A
B
C
D
Overwriting a.txt
with open("a.txt") as af:
    with open("five.txt") as ff:
        for line1, line2 in zip(af, ff):
            print(line1.strip(), line2.strip())
A one
B two
C three
D four
a = "A"
b = "B"
print(f"{a}\t{b}")
A   B

steps

  1. Make a python file and take two files from command line argument using sys/typer
  2. open both files (using nested with blocks)
  3. make use of zip to go over lines from both files at time
  4. make use of string formating to print appropriately

Problem 5 - Line with most words

%load_problem line-with-most-words
Problem: Line with Most Words

Write a program line_with_most_words.py that takes a filename as command-line argument and prints the line with the most number of words from the file.

$ cat files/words.txt
one
one two
one two three
one two three four
one two three four five
two three four five
three four five
four five
five
one-two-three-four-five-six-seven

$ python line_with_most_words.py files/words.txt
one two three four five

You can verify your solution using:

%verify_problem line-with-most-words

%%file line_with_most_words.py
# your code here


%%file line_with_most_words.py
# your code here


how do you get words from a string?

# line.split() # this will convert your line into words
def find_number_of_words(line):
    pass
    
max(f, key=find_number_of_words)

steps

  1. Write a python file with will take filename as command line argument using sys/typer
  2. write a function wordcount which will find nmber of words in a line
  3. open the file in read mode and pass filehandle to max and key should be the function wordcount

Problem 6 - Grep command

%load_problem grep
Problem: Grep Command

Implement Unix command grep in Python.

Write a program grep.py that takes a pattern and a file as command-line arguments and print all the lines in the file that contain that pattern.

The pattern could be any text and there is no need to support regular expressions.

$ cat files/zen-of-python.txt
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

$ python grep.py never files/zen-of-python.txt
Errors should never pass silently.
Now is better than never.
Although never is often better than *right* now.

$ grep the files/zen-of-python.txt
Special cases aren't special enough to break the rules.
In the face of ambiguity, refuse the temptation to guess.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.

You can verify your solution using:

%verify_problem grep

%%file grep.py
# your code here


steps

  1. Most steps are same for opening the file
  2. make if condition to check if given pattern/word is in given line
"this" in "jshdakjsah ksdjhf dsdkjfhkjds fksdjhf"
False
"this" in "this is another statement"
True

Problem 7 - Point double

%load_problem point-double
Problem: Double a Point

Add a method double to the Point class that doubles both x and y coordinates of the point.

You can start with this code for Point class.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def getx(self):
        return self.x

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

    def __str__(self):
        return f"({self.x}, {self.y})"

The expected behavior:

>>> p = Point(2, 3)
>>> p2 = p.double()
>>> p2
Point(4, 6)
>>> p.double().double()
Point(8, 12)

You can verify your solution using:

%verify_problem point-double

# your code here

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def getx(self):
        return self.x

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

    def __str__(self):
        return f"({self.x}, {self.y})"


    def double(self):
        return Point(....)
SyntaxError: invalid syntax (2001981345.py, line 19)

steps

  1. add a method double to Point class

Problem 8 - Sales by day

%load_problem sales-by-day
Problem: Sales by Day

Write a program sales.py to compute the total sale amount per day, given a text file with details of transactions with three columns Order Id, Date and Amount.

Here is a sample input file.

$ cat files/orders.txt
1001 2023-01-01 100
1002 2023-01-01 50
1003 2023-01-02 50
1004 2023-01-02 150
1005 2023-01-01 25

The file contains multiple transactions, one in row. Each row will have three fields, Order Id, Date and Amount, seperated by a space.

YOur program should take the order file as a command-line argument and print the total same amount per day. The output should be sorted by date.

$ python sales.py files/orders.txt
2023-01-01 175
2023-01-02 200

Please note that you are expected to parse the file yourself and not use pandas.

You can verify your solution using:

%verify_problem sales-by-day

%%file sales.py
# your code here


record = [("T1", 12, 0.5),
          ("T2", 11,  0.6),
          ()]

steps

  1. Make use of dictinary to find sum of amount (3rd column) just like we did in word frequncy program
  2. one you have dictinary of dates:total_amount , pass this dictionry to sorted and put a for loop to print date and amount

Problem 9 : sort words

%load_problem sort-words
Problem: Sort Words

Write a function sort_words to rearrange the words in a sentense in the sorted or order.

>>> sort_words("one two three four five")
'five four one three two'
>>> sort_words("white cat and black dog")
'and black cat dog white'
>>> sort_words("have a nice day")
'a day have nice'

You can verify your solution using:

%verify_problem sort-words

# your code here


steps

  1. make use spit to make words
  2. make use of sorted to sort
  3. make use of join to make sentent again