{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "editable": false }, "outputs": [], "source": [ "# EXECUTE THIS ONE FIRST!\n", "\n", "from pathlib import Path\n", "\n", "# Constants for the exercises:\n", "WORKING_DIR = Path.cwd()\n", "DATA_DIR = WORKING_DIR.parent / \"data\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. Sum numbers listed in a file\n", "Fill ____ pieces of the code below. `sum_numbers_in_file` function takes a input file path as argument, reads the numbers listed in the input file and returns the sum of those numbers. You can assume that each line contains exactly one numeric value." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def sum_numbers_in_file(input_file):\n", " total = 0\n", " with ____(input_file) as ____:\n", " for line in ____:\n", " ____ = line.strip() # Remove potential white space\n", " total += float(____)\n", " return _____" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "editable": false }, "outputs": [], "source": [ "in_file = DATA_DIR / \"numbers.txt\"\n", "assert sum_numbers_in_file(in_file) == 189.5" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. Reading first word from each line of a file\n", "Implement `find_first_words` function which takes an input file path as argument. The function should find the first word of each line in the file and return these words as a list. If a line is empty, the returned list should contain an empty string for that line." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your implementation here" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "editable": false }, "outputs": [], "source": [ "in_file1 = DATA_DIR / \"simple_file.txt\"\n", "in_file2 = DATA_DIR / \"simple_file_with_empty_lines.txt\"\n", "\n", "expected_file_1 = [\"First\", \"Second\", \"Third\", \"And\"]\n", "assert find_first_words(in_file1) == expected_file_1\n", "\n", "expected_file_2 = [\"The\", \"\", \"First\", \"nonsense\", \"\", \"Then\"]\n", "assert find_first_words(in_file2) == expected_file_2" ] } ], "metadata": { "celltoolbar": "Edit Metadata", "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.0" } }, "nbformat": 4, "nbformat_minor": 2 }