{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "BUoanKSko5J7"
   },
   "source": [
    "## 3. python data handling\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "CWGXlrmspaC0"
   },
   "source": [
    "### 3.1: what do these do?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "DGchMDOKpYww"
   },
   "outputs": [],
   "source": [
    "print('mywordlistparts'[::-1])\n",
    "# reversing the list\n",
    "\n",
    "print('mywordlistparts'[::-2])\n",
    "# reversing the list using only every second element\n",
    "\n",
    "print('mywordlistparts'[3::][::-1])\n",
    "# take the list from the fourth element on and reverse it\n",
    "\n",
    "print('mywordlistparts'[3::-1])\n",
    "# take the fourth to last element of the reversed list\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "SBwaIThJuCGE"
   },
   "source": [
    "### 3.2 Manual list sorting\n",
    "Take the list and resort it from smallest to largest number. You should use indexing and slicing, including the third *step* parameter (e. g. for reversing)\n",
    "- [9, 0, 8, 1, 7, 2, 6, 3, 5, 4]\n",
    "- [4, 5, 6, 0, 1, 3, 2, 7, 9, 8]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "86mmXg4Co5KF"
   },
   "outputs": [],
   "source": [
    "# The first list has the structure that every second entry is already sorted.\n",
    "# For the reversed list the same thing is true.\n",
    "l1 = [9, 0, 8, 1, 7, 2, 6, 3, 5, 4]\n",
    "\n",
    "##### Step by step solution:\n",
    "\n",
    "# First we get out every second entry forwards.\n",
    "# The used slice for this is: [1::2].\n",
    "# This means: [from element with index 1 (=second element): until the end (therefore no number): in steps of two]\n",
    "l1_sorted = l1[1::2]\n",
    "print('l1_sorted =', l1_sorted)\n",
    "# This leaves us with l1_sorted = [0, 1, 2, 3, 4]\n",
    "\n",
    "# Next we take the other half.\n",
    "# The used slice for this is: [0:-1:2].\n",
    "# This means: [from the first element: [leaving out the last element (stop not included!): steps of two]\n",
    "# You don't have to specify the exact end of the slice, so an alternative slice may be: [0::2]\n",
    "l1_sorted_helper = l1[0:-1:2]\n",
    "print('l1_sorted_helper =', l1_sorted_helper)\n",
    "# This gives us l1_sorted_helper = [9, 8, 7, 6, 5]\n",
    "\n",
    "# The best ways to reverse the list is either inplace (the actual list is modified) ...\n",
    "l1_sorted_helper.reverse()\n",
    "print('reversed l1_sorted_helper =', l1_sorted_helper)\n",
    "\n",
    "# ... or via another list slice.\n",
    "l1_sorted_helper.reverse () # Just change back the inplace modification from line 22.\n",
    "l1_sorted_helper = l1_sorted_helper[::-1] # This takes the full list but backwards.\n",
    "print('reversed l1_sorted_helper =', l1_sorted_helper)\n",
    "\n",
    "\n",
    "# Put lists together either using inplace modification l1_sorted.extend(l1_sorted_helper) or:\n",
    "l1_sorted += l1_sorted_helper\n",
    "print('completely sorted l1_sorted =', l1_sorted)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "icXt1Yh2o5Kn"
   },
   "outputs": [],
   "source": [
    "# The second list is more of a mess, we simply want to cut out slices to rearrange them.\n",
    "l2 = [4, 5, 6, 0, 1, 3, 2, 7, 9, 8]\n",
    "\n",
    "##### Step by step solution:\n",
    "\n",
    "l2_1 = l2[:3] \n",
    "# This gives us l2_1 = [4, 5, 6] remember, that the element with index 3 is not taken into the slice!\n",
    "# The slice l2[:2] would only be [4, 5].\n",
    "l2_2 = l2[3:5]\n",
    "# This gives us l2_2 = [0, 1].\n",
    "l2_3 = l2[5:7][::-1]\n",
    "# This leaves us with l2_3 = [2, 3].\n",
    "# An alternative slice to get this is l2_3 = l2[6:5:-1].\n",
    "l2_4 = [l2[-3]]\n",
    "# This gives us l2_4 = [7] --> We need extra brackets in this form as l2[-3] is only the number, NOT a slice.\n",
    "l2_5 = l2[-2:][::-1] \n",
    "# This leaves us with l2_5 = [8, 9].\n",
    "# For alternatives see line 13 and vary the indices: l2_5 = l2[-1:-2:-1].\n",
    "\n",
    "\n",
    "# Put now all small lists together to the completely sorted list l2_sorted:\n",
    "l2_sorted = l2_2 + l2_3 + l2_1 + l2_4 + l2_5\n",
    "print('completely sorted l2_sorted =', l2_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "jaxDWKpFr64t"
   },
   "source": [
    "### Example 3.3 string sorting\n",
    "How does the string 'TESTtest' sort? [Why is that?](https://home.unicode.org/)\n",
    "\n",
    "Characters in Python are encoded as uniform as default. This means, that every symbol in a string is represented by a certain byte object. The *sorted* function works with respect to these byte objects."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "W64-5mEIo5LK"
   },
   "source": [
    "## 5. Control structures\n",
    "\n",
    "### 5.1 Leap year calculator\n",
    "Write a function which you can pass a year to and it tells you whether the year is a leap year or not. A year is a leap year, if it can be completely divided by 4, but not, if it can also be divided completely by 100, but again it is, if completely divisible by 400. The answer should have a similar form to:\n",
    "\n",
    "    leap_year_calc(2000)\n",
    "    --> \"the year 2000 is a leap year!\"\n",
    "\n",
    "Test your function with the years: 2000 (True), 2004 (True), 2018 (False), 2100 (False)\n",
    "\n",
    "ADDITIONAL task: Tell the function caller the reason."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "C2nPkohHo5LO"
   },
   "outputs": [],
   "source": [
    "#### Step by Step solution:\n",
    "\n",
    "# Define a function with a name, for example the one below with one passed parameter:\n",
    "def is_leap_year(year):\n",
    "    \n",
    "    if year%400 == 0: \n",
    "        # In this case it's always gonna be a leap year.\n",
    "        print('The year %s is a leap year!'%year)\n",
    "        # Give an optional return value as it is true to be a leap year.\n",
    "        return True \n",
    "    \n",
    "    elif year%4 == 0:\n",
    "        # In this case it's only true if another requirement is fulfilled so do another test.\n",
    "        \n",
    "        if year%100 != 0:\n",
    "            # In this case it's always gonna be a leap year.\n",
    "            print('The year %s is a leap year!'%year)\n",
    "            # Give an optional return value as it is true to be a leap year.\n",
    "            return True \n",
    "        \n",
    "    # In all other cases it is not true.\n",
    "    print('The year %s is NOT a leap year!'%year)\n",
    "    # Give an optional return value as it is true to be a leap year.\n",
    "    return False\n",
    "\n",
    "# Test the given years:\n",
    "is_leap_year(2000)\n",
    "is_leap_year(2004)\n",
    "is_leap_year(2018)\n",
    "is_leap_year(2100)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "iN0ajERXo5Li"
   },
   "source": [
    "## End of examples about control structures"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Hocgof9to5Lk"
   },
   "source": [
    "### 5.2 Processing multiple objects using lists\n",
    "Write a for loop, that processes all years given in the last example "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "Tr3PTlG9o5Lo"
   },
   "outputs": [],
   "source": [
    "# Simple for-loop going through a list with the given years\n",
    "for year in [2000, 2004, 2018, 2100]:\n",
    "    is_leap_year(year)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "-TJu2xSHo5L-"
   },
   "source": [
    "### 5.3 Fibonacci numbers\n",
    "Write a function that returns a list of fibonacci numbers up to a given threshold.\n",
    "Fibonacci numbers are defined by starting from [1,1] always appending the sum of the two former elements to the list --> [1,1,2] --> [1,1,2,3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "qOtDEsjmo5MC"
   },
   "outputs": [],
   "source": [
    "##### Step by Step solution:\n",
    "\n",
    "# Define a function first with a passed parameter\n",
    "def fibonacci(n):\n",
    "    # The first two numbers are [1, 1].\n",
    "    # Catch the case in which the caller asks for special cases:\n",
    "    \n",
    "    # Asking for zero length list makes no sense, lets return an empty list:\n",
    "    if n == 0:\n",
    "        return []\n",
    "    \n",
    "    # Asking for one fibonacci number:\n",
    "    elif n == 1:\n",
    "        return [1]\n",
    "    \n",
    "    # Asking for two fibonacci numbers:\n",
    "    elif n == 2: \n",
    "        return [1, 1]\n",
    "    \n",
    "    # All other cases actually need a computation:\n",
    "    else:\n",
    "        # We need to initialize a list which we can then work with\n",
    "        x = [1, 1]\n",
    "        \n",
    "        # Loop over the list n times appending the sum of the last two elements.\n",
    "        # It is n-2 because the list already contains n==2 elements, so no loop would be needed.\n",
    "        for i in range(n-2):\n",
    "            x.append(x[-2]+x[-1])\n",
    "        return x\n",
    "\n",
    "for n in [0, 2, 4, 6, 10]:\n",
    "    print(fibonacci(n))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "BfiwqUYvo5MZ"
   },
   "source": [
    "## Wrap-up exercise"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "dYAaqdGko5Md"
   },
   "outputs": [],
   "source": [
    "# define the file name\n",
    "file_name = 'simple_data_set.csv'\n",
    "\n",
    "# open the file securely\n",
    "with open(file_name, 'r') as f:\n",
    "    #get all lines\n",
    "    lines = f.readlines()\n",
    "\n",
    "    # f can already be closed\n",
    "\n",
    "# create an empty dict\n",
    "data = {}\n",
    "\n",
    "# clean and split the first row that contains the keys\n",
    "# strip takes away the \\n at the end of the string\n",
    "keys = lines[0].strip().split(',')\n",
    "# create a dict entry with an empty list for each key\n",
    "for key in keys:\n",
    "    data[key] = []\n",
    "    \n",
    "print(\"The keys of the dicts are:\", data.keys())\n",
    "\n",
    "# loop over the rest of the lines\n",
    "for line in lines[1:]:\n",
    "    \n",
    "    # split the line\n",
    "    entries = line.strip().split(',')\n",
    "    \n",
    "    # loop over the keys and entries as zip\n",
    "    for key, entry in zip(keys, entries):\n",
    "        # append each entry to the appropriate list in the dict\n",
    "        # transform to float\n",
    "        if key != 'species':\n",
    "            entry = float(entry)\n",
    "        data[key].append( entry )\n",
    "\n",
    "# define a function to compute the mean value\n",
    "def mean(values):\n",
    "    # sum the values\n",
    "    summed_values = sum(values)\n",
    "    # return the sum divided by the number of samples\n",
    "    return summed_values/len(values)\n",
    "\n",
    "print(\"Start of data inspection:\")\n",
    "print()\n",
    "# loop over list\n",
    "for key, values in data.items():\n",
    "    \n",
    "    # skip species\n",
    "    if key == 'species':\n",
    "        continue\n",
    "    else:\n",
    "        print(\"Presenting feature {}\".format(key))\n",
    "        # compute numerical attributes\n",
    "        print(\"  number of entries: {}\".format(len(values)))\n",
    "        print(\"  minimum value: {}\".format(min(values)))\n",
    "        print(\"  maximum value: {}\".format(max(values)))\n",
    "        print(\"  mean value: {:.3f}\".format(mean(values)))\n",
    "        # separating the output a bit\n",
    "        print()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "LRoUjqQ7o5My"
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "name": "1_Solutions.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "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.8.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
