{"id":33380,"date":"2023-02-07T11:35:21","date_gmt":"2023-02-07T06:05:21","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/"},"modified":"2023-02-07T11:35:21","modified_gmt":"2023-02-07T06:05:21","slug":"solved-recursive-to-iterative-using-a-systematic-method-closed","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/","title":{"rendered":"[Solved] Recursive to iterative using a systematic method [closed]"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-39128242\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"39128242\" data-parentid=\"38567618\" data-score=\"4\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>So, to restate the question. We have a function <em>f<\/em>, in our case <code>fac<\/code>. <\/p>\n<pre><code>def fac(n):\n    if n==0:\n        return 1\n    else:\n        return n*fac(n-1)\n<\/code><\/pre>\n<p>It is implemented recursively. We want to implement a function <code>facOpt<\/code> that does the same thing but iteratively. <code>fac<\/code> is written almost in the form we need. Let us rewrite it just a bit:<\/p>\n<pre><code>def fac_(n, r):\n    return (n+1)*r\n\ndef fac(n):\n    if n==0:\n        return 1\n    else:\n        r = fac(n-1)\n        return fac_(n-1, r)\n<\/code><\/pre>\n<p>This is exactly the recursive definition from section 4.2. Now we need to rewrite it iteratively:<\/p>\n<pre><code>def facOpt(n):\n    if n==0:\n        return 1\n    x = 1\n    r = 1\n    while x != n:\n        x = x + 1\n        r = fac_(x-1, r)\n    return r\n<\/code><\/pre>\n<p>This is exactly the iterative definition from section 4.2. Note that <code>facOpt<\/code> does not call itself anywhere. Now, this is neither the most clear nor the most pythonic way of writing down this algorithm &#8212; this is just a way to transform one algorithm to another. We can implement the same algorithm differently, e.g. like that:<\/p>\n<pre><code>def facOpt(n):\n    r = 1\n    for x in range(1, n+1):\n        r *= x \n    return r\n<\/code><\/pre>\n<p>Things get more interesting when we consider more complicated functions. Let us write <code>fibObt<\/code> where <code>fib<\/code> is :<\/p>\n<pre><code>def fib(n):\n    if n==0:\n        return 0\n    elif n==1:\n        return 1\n    else:\n        return fib(n-1) + fib(n-2)\n<\/code><\/pre>\n<p><code>fib<\/code> calls itself two times, but the recursive pattern from the book allows only a single call. That is why we need to extend the function to returning not one, but two values. Fully reformated, <code>fib<\/code> looks like this:<\/p>\n<pre><code>def fibExt_(n, rExt):\n    return rExt[0] + rExt[1], rExt[0]\n\ndef fibExt(n):\n    if n == 0:\n        return 0, 0\n    elif n == 1:\n        return 1, 0\n    else:\n        rExt = fibExt(n-1)\n        return fibExt_(n-1, rExt)\n\ndef fib(n):\n    return fibExt(n)[0]\n<\/code><\/pre>\n<p>You may notice that the first argument to <code>fibExt_<\/code> is never used. I just added it to follow the proposed structure exactly.<br \/>\nNow, it is again easy to turn <code>fib<\/code> into an iterative version:<\/p>\n<pre><code>def fibExtOpt(n):\n    if n == 0:\n        return 0, 0\n    if n == 1:\n        return 1, 0\n    x = 2\n    rExt = 1, 1\n    while x != n:\n        x = x + 1\n        rExt = fibExt_(x-1, rExt)\n    return rExt\n\ndef fibOpt(n):\n    return fibExtOpt(n)[0]\n<\/code><\/pre>\n<p>Again, the new version does not call itself. And again one can streamline it to this, for example:<\/p>\n<pre><code>def fibOpt(n):\n    if n &lt; 2:\n        return n\n    a, b = 1, 1\n    for i in range(n-2):\n        a, b = b, a+b\n    return b\n<\/code><\/pre>\n<p>The next function to translate to iterative version is <code>bin<\/code>:<\/p>\n<pre><code>def bin(n,k):\n    if k == 0 or k == n:\n        return 1\n    else:\n        return bin(n-1,k-1) + bin(n-1,k)\n<\/code><\/pre>\n<p>Now neither <code>x<\/code> nor <code>r<\/code> can be just numbers. The index (<code>x<\/code>) has two components, and the cache (<code>r<\/code>) has to be even larger. One (not quite so optimal) way would be to return the whole previous row of the Pascal triangle:<\/p>\n<pre><code>def binExt_(r):\n    return [a + b for a,b in zip([0] + r, r + [0])]\n\ndef binExt(n):\n    if n == 0:\n        return [1]\n    else:\n        r = binExt(n-1)\n        return binExt_(r)\n\ndef bin(n, k):\n    return binExt(n)[k]\n<\/code><\/pre>\n<p>I have&#8217;t followed the pattern so strictly here and removed several useless variables. It is still possible to translate to an iterative version directly:<\/p>\n<pre><code>def binExtOpt(n):\n    if n == 0:\n        return [1]\n    x = 1\n    r = [1, 1]\n    while x != n:\n        r = binExt_(r)\n        x += 1\n    return r\n\ndef binOpt(n, k):\n    return binExtOpt(n)[k]\n<\/code><\/pre>\n<p>For completeness, here is an optimized solution that caches only part of the row:<\/p>\n<pre><code>def binExt_(n, k_from, k_to, r):\n    if k_from == 0 and k_to == n:\n        return [a + b for a, b in zip([0] + r, r + [0])]\n    elif k_from == 0:\n        return [a + b for a, b in zip([0] + r[:-1], r)]\n    elif k_to == n:\n        return [a + b for a, b in zip(r, r[1:] + [0])]\n    else:\n        return [a + b for a, b in zip(r[:-1], r[1:])]\n\ndef binExt(n, k_from, k_to):\n    if n == 0:\n        return [1]\n    else:\n        r = binExt(n-1, max(0, k_from-1), min(n-1, k_to+1) )\n        return binExt_(n, k_from, k_to, r)\n\ndef bin(n, k):\n    return binExt(n, k, k)[0]\n\ndef binExtOpt(n, k_from, k_to):\n    if n == 0:\n        return [1]\n    ks = [(k_from, k_to)]\n    for i in range(1,n):\n        ks.append((max(0, ks[-1][0]-1), min(n-i, ks[-1][1]+1)))\n    x = 0\n    r = [1]\n    while x != n:\n        x += 1\n        r = binExt_(x, *ks[n-x], r)\n    return r\n\ndef binOpt(n, k):\n    return binExtOpt(n, k, k)[0]\n<\/code><\/pre>\n<p>In the end, the most difficult task is not switching from recursive to iterative implementation, but to have a recursive implementation that follows the required pattern. So the real question is how to create <code>fibExt'<\/code>, not <code>fibExtOpt<\/code>.<\/p>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">4<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Recursive to iterative using a systematic method [closed] <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] So, to restate the question. We have a function f, in our case fac. def fac(n): if n==0: return 1 else: return n*fac(n-1) It is implemented recursively. We want to implement a function facOpt that does the same thing but iteratively. fac is written almost in the form we need. Let us rewrite it &#8230; <a title=\"[Solved] Recursive to iterative using a systematic method [closed]\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/\" aria-label=\"More on [Solved] Recursive to iterative using a systematic method [closed]\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[349,494],"class_list":["post-33380","post","type-post","status-publish","format-standard","hentry","category-solved","tag-python","tag-recursion"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>[Solved] Recursive to iterative using a systematic method [closed] - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Recursive to iterative using a systematic method [closed] - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] So, to restate the question. We have a function f, in our case fac. def fac(n): if n==0: return 1 else: return n*fac(n-1) It is implemented recursively. We want to implement a function facOpt that does the same thing but iteratively. fac is written almost in the form we need. Let us rewrite it ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2023-02-07T06:05:21+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-recursive-to-iterative-using-a-systematic-method-closed\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-recursive-to-iterative-using-a-systematic-method-closed\\\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#\\\/schema\\\/person\\\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Recursive to iterative using a systematic method [closed]\",\"datePublished\":\"2023-02-07T06:05:21+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-recursive-to-iterative-using-a-systematic-method-closed\\\/\"},\"wordCount\":358,\"publisher\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#organization\"},\"keywords\":[\"python\",\"recursion\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-recursive-to-iterative-using-a-systematic-method-closed\\\/\",\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-recursive-to-iterative-using-a-systematic-method-closed\\\/\",\"name\":\"[Solved] Recursive to iterative using a systematic method [closed] - JassWeb\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#website\"},\"datePublished\":\"2023-02-07T06:05:21+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-recursive-to-iterative-using-a-systematic-method-closed\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-recursive-to-iterative-using-a-systematic-method-closed\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-recursive-to-iterative-using-a-systematic-method-closed\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Recursive to iterative using a systematic method [closed]\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#website\",\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/jassweb.com\\\/wp-content\\\/uploads\\\/2021\\\/02\\\/jass-website-logo-1.png\",\"contentUrl\":\"https:\\\/\\\/jassweb.com\\\/wp-content\\\/uploads\\\/2021\\\/02\\\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#\\\/schema\\\/logo\\\/image\\\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#\\\/schema\\\/person\\\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/wp-content\\\/litespeed\\\/avatar\\\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400\",\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/wp-content\\\/litespeed\\\/avatar\\\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400\",\"contentUrl\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/wp-content\\\/litespeed\\\/avatar\\\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\\\/\\\/jassweb.com\"],\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/author\\\/jaspritsinghghumangmail-com\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Recursive to iterative using a systematic method [closed] - JassWeb","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:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Recursive to iterative using a systematic method [closed] - JassWeb","og_description":"[ad_1] So, to restate the question. We have a function f, in our case fac. def fac(n): if n==0: return 1 else: return n*fac(n-1) It is implemented recursively. We want to implement a function facOpt that does the same thing but iteratively. fac is written almost in the form we need. Let us rewrite it ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/","og_site_name":"JassWeb","article_published_time":"2023-02-07T06:05:21+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Recursive to iterative using a systematic method [closed]","datePublished":"2023-02-07T06:05:21+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/"},"wordCount":358,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["python","recursion"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/","url":"https:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/","name":"[Solved] Recursive to iterative using a systematic method [closed] - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2023-02-07T06:05:21+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-recursive-to-iterative-using-a-systematic-method-closed\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Recursive to iterative using a systematic method [closed]"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/33380","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=33380"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/33380\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=33380"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=33380"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=33380"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}