<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Caynan</title>
  
  <link href="/atom.xml" rel="self"/>
  
  <link href="https://www.caynan.org/"/>
  <updated>2017-04-05T18:13:11.727Z</updated>
  <id>https://www.caynan.org/</id>
  
  <author>
    <name>Caynan Sousa</name>
    
  </author>
  
  <generator uri="http://hexo.io/">Hexo</generator>
  
  <entry>
    <title>Course Dependency Network</title>
    <link href="https://www.caynan.org/2017/course-dependency-network/"/>
    <id>https://www.caynan.org/2017/course-dependency-network/</id>
    <published>2017-04-02T18:45:19.000Z</published>
    <updated>2017-04-05T18:13:11.727Z</updated>
    
    <content type="html"><![CDATA[<p>Let’s do some data visualization on networks (graphs)…</p>
<a id="more"></a>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.7.3/d3.js"></script>
    <script src="https://d3js.org/d3-color.v1.min.js"></script>
    <script src="https://d3js.org/d3-interpolate.v1.min.js"></script>
    <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
    <script src="https://d3js.org/d3-scale.v1.min.js"></script>
    <script src="js/d3-tip.js"></script>

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g=" crossorigin="anonymous"></script>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>




  <style>
    .link {
      stroke: #ccc;
    }

    .node text {
      pointer-events: none;
      font: 10px sans-serif;
    }

    .d3-tip {
      line-height: 1;
      font-weight: bold;
      padding: 12px;
      background: rgba(0, 0, 0, 0.8);
      color: #fff;
      border-radius: 2px;
    }

    .d3-tip:after {
      box-sizing: border-box;
      display: inline;
      font-size: 10px;
      width: 100%;
      line-height: 1;
      color: rgba(0, 0, 0, 0.8);
      content: "\25BC";
      position: absolute;
      text-align: center;
    }

    .d3-tip.n:after {
      margin: -1px 0 0 0;
      top: 100%;
      left: 0;
    }
  </style>



<p>Below you can choose a course (or two) and se the difference between them, you can also double-click on any given node to see only it’s immediate neighbors.</p>
<p>All courses have a central node (the bigger one) which basically is connected to all courses which don’t have dependencies.</p>
<p>For example, if you choose <code>administracao_n_ss</code> you can see all the courses from the business major at the Campina Grande campus, you can compare it with the same major but on a different campus (e.g: <code>administracao_n_cg</code>) you cann see how different they are, the one from the Campina Grande campus have more classes from different departments, and have a different topology, you can hover over the node to see their name (sorry they’re all in portuguese).</p>
<p>Have Fun!!</p>
<div class="alert info"><ul>
<li>You can <strong>double click</strong> on node to see only their immediate neighbors.</li>
<li>You can <strong>hover over</strong> the node to see their names.</li>
<li>The bigger node show the beginning of the course (all classes you can take without any pre-requisite).</li>
</ul>
</div>


<div class="row">
    <div class="col-md-6">
        <div class="input-group center">
            <div class="dropdown">
                <button id="dropdown1" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
                    engenharia_eletrica_cg
                    <span class="caret"></span>
                </button>
                <ul id="options1" class="dropdown-menu scrollable-menu">

                </ul>
            </div>
        </div>
    </div>
    </div>
        <!-- endcontent -->
          <div id="chart1" style="width=100%; margin: 0 auto;"></div>
        <!-- content -->


        <div class="input-group center">
            <div class="dropdown">
                <button id="dropdown2" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
                    ciencia_da_computacao_d_cg
                    <span class="caret"></span>
                </button>
                <ul id="options2" class="dropdown-menu scrollable-menu">

                </ul>
            </div>
        </div>
        <!-- endcontent -->
          <div id="chart2" style="width=100%; margin: 0 auto;"></div>
        <!-- content -->



<script src="js/d3-network.js"></script>



]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Let’s do some data visualization on networks (graphs)…&lt;/p&gt;
    
    </summary>
    
    
      <category term="D3.js, data visualization" scheme="https://www.caynan.org/tags/D3-js-data-visualization/"/>
    
  </entry>
  
  <entry>
    <title>Visualizing the Brazilian Semiarid</title>
    <link href="https://www.caynan.org/2017/brazil-semiarid/"/>
    <id>https://www.caynan.org/2017/brazil-semiarid/</id>
    <published>2017-03-20T21:26:02.000Z</published>
    <updated>2017-04-05T18:13:11.719Z</updated>
    
    <content type="html"><![CDATA[<p>Let’s do some data visualizations on the Brazilian Semiarid!!</p>
<a id="more"></a>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.7.3/d3.js"></script>
    <script src="https://d3js.org/d3-color.v1.min.js"></script>
    <script src="https://d3js.org/d3-interpolate.v1.min.js"></script>
    <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
    <script src="https://d3js.org/d3-scale.v1.min.js"></script>
    <script src="//d3js.org/topojson.v1.min.js"></script>


<p>Also Know as Sertão.</p>
<p>Originally the term referred to the vast hinterlands of Asia and South America that Lusitanian explorers encountered. In Brazil it referred to backlands away from the Atlantic coastal regions where the Portuguese first settled in South America in the early sixteenth century. A Brazilian historian once referred to colonial life in Brazil as a “civilization of crabs”, as most settlers clung to the shoreline, with few trying to make inroads into the sertão. In modern terms, “sertão” refers to the semi-arid region in Northeastern Brazil comprising parts of the states of Alagoas, Bahia, Pernambuco, Paraíba, Rio Grande do Norte, Ceará, Maranhão, Piauí, and parts of northern Minas Gerais. The term Vaqueiro is similar to the generic use of “cowboy” in the United States.</p>
<p>Geographically, the sertão consists mainly of low uplands that form part of the Brazilian Highlands. Most parts of the sertão are between 200 and 500 meters above sea level, with higher elevations found on the eastern edge in the Planalto da Borborema, where it merges into a sub-humid region known as agreste, in the Serra da Ibiapaba in western Ceará and in the Serro do Periquito of central Pernambuco. In the north, the sertão extends to the northern coastal plains of Rio Grande do Norte state, whilst in the south it fades out in the northern fringe of Minas Gerais. Two major rivers cross the sertão, the Rio Jaguaribe and the Rio Piranhas further east. Apart from the Rio São Francisco, which originates outside the region, other rivers dry out after the rainy periods end.</p>
<h1 id="visualizing-info-about-it">Visualizing info about it</h1>
<p>Let’s plot some maps of this region with some interesting data.</p>
<h2 id="quantity-of-water-supply-stops">Quantity of water supply stops</h2>
<p>Let’s see which cities had the highest rate of stop in the water supply. We’re using a continuos color scale from blue to red, which means that the lower the number of water supply stops during the year of 2015 the bluer the city is and the more stops we have the city is in a darker shade of red. Grey cities show are cities on which we don’t have data.</p>

    <div id="chart-paralizations"></div>



<script>
    width = 600,
    height = 800;

    var svg_paralizations = d3.select("#chart-paralizations")
    .append("svg")
    .attr('version', '1.1')
    .attr('viewBox', '0 0 ' + width + ' ' + height)
    .attr('width', '100%')
    .attr('class', 'map-chart');

    var projection = d3.geoAlbers()
    .center([-36.820037, -7.195265])
    .rotate([0, 0])
    .parallels([0, 0])
    .scale(2800);

    var path = d3.geoPath().projection(projection);

    d3.queue()
    .defer(d3.json, "cities_sertao.json")
    .defer(d3.csv, "data_sertao.csv")
    .await(draw_paralizations);

    function draw_paralizations(error, br, dados_csv) {
      if (error) throw error;

      var scale = d3.scaleLinear()
        .domain([0, 50])
        .range([0, 1]);      

      var municipios = topojson.feature(br, br.objects.municipios_sab);

      svg_paralizations.selectAll(".municipios")
      .data(municipios.features)
      .enter().append("path")
      .attr("id", function(d) {return "chart-paralizations-municipio-" + d.properties.ID;})
      .attr("d", path)
      .style("opacity", 0.8);

      for (var i = 0; i < dados_csv.length; i++) {
        svg_paralizations.select("#chart-paralizations-municipio-" + dados_csv[i].geoid)
        .attr("fill", function (){
          if (isNaN(dados_csv[i].qty_water_supply_paralizations)) return "#D3D3D3";
          return d3.interpolateRdYlBu(scale(+dados_csv[i].qty_water_supply_paralizations))
        });
      }
    }
  </script>


<h2 id="regions-with-the-highest-demand-for-water">Regions with the highest demand for water</h2>
<p>Let’s see where is concentrated the highest number of people with water supply, so we can see which regions has the highest demand for water. We’re using a color scale from light blue to dark blue, the higher the demand the darker is the shade of blue. Grey cities show are cities on which we don’t have data.</p>

    <div id="chart-water-supply"></div>



  <script>
      width = 600,
      height = 800;

      var svg_water = d3.select("#chart-water-supply")
      .append("svg")
      .attr('version', '1.1')
      .attr('viewBox', '0 0 ' + width + ' ' + height)
      .attr('width', '100%')
      .attr('class', 'map-chart');

      var projection = d3.geoAlbers()
      .center([-36.820037, -7.195265])
      .rotate([0, 0])
      .parallels([0, 0])
      .scale(2800);

      var path = d3.geoPath().projection(projection);

      d3.queue()
      .defer(d3.json, "cities_sertao.json")
      .defer(d3.csv, "data_sertao.csv")
      .await(draw_water);

      function draw_water(error, br, dados_csv) {
        if (error) throw error;

        var scale = d3.scaleLinear()
          .domain([1714, 22590])
          .range([0, 1]);      

        var municipios = topojson.feature(br, br.objects.municipios_sab);

        svg_water.selectAll(".municipios")
        .data(municipios.features)
        .enter().append("path")
        .attr("id", function(d) {return "chart-water-supply-municipio-" + d.properties.ID;})
        .attr("d", path)
        .style("opacity", 0.8);

        for (var i = 0; i < dados_csv.length; i++) {
          svg_water.select("#chart-water-supply-municipio-" + dados_csv[i].geoid)
          .attr("fill", function (){
            var value = +dados_csv[i].pop_with_water_supply
            if (isNaN(value)) return "#D3D3D3";
            return d3.interpolateBlues(scale(value))
          });
        }
      }
    </script>


<h2 id="if-the-city-has-selective-waste-collection-or-not">If the City Has Selective Waste Collection or Not</h2>
<p>Let’s see which cities have selective waste collection or not, cities in green have it and cities in red don’t have it. Grey cities show cities on which we don’t have data.</p>

    <div id="chart-waste"></div>



  <script>
      width = 600,
      height = 800;

      var svg_waste = d3.select("#chart-waste")
      .append("svg")
      .attr('version', '1.1')
      .attr('viewBox', '0 0 ' + width + ' ' + height)
      .attr('width', '100%')
      .attr('class', 'map-chart');

      var projection = d3.geoAlbers()
      .center([-36.820037, -7.195265])
      .rotate([0, 0])
      .parallels([0, 0])
      .scale(2800);

      var path = d3.geoPath().projection(projection);

      d3.queue()
      .defer(d3.json, "cities_sertao.json")
      .defer(d3.csv, "data_sertao.csv")
      .await(draw_waste);

      function draw_waste(error, br, dados_csv) {
        if (error) throw error;    

        var municipios = topojson.feature(br, br.objects.municipios_sab);

        svg_waste.selectAll(".municipios")
        .data(municipios.features)
        .enter().append("path")
        .attr("id", function(d) {return "chart-waste-supply-municipio-" + d.properties.ID;})
        .attr("d", path)
        .style("opacity", 0.8);

        for (var i = 0; i < dados_csv.length; i++) {
          svg_waste.select("#chart-waste-supply-municipio-" + dados_csv[i].geoid)
          .attr("fill", function (){
            var value = dados_csv[i].has_selective_waste_collection

            if (value == "NA") {
              return "#D3D3D3"
            }
            else if (value == "TRUE") {
              return "#77dd77"
            }
            else {
              return "#ff6961"
            }
          });
        }
      }
    </script>



]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Let’s do some data visualizations on the Brazilian Semiarid!!&lt;/p&gt;
    
    </summary>
    
    
      <category term="Data Visualization, Data Analysis, Brazil, Semiarid" scheme="https://www.caynan.org/tags/Data-Visualization-Data-Analysis-Brazil-Semiarid/"/>
    
  </entry>
  
  <entry>
    <title>How Random Are You?</title>
    <link href="https://www.caynan.org/2017/how-random-are-you/"/>
    <id>https://www.caynan.org/2017/how-random-are-you/</id>
    <published>2017-02-24T21:26:02.000Z</published>
    <updated>2017-04-05T18:13:11.755Z</updated>
    
    <content type="html"><![CDATA[<p>How random do you really think you are?</p>
<a id="more"></a>

<p>This chart is an improvement on a colleague work, which can be found <a href="https://arthurgca.github.io/visualizacaodados/#" target="_blank" rel="external">here</a>.</p>
<p>I tried to improve the information communication channel, by using a heat map. The use of a heat map allowed us to have a better insight on the hours and days of the week on which the people who completed the survey perceived their selves as the most random.</p>
<p>The previous chart also used mean to aggregate all the users that answered on a given time slot, I choose to use median, since is a more robust metric to outliers, people who perceived theirselves as really bad(0) or really random (10).</p>
<p>Without further ado…</p>
<h2 id="here-is-the-chart">Here is the chart</h2>

<style>
  rect.bordered {
    stroke: #E6E6E6;
    stroke-width:2px;
  }

  text.mono {
    font-size: 9pt;
    font-family: Consolas, courier;
    fill: #aaa;
  }

  text.axis-workweek {
    fill: #000;
  }

  text.axis-worktime {
    fill: #000;
  }
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>

<div id="chart"></div>
    <script type="text/javascript">
      var margin = { top: 50, right: 0, bottom: 100, left: 30 },
          width = 740 - margin.left - margin.right,
          height = 400 - margin.top - margin.bottom,
          gridSize = Math.floor(width / 24),
          legendElementWidth = gridSize*2,
          buckets = 9,
          colors = ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"], // alternatively colorbrewer.YlGnBu[9]
          days = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
          times = ["12p", "1a", "2a", "3a", "4a", "5a", "6a", "7a", "8a", "9a", "10a", "11a", "12a", "1p", "2p", "3p", "4p", "5p", "6p", "7p", "8p", "9p", "10p", "11p"];
          datasets = "data.tsv";

      var svg = d3.select("#chart").append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
          .append("g")
          .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

      var dayLabels = svg.selectAll(".dayLabel")
          .data(days)
          .enter().append("text")
            .text(function (d) { return d; })
            .attr("x", 0)
            .attr("y", function (d, i) { return i * gridSize; })
            .style("text-anchor", "end")
            .attr("transform", "translate(-6," + gridSize / 1.5 + ")")
            .attr("class", function (d, i) { return ((i >= 0 && i <= 4) ? "dayLabel mono axis axis-workweek" : "dayLabel mono axis"); });

      var timeLabels = svg.selectAll(".timeLabel")
          .data(times)
          .enter().append("text")
            .text(function(d) { return d; })
            .attr("x", function(d, i) { return i * gridSize; })
            .attr("y", 0)
            .style("text-anchor", "middle")
            .attr("transform", "translate(" + gridSize / 2 + ", -6)")
            .attr("class", function(d, i) { return ((i >= 7 && i <= 18) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis"); });

      var heatmapChart = function(tsvFile) {
        d3.tsv(tsvFile,
        function(d) {
          return {
            day: +d.day,
            hour: +d.hour,
            value: +d.value
          };
        },
        function(error, data) {
          var colorScale = d3.scale.quantile()
              .domain([0, buckets - 1, d3.max(data, function (d) { return d.value; })])
              .range(colors);

          var cards = svg.selectAll(".hour")
              .data(data, function(d) {return d.day+':'+d.hour;});

          cards.append("title");

          cards.enter().append("rect")
              .attr("x", function(d) {return (d.hour) * gridSize; })
              .attr("y", function(d) { return (d.day) * gridSize; })
              .attr("rx", 4)
              .attr("ry", 4)
              .attr("class", "hour bordered")
              .attr("width", gridSize)
              .attr("height", gridSize)
              .style("fill", colors[0]);

          cards.transition().duration(1000)
              .style("fill", function(d) { return colorScale(d.value); });

          cards.select("title").text(function(d) { return d.value; });

          cards.exit().remove();

          console.log([].concat(colorScale.quantiles()))
          var legend = svg.selectAll(".legend")
              .data([].concat(colorScale.quantiles()), function(d) {console.log(d); return d; });

          legend.enter().append("g")
              .attr("class", "legend");

          legend.append("rect")
            .attr("x", function(d, i) { return legendElementWidth * i; })
            .attr("y", height)
            .attr("width", legendElementWidth)
            .attr("height", gridSize / 2)
            .style("fill", function(d, i) { return colors[i]; });

          legend.append("text")
            .attr("class", "mono")
            .text(function(d) {return "≥ " + +d.toFixed(1); })
            .attr("x", function(d, i) { return legendElementWidth * i; })
            .attr("y", height + gridSize);

          legend.exit().remove();

        });
      };

      heatmapChart(datasets);
    </script>
         


<h2 id="insights">Insights</h2>
<p>What this visualization tell us, is that first we probably have more people answering the form on Thursday; Second, it tell us that the majority of people tend to think that they are not that random.</p>
<p>We need more data, specially data from different days of the week, but we can see from the visualization that we probably don’t have a great correlation between day of the week/hour and how random a person perceive itself.</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;How random do you really think you are?&lt;/p&gt;
    
    </summary>
    
    
      <category term="Data Visualization, Data Analysis" scheme="https://www.caynan.org/tags/Data-Visualization-Data-Analysis/"/>
    
  </entry>
  
  <entry>
    <title>Linked List in Python</title>
    <link href="https://www.caynan.org/2016/linked-list-python/"/>
    <id>https://www.caynan.org/2016/linked-list-python/</id>
    <published>2016-10-23T22:13:31.000Z</published>
    <updated>2017-04-05T18:13:11.755Z</updated>
    
    <content type="html"><![CDATA[<p>Today, we’re going to implement a linked list in python</p>
<a id="more"></a>

<h3 id="overview">Overview</h3>
<blockquote><p>In computer science, a linked list is a data structure consisting of a group<br>of nodes which together represent a sequence. Under the simplest form, each<br>node is composed of a data and a reference (in other words, a link) to the<br>next node in the sequence; more complex variants add additional links. This<br>structure allows for efficient insertion or removal of elements from any<br>position in the sequence.  </p>
<footer><strong>Wikipedia</strong><cite><a href="http://en.wikipedia.org/wiki/Linked_list" target="_blank" rel="external">Linked List</a></cite></footer></blockquote>


<p>Linked Lists are really simple data structures, we only have to remember when solving problems that involve them, to notice if we’re using singly linked lists (only have links to the next node) or doubly linked lists (links for previous and next nodes).</p>
<h3 id="code">CODE!</h3>
<p>Enough talking let’s start coding. First you should note the elements that a Linked List have, I see two of them, a Node and obviously the Linked List in itself, which if you think we could represent as a Node, we only need the Head of a Linked List to represent it.</p>
<p>So let’s create two classes in python, <code>Node</code> that is going to serve as a container for the data, and <code>LinkedList</code> that is going to provide us with different methods to manipulate the data structure.</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">_Node</span><span class="params">(object)</span>:</span></div><div class="line">   <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, data=None, next=None)</span>:</span></div><div class="line">      self.data = data</div><div class="line">      self.next = next</div><div class="line"></div><div class="line">   <span class="function"><span class="keyword">def</span> <span class="title">__str__</span><span class="params">(self)</span>:</span></div><div class="line">      <span class="keyword">return</span> str(self.data)</div></pre></td></tr></table></figure>

<p>There is only two things to note on our implementation of <strong>Node</strong>, first we’re declaring it as a protected class, eventhough Python don’t have a true protected notion, it’s more of a <a href="https://google-styleguide.googlecode.com/svn/trunk/pyguide.html#Naming" target="_blank" rel="external">notation</a>, but I’m digressing here, the other interesting thing is that we’re rewriting the <code>__str__</code> method from object, Node’s superclass, so every time we print our Nodes we’re going to see the data they store, which in my opinion makes more sense.</p>
<p>Now let’s see our biggest class, <strong>LinkedList</strong>:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">LinkedList</span><span class="params">(object)</span>:</span></div><div class="line">   <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></div><div class="line">      self.length = <span class="number">0</span></div><div class="line">      self.head = <span class="keyword">None</span></div><div class="line"></div><div class="line">   <span class="function"><span class="keyword">def</span> <span class="title">__str__</span><span class="params">(self)</span>:</span></div><div class="line">      <span class="keyword">return</span> self._toString()</div><div class="line"></div><div class="line">   <span class="function"><span class="keyword">def</span> <span class="title">__len__</span><span class="params">(self)</span>:</span></div><div class="line">      <span class="keyword">return</span> self.length</div><div class="line"></div><div class="line">   <span class="function"><span class="keyword">def</span> <span class="title">_toString</span><span class="params">(self)</span>:</span></div><div class="line">      node = self.head</div><div class="line">      string_to_return = []</div><div class="line"></div><div class="line">      <span class="comment"># Print the value of the nodes</span></div><div class="line">      <span class="keyword">while</span> node:</div><div class="line">      string_to_return.append(<span class="string">'%s '</span> % node)</div><div class="line">      node = node.next</div><div class="line"></div><div class="line">      <span class="keyword">return</span> <span class="string">''</span>.join(string_to_return).strip()</div></pre></td></tr></table></figure>

<p>There are two things worth noting in this part of our class, first we’re rewriting the method <code>__len__</code> from object, which permit us call <code>len</code> in our LinkedList, also note we’re using a list to accumulate the string in the <code>_toString</code> method, this is to avoid waste of space, since strings are immutable in python, using something like <code>+=</code> will result in many objects.</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span><span class="params">(self, data)</span>:</span></div><div class="line">   <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="keyword">None</span>:</div><div class="line">      self.head = _Node(data=data)</div><div class="line">      self.length += <span class="number">1</span></div><div class="line">   <span class="keyword">else</span>:</div><div class="line">      node = self.head</div><div class="line">      <span class="keyword">while</span> node:</div><div class="line">         <span class="keyword">if</span> node.next <span class="keyword">is</span> <span class="keyword">None</span>:</div><div class="line">            node.next = _Node(data=data)</div><div class="line">            self.length += <span class="number">1</span></div><div class="line">            <span class="keyword">break</span></div><div class="line">         <span class="keyword">else</span>:</div><div class="line">            node = node.next</div></pre></td></tr></table></figure>

<p>Our add method, is pretty straight forward, if our Linked List is empty (head is None) we create a new node as head. If not, we find the tail of list, and insert our new Node after it.</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(self, x)</span>:</span></div><div class="line">   <span class="keyword">for</span> i <span class="keyword">in</span> range(self.length):</div><div class="line">      <span class="keyword">if</span> node.data = x:</div><div class="line">         <span class="keyword">return</span> i</div><div class="line">      <span class="keyword">else</span>:</div><div class="line">         node = node.next</div><div class="line">   <span class="keyword">raise</span> Exception(<span class="string">'Item Not Found!)</span></div></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">remove</span><span class="params">(self, x)</span>:</span></div><div class="line">   <span class="comment"># case is empty</span></div><div class="line">   <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="keyword">None</span>:</div><div class="line">      <span class="keyword">raise</span> Exception(<span class="string">'Trying to remove from empty list'</span>)</div><div class="line">   <span class="comment"># case is head</span></div><div class="line">   <span class="keyword">elif</span> self.head.data == x:</div><div class="line">      self.head = <span class="keyword">None</span></div><div class="line">      self.length -= <span class="number">1</span></div><div class="line">   <span class="comment"># other cases</span></div><div class="line">   <span class="keyword">else</span>:</div><div class="line">      node = self.head</div><div class="line">      <span class="keyword">while</span> node:</div><div class="line">         <span class="keyword">if</span> node.next <span class="keyword">is</span> <span class="keyword">None</span>:</div><div class="line">            <span class="keyword">raise</span> Exception(<span class="string">'Item Not Found!'</span>)</div><div class="line">         <span class="keyword">elif</span> node.next.data == x:</div><div class="line">            node.next = node.next.next</div><div class="line">            self.length -= <span class="number">1</span></div><div class="line">         <span class="keyword">else</span>:</div><div class="line">            node = node.next</div></pre></td></tr></table></figure>

<p>We finally get to our final methods, <code>index</code>, which provide us the index of a given Node, if it exists, and <code>remove</code> which as the name says remove some node given the data it contains.</p>
<h3 id="the-end">The End</h3>
<p>Well folks that was it, as an exercise try to implement a doubly linked list, without looking to the code here, so you could make sure that you’re truly understanding linked lists, and not simply rewriting the code.</p>
<p>image by <a href="https://unsplash.com/search/train?photo=kRqA1yFZp1s" target="_blank" rel="external">Marina Molineiro</a></p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Today, we’re going to implement a linked list in python&lt;/p&gt;
    
    </summary>
    
    
      <category term="python" scheme="https://www.caynan.org/tags/python/"/>
    
      <category term="data structure" scheme="https://www.caynan.org/tags/data-structure/"/>
    
  </entry>
  
</feed>
