有办法让这段Python代码运行得更快吗?

huangapple go评论84阅读模式
英文:

Anyway to make this code goes faster in python?

问题

以下是您提供的代码的翻译部分:

from sys import setrecursionlimit
setrecursionlimit(10 ** 6)

MOD = 1000000007
dp = [0] * 1000001

def DP(dp, left):
    if(dp[left] != 0):
        return dp[left]
    for i in range(1, 7):
        if(left - i >= 0):
            dp[left] += DP(dp, left - i)
            dp[left] %= MOD
    return dp[left]

n = int(input())
dp[0] = 1
print(DP(dp, n))

请注意,这段代码的翻译并没有进行性能优化。如果您希望提高代码的运行速度,可以考虑使用迭代而不是递归来实现动态规划,这通常会更快。此外,您还可以尝试使用其他算法来解决问题,以提高性能。

英文:
from sys import setrecursionlimit
setrecursionlimit(10 ** 6)

MOD = 1000000007
dp = [0] * 1000001

def DP(dp, left):
    if(dp[left] != 0):
        return dp[left]
    for i in range(1, 7):
        if(left - i >= 0):
            dp[left] += DP(dp, left - i)
            dp[left] %= MOD
    return dp[left]

n = int(input())
dp[0] = 1
print(DP(dp, n))

Is there anyway to make this code goes faster? It can run when n is around 100000 but it was slowdown when n=654321. The task is to count the way to combining 1, 2, 3, 4, 5, 6 (a dice's faces) to make n. Example: when n=3, all the way to create n is 4: 1+1+1; 2+1; 1+2; 3. I was trying to use Dynamic Programming skill to solve but timeout. Thanks for your help!

答案1

得分: 0

让我们尝试使用自底向上的表格法,我们迭代地首先计算较小问题的值,然后使用这些值来计算该值。

def DP(n):
    MOD = 1000000007
    dp = [0] * (n + 1)
    dp[0] = 1

    for i in range(1, n+1):
        for j in range(1, 7):
            if i >= j:
                dp[i] += dp[i - j]
                dp[i] %= MOD
    return dp[n]

n = int(input())
print(DP(n))
英文:

Lets try to use a bottom-up, tabulation method, we iteratively compute the values for smaller problems first and then use these values to compute the value.

def DP(n):
    MOD = 1000000007
    dp = [0] * (n + 1)
    dp[0] = 1

    for i in range(1, n+1):
        for j in range(1, 7):
            if i >= j:
                dp[i] += dp[i - j]
                dp[i] %= MOD
    return dp[n]

n = int(input())
print(DP(n))

答案2

得分: 0

内部循环可以通过使用前缀和进行优化。使用长度为 n+1 的数字列表来存储前缀和。

def DP(n):
    MOD = 1000000007
    dp = [0] * (n + 1)
    dp[0] = 1
    for i in range(1, n+1):
        for j in range(1, min(i, 6) + 1):
            dp[i] = (dp[i] + dp[i-j]) % MOD
    return dp[n]

n = int(input())
print(DP(n))
英文:

The inner loop can be optimized by using a prefix sums. A list of numbers with list length of n+1 to store the prefix sums.

def DP(n):
    MOD = 1000000007
    dp = [0] * (n + 1)
    dp[0] = 1
    for i in range(1, n+1):
        for j in range(1, min(i, 6) + 1):
            dp[i] = (dp[i] + dp[i-j]) % MOD
    return dp[n]

int(input())
print(DP(n))

huangapple
  • 本文由 发表于 2023年6月12日 11:27:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定