哈利波特获赠了一张价值不菲的魔法课程优惠卡,卡上余额假设为n
,但是仅限购买2套课程,如果没用完的余额将无法使用。假设课程价格用一个数字列表courses来表示,我们的任务就是根据给定的金额来选购合适的课程,将这张优惠卡的价值发挥到最大(总和刚好等于卡面金额)。请编写一个python3函数,返回最佳的组合课程的索引。如果存在多个总价值相同的组合,那么取最先出现的那组;如果
示例:
输入:2000,[1000, 1000]
,输出:[0,1]
输入:3000, [1000, 1000]
,输出:None
输入:5000,[1000,2000,3000,4000,5000]
,输出:[0,3]
。虽然[1,2]
的元素对应加起来也是5000
但是位置靠后。
题目难度:简单
题目来源:codewars
def buy(n: int, courses: list):
pass
assert buy(2000, [1000, 1000]) == [0, 1]
assert buy(3000, [1000, 1000]) == None
assert buy(5000, [1000,2000,3000,4000,5000]) == [0,3]
public ArrayList<Integer> buy(Integer integer,ArrayList<Integer> arrayList){
ArrayList<Integer> result = new ArrayList<>();
for (int i = 0; i < arrayList.size(); i++) {
for (int j = i+1; j <arrayList.size() ; j++) {
if (integer== arrayList.get(i)+arrayList.get(j)){
result.add(arrayList.get(i));
result.add(arrayList.get(j));
break;
}
}
}
return result;
}
@Test
public void testBuy(){
ArrayList<Integer> ins = new ArrayList<>();
ins.add(1000);
ins.add(1000);
ins.add(3000);
ins.add(4000);
ins.add(5000);
System.out.println(buy(5000, ins));
}
def buy(n: int, courses: list):
for i, price in enumerate(courses):
if n - price in courses[i+1:]:
return [i, courses[i+1:].index(n-price) + i + 1]
return None
if __name__ == "__main__":
assert buy(2000, [1000, 1000]) == [0, 1]
assert buy(3000, [1000, 1000]) is None
assert buy(5000, [1000, 21000, 3000, 4000, 5000]) == [0, 3]
1 个赞
def buy(n: int, courses: list):
for index1, value1 in enumerate(courses):
for index2, value2 in enumerate(courses[index1 + 1:]):
if value1 + value2 == n:
print([index1, index1 + index2 + 1])
return [index1, index1 + index2 + 1]
assert buy(2000, [1000, 1000]) == [0, 1]
assert buy(3000, [1000, 1000]) == None
assert buy(5000, [1000, 2000, 3000, 4000, 5000]) == [0, 3]