23  Nurturing Session 3

%load_problem wget
Problem: Wget

Write a program wget.py that takes a URL as command-line argument and downloads that to current directory.

$ python wget.py https://anandology.com/tmp/hello.txt
Downloaded to hello.txt

$ python wget.py https://anandology.com/tmp/python.png
Downloaded to python.png

Please note that the filename to save the URL is identified from the URL.

You can verify your solution using:

%verify_problem wget

%%file wget.py
# your code here
import sys



def download(url, file):
    pass

def filename(url):
    return url.split("/")[-1]

if __name__ == '__main__':
    url = sys.argv[1]
    file = filename(url)
    downloaded(url, file)

Overwriting wget.py
import requests
r = requests.get("https://anandology.com/tmp/hello.txt")
r.status_code
200
r.text
'Hello, world!\n'
url = "https://anandology.com/tmp/hello.txt"
with open("hello.txt", "wb") as f:
    f.write(r.content)
!cat hello.txt
Hello, world!
def filename(url):
    return url.split("/")[-1]
filename(url)
'hello.txt'
%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


with open("/opt/files/10.txt") as f:
    print(sum([int(line.strip()) for line in f]))
        
55
%load_problem frankfurter
Problem: Frankfurter Exchange Rates

Write a program frankfurter.py to list the historical currency rate of a currency against a base currency using Frankfurter Exchange Rate API.

make use of api https://api.frankfurter.dev/v1/end..start url in your api

The program should take the following command-line arguments.

  -c CURRENCY, --currency CURRENCY
                        target currency, default INR
  -b BASE, --base BASE  base currency, default USD
  -d DATE, --date DATE  First date to consider, default yesterday
  -n DAYS, --days DAYS  number of days to display

The program should display the curreny rate between the base currency and the target currency for n days starting from yesterday. Optionally, the start date could be provided as a command-line argument.

Please note that there convertion data is not available on weekends. So the number of rows of data shown may be less than n.

The Output Format

The output needs to be properly tabulated. Please use Python library tabulate for doing this.

Please refer to Printing Tables with Tabulate in the Python Cookbook to learn how to the the tabulate library.

Usage

$ python frankfurter.py
Date          USD    INR
----------  -----  -----
2023-10-18      1  83.25
2023-10-17      1  83.22
2023-10-16      1  83.25
2023-10-13      1  83.27
2023-10-12      1  83.24
2023-10-11      1  83.18
2023-10-10      1  83.24
2023-10-09      1  83.3
$ python frankfurter.py -n 2
Date          USD    INR
----------  -----  -----
2023-10-18      1  83.25
2023-10-17      1  83.22
$ python frankfurter.py -b GBP
Date          GBP     INR
----------  -----  ------
2023-10-18      1  101.55
2023-10-17      1  101.31
2023-10-16      1  101.37
2023-10-13      1  101.41
2023-10-12      1  102.47
2023-10-11      1  102.24
2023-10-10      1  101.96
2023-10-09      1  101.39
$ python frankfurter.py -b GBP -c USD
Date          GBP     USD
----------  -----  ------
2023-10-18      1  1.2198
2023-10-17      1  1.2173
2023-10-16      1  1.2176
2023-10-13      1  1.2178
2023-10-12      1  1.231
2023-10-11      1  1.2292
2023-10-10      1  1.2249
2023-10-09      1  1.2172
$ python frankfurter.py -d 2023-01-31
Date          USD    INR
----------  -----  -----
2023-01-31      1  81.82
2023-01-30      1  81.53
2023-01-27      1  81.61
2023-01-26      1  81.53
2023-01-25      1  81.57
2023-01-24      1  81.62
2023-01-23      1  81.36

Hints

You can verify your solution using:

%verify_problem frankfurter

%%file frankfurter.py
# your code here
import typer
from typing import Annotated
import tabulate


def extract_data_from_json(jsondata, base, currency):
    headers = ["Date", base, currency]
    data = list(zip(jsondata['rates'].keys(), [1]*len(urldata['rates']),[v[currency] for v in urldata['rates'].values()]))    
    print(tabulate.tabulate(data, headers=headers))

def get_currency_data(currency: Annotated[str, typer.Option("--CURRENCY", "-c", help="Target currency")]="INR",
                      base:Annotated[str, typer.Option("--base", "-b", help="Base currency")]="USD",
                      date: Annotated[str, typer.Option("--date", "-d", help="Date for which data is requested")]=None,
                      days: Annotated[int, typer.Option("--days", "-n", help="Number of days")]=10):
    if date is None:
        date = datetime.datetime.today() - datetime.timedelta(days=1)

    # get end date ...date - timedelta(days=n)

    # compute the url

    # fethch data using request
    
    extract_data_from_json(jsondata)
    


if __name__ == "__main__":
    typer.run(get_currency_data)
Overwriting frankfurter.py
!python frankfurter.py --help
                                                                                

 Usage: frankfurter.py [OPTIONS]                                                

                                                                                

╭─ Options ────────────────────────────────────────────────────────────────────╮

│ --CURRENCY  -c      TEXT     Target currency [default: INR]                  │

│ --base      -b      TEXT     Base currency [default: USD]                    │

│ --date      -d      TEXT     Date for which data is requested                │

│ --days      -n      INTEGER  Number of days [default: 10]                    │

│ --help                       Show this message and exit.                     │

╰──────────────────────────────────────────────────────────────────────────────╯


import requests
startdate = "2026-01-01"
n = 9
import datetime
start = datetime.date.fromisoformat(startdate)
end = start - datetime.timedelta(days=n) # end is n days behind the start!
end
datetime.date(2025, 12, 23)
startf = startdate
endf = end.strftime("%Y-%m-%d")
url = f"https://api.frankfurter.dev/v1/{endf}..{startf}"
url
'https://api.frankfurter.dev/v1/2025-12-23..2026-01-01'
params = {"base": "USD",
          "to": "GBP"}
r = requests.get(url, params= params)
r.status_code
200
r.json()
{'amount': 1.0,
 'base': 'USD',
 'start_date': '2025-12-23',
 'end_date': '2025-12-31',
 'rates': {'2025-12-23': {'GBP': 0.74062},
  '2025-12-24': {'GBP': 0.74056},
  '2025-12-29': {'GBP': 0.74163},
  '2025-12-30': {'GBP': 0.74101},
  '2025-12-31': {'GBP': 0.74264}}}
urldata = r.json()
headers = ["Date", params['base'], params['to']]
data = list(zip(urldata['rates'].keys(), [1]*len(urldata['rates']),[v['GBP'] for v in urldata['rates'].values()]))
import tabulate
def extract_data_from_json(jsondata, base, currency):
    headers = ["Date", base, currency]
    data = list(zip(jsondata['rates'].keys(), [1]*len(urldata['rates']),[v[currency] for v in urldata['rates'].values()]))    
    print(tabulate.tabulate(data, headers=headers))
extract_data_from_json(urldata, "USD", "GBP")
Date          USD      GBP
----------  -----  -------
2025-12-23      1  0.74062
2025-12-24      1  0.74056
2025-12-29      1  0.74163
2025-12-30      1  0.74101
2025-12-31      1  0.74264
[urldata['rates']]
[{'2025-12-23': {'GBP': 0.74062},
  '2025-12-24': {'GBP': 0.74056},
  '2025-12-29': {'GBP': 0.74163},
  '2025-12-30': {'GBP': 0.74101},
  '2025-12-31': {'GBP': 0.74264}}]
data
[('2025-12-23', 1, 0.74062),
 ('2025-12-24', 1, 0.74056),
 ('2025-12-29', 1, 0.74163),
 ('2025-12-30', 1, 0.74101),
 ('2025-12-31', 1, 0.74264)]
[v['GBP'] for v in urldata['rates'].values()]
[0.74062, 0.74056, 0.74163, 0.74101, 0.74264]
import tabulate
print(tabulate.tabulate(data, headers=headers))
Date          USD      GBP
----------  -----  -------
2025-12-23      1  0.74062
2025-12-24      1  0.74056
2025-12-29      1  0.74163
2025-12-30      1  0.74101
2025-12-31      1  0.74264
%load_problem longest-argument
Problem: 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.

You can verify your solution using:

%verify_problem longest-argument

%%file longest_argument.py
# your code here


words = ["one", "two", "three", "four"]
max(words, key=len)
'three'
%load_problem timer
Problem: Timer

Write a class Timer that can be used to find out time taken by some code execution. Make use of time.time function to get current time stamp in seconds.

def do_something():
    time.sleep(2)

timer = Timer()

timer.start()
do_something()
timer.stop()

print(timer.get_elapsed_time())
# 2.000

You can verify your solution using:

%verify_problem timer

# your code here
import time

class Timer:

    def __init__(self):
        self.startime = 0
        self.endtime = 0

    def start(self):
        self.startime = time.time()

    def stop(self):
        self.endtime = time.time()

    def get_elapsed_time(self):
        return self.endtime - self.startime
        
%verify_problem timer
Found 2 checks
✗ test sleep(0.5)
Traceback (most recent call last):
  File "/opt/arcesium-finop-25/pipalhub-magic/pipalhub_magic.py", line 237, in run
    result = self.do_eval(self.code, env)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/arcesium-finop-25/pipalhub-magic/pipalhub_magic.py", line 219, in do_eval
    exec(self.code, env)
  File "<string>", line 2, in <module>
ModuleNotFoundError: No module named 'pytest'
✗ test sleep(1)
Traceback (most recent call last):
  File "/opt/arcesium-finop-25/pipalhub-magic/pipalhub_magic.py", line 237, in run
    result = self.do_eval(self.code, env)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/arcesium-finop-25/pipalhub-magic/pipalhub_magic.py", line 219, in do_eval
    exec(self.code, env)
  File "<string>", line 2, in <module>
ModuleNotFoundError: No module named 'pytest'
💥 Oops! Your solution to problem timer is incorrect or incomplete.
def do_something():
    time.sleep(2)

timer = Timer()

timer.start()
do_something()
timer.stop()

print(timer.get_elapsed_time())
# 2.000
2.0002193450927734