{ "cells": [ { "cell_type": "markdown", "metadata": { "kernel": "scala" }, "source": [ "# Imperative vs functional programming style\n", "\n", "In this notebook, the same task is implemented in three different programming languages using two different programming styles. The task in question is figuring out from a [letter dataset](letters.csv) all the authors who write more than 10 letters, and ordering them in decreasing order by their letter count.\n", "\n", "## Imperative\n", "\n", "Imperative programming is a style where you go through items, gathering new information bit by bit into new data structures." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "kernel": "python3" }, "outputs": [ { "data": { "text/plain": [ "[('Maria Celeste Galilei', 49),\n", " ('Geri Bocchineri', 49),\n", " ('Mario Guiducci', 30),\n", " ('Francesco Niccolini', 16)]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Python\n", "import pandas\n", "dt = pandas.read_csv(\"letters.csv\").to_dict(orient='records')\n", "# First, create an author name to letter count dictionary\n", "m = dict()\n", "# Now, go through all the letters, increasing the by author counts each time for the relevant author\n", "for row in dt:\n", " m[row['Author']] = m.get(row['Author'],0) + 1\n", "# Then, create a second dictionary, and copy into that only the authors and counts where the counts are over 10\n", "n = dict()\n", "for key,value in m.items():\n", " if (value>10):\n", " n[key] = value\n", "# Finally, sort the authors by decreasing counts\n", "sorted(n.items(), key=lambda p: (p[1],p[0]), reverse=True)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "kernel": "ir" }, "outputs": [ { "data": { "text/html": [ "