<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pedro Campos on Medium]]></title>
        <description><![CDATA[Stories by Pedro Campos on Medium]]></description>
        <link>https://medium.com/@pedrofreitascampos?source=rss-4af649b2abaa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DFP4CbCVg2Qqs2EW.</url>
            <title>Stories by Pedro Campos on Medium</title>
            <link>https://medium.com/@pedrofreitascampos?source=rss-4af649b2abaa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:36:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pedrofreitascampos/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Interview assignment #1: memory-less itemset counting]]></title>
            <link>https://medium.com/@pedrofreitascampos/interview-assignment-1-memory-less-itemset-counting-126570412c00?source=rss-4af649b2abaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/126570412c00</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[interview-assignment]]></category>
            <category><![CDATA[tech-interview]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Pedro Campos]]></dc:creator>
            <pubDate>Tue, 17 Mar 2020 18:07:33 GMT</pubDate>
            <atom:updated>2020-03-17T18:13:10.031Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCTINHgVU2Gz-z24aGccqQ.jpeg" /><figcaption>The kind of photo you will get if you search for “n choose k” on <a href="https://unsplash.com/s/photos/n-choose-k?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>— Photo by <a href="https://unsplash.com/@outoflight?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Carl Schlabach</a></figcaption></figure><p>Since I am interviewing for new jobs, I’ve decided to start a series on interview assignments I am being asked to do, in order to both structure my thoughts on these topics and take a second look at my work.</p><p>The reason I felt compelled in sharing this write-up is two-fold:</p><ul><li>to share with others the kind of assignments out there in the job market, and what kind of challenges and learning opportunities can be drawn from these;</li><li>to potentially get any constructive feedback on my work (assuming anyone would read this)</li></ul><h3>The assignment</h3><p>This assignment was submitted by a Berlin startup on the AI-driven retail business, for the role of data engineer. There was a really good chemistry during the initial recruiter talk (in which I was asked a brainteaser as well), so it was without surprise that I was sent the technical assignment a few days later.</p><p>The problem focused on data processing under a low memory environment, in particular, identifying/counting pairwise product associations across baskets, for a large number of baskets.</p><p>Presumably this is would act as a pre-processing step for association-rule learning, supporting product recommendations, but the context was not revealed to this extent.</p><p>Ultimately, the problem’s challenges boiled down to a couple of important points, which I state below.</p><h4>Problem statement</h4><ol><li>Determine (pairwise) itemset frequency from shopping basket records</li><li>Assume very little memory, or at least not enough to hold neither infile nor outfile</li></ol><p><strong>Further details on the input data:</strong></p><ul><li>Provided as csv.gz</li><li>Records pertaining to same basket are in contiguous rows</li><li>Number of items per basket is small</li></ul><h3>Algorithm Design &amp; Analysis</h3><p>As a disclaimer, I discarded upfront the use auxiliary data stores, due to the memory footprint it would entail. I didn’t know enough about the environment to assume it would be possible, and instead of asking and waiting for an answer from the recruiter, decided to clearly state my assumption and run with it — in my experience, the reviewers are usually ok with this unless it clearly violates the spirit of the assignment.</p><h4>Subproblem 1: streaming data</h4><p>An immediate consequence of not being able to load the input file in memory is that data needs to be streamed from the disk rather than loaded upfront.</p><p>This is typically a good practice anyway, unless the processing logic requires querying/searching the data, which is not the case for this particular problem, because the data is already ordered and grouped by basket on the input file.</p><blockquote>Python of course, makes this really easy to implement, as its file pointer reads row-by-row by simply iterating over it.</blockquote><h4>Subproblem 2: itemset counting</h4><p>In order to count itemsets in a basket, however, there needs to be some sort of tracking of the products seen so far in that basket, so that latter products can be combined with previous ones for that particular basket.</p><p>Since it is mentioned that the number of products for each basket is small, one can likely assume there is enough memory in the target environment to keep track of occurred products in a given basket, and thus use a supporting (lightweight) data structure for the effect (e.g. list).</p><p>As soon as the full set of products in a basket is known (i.e. the resulting list of products at the point at which the basket_id changes to the next one), it is easy to create pairwise combinations of those, using, for example, itertools.combinations.</p><p>One can however slightly optimize the algorithm by creating combinations &quot;on-the-fly&quot;, as new individual records are processed, by combining each new product with all others known thus far, for the same basket.</p><p>In terms of algorithm time complexity, this optimization will not change anything, as for <em>N</em> baskets, <em>P</em> products per basket and <em>k=2</em> items per association set the complexity will be, for both cases, given by <em>O(N* P choose k)≈O(NPᵏ)=O(N), </em>considering that P can be considered constant, but it will remove the unnecessary work of iterating twice over the basket’s contents.</p><p>After combining all products in a basket, one will need to increment each relevant itemset’s cumulative count across baskets, and will thus need a counter data structure which is able to efficiently handle this (e.g hash table, python dict or collections.Counter).</p><p>This counter is expected to represent the memory consumption bottleneck, as it will very likely eventually contain very large numbers of keys, given that <em>#keys=#products*(#products-1) </em>with 2-sets, and assuming a large number of distinct products to choose from.</p><p>In fact, the space complexity will end up being exponential due to task’s combinatorial nature— more specifically, it will be <em>O(</em>i<em>temsets)=O(T²), T </em>being the total number of possible products, and it is quite foreseeable that one would soon run into memory issues for a given threshold of <em>T.</em></p><p>For example, for a store with 1000 distinct products, the worst case memory requirements would be 1000*999 keys with corresponding integer values:</p><p>In [12]:</p><pre>import itertools<br>import sys</pre><pre>sys.getsizeof(dict(zip(range(int(1e6)), itertools.cycle([1]))))</pre><p>Out[12]:</p><pre>41943152</pre><p>Which would require ~42 MB, thus comparable to the size of the input file in memory (plus it has exponential asymptotic complexity).</p><p><strong>Relaxing memory requirements</strong></p><p>There are at least a couple of ways in which one could relax this bottleneck:</p><ol><li>Ditch the in-memory counter altogether, and use an in-disk counter instead</li><li>Use the in-memory counter as a <em>buffer</em>, and <em>swap</em> intermediate counts on disk</li></ol><p>The main issue with option 1, is that, while the implementation is much simpler, it should lead to a significant performance degradation, as the program becomes more I/O bound.</p><p>Option 2, on the other hand, requires more logic and more code, which is generally undesirable, but theoretically allows for a significantly better runtime, depending on just how stringent the memory constraints are.</p><blockquote>A final, adaptive, option, is to infer the available system memory at startup and only swap if it is strictly required, this will optimize for runtime while satisfying the memory constraints, in any case, a thesis which I support with data further below.</blockquote><h3>Subproblem 3: buffering/swapping</h3><p>As explained above, the rationale supporting a swapping strategy is that intermediate results are stored in disk due to memory constraints, and that intermediate results can be combined with new results to ultimately achieve consistent final results.</p><p>An issue with this step, however, is that besides I/O being generally slow, simple files on disk don’t allow for efficient querying/searching, so if one needs to, for example, increment the count of a given itemset in disk, one can:</p><ol><li>Do a linear search on the file for each and every record in buffer</li><li>Guarantee some sort of ordering on the file and perform binary searches for every record</li><li>Create a addressed file for each itemset, containing the intermediate counts</li></ol><p>Option 1 does not seem off-the-bat like an efficient solution, as its time complexity is <em>O(N*itemsets)</em>≈<em>O</em>(NT²).</p><p>Option 2, while better, would still require both internal sorting, external sorting and binary search logic, and would lead to a time complexity of <em>O(N*log(itemsets))=O(N*log(T²))≈O(N*log(T)).</em></p><p>Option 3, however, makes itemsets in fact directly “queryable” on disk, significantly cutting the increment/update for a given itemset to <em>O(1).</em></p><blockquote>This method would work by simply storing the count of any given itemset on a file on disk, named after that itemset. The overall complexity for this step would thus be reduced to <em>O(N)</em>, which represents the minimum conceivable time complexity for this particular sub-problem.</blockquote><h3>Subproblem 4: consolidating results</h3><p>The final step requires that all results are consolidated into a single file.</p><blockquote>This can be achieved by concatenating all files in the swap folder one-by-one and combining them into a single file, plus ensuring that whatever remains in the in-memory buffer, if anything, is also accounted for. The time complexity of this step would then be <em>O(Tᵏ)</em> as well, since the number of files should equal the number of itemsets.</blockquote><h3>Time &amp; Space complexity</h3><p>Given the above design choices, the estimated complexities for the program are:</p><blockquote>Time:<strong> </strong>O(<em>N</em>), for <em>N</em> baskets</blockquote><blockquote><strong>Space:</strong> <em>O(Tᵏ)</em>, for <em>T</em> total distinct products, or <em>O(1) </em>when swapping is enabled</blockquote><h3>Implementation</h3><p>I usedPython to implement the algorithm — while it is not an ideal choice performance-wise (at least not vanilla Python), it is very accessible, friendly to experimentation and prototyping. Given a production environment, however, one could argue for another technology, depending on the application requirements.</p><p>Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e13c08ed804446235f5b889158d7b7f5/href">https://medium.com/media/e13c08ed804446235f5b889158d7b7f5/href</a></iframe><p>I used black to format the code, I&#39;m not the greatest fan of it&#39;s formatting choices, but I do appreciate the “unforgiving” consistency!</p><p>And this is how the help menu looks like:</p><p>In [23]:</p><pre>python count_itemsets.py --help</pre><pre>usage: count_itemsets.py [-h] -i INPUT_FILE [-o OUTPUT_FILE]<br>                         [--swap-folder SWAP_FOLDER] [-m MEMORY_LIMIT]<br>                         [--log-level {error,info,debug}]</pre><pre>Counts pairwise itemset frequency from basket data. Handles memory limitations by using a swap strategy upon hitting a specified memory limit, which can be automatically inferred from system availability</pre><pre>optional arguments:<br>  -h, --help            show this help message and exit<br>  -i INPUT_FILE, --input INPUT_FILE<br>                        Basket data file location (must be .csv.gz)<br>  -o OUTPUT_FILE, --output OUTPUT_FILE<br>                        Results CSV location<br>  --swap-folder SWAP_FOLDER<br>                        Temporary checkpoints folder9<br>  -m MEMORY_LIMIT, --memory-limit MEMORY_LIMIT<br>                        Maximum memory consumption allowed, in MB, before<br>                        using swap strategy. Available options: &quot;auto&quot;<br>                        (determines system limits automatically); any valid<br>                        value in MB (sets a hard limit)<br>  --log-level {error,info,debug}</pre><h3>Bonus questions</h3><p>A few extra questions were included on the assignfment, presumably to prepare for its discussion, if I get that far.</p><h4>Generate datasets with different scales, and measure the runtime of your algorithm.Does it behave as expected?</h4><p>Below is the runtime by dataset scale and enforced memory limit, in seconds (disclaimer: only one test!):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*It0T_UpCbdJsq0WFXTPUXw.png" /></figure><p>From the table it is clear that there are two axis of performance degradation: dataset scale and memory constraints.</p><p>Regarding the dataset scale, given that the runtime complexity is linear with number of records, the result is not entirely expected for lower memory limits, and should likely be explained by the excessive amount of I/O calls done when throttling memory — this hypothesis is further suggested by the fact that, as memory constraints are released for the same dataset scale, the runtime performance approaches the expected factors (i.e. for 6GB of memory at scale 1 and 3, 22*3≈70.</p><p>Restricting the memory makes the program I/O bound, which slows it down considerably and thus this seems a serious bottleneck on program performance.</p><p>A way of solving this would be to transfer this burden to an external database/data store, but whether it can be used or not in the context of this problem would require more knowledge of the run environment. The next thing one could do, would be to profile the program and see where is the bottleneck (the assumption right now is that it would be on write), or one could use multhreading to ensure the CPUs are working for you even when you need to wait for I/O.</p><h4>The baskets in the example data are generated randomly, and therefore each product combination appears in approximately the same number of baskets. Would the algorithm still work if this wasn’t the case, and some product combinations would occur much more often than others?</h4><p>Yes, this particular algorithm would suffer more from an increase in number of baskets or distinct products than from a non-uniform distribution of itemsets across baskets.</p><h4>How would the problem change if we are also interested in the occurrence of combinations of three products within a basket?</h4><p>The program would require much more memory, since the space complexity would become <em>O(T³) from O(T²)</em>, and as a consequence would also require more I/O when restricting memory and thus become much slower.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=126570412c00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thailand 2020: tropical disease risk assessment]]></title>
            <link>https://medium.com/@pedrofreitascampos/thailand-2020-tropical-disease-risk-assessment-2eb677914169?source=rss-4af649b2abaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eb677914169</guid>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[health]]></category>
            <dc:creator><![CDATA[Pedro Campos]]></dc:creator>
            <pubDate>Mon, 06 Jan 2020 16:49:07 GMT</pubDate>
            <atom:updated>2020-01-30T17:36:09.494Z</atom:updated>
            <content:encoded><![CDATA[<h3>Thailand: what’s the real risk for tourists contracting tropical diseases in 2020?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y3EYzjZOyx6V3zVrv4yeEg.jpeg" /><figcaption>The world’s tiniest — and most dangerous — rubber ball</figcaption></figure><p>In a few weeks time, me, my wife and our then 10 month old daughter will be traveling to Thailand for a 1 month period. After pondering for some weeks, we took the decision to do this trip — and indeed booked the whole thing — about 6 months ago, <a href="https://www.bangkokpost.com/thailand/general/1695312/dengue-fever-epidemic-declared">just before a state of epidemic was declared for Dengue in Thailand</a>, and did it after being positively convinced by a fair amount of research on the overall safety of the trip, in specific in regard to our infant daughter.</p><p>Of course, finding out about the Dengue outbreak a couple of months down the line made us uneasy about the whole trip, but since there were still a few months to go to, we decided to patiently sit the concerns out, even if with the outbreak’s specter haunting some — if not most — of our feelings and conversations on the trip.</p><p>The <a href="https://edition.cnn.com/2020/01/06/health/china-pneumonia-intl-hnk/index.html">recent news of an outbreak of some unknown sort of viral pneumonia in Wuhan, China</a>, however, was the final drop on a slow but steady anxiety buildup regarding the trip, particularly since we will be in Bangkok during Chinese new year, something we were actually pretty much looking forward to. Soon after processing the news, both me and my wife (ok, perhaps more my wife) proceeded to indiscriminately pour out our accumulated concerns onto the trip’s emotional baggage, which inevitably culminated in a mini-breakdown of sorts, in which we put into question our entire parental abilities and judgment.</p><p>Should we cancel the trip? Is it worth jeopardizing our child’s health when she will be arguably getting nothing in return on the long run? How will we justify adult her that she contracted — knock on wood — a tropical disease when an infant, because we wanted to chill on paradisiac beaches and do some temple-hopping while being fully aware of a plethora of tropical diseases literally hovering around us? How selfish are we as parents?</p><p>In my view, the only way to answer these questions would be to ignore the noise, gather the most objective information possible (namely, hard facts) and do our own risk assessment.</p><p>As a disclaimer, I must say that it is in my opinion quite understandable that alarmisms exist and indeed should perhaps be reasonably encouraged, when it comes to public health preservation against epidemics. For untreatable diseases like Dengue, prevention is key, and the best way to prevent is to be aware and informed, and well, in a society so dense with information that only the loudest voices and outcries ever get heard, you really do need to sometimes dramatize to cut the damage short.</p><p>On the other hand, for an individual traveling for a few days or weeks in Thailand during dry season, staying in well rated accommodations, avoiding border areas and strictly following mosquito avoidance guidelines, my intuition was that the real risk was minimal — the question was then: could I confirm this objectively and in a way that would convince both me and my considerably more risk-averse wife?</p><p>The first thing I did on my assessment was to identify our unattended concerns regarding the trip. If on one hand, we knew the long and frequent flights, the heat, the possibility of food poisoning and a bunch of tropical diseases which she is vaccinated against did not pose a significant risk to our daughter, on the other hand, during the last 6 months we had gathered a new set of concerns to juggle with. Namely, we were now concerned with: 1) Malaria, 2) Dengue, 3) Viral pneumonia in Wuhan, 4) Elephant Tuberculosis 5) Mosquitoes in hotel swimming pools 6) Water-borne diseases in southern Thai islands</p><p>My research methodology on these topics followed the googling method, and I generally favored scientific articles or blog posts, news articles from reputable sources and travel blog posts, in this particular order.</p><p>The whole thing took me half a day and, well, all in all my conclusions are summarized by this table (please note at the time I wrote this there was still no official name for what is know known as the Novel Coronavirus so I just called it SARS):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*WcZ4K4GeuwkGrznEKZqiKQ.png" /><figcaption>a complete layman’s risk table for Thailand tropical diseases</figcaption></figure><p>These conclusions are supported by a small body of knowledge I gathered, which I share below, addressing each concern individually in order of level in the <em>concernometer</em> scale.</p><blockquote>1<strong>. </strong>There is an extremely low risk<strong> for Malaria infection</strong> in the places we are travelling to</blockquote><p>Our trip will take us to Bangkok, Ayutthaya, Kanchanaburi, Chiang Mai, Koh Phi Phi and Koh Phangan, all of which are considered low risk or no risk for Malaria, as illustrated below:</p><figure><img alt="Malaria risk map for Thailand, 2019" src="https://cdn-images-1.medium.com/max/800/1*IjJZ-a5JcK8HzRaZ_aZqkg.png" /><figcaption>As usual everywhere in the world, your neighbors suck and are mostly responsible for your issues</figcaption></figure><p>This actually pretty much mirrors what had been told to us in the <em>Institut für Tropenmedizin</em>, in Berlin.</p><p>Besides this, the Malaria mosquito (aka <em>anopheles</em>) blood feasts primarily at night time, in which our daughter will preferably be already home asleep.</p><blockquote>2. There is a <strong>very low risk for Dengue infection</strong> during our trip</blockquote><p>I first explored risk factors for Dengue and then counterbalanced them with mitigating factors.</p><p><strong>Risk factors:</strong></p><ul><li><strong>Dengue </strong><a href="https://www.bangkokpost.com/thailand/general/1695312/dengue-fever-epidemic-declared"><strong>reached epidemic status</strong></a><strong> in the last rainy season in Thailand</strong>, doubling the last 5 year average number of cases</li><li>Overall <a href="http://www.samuitimes.com/thailand-experiencing-largest-dengue-epidemic-two-decades/"><strong>around 136.000 people were infected</strong></a> in 2019 in Thailand, of which <strong>around 1000 died</strong></li><li>The Dengue mosquito, the <em>Aedis aegypti,</em> <a href="https://en.wikipedia.org/wiki/Aedes_aegypti"><strong>is widespread and highly adaptable</strong></a>, only needing small water containers to breed and multiply — it therefore <strong>strives in both urban and rural areas</strong></li></ul><p><strong>Mitigating factors:</strong></p><ul><li><strong>Overall mortality rate for Dengue fever </strong><a href="https://emedicine.medscape.com/article/215840-overview"><strong>is only 1%</strong></a>. If you consider that there are 69 million people in Thailand, and 136.000 cases makes for only 0.2% of the population, then it follows that only 0.002% of the population, or 1 in 50000, die due to Dengue infection — and they live there the whole year! In comparison, 12000 people died due to road accidents in Thailand, which puts the likelihood of dying in a car accident at 0.017%, almost 10x as high as dying from a Dengue infection</li><li><a href="https://emedicine.medscape.com/article/215840-overview"><strong>It is rare to have severe complications on your first Dengue infection</strong></a>, in some cases you don’t even know you had Dengue. Severe complications arise in the great majority of cases from secondary infections from different strains (there are 4 in total), in which your immune system reacts very violently for not yet well understood reasons</li><li>Even though these trends seem to be transient in nature, there is at any given time apparent <strong>regional bias on incidence, </strong>in specific,<strong> </strong>the biggest incidence currently is in the north eastern and eastern region of Thailand, where we will not travel, and Phuket, in which we are only passing by briefly</li><li>There is sadly a <a href="https://www.theguardian.com/global-development/2019/dec/30/asias-hardest-year-for-dengue-fever-in-pictures"><strong>socio-economic bias on incidence</strong></a>, as poorer households are more at risk due to lower education on the disease and closer proximity to stale and dirty water sources</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzkpzQ9N7udWeSnhPc7d4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZ93l7Jf-bpwAqF_vdqcrA.png" /><figcaption>Dengue excels in these conditions: stale, dirty rain water in all kinds of containers</figcaption></figure><ul><li>The prevalence of the mosquito which caries <strong>Dengue is extremely seasonal</strong>, as it is highly reliant on environmental factors (in specific, needs lots of water and vertebrate blood). So when the water disappears, it does to, which is why <strong>roughly 75% of all Dengue cases are reported between May and September of each year</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYoyCONwBKy4GUNIG8GQuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7VTyZ5gChOxN1N2BpnT6YQ.png" /><figcaption>from “<a href="http://Spatial and temporal patterns of dengue incidence in northeastern Thailand 2006–2016"><em>Spatial and temporal patterns of dengue incidence in northeastern Thailand 2006–2016</em></a><em>”</em></figcaption></figure><p>Additionally, for the places where we will travel to in the north of Thailand it almost never rains in February:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*Ps-RcD7KEhjv9uSLrjpGMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*taPmIDBacbh8xgo6kggRqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*DCAM_Eyd7muWHMuzkr239g.png" /></figure><ul><li><a href="https://www.who.int/denguecontrol/faq/en/index5.html">Dengue does not seem to be contagious between humans</a></li><li>Besides all this, there are <strong>many preventable measures </strong>which can be taken to avoid getting bitten by mosquitoes. Mosquito repellents (DEET or Picaridin for adults, and a more skin-sensitive variant of Picaridin for infants) <a href="https://www.youtube.com/watch?v=fRWR_4-HZZU">are extremely effective</a> and if we follow the instructions with discipline, as well as washing our clothes with Permathrin, use mosquito nets, use baggy neutral-colored clothes and empty any water containers around wherever we stay (mosquitoes tend to operate 50–100 meters from their breeding location), I think the risk is very very low</li></ul><blockquote>3. We should monitor the viral pneumonia outbreak in Wuhan</blockquote><p>It is way too early to assess the situation, <a href="https://www.bbc.com/news/world-asia-china-51000910">they have ruled out SARS recently</a> but there’s still very little information. I think once we are one week away from the trip there will be more information on this outbreak and we can further study the situation.</p><blockquote>4. There is a <strong>extremely low risk </strong>for tuberculosis infection from elephants, in Thailand</blockquote><ul><li>In 2008, it was estimated that <a href="https://www.healio.com/infectious-disease/zoonotic-infections/news/print/infectious-disease-news/%7B193d8ef8-75be-4476-a39c-92b22d0b10d8%7D/tuberculosis-in-elephants-a-reverse-zoonosis"><strong>around 15% of elephants in the USA and India had TB</strong></a>, which was sadly originally transmitted to elephants from humans</li><li>People infected have<strong> </strong><a href="https://www.healio.com/infectious-disease/zoonotic-infections/news/print/infectious-disease-news/%7B193d8ef8-75be-4476-a39c-92b22d0b10d8%7D/tuberculosis-in-elephants-a-reverse-zoonosis"><strong>usually had close and prolonged direct or indirect contact with elephants</strong></a> although infection through air for brief contact (e.g. if elephant sneezes or coughs) can also occur, theoretically at least (of all the cases I read, all infected were carers for the elephants, never tourists or sanctuary visitors)</li><li>The BCG vaccine <a href="https://en.wikipedia.org/wiki/Tuberculosis#Vaccines"><strong>reduces infection probability by 20%</strong></a>, and reduces probability that Tuberculosis bacteria will develop into active disease by 60% on those infected</li><li>In Thailand, there had never been elephant Tuberculosis infections registered up until 2016, when <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3294569/"><strong>4 elephants were found to be infected</strong></a><strong> </strong>— however their mahouts (carers) <strong>were not infected</strong>, despite having cared for them for 4 years</li><li>Infected elephants <strong>usually but not always show clear symptoms of infection </strong>like chronic weight loss, weakness and trunk discharges, see image below for example:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*Lrcr9MXwjdH1PwMZUdRJwQ.png" /><figcaption>disturbing image of a quarantined elephant with Tuberculosis</figcaption></figure><blockquote>5. There is a <strong>low risk </strong>of finding mosquitoes in swimming pools in hotels</blockquote><p>Well maintained pools, which are regularly scrubbed and cleaned by pool carers, have properly functioning motors circulating its water and are treated with chlorine<a href="https://www.swimuniversity.com/pool-mosquitoes/"> are an unfavorable environment for mosquitoes to breed</a>.</p><blockquote>6. The skin rashes from swimming in Koh Phi Phi seem to be “Seabather’s eruption”</blockquote><p>This condition is caused by sea lice (jellyfish larvae) and can happen anywhere in the world.</p><p>So all in all, we both agreed it is not much more likely for our daughter to fall ill to a tropical disease in Thailand, than it is for her to be involved in any kind of accident (e.g. car, fall, etc.) back home in Berlin.</p><p>We are now more assured and able to put the admittedly worrying news into perspective, and are very much looking forward to building these memories with our daughter, which we can later share through stories and media collected. We also happen to believe that exposing her to completely new experiences and cultures at this young age will do wonders for her cognitive and emotional development. Thailand, here we come!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eb677914169" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HackerRank “Statistics in 10 days”]]></title>
            <link>https://medium.com/@pedrofreitascampos/hackerrank-statistics-in-10-days-b229c4f28d11?source=rss-4af649b2abaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/b229c4f28d11</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[hackerrank]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[Pedro Campos]]></dc:creator>
            <pubDate>Fri, 11 Aug 2017 22:43:39 GMT</pubDate>
            <atom:updated>2018-05-05T14:45:51.278Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day 2</h4><h4><a href="https://www.hackerrank.com/challenges/s10-mcq-1">Exercise 1: Basic Probability</a></h4><blockquote>In a single toss of 2 fair (evenly-weighted) six-sided dice, find the probability that their sum will be <em>at most 9</em>.</blockquote><p>Following the naive probability definition, if all experiment outcomes are equally likely, the probability of an event is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*2IC44GVeulm5ZRUWSu9s9A.png" /></figure><h4>Numerical approach</h4><p>The numerical brute force approach is really just to sum up all possible pairwise dice rolls, count those which sum at most 9 and then divide by the total number of combinations. The result is then 5/6, or, in Python words:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPrvNuWqH54MzYoWUdZ1-Q.png" /></figure><p>Worst case time complexity here is <em>O(n</em>^k<em>)</em>, because we’ll end up with <em>n^k</em> total_experiment_outcomes to iterate through.</p><p>A note on itertools.product:</p><ul><li>Very cool function which does the dot product of an arbitrary number of iterables — has <em>O(m*n)</em> complexity for <em>m</em> iterables of length <em>n , n </em>being the length of the longest iterable</li></ul><h4>Mathematical approach</h4><p>Fortunately, this can instead be solved using counting principles such as the multiplication rule in human <em>O(1)</em>. In specific, if we note the following:</p><ol><li>Any experiment resulting in both dice rolling between 1 to 4 are guaranteed to be under 9</li><li>If an experiment involves a dice roll of 5, then the other roll can be between 1 and 4 (note that this can happen in any order)</li><li>If an experiment involves a dice roll of 6, then the other roll can be between 1 and 3 (note that this can happen in any order)</li></ol><p>Then it comes that our favorable cases can be counted as:</p><p><em>4²+4¹*2+3¹*2=16+8+6=30</em></p><p>Since we have 6²=36 total outcomes, it follows that:</p><p><em>P(sum≤9)=30/36 = 5/6</em></p><h4><a href="https://www.hackerrank.com/challenges/s10-mcq-2">Exercise 2: More Dice</a></h4><blockquote>In a single toss of 2 fair (evenly-weighted) six-sided dice, find the probability that the values rolled by each die will be <em>different</em> and the two dice have a sum of 6.</blockquote><p>No point in coding here, it suffices to note that there are only 6 ways of rolling a sum of 6:</p><p>(1, 5), (2, 4) (3, 3), (3, 3), (4, 2), (5, 1)</p><p>But two of them result from identical rolls, so we remove them and end up only with 4 favorable cases.</p><p>Let <em>a </em>be the result of rolling dice <em>A</em> and <em>b </em>the result of <em>B:</em></p><p><em>P(a+b=6 ∩a ≠b)=4/36=1/9</em></p><h4><a href="https://www.hackerrank.com/challenges/s10-mcq-3">Exercise 3: Compound Event Probability</a></h4><blockquote>There are 3 urns labeled <strong>X</strong>, <strong>Y</strong>, and <strong>Z</strong>.</blockquote><blockquote>Urn <strong>X</strong> contains 4 red balls and 3 black balls.</blockquote><blockquote>Urn <strong>Y</strong> contains 5 red balls and 4 black balls.</blockquote><blockquote>Urn <strong>Z</strong> contains 4 red balls and 4 black balls.</blockquote><blockquote>One ball is drawn from each of the 3 urns. What is the probability that, of the 3 balls drawn, 2 are red and 1 is black?</blockquote><p>Ok, again no coding required. This is now a counting problem with a twist, since we need to deal with compound event probabilities.</p><p>First, we’d like to calculate the probabilities of drawing red (<strong>R</strong>) or black (<strong>B</strong>) for each urn <strong>X</strong>, <strong>Y</strong> and <strong>Z:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*GoOafZC84b_K-Rn_tESgcg.png" /><figcaption>world exclusive caption of a pnd.DataFrame — thanks for the table support, Medium</figcaption></figure><p>Next, we need to count all favorable combinations of draws, which should be fairly easy here (note that order does not matter):</p><p><em>(R, R, B), (R, B, R), (B, R, R)</em></p><p>And the associated probabilities of these outcomes are:</p><p>P(R,R,B)=P(R|X)*P(R|Y)*P(B|Z)=4/7*5/9*1/2=20/126</p><p>P(R,B,R)=P(R|X)*P(B|Y)*P(R|Z)=4/7*4/9*1/2=16/126</p><p>P(B,R,R)=P(B|X)*P(R|Y)*P(R|Z)=3/7*5/9*1/2=15/126</p><p>Cool, now, we need to stitch this all together:</p><p>P(#B=2<em>∩#R=1)=P(R,R,B)+P(R,B,R)+P(B,R,R)</em></p><p>P(#B=2<em>∩#R=1)=20/126+16/126+15/126=51/126=17/42</em></p><p>We’d probably need to code if we had to draw from something like 1k urns instead, then it would get real interesting!</p><h4>Bonus Exercise 3.1: Compound Event Probability Ultra</h4><blockquote>So let’s now change the previous exercise to have 1001 urns with 1000 balls. Let’s also assume that the number of red and black balls on each urn <strong>i </strong>from 0 to 1000 is determined by the following rule:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/1*6e9KX18P1QD_3QtdJfI3Gg.png" /></figure><blockquote>What is the probability that you draw 601 black and 400 red balls?</blockquote><p>We probably need code now…</p><p>First, let’s determine the prior probability matrix of drawing red from each urn <strong><em>i. </em></strong>Following from the problem statement:</p><p>P(R|i)=i/1000, 0≤i≤1000</p><p>And thus, since P(B|i)=1-P(R|i), comes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Gah01_iAA1dxduEwsFcOPQ.png" /><figcaption>combinatorics and the 1001 urns</figcaption></figure><p>We now need to identify all possible combinations of draws from the 1001 urns which will lead to 601 black and 400 red balls - this is the part where we need code.</p><p>As a spoiler, we can calculate upfront the number of possible combinations, keeping in mind that we should divide the total number of permutations by the product of permutations in which order does not really matter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*RGFw8NWznN7F1vS4i_0wcA.png" /><figcaption>this breaks the matrix</figcaption></figure><p>This amounts to 826994618742176886857219029039122721720403818658048972159060093505255493573757993077449466057757209525107340068439049135868207562311987225440360216008233757326421137950364106208566066436734318145314695083076583555693616347940241555277559225141977999596150185492803911599522704296300809199150 possible favorable outcomes, and we will probably have issues keeping all of them in memory.</p><p>Anyways, here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c6820a1e6279dc2a8824c2ab1c14512/href">https://medium.com/media/2c6820a1e6279dc2a8824c2ab1c14512/href</a></iframe><p>Note in line 19 that we need to unpack the itertools.permutations generator so that we can then run the set . This is very important, otherwise we will end up with 1001! cases instead, since we are not removing the repeated combinations (remember, order does matter here).</p><p>Regardless, as expected, this still produces a MemoryError:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GoSCewL4OIEyl5QrCVdvew.png" /></figure><p>Hardly surprising, considering that each outcome amounts to 4032 bytes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*llpSJoMnwaZKtIPHprYC4w.png" /></figure><p>And thus the total memory required would be at least 4032 * 1001! ≈1.62x10²⁵⁷⁵ bytes, which is like 2555 orders of magnitude more information that currently stored on earth.</p><p>We could, of course, try working around this by doing something smarter than unpacking the permutations into a list and applying the set (for example, iterating and keeping a dict of covered combinations), but we’d still have a huge runtime to deal with, considering we’d have 1001!/601!400! loops to run through.</p><p>Instead, let’s reformulate the problem to calculate the probability of drawing 6 red and 4 black balls from 10 urns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S44DiaOpmt-8v6cMOI20Gg.png" /></figure><p>So the result is 23.45% probability, and the permutations take around 261.8 MB in memory. Hurray!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b229c4f28d11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HackerRank “Statistics in 10 days”]]></title>
            <link>https://medium.com/@pedrofreitascampos/hackerrank-statistics-in-10-days-d874fa052c91?source=rss-4af649b2abaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/d874fa052c91</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[hackerrank]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Pedro Campos]]></dc:creator>
            <pubDate>Tue, 01 Aug 2017 21:41:24 GMT</pubDate>
            <atom:updated>2017-08-03T18:53:45.681Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day 1</h4><h4><a href="https://www.hackerrank.com/challenges/s10-quartiles">Exercise 1: Quartiles</a></h4><p>This exercise was about getting 1st, 2nd and 3rd quartiles of an array, with the guarantee that these would be integers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/634f60778d3410bd1ce6400c1ed10002/href">https://medium.com/media/634f60778d3410bd1ce6400c1ed10002/href</a></iframe><h4>Time complexity</h4><p>This fairly standard solution pulls it off with <em>O(n*logn)</em> complexity, bottlenecked by the Python built-in sorted (see <a href="https://en.wikipedia.org/wiki/Timsort">Timsort</a>), which is of course necessary for this application.</p><p>Other aspects of the time complexity:</p><ul><li>split on whitespace is <em>O(s), </em>with <em>s </em>being the string length. Since the string length is actually 2 * <em>n </em>(because of the whitespace separator)<em> , </em>we can rewrite it as <em>O(n)</em></li><li>The slicing in Python is <em>O(k), k </em>being the slice size</li></ul><h4>Other notes</h4><ul><li>Median calculation is sadly inelegant, since the rules change for odd and even cardinality sets. <a href="http://mathworld.wolfram.com/StatisticalMedian.html">In particular, if you have an even cardinality list, you need to determine the average of the two inmost elements, but if you have an odd cardinality list, you just take the element in the middle instead</a></li><li>As usual, corner cases are pretty important. For example, normally it’d have returned (0, 0, 0) for an empty list if there wasn’t a check inside median. Instead, it should raise an exception, as the median of an empty set is undefined</li><li>Apparently, <a href="https://stackoverflow.com/a/37956466">PEP-8 does not require spaces around maths operators since 2012</a></li></ul><h4>Mistakes</h4><ul><li>Well, none</li></ul><h4><a href="https://www.hackerrank.com/challenges/s10-interquartile-range">Exercise 2: Inter-Quartile Range</a></h4><p>On this exercise, it was required to expand on the work of the previous exercise by not only returning the IQR but building an array from a list of values and a list of respective frequencies on the built array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ac36363e022a8778084b9471e7bec8d/href">https://medium.com/media/0ac36363e022a8778084b9471e7bec8d/href</a></iframe><h4>Time complexity</h4><p>Seeing that sorted is the bottleneck, complexity for this program is <em>O(NlogN)</em>, with <em>N</em> being the size of the list <em>X</em>.</p><p>Other aspects of the time complexity:</p><ul><li>zip runs in <a href="https://stackoverflow.com/questions/36877715/what-is-the-time-complexity-of-zip-in-python"><em>O(N*M)</em></a>, <em>M</em> being the number of iterables and <em>N</em> the minimum length of the iterables (because zip truncates). In our case, that would be <em>O(N)</em> since M=2</li><li>The two zip over the original lists , plus the for loop on <em>N</em> elements in expand_list amount to <em>O(3N)~O(N) </em>complexity</li><li>The quartiles function calls median 3 times, which has <em>O(1)</em>, and performs 2 slices of <em>N</em>/2 elements, so is <em>O(2N)~O(N).</em></li></ul><p>Optimizations:</p><ul><li>Unnecessary work: reduced complexity from <em>O(N+sum(F)*log(N+sum(F)) </em>to <em>O(NlogN)</em>, by sorting both lists just after getting it from input, rather than doing it later on the expanded list</li></ul><h4>Other notes</h4><ul><li><a href="https://www.hackerrank.com/challenges/s10-interquartile-range/forum/comments/173186">Very good comment on the caveats of using the old problem’s definition of quartiles</a>, mainly focusing on the inadequacy of the continuous distributions’ definition on discrete distributions</li></ul><h4>Mistakes</h4><ul><li><strong>Interpretation:</strong> should have returned float on the results, kind of sucks that the HackerRank tester is strict on types — seems pretty anti-pythonic anyways</li><li><strong>Syntax:</strong> forgot to wrap <em>x </em>element values on list before multiplying by frequency <em>f</em></li></ul><h4>Exercise 3: Standard Deviation</h4><p>This is back to straightforward territory. Calculate the stdev of a list of ints:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff0d85f0d98d9fd571c3588e7e58c74a/href">https://medium.com/media/ff0d85f0d98d9fd571c3588e7e58c74a/href</a></iframe><h4>Time complexity</h4><p>Should be <em>O(4N)~O(N).</em></p><p>Other notes:</p><ul><li>There is some unnecessary work being done by looping 4 times over the list. We could instead just loop twice (we need a pre-calculated mean on the stdev calculation) and perform all operations on each iteration, although it will make the code a bit uglier without really reducing complexity</li></ul><h4>Mistakes</h4><ul><li><strong>Functional</strong>: incorrectly mapped raw_input output to int</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d874fa052c91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HackerRank “Statistics in 10 days”]]></title>
            <link>https://medium.com/@pedrofreitascampos/hackerrank-statistics-in-10-days-e83361b46f9?source=rss-4af649b2abaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/e83361b46f9</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[hackerrank]]></category>
            <dc:creator><![CDATA[Pedro Campos]]></dc:creator>
            <pubDate>Mon, 31 Jul 2017 22:53:47 GMT</pubDate>
            <atom:updated>2017-08-01T20:14:43.529Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day 0</h4><p>I registered on three <a href="https://www.hackerrank.com/">HackerRank </a>tutorial tracks and I started doing them today.</p><p>As a disclaimer, I have chosen to solve these in Python rather than C++ as I feel I can still hone my Python skills a bit more, especially when it comes to performance. Perhaps once I’m over with them I can retry in C++, as practice.</p><h4><a href="https://www.hackerrank.com/challenges/s10-basic-statistics">Exercise 1: Mean, Median and Mode</a></h4><p>So, I boldly chose to start by solving exercise 1, and, well, that was pretty straightforward to say the least — just had to calculate mean, median and mode of an array.</p><p>I did however learn that you can import the most common scientific computing packages in HackerRank, which is nice because `numpy`<em> </em>and `scipy.stats` already do all the dirty work for you.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3aa0f6a639c8da24cfd89a9547d5e4c/href">https://medium.com/media/a3aa0f6a639c8da24cfd89a9547d5e4c/href</a></iframe><blockquote>Apparently, good coders write code, great coders reuse it</blockquote><blockquote><em>— </em><a href="https://www.youtube.com/watch?v=rz5TGN7eUcM">apparently kid</a></blockquote><h4><a href="https://www.hackerrank.com/challenges/s10-weighted-mean">Exercise 2: Weighted means</a></h4><p>Forget what I had written earlier about being able to import anything, it seems like that particular trick didn’t work for the second exercise.</p><p>That meant I had to do a whole list comprehension by myself in vanilla python2.7.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3aecca443b3b2ac284c050e3882ee4e/href">https://medium.com/media/c3aecca443b3b2ac284c050e3882ee4e/href</a></iframe><blockquote>The HackerRank giveth and the HackerRank taketh away</blockquote><blockquote>— some PO at HackerRank</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e83361b46f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A visual introduction to Machine Learning]]></title>
            <link>https://medium.com/@pedrofreitascampos/a-visual-introduction-to-machine-learning-c8b1c111e150?source=rss-4af649b2abaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8b1c111e150</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Pedro Campos]]></dc:creator>
            <pubDate>Thu, 10 Nov 2016 13:18:13 GMT</pubDate>
            <atom:updated>2016-11-10T13:20:59.799Z</atom:updated>
            <content:encoded><![CDATA[<p>Great intro to Machine Learning (classification), going through all the steps of data exploration and model development in a visually compelling way:</p><p><a href="http://www.r2d3.us/visual-intro-to-machine-learning-part-1/">A visual introduction to machine learning</a></p><p>Just kind of disappointed they do not justify the choice of Regression Trees… and me as an avid ML noob have been going around the office trying to figure if anybody knows why RTs beat PCA or OLR. At least I know some acronyms by now, I guess.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8b1c111e150" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>