I have been tasked with doing a cardtrick that simulates a sequence of cards. The sequence is that the first card is taken out and placed at the bottom, the second card is placed on the table. This process is repeated until all cards have been laid on the table. If you have the order that is given in "Q_kort",you will lay out the cards in order of size (1, 2, 3... etc). Don't know how to do the process. Trying a forloop but it treats all elements the same. How do you make it so that it becomes every other element? We should do it with an Array. Below is what I got but doesnt really work.
from array import array
Q_kort = array("i", [7, 1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10])
class Kort:
def __init__(self, Q_kort):
self.__Q_kort = Q_kort
def enqueue(self, x):
sist = self.__Q_kort.append(x)
return sist
def dequeue(self):
forst = self.__Q_kort.pop(0)
return forst
def magic():
kort = Kort(Q_kort)
for element in Q_kort:
kort.dequeue()
kort.enqueue(element)
print(element)
magic()
CodePudding user response:
use collections.deque
ex)
In [1]: from collections import deque
In [2]: d = deque()
In [3]: d.append(1)
In [4]: d.append(2)
In [5]: d.appendleft(3)
In [6]: d.append(4)
In [7]: d.appendleft(5)
In [8]: d
Out[8]: deque([5, 3, 1, 2, 4])
In [9]: d.pop()
Out[9]: 4
In [10]: d.popleft()
Out[10]: 5
In [11]: d
Out[11]: deque([3, 1, 2])
CodePudding user response:
This is really much simpler than you think, you don't even need to define a class, two functions, etc (btw, append
does not return a value, so sist = self.__Q_kort.append(x)
assigns None
to sist
).
Just use the cards as requested, until you don't have any more of them:
def magic(arr):
while arr:
arr.append(arr.pop(0)) #one card to the bottom
print(arr.pop(0)) #one card on the table
magic(array("i", [7, 1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10]))
1
2
3
4
5
6
7
8
9
10
11
12
13
CodePudding user response:
I think this is what you want to do
from array import array
from collections import deque
Q_kort = [7, 1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10]
class Kort(deque):
def __init__(self, Q_kort):
super().__init__(Q_kort)
def enqueue(self):
out = super().popleft()
super().append(out)
#print('out:',out)
def dequeue(self):
forst = self.popleft()
return forst
def magic():
output = []
kort = Kort(Q_kort)
for _ in Q_kort:
kort.enqueue()
out = kort.dequeue()
print(out)
output.append(out)
return output
output = magic()
print(output)
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]