将python转换为R的建议?

问题描述 投票:-3回答:1

我有一个功能,可以用1、5、25和50数出每一种可能的制作100的方法。

我希望它在R中工作,有什么建议吗?

def changes(amount, coins): ways = [0] * (amount + 1) ways[0] = 1 for coin in coins: for j in range(coin, amount + 1): ways[j] += ways[j - coin] return ways[amount] print(changes(100, [1, 5, 25, 50]))

python r
1个回答
0
投票

这里或多或少是直接翻译,但有一点点增强,因此适用于amount < max(coins) ...

changes <- function(amount, coins) {
  ways <- rep(0, amount + 1)
  ways[1] <- 1
  for (coin in coins[coins < amount]) {   #added [coins<amount] not in python version
    for (j in coin:(amount + 1)) {
      ways[j + 1] <- ways[j + 1] + ways[j + 1 - coin]
    }
  }
  return(ways[amount + 1])
}

changes(100, c(1, 5, 25, 50))
[1] 74
© www.soinside.com 2019 - 2024. All rights reserved.