{ "cells": [ { "cell_type": "markdown", "id": "bd05e0b5", "metadata": {}, "source": [ "# Task 1: Zip List\n", "\n", "You are given two list @a and @b of same size.\n", "\n", "Create a subroutine sub zip(@a, @b) that merge the two list as shown in the example below.\n", "Example\n", "```\n", "Input: @a = qw/1 2 3/; @b = qw/a b c/;\n", "Output: zip(@a, @b) should return qw/1 a 2 b 3 c/;\n", " zip(@b, @a) should return qw/a 1 b 2 c 3/;\n", "```" ] }, { "cell_type": "markdown", "id": "4ca2c151", "metadata": {}, "source": [ "There is a python builtin function called zip which doesn't do exactly what we are looking for. It produces a list of tuples paired by position and truncated to the shortest list." ] }, { "cell_type": "code", "execution_count": 1, "id": "04fd3afe", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3]\n", "b = ['a', 'b', 'c']\n", "\n", "zip(a, b)" ] }, { "cell_type": "code", "execution_count": 2, "id": "d62a76f9", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(1, 'a'), (2, 'b'), (3, 'c')]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(zip(a, b))" ] }, { "cell_type": "markdown", "id": "94604825", "metadata": {}, "source": [ "Defining my own zip function but using the builtin zip function within it I can convert a list of tuples into a list:" ] }, { "cell_type": "code", "execution_count": 3, "id": "1e8b38dd", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 'a', 2, 'b', 3, 'c']" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import itertools\n", "\n", "def zip(a, b):\n", " zipped = __builtin__.zip(a, b)\n", " return list(itertools.chain(*zipped))\n", "\n", "zip(a, b)" ] }, { "cell_type": "markdown", "id": "def9f2bf", "metadata": {}, "source": [ "Test with the arguments reversed:" ] }, { "cell_type": "code", "execution_count": 4, "id": "fa9a665b", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 1, 'b', 2, 'c', 3]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "zip(b, a)" ] } ], "metadata": { "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.10" } }, "nbformat": 4, "nbformat_minor": 5 }