抢凳子游戏:
思路:一个随机数,将对应位置的淘汰,将其他的放到第一位:
import random list = [1, 2, 3, 4, 5, 6, 7] while True: if len(list) == 1: # pop的只剩最后一位了 print('游戏结束,{}获得了胜利'.format(list[0])) break hit = random.randint(1, 3) # 随机数指定倒数第几位淘汰 while hit >= 1: pop1 = list.pop() # 取出后面的数将它放到最前面 if hit == 1: print('{}被淘汰了'.format(pop1)) # hit等于1的时候,就是该淘汰的人 break list.insert(0, pop1) hit -= 1
链表:
class Node(): def __init__(self, date=None, next=None): self._data = date self._next = next def setDate(self, Newdata): self._data = Newdata def setNext(self, NewNext): self._next = NewNext def getDate(self): return self._data def getNext(self): return self._next class linkList(): def __init__(self): self._head = Node() self._length = 0 def tail_add(self, Newdata): newdate = Node(Newdata, None) if self._length == 0: self._head = newdate self._length = 1 else: current = self._head while current.getNext() != None: current = current.getNext() current.setnext(newdate) self._length += 1
图:
A机场可以到达BCD
B机场可以到无
C机场可以到D
D机场可以到A
import numpy as np class AdjacencyMatrix(): def __init__(self, n=2): self.Matrix = np.zeros([n, n]) def get_matrix(self): for i in self.Matrix: print(i) def add(self, x, y, value): self.Matrix[x, y] = value # 设置节点之间的关系 airport = AdjacencyMatrix(4) # 4个飞机节点 airport.add(0, 1, 1) airport.add(0, 2, 1) airport.add(0, 3, 1) airport.add(2, 3, 1) airport.add(3, 1, 1) airport.get_matrix()