{"id":7216,"date":"2020-04-26T11:01:02","date_gmt":"2020-04-26T05:31:02","guid":{"rendered":"https:\/\/www.csestack.org\/?p=7216"},"modified":"2022-06-28T16:27:44","modified_gmt":"2022-06-28T10:57:44","slug":"hailstone-sequence-python-recursion","status":"publish","type":"post","link":"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/","title":{"rendered":"[Solved] Hailstone Sequence in Python (With or Without Recursion)"},"content":{"rendered":"\n<p>In this tutorial, you will learn what is hailstone sequence, how to write a Python program to find the hailstone sequence with and without recursion.<\/p>\n\n\n\n<p>Let&#8217;s start with the basic algorithm to find the hailstone sequence.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-69fd5b1a87ba6\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #000000;color:#000000\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #000000;color:#000000\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-69fd5b1a87ba6\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/#Hailstone_Sequence_Algorithm\" >Hailstone Sequence Algorithm<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/#Hailstone_Sequence_Python_Program_using_while_Loop\" >Hailstone Sequence Python Program using while Loop<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/#Hailstone_Sequence_Python_Program_with_Recursion\" >Hailstone Sequence Python Program with Recursion<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/#Find_the_Length_of_the_Hailstone_Sequence\" >Find the Length of the Hailstone Sequence<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/#Find_the_Maximum_Length_of_Hailstone_Sequence_for_the_Range_of_Given_Numbers\" >Find the Maximum Length of Hailstone Sequence for the Range of Given Numbers<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/#Plot_Hailstone_Sequence_in_Graph\" >Plot Hailstone Sequence in Graph<\/a><\/li><\/ul><\/nav><\/div>\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Hailstone_Sequence_Algorithm\"><\/span>Hailstone Sequence Algorithm<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<ul class=\"wp-block-list\"><li>Take a number (says &#8216;n&#8217;) as an input.<\/li><li>Print the value of &#8216;n&#8217;.<\/li><li>while n != 1<br>a) Print the value of &#8216;n&#8217;.<br>b) If &#8216;n&#8217; is odd, calculate the next number as n*3+1.<br>c) If &#8216;n&#8217; is even, calculate the next number as n\/2.<\/li><\/ul>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Input : 10<br>Output (Hailstone Sequence): 10 -&gt; 5 -&gt; 16 -&gt; 8 -&gt; 4 -&gt; 2 -&gt;1<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">Input : 17\nOutput (Hailstone Sequence): 17 -&gt; 52 -&gt; 26 -&gt; 13 -&gt; 40 -&gt; 20 -&gt;10 -&gt; 5 -&gt; 16 -&gt; 8 -&gt; 4 -&gt; 2 -&gt; 1<\/pre>\n\n\n\n<p>If you plot the graph for hailstone sequences for 10, 11, 12, 13, 14 and 15, it looks like below.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img fetchpriority=\"high\" decoding=\"async\" width=\"640\" height=\"480\" src=\"https:\/\/www.csestack.org\/wp-content\/uploads\/2020\/04\/hailstone_sequence_graph.png\" alt=\"hailstone sequence graph using matplotlib\" class=\"wp-image-7224\" srcset=\"https:\/\/www.csestack.org\/wp-content\/uploads\/2020\/04\/hailstone_sequence_graph.png 640w, https:\/\/www.csestack.org\/wp-content\/uploads\/2020\/04\/hailstone_sequence_graph-300x225.png 300w\" sizes=\"(max-width: 640px) 100vw, 640px\" \/><\/figure>\n\n\n\n<p>(I will share the code for piloting the graph at end of this tutorial.)<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Hailstone_Sequence_Python_Program_using_while_Loop\"><\/span>Hailstone Sequence Python Program using while Loop<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>We are using <a href=\"https:\/\/www.csestack.org\/python-for-while-loop-else\/\">Python while loop<\/a> to solve this problem.<\/p>\n\n\n\n<p><strong>Python Program:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:false,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">def hailstone_seq(start):\n  list_out = []\n  while start &gt; 1:\n    list_out.append(int(start))\n    if start%2 == 1:\n      start = int(start*3+1)\n    else:\n      start = int(start\/2)\n  list_out.append(1)\n  return list_out\n \nif __name__ == &quot;__main__&quot;:\n  n = input(&quot;Enter the number:&quot;)\n  if n.isnumeric():\n    n = int(n)\n    list_out = hailstone_seq(n)\n    print(&quot;Hailstone Sequence: &quot;, list_out)\n  else:\n    print(&quot;Invalid input.&quot;)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Enter the number: 10\nHailstone Sequence: [10, 5, 16, 8, 4, 2, 1]<\/pre>\n\n\n\n<p>When you take the user input, check if the user input value is numeric or not. You can check it with the <code>isnumeric()<\/code> string method.<\/p>\n\n\n\n<p>Other parts of the code are self-explanatory.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Hailstone_Sequence_Python_Program_with_Recursion\"><\/span>Hailstone Sequence Python Program with Recursion<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Hope you are familiar with the <a href=\"https:\/\/www.csestack.org\/dynamic-programming-recursion\/\">recursion programming concepts<\/a>. <\/p>\n\n\n\n<p><strong>Python Program:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:false,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">def hailstone_seq_rec(start, list_out=[]):\n\n  #base condition\n  if start == 1:\n    list_out.append(1)\n    return list_out\n\n  list_out.append(int(start))\n\n  if start%2 == 1:\n    return hailstone_seq_rec(start*3+1, list_out)\n  else:\n    return hailstone_seq_rec(start\/2, list_out)\n\nif __name__ == &quot;__main__&quot;:\n  n = input(&quot;Enter the number:&quot;)\n  if n.isnumeric():\n    n = int(n)\n    list_out = hailstone_seq_rec(n)\n    print(&quot;Hailstone Sequence: &quot;, list_out)\n  else:\n    print(&quot;Invalid input.&quot;)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Enter the number: 15\nHailstone Sequence: [15, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1]<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Find_the_Length_of_the_Hailstone_Sequence\"><\/span>Find the Length of the Hailstone Sequence<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>You can find the length of the hailstone sequence simply by finding the length of the list having all the hailstone sequence numbers.<\/p>\n\n\n\n<p>If our aim is to find only the length of the sequence, it is not efficient to store all hailstone sequence values. Instead of that, we calculate the length.<\/p>\n\n\n\n<p>The same code we used to find the hailstone sequence can be used to calculate the length with a few lines of changes in code.<\/p>\n\n\n\n<p><strong>Python Program<\/strong>: <strong>Without using recursion (while loop)<\/strong><\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:false,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">def hailstone_seq_len(start):\n  len_seq = 0\n\n  while start &gt; 1:\n    len_seq = len_seq+1\n    if start%2 == 1:\n      start = int(start*3+1)\n    else:\n      start = int(start\/2)\n\n  return len_seq+1\n \nif __name__ == &quot;__main__&quot;:\n  n = input(&quot;Enter the number:&quot;)\n  if n.isnumeric():\n    n = int(n)\n    len_seq = hailstone_seq_len(n)\n    print(&quot;Length of Hailstone Sequence = &quot;, len_seq)\n  else:\n    print(&quot;Invalid input.&quot;)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Enter the number:10\nLength of Hailstone Sequence = 7<\/pre>\n\n\n\n<p><strong>Python Program:<\/strong> <strong>Using recursion<\/strong><\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:false,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">def hailstone_seq_rec_len(start, len_seq=0):\n\n  #base condition\n  if start == 1:\n    return len_seq+1\n\n  len_seq =len_seq+1\n\n  if start%2 == 1:\n    return hailstone_seq_rec_len(start*3+1, len_seq)\n  else:\n    return hailstone_seq_rec_len(start\/2, len_seq)\n\nif __name__ == &quot;__main__&quot;:\n  n = input(&quot;Enter the number:&quot;)\n  if n.isnumeric():\n    n = int(n)\n    len_seq = hailstone_seq_rec_len(n)\n    print(&quot;Length of the hailstone sequence = &quot;, len_seq)\n  else:\n    print(&quot;Invalid input.&quot;)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Enter the number:15\nLength of the hailstone sequence = 18<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Find_the_Maximum_Length_of_Hailstone_Sequence_for_the_Range_of_Given_Numbers\"><\/span>Find the Maximum Length of Hailstone Sequence for the Range of Given Numbers<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p><strong>Problem statement: <\/strong>Write a program hailstones.py that prints all hailstone sequences with starting numbers from 1 to n and prints the number that has the longest hailstone sequence.<\/p>\n\n\n\n<p>You have to find the seed having the maximum length of the hailstone sequence for the hailstone sequences for all the numbers in the range of given numbers.<\/p>\n\n\n\n<p><strong>Algorithm:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Take two numbers as input (says a, b).<\/li><li>Find a hailstone sequence length of all the values ranging from a to b.<\/li><li>Return maximum length out of all the lengths of hailstone sequences.<\/li><\/ul>\n\n\n\n<p><strong>Python Program:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:false,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">def hailstone_seq_len(start):\n  len_seq = 0\n\n  while start &gt; 1:\n    len_seq = len_seq+1\n    if start%2 == 1:\n      start = int(start*3+1)\n    else:\n      start = int(start\/2)\n\n  return len_seq+1\n \nif __name__ == &quot;__main__&quot;:\n  a = input(&quot;Enter the number a:&quot;)\n  b = input(&quot;Enter the number b:&quot;)\n  max_len = 0\n  max_seed = 0\n  if a.isnumeric() and b.isnumeric():\n    a = int(a)\n    b = int(b)\n    for i in range(a, b+1):\n      len_temp = hailstone_seq_len(i)\n      if len_temp &gt; max_len:\n        max_len = len_temp\n        max_seed = i\n    print(&quot;Max length of the Hailstone Sequence is %d for seed %d.&quot; %(max_len, max_seed))\n\n  else:\n    print(&quot;Invalid input.&quot;)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Enter the number a: 10\nEnter the number b: 15\nMax length of the Hailstone Sequence is 18 for seed 14.<\/pre>\n\n\n\n<p>When I attended an interview with NVIDIA, they asked me to optimize it further.<\/p>\n\n\n\n<p>We can use a dynamic programming approach to optimize this problem. <\/p>\n\n\n\n<p>Let&#8217;s look at the hailstone sequence for 10 and 11.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">[10, 5, 16, 8, 4, 2, 1] \n[11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]<\/pre>\n\n\n\n<p>Here the total iteration to calculate hailstone sequence length will be 22.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">7 (length of hailstone sequence for 10) + 15 (length of hailstone sequence for 11)= 22<\/pre>\n\n\n\n<p><strong>How can we optimize it?<\/strong><\/p>\n\n\n\n<p>Observe the sequence for 10 and 11. The hailstone sequence for 10 is a subset of the hailstone sequence for 11.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Calculate the length of the hailstone sequence for 10. (The number of iterations required is 7).<\/li><li>Store the length in the hailstone sequence for 10 in the dictionary (says &#8216;hs_len_dict&#8217;).<\/li><li>Calculate the length of the hailstone sequence for 11.  This can be calculated by finding the light of the hailstone sequence to 10 (The number of Iteration requires is 8) plus the length of the hailstone sequence for 10 (from the dictionary).<\/li><li>So the total iterations required for calculating the length of the hailstone sequence for 10 and 11 is 15 (7+8).<\/li><\/ul>\n\n\n\n<p>With this optimization, we have saved the number of iterations from 22 to 15.<\/p>\n\n\n\n<p><strong>Python Program with Optimization:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:false,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">hs_len_dict = {}\n \nitr = 0\n \ndef hailstone_seq_len(start):\n  global itr\n  len_seq = 0\n  \n  while start &gt; 1:\n    itr = itr+1\n\n    if start in hs_len_dict:\n      return hs_len_dict[start]+len_seq\n  \n    len_seq = len_seq+1\n    if start%2 == 1:\n      start = int(start*3+1)\n    else:\n      start = int(start\/2)\n  \n  return len_seq+1\n  \nif __name__ == &quot;__main__&quot;:\n  a = input(&quot;Enter the number a:&quot;)\n  b = input(&quot;Enter the number b:&quot;)\n  max_len = 0\n  max_seed = 0\n  if a.isnumeric() and b.isnumeric():\n    a = int(a)\n    b = int(b)\n    for i in range(a, b+1):\n      len_temp = hailstone_seq_len(i)\n      hs_len_dict[i] = len_temp\n        \n      if len_temp &gt; max_len:\n        max_len = len_temp\n        max_seed = i\n    print(&quot;Max lenght of the Hailstone Sequence is %d for seed %d&quot; %(max_len, max_seed))\n  \n  else:\n    print(&quot;Invalid input.&quot;)\n\n  print(&quot;Number of iteration: &quot;, itr)<\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>The final output of the optimized code will be the same, but the process is optimized. The number of iterations required has dropped from 72 to 39.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Enter the number a:\nEnter the number b:\nMax length of the Hailstone Sequence is 18 for seed 14\nNumber of iteration: 39<\/pre>\n\n\n\n<p>You can also further optimize this program by calculating the square root of the number. (Hint: If the given number is a square of two, the length of the Hailstone Sequence is the square root of that number.)<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Plot_Hailstone_Sequence_in_Graph\"><\/span>Plot Hailstone Sequence in Graph<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>We are using <code>matplotlob<\/code> library for plotting the graph. It is one of the most used <a href=\"https:\/\/www.csestack.org\/python-libraries-for-data-science\/\">Data Science Python libraries<\/a> used for graph plots.<\/p>\n\n\n\n<p>If you don&#8217;t have <code>matplotlib<\/code> library installed, you can install it using pip tool. Here is the command.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">pip install matplotlib<\/pre>\n\n\n\n<p>Let&#8217;s plot the graph for hailstone sequences for 10 to 15.<\/p>\n\n\n\n<p><strong>Python Program:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block norun\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:false,&quot;className&quot;:&quot;norun&quot;,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">from matplotlib import pyplot as plt\n \ndef hailstone_seq(start):\n  list_out = []\n  while start &gt; 1:\n    list_out.append(int(start))\n    if start%2 == 1:\n      start = int(start*3+1)\n    else:\n      start = int(start\/2)\n  list_out.append(1)\n  return list_out\n \nif __name__ == &quot;__main__&quot;:\n  a = 10\n  b = 15\n  for i in range(a, b+1):\n    list_out = hailstone_seq(i)\n    plt.plot(list_out, label='HS for %d'%i)\n    plt.legend()\n  plt.show()<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" width=\"640\" height=\"480\" src=\"https:\/\/www.csestack.org\/wp-content\/uploads\/2020\/04\/hailstone_sequence_graph.png\" alt=\"\" class=\"wp-image-7224\" srcset=\"https:\/\/www.csestack.org\/wp-content\/uploads\/2020\/04\/hailstone_sequence_graph.png 640w, https:\/\/www.csestack.org\/wp-content\/uploads\/2020\/04\/hailstone_sequence_graph-300x225.png 300w\" sizes=\"(max-width: 640px) 100vw, 640px\" \/><\/figure>\n\n\n\n<p>Hailstone Sequence in Python is a very interesting and common problem of sequencing. <\/p>\n\n\n\n<p>This problem has been asked in many interviews for different companies.<\/p>\n\n\n\n<p>If you have any questions regarding the hailstone sequence problem, let&#8217;s discuss it in the comment.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>[Solved] Hailstone Sequence in Python with and without recursion. Find the Maximum Length of Hailstone Sequence for the Range of Given Numbers.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7,73],"tags":[318],"class_list":["post-7216","post","type-post","status-publish","format-standard","hentry","category-code","category-python","tag-coding-challenge"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.3 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>[Solved] Hailstone Sequence in Python (With or Without Recursion)<\/title>\n<meta name=\"description\" content=\"Hailstone Sequence in Python with and without recursion. Find the Maximum Length of Hailstone Sequence for the Range of Given Numbers.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Hailstone Sequence in Python (With or Without Recursion)\" \/>\n<meta property=\"og:description\" content=\"Hailstone Sequence in Python with and without recursion. Find the Maximum Length of Hailstone Sequence for the Range of Given Numbers.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/\" \/>\n<meta property=\"og:site_name\" content=\"CSEstack\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/aniruddha.ca\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/aniruddha.ca\" \/>\n<meta property=\"article:published_time\" content=\"2020-04-26T05:31:02+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-06-28T10:57:44+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.csestack.org\/wp-content\/uploads\/2020\/04\/hailstone_sequence_graph.png\" \/>\n<meta name=\"author\" content=\"Aniruddha Chaudhari\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@ani_chaudhari\" \/>\n<meta name=\"twitter:site\" content=\"@ani_chaudhari\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Aniruddha Chaudhari\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/hailstone-sequence-python-recursion\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/hailstone-sequence-python-recursion\\\/\"},\"author\":{\"name\":\"Aniruddha Chaudhari\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#\\\/schema\\\/person\\\/634ef1a9c4f38b0d340c6d45fa771218\"},\"headline\":\"[Solved] Hailstone Sequence in Python (With or Without Recursion)\",\"datePublished\":\"2020-04-26T05:31:02+00:00\",\"dateModified\":\"2022-06-28T10:57:44+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/hailstone-sequence-python-recursion\\\/\"},\"wordCount\":723,\"commentCount\":1,\"publisher\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#\\\/schema\\\/person\\\/634ef1a9c4f38b0d340c6d45fa771218\"},\"image\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/hailstone-sequence-python-recursion\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2020\\\/04\\\/hailstone_sequence_graph.png\",\"keywords\":[\"coding challenge\"],\"articleSection\":[\"Code\",\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.csestack.org\\\/hailstone-sequence-python-recursion\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/hailstone-sequence-python-recursion\\\/\",\"url\":\"https:\\\/\\\/www.csestack.org\\\/hailstone-sequence-python-recursion\\\/\",\"name\":\"[Solved] Hailstone Sequence in Python (With or Without Recursion)\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/hailstone-sequence-python-recursion\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/hailstone-sequence-python-recursion\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2020\\\/04\\\/hailstone_sequence_graph.png\",\"datePublished\":\"2020-04-26T05:31:02+00:00\",\"dateModified\":\"2022-06-28T10:57:44+00:00\",\"description\":\"Hailstone Sequence in Python with and without recursion. Find the Maximum Length of Hailstone Sequence for the Range of Given Numbers.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/hailstone-sequence-python-recursion\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.csestack.org\\\/hailstone-sequence-python-recursion\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/hailstone-sequence-python-recursion\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2020\\\/04\\\/hailstone_sequence_graph.png\",\"contentUrl\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2020\\\/04\\\/hailstone_sequence_graph.png\",\"width\":640,\"height\":480,\"caption\":\"hailstone sequence graph using matplotlib\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/hailstone-sequence-python-recursion\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.csestack.org\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Hailstone Sequence in Python (With or Without Recursion)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#website\",\"url\":\"https:\\\/\\\/www.csestack.org\\\/\",\"name\":\"CSEstack\",\"description\":\"Computer Science &amp; Programming Portal\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#\\\/schema\\\/person\\\/634ef1a9c4f38b0d340c6d45fa771218\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.csestack.org\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#\\\/schema\\\/person\\\/634ef1a9c4f38b0d340c6d45fa771218\",\"name\":\"Aniruddha Chaudhari\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/Aniruddha-Chaudhari.jpg\",\"url\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/Aniruddha-Chaudhari.jpg\",\"contentUrl\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/Aniruddha-Chaudhari.jpg\",\"width\":634,\"height\":634,\"caption\":\"Aniruddha Chaudhari\"},\"logo\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/Aniruddha-Chaudhari.jpg\"},\"description\":\"I am a Python enthusiast who loves Linux and Vim. I hold a Master of Computer Science degree from NIT Trichy and have 10 years of experience in the IT industry, focusing on the Software Development Lifecycle from Requirements Gathering, Design, Development to Deployment. I have worked at IBM, Ericsson, and NetApp, and I share my knowledge on CSEstack.org.\",\"sameAs\":[\"https:\\\/\\\/www.csestack.org\",\"https:\\\/\\\/www.facebook.com\\\/aniruddha.ca\",\"pythonwithani\",\"https:\\\/\\\/www.linkedin.com\\\/in\\\/aniruddha28\\\/\",\"https:\\\/\\\/x.com\\\/ani_chaudhari\",\"https:\\\/\\\/www.youtube.com\\\/channel\\\/UCw0a__B0eJsvCujkSIfLTAA\"],\"url\":\"https:\\\/\\\/www.csestack.org\\\/author\\\/anicse\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Hailstone Sequence in Python (With or Without Recursion)","description":"Hailstone Sequence in Python with and without recursion. Find the Maximum Length of Hailstone Sequence for the Range of Given Numbers.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Hailstone Sequence in Python (With or Without Recursion)","og_description":"Hailstone Sequence in Python with and without recursion. Find the Maximum Length of Hailstone Sequence for the Range of Given Numbers.","og_url":"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/","og_site_name":"CSEstack","article_publisher":"https:\/\/www.facebook.com\/aniruddha.ca","article_author":"https:\/\/www.facebook.com\/aniruddha.ca","article_published_time":"2020-04-26T05:31:02+00:00","article_modified_time":"2022-06-28T10:57:44+00:00","og_image":[{"url":"https:\/\/www.csestack.org\/wp-content\/uploads\/2020\/04\/hailstone_sequence_graph.png","type":"","width":"","height":""}],"author":"Aniruddha Chaudhari","twitter_card":"summary_large_image","twitter_creator":"@ani_chaudhari","twitter_site":"@ani_chaudhari","twitter_misc":{"Written by":"Aniruddha Chaudhari","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/#article","isPartOf":{"@id":"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/"},"author":{"name":"Aniruddha Chaudhari","@id":"https:\/\/www.csestack.org\/#\/schema\/person\/634ef1a9c4f38b0d340c6d45fa771218"},"headline":"[Solved] Hailstone Sequence in Python (With or Without Recursion)","datePublished":"2020-04-26T05:31:02+00:00","dateModified":"2022-06-28T10:57:44+00:00","mainEntityOfPage":{"@id":"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/"},"wordCount":723,"commentCount":1,"publisher":{"@id":"https:\/\/www.csestack.org\/#\/schema\/person\/634ef1a9c4f38b0d340c6d45fa771218"},"image":{"@id":"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/#primaryimage"},"thumbnailUrl":"https:\/\/www.csestack.org\/wp-content\/uploads\/2020\/04\/hailstone_sequence_graph.png","keywords":["coding challenge"],"articleSection":["Code","Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/","url":"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/","name":"[Solved] Hailstone Sequence in Python (With or Without Recursion)","isPartOf":{"@id":"https:\/\/www.csestack.org\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/#primaryimage"},"image":{"@id":"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/#primaryimage"},"thumbnailUrl":"https:\/\/www.csestack.org\/wp-content\/uploads\/2020\/04\/hailstone_sequence_graph.png","datePublished":"2020-04-26T05:31:02+00:00","dateModified":"2022-06-28T10:57:44+00:00","description":"Hailstone Sequence in Python with and without recursion. Find the Maximum Length of Hailstone Sequence for the Range of Given Numbers.","breadcrumb":{"@id":"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/#primaryimage","url":"https:\/\/www.csestack.org\/wp-content\/uploads\/2020\/04\/hailstone_sequence_graph.png","contentUrl":"https:\/\/www.csestack.org\/wp-content\/uploads\/2020\/04\/hailstone_sequence_graph.png","width":640,"height":480,"caption":"hailstone sequence graph using matplotlib"},{"@type":"BreadcrumbList","@id":"https:\/\/www.csestack.org\/hailstone-sequence-python-recursion\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.csestack.org\/"},{"@type":"ListItem","position":2,"name":"[Solved] Hailstone Sequence in Python (With or Without Recursion)"}]},{"@type":"WebSite","@id":"https:\/\/www.csestack.org\/#website","url":"https:\/\/www.csestack.org\/","name":"CSEstack","description":"Computer Science &amp; Programming Portal","publisher":{"@id":"https:\/\/www.csestack.org\/#\/schema\/person\/634ef1a9c4f38b0d340c6d45fa771218"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.csestack.org\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/www.csestack.org\/#\/schema\/person\/634ef1a9c4f38b0d340c6d45fa771218","name":"Aniruddha Chaudhari","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.csestack.org\/wp-content\/uploads\/2019\/03\/Aniruddha-Chaudhari.jpg","url":"https:\/\/www.csestack.org\/wp-content\/uploads\/2019\/03\/Aniruddha-Chaudhari.jpg","contentUrl":"https:\/\/www.csestack.org\/wp-content\/uploads\/2019\/03\/Aniruddha-Chaudhari.jpg","width":634,"height":634,"caption":"Aniruddha Chaudhari"},"logo":{"@id":"https:\/\/www.csestack.org\/wp-content\/uploads\/2019\/03\/Aniruddha-Chaudhari.jpg"},"description":"I am a Python enthusiast who loves Linux and Vim. I hold a Master of Computer Science degree from NIT Trichy and have 10 years of experience in the IT industry, focusing on the Software Development Lifecycle from Requirements Gathering, Design, Development to Deployment. I have worked at IBM, Ericsson, and NetApp, and I share my knowledge on CSEstack.org.","sameAs":["https:\/\/www.csestack.org","https:\/\/www.facebook.com\/aniruddha.ca","pythonwithani","https:\/\/www.linkedin.com\/in\/aniruddha28\/","https:\/\/x.com\/ani_chaudhari","https:\/\/www.youtube.com\/channel\/UCw0a__B0eJsvCujkSIfLTAA"],"url":"https:\/\/www.csestack.org\/author\/anicse\/"}]}},"_links":{"self":[{"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/posts\/7216","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/comments?post=7216"}],"version-history":[{"count":14,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/posts\/7216\/revisions"}],"predecessor-version":[{"id":10007,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/posts\/7216\/revisions\/10007"}],"wp:attachment":[{"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/media?parent=7216"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/categories?post=7216"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/tags?post=7216"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}