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.txtonetwothreefourfive
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'
withopen("five.txt") as f:print(max(f, key=len))
three
steps
Take argument from commandline using sys/typer
open the file using with statement
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.txt12345678910
Writing ten.txt
steps
Take filename/path from commandline argument using sys/typer
open the file with with statement
process line by converting into a number (int)
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.
words = ["one", "two", "three"]numbers = [1 , 2, 3]{ w:n for w, n inzip(words, numbers)}
{'one': 1, 'two': 2, 'three': 3}
steps
make a function with name inverdict
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.txtABCD
Overwriting a.txt
withopen("a.txt") as af:withopen("five.txt") as ff:for line1, line2 inzip(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
Make a python file and take two files from command line argument using sys/typer
open both files (using nested with blocks)
make use of zip to go over lines from both files at time
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
Write a python file with will take filename as command line argument using sys/typer
write a function wordcount which will find nmber of words in a line
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
Most steps are same for opening the file
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})"
SyntaxError: invalid syntax (2001981345.py, line 19)
steps
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.
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
Make use of dictinary to find sum of amount (3rd column) just like we did in word frequncy program
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'