首页 > 解决方案 > 如何在单个约束下计算 Python 中两个数组中的值?

问题描述

所以我已经尝试学习 Python 有一段时间了(大约 2 个月),虽然我已经掌握了基础知识,但我正在尝试来自 HackerRank.com 的一些更具挑战性的场景。我觉得我有点接近这里的答案,因为我觉得这里的问题相当简单。

我知道需要设置这些值,以便 n(键盘数量)和 m(驱动器数量)不超过 b(预算),但尽可能接近该数字。

如果不可能小于或等于 b,那么我需要打印一个 -1 来代替。

参数的顺序是 b(预算)、n(键盘)、m(驱动器)。下一行输入是键盘的价格,最后一行输入是驱动器的价格。

例如:

样本输入:

10 2 3
3 1
5 2 8

样本输出:

9

这是到目前为止的代码:

#!/bin/python3

import os
import sys

#
# Complete the getMoneySpent function below.
#
def getMoneySpent(keyboards, drives, b):
    
    keyboards = int(keyboards * n)
    drives = int(drives * m)
    if keyboards + drives > b:
        return -1
    else:
        return keyboards + drives
    


if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    bnm = input().split()

    b = int(bnm[0])

    n = int(bnm[1])

    m = int(bnm[2])

    keyboards = list(map(int, input().rstrip().split()))

    drives = list(map(int, input().rstrip().split()))

    #
    # The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items
    #

    moneySpent = getMoneySpent(keyboards, drives, b)

    fptr.write(str(moneySpent) + '\n')

    fptr.close()

实际上,我收到一条错误消息:

    Traceback (most recent call last):
  File "Solution.py", line 39, in <module>
    moneySpent = getMoneySpent(keyboards, drives, b)
  File "Solution.py", line 11, in getMoneySpent
    keyboards = int(keyboards * n)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

标签: pythonarrays

解决方案


推荐阅读