python中的ThrowCards
给定的是一组有序的python中的ThrowCards,python,Python,给定的是一组有序的n卡片,编号为1至n,卡片1在顶部,卡片n在底部 只要卡组中至少有两张卡,则执行以下操作: 扔掉上面的牌,将现在在牌组顶部的牌移动到牌组底部 我的任务是找到最后一张k丢弃的卡和最后一张剩余卡的顺序 每行输入包含两个非负数 n,其中n≤ 5000 k,其中k
n
卡片,编号为1
至n
,卡片1
在顶部,卡片n
在底部
只要卡组中至少有两张卡,则执行以下操作:
- 扔掉上面的牌,将现在在牌组顶部的牌移动到牌组底部
k
丢弃的卡和最后一张剩余卡的顺序
- 每行输入包含两个非负数
,其中n
n≤ 5000
,其中k
k
- 对于每个输入行,生成两行输出
- k个丢弃卡的序列
- 剩下的最后一张牌
7 2
19 4
10 5
6 3
4000 7
Last 2 cards discarded: [4, 2]
Remaining card: 6
Last 4 cards discarded: [2, 10, 18, 14]
Remaining card: 6
Last 5 cards discarded: [9, 2, 6, 10, 8]
Remaining card: 4
Last 3 cards discarded: [5, 2, 6]
Remaining card: 4
Last 7 cards discarded: [320, 1344, 2368, 3392, 832, 2880, 1856]
Remaining card: 3904
样本输入的输出
7 2
19 4
10 5
6 3
4000 7
Last 2 cards discarded: [4, 2]
Remaining card: 6
Last 4 cards discarded: [2, 10, 18, 14]
Remaining card: 6
Last 5 cards discarded: [9, 2, 6, 10, 8]
Remaining card: 4
Last 3 cards discarded: [5, 2, 6]
Remaining card: 4
Last 7 cards discarded: [320, 1344, 2368, 3392, 832, 2880, 1856]
Remaining card: 3904
我的代码将继续打印出准确的答案,但在下一行中没有任何答案。我很困惑为什么每次输出后都不打印 这是我的密码:
def throw_card(n,k):
lst=[]
bst=[]
for i in range(1,n+1):
lst.append(i)
while lst[0]!=lst[1] and len(lst)>1 and n<=5000 and k<n:
bst.append(lst.pop(0))
if len(lst)==1:
break
else:
lst.append(lst[0])
lst.remove(lst[0])
print('Last',k,'cards discarded: ',bst[n-(k+1):])
print('Remaining card: ',lst.pop())
print(throw_card(7,2))
print(throw_card(19,4))
print(throw_card(10,5))
print(throw_card(6,3))
print(throw_card(4000,7))
当您执行打印(掷卡(7,2))
时,您正在打印掷卡
函数的返回值。您的函数不返回任何内容(也称为None
)
你应该做的就是调用你的函数
throw_card(7,2)
throw_card(19,4)
throw_card(10,5)
throw_card(6,3)
throw_card(4000,7)
与您的问题无关:我建议使用数据类型
collections.deque
(发音为“deck”,意思是“双端队列”)来处理您的卡片组。它经过优化,允许从两端快速插入和移除(以中间较慢的操作为代价)。由于您所做的一切都是append
和pop(0)
,因此它将完全满足您的需要,并且比列表更高效。