python - 如何在单个约束下计算 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'
解决方案
推荐阅读
- c++ - C++如何运行多个可以随时调用的后台函数线程?
- c# - 你应该调用 HttpRequest.Abort() 吗?
- visual-studio-2012 - 为“_MSC_VER”检测到错误 LNK2038 不匹配:值“1700”与 xxxx.obj 中的值“1900”不匹配
- javascript - 在 React 中做两件事 onClick
- java - 为了安全起见,将 new String(char[]) 作为密码参数传递给只接受字符串作为参数的方法是否安全?
- entity-framework - EntityFramework Core Timeout 已过期。操作完成前超时时间已过或服务器无响应
- java - 保存前重命名多部分文件
- python - 从嵌套列表中删除元素
- r - 使用 dplyr 的多个 group_by 和 top_n
- php - 客户注册未将信息添加到 phpmyadmin