【问题标题】:Write recursive pseudocode problem in python code在python代码中编写递归伪代码问题
【发布时间】:2020-04-05 15:35:51
【问题描述】:

我无法解决以下问题:

我应该在 python 中实现伪代码。 h 只是一些给定的列表。我尝试了各种各样的东西,最近例如:

def _p_recursion(n,i):
    if n == 0:
        return h[n+i]

    for i in range(1,n+1):
        s = 0
        s = h[i] + _p_recursion(n-i,i)
    v.append(s)
    return s    

v=[]    
h =[0,3,11,56,4]

_p_recursion(2,0)   

我知道为什么它不起作用,但我无法提出解决方案。这感觉像是一个非常简单的问题,但我已经坚持了几个小时。我对递归函数不是很有经验,只有真正的基本函数。我想不出一个。感觉想出解决方案的最简单方法必须是将 p(n) 的所有可能输出附加到一个数组中,然后可以轻松找到最大值。对于上述代码中的值,列表 v 中缺少 11。任何人都可以给我一个提示,如何使用 python 语句来解决这个问题 for, if, while...

提前致谢!

【问题讨论】:

  • 您至少应该自己尝试一下,在此处发布您的代码并询问您遇到的具体问题

标签: python python-3.x recursion pseudocode


【解决方案1】:

代码

def p(n):
  " Implements function shown in image "
  if n == 0:
    return 0

  # Finds the max of h[i] + p(n-i)
  # with p(n-i) found recursively
  # Gets access to h from the global namespace
  return max(h[i] + p(n-i) for i in range(1, n+1))

更明确的递归函数

   def p(n):
      " Implements function shown in image "
      if n == 0:
        return 0

      # Stores previous results in an array for formula
      # then computes max
      previous = []
      for i in range(1, n+1):
          previous.add(h[i] + p(n-i)) 
      return max(previous)

测试

h = range(10)

for i in range(len(h)):
  print(i, p(i))

输出

0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9

性能

darrylg 解决方案

def p_dg(n):
  " Implements function shown in image "
  if n == 0:
    return 0

  # Finds the max of h[i] + p(n-i)
  # with p(n-i) found recursively
  # Gets access to h from the global namespace
  return max(h[i] + p_dg(n-i) for i in range(1, n+1))

海报(卡尔)解决方案

def p(n,m):
    if n == 0:
        return 0

    for i in range(1,n+1):
        s = h[i] + p(n-i,m)
        m[n-1].append(s)

    return max(m[n-1])


def p_caller(n):
    if type(n) != int:
        return
    m =[] 
    for g in range(n):
        m.append([])

    return p(n,m)

带有缓存(记忆)的darrylg解决方案

def p_cache(n, cache = {}):
  if n in cache:
    return cache[n]

  if n == 0:
    return 0

  cache[n] =  max(h[i] + p_cache(n-i) for i in range(1, n+1))

  return cache[n]

时间(秒)

darrylg method
time taken: 0.20136669999965306
Poster method (Karl)
time taken: 26.77383000000009
darrylg with memoization
time taken: 0.00013790000002700253

因此缓存大大提高了性能。

计时码

import time
import random

# timing software allows timing recursive functions
# Source: https://stackoverflow.com/questions/29560643/python-counting-executing-time-of-a-recursion-function-with-decorator
def profile(f):
    is_evaluating = False
    def g(x):
        nonlocal is_evaluating
        if is_evaluating:
            return f(x)
        else:
            start_time = time.perf_counter()
            is_evaluating = True
            try:
                value = f(x)
            finally:
                is_evaluating = False
            end_time = time.perf_counter()
            print('time taken: {time}'.format(time=end_time-start_time))
            return
    return g

# darrylg method
@profile
def p_dg(n):
  " Implements function shown in image "
  if n == 0:
    return 0

  # Finds the max of h[i] + p(n-i)
  # with p(n-i) found recursively
  # Gets access to h from the global namespace
  return max(h[i] + p_dg(n-i) for i in range(1, n+1))

# Poster (Karl) method
def p(n,m):
    if n == 0:
        return 0

    for i in range(1,n+1):
        s = h[i] + p(n-i,m)
        m[n-1].append(s)

    return max(m[n-1])

@profile
def p_caller(n):
    if type(n) != int:
        return
    m =[] 
    for g in range(n):
        m.append([])

    return p(n,m)

# darrylg with caching (Memoization)
@profile
def p_cache(n, cache = {}):
  if n in cache:
    return cache[n]

  if n == 0:
    return 0

  cache[n] =  max(h[i] + p_cache(n-i) for i in range(1, n+1))

  return cache[n]

h = [random.randint(0, 100) for _ in range(18)]

l = 17
print('darrylg method')
p_dg(l)

print('Poster method (Karl)')
p_caller(l)

print('darrylg with memoization')
p_cache(l)

【讨论】:

  • 谢谢!我试图理解代码的最后一行“return max(h[i] + p(n-i) for i in range(1, n+1))”。如果没有内置的 max() 函数,有什么办法可以编写该部分?
  • @KarlKarlsson range(1, n+1)1, 2,...n 生成数字(不包括 n+1)。所以这类似于返回 max(h[1]+p(n-1), h[2]+p(n-2), ...h[n]+p[0]) 来生成p(n) 的值。在返回之前,它必须递归计算 p(0) 到 p(n-1) 以填写公式。这将是低效的,但在实际系统中,您将使用一种称为“记忆”的技术来提高此递归函数的效率。
  • 但是我仍然如何以“低效”的方式编写代码,只使用递归调用?
  • @KarlKarlsson——我的解决方案确实“仅使用递归 alls 以低效的方式编写代码”。这是因为它在计算最大值之前具有递归计算 (h[i] + p(n-i) for i in range(1, n+1)。我将使用更明确的递归公式更新我的答案。
  • 我最终找到了另一种解决这个问题的方法。参见下面的代码: def p(n,m): if n == 0: return 0 for i in range(1,n+1): s = h[i] + p(n-i,m) m [n-1].append(s) return max(m[n-1]) def p_caller(n): if type(n) != int: return m =[] for g in range(n): m. append([]) return p(n,m) 我的解决方案与你的解决方案相比,时间复杂度是多少?
【解决方案2】:

我无法在上一篇文章中评论我的代码,所以我将其写在这里: (我的问题解决方案)

def p(n,m):
    if n == 0:
        return 0

    for i in range(1,n+1):
        s = h[i] + p(n-i,m)
        m[n-1].append(s)
    return max(m[n-1])


def p_caller(n):
    if type(n) != int:
        return
    m =[] 
    for g in range(n):
        m.append([])
    return p(n,m)

我永远不会真正只调用 p() p_caller() DarrylG 解决问题:

def p(n):
    if n == 0:
        return 0

# Finds the max of h[i] + p(n-i)
# with p(n-i) found recursively
# Gets access to h from the global namespace
    return max(h[i] + p(n-i) for i in range(1, n+1))

这些方法在最坏情况下的时间复杂度有何不同?为什么?

【讨论】:

    猜你喜欢
    • 2010-11-29
    • 2016-09-22
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多