python - 气泡排序开关和旋转挑战

标签 python python-3.x list sorting

我正在尝试创建一个包含切换和旋转功能的 MarblesBoard 类。

我的代码如下:

class MarblesBoard():
def __init__(self, balls):
    self.balls = balls
def __repr__(self):
    return " ".join(str(i) for i in self.balls)

def switch(self):
    lst=list(self.balls)
    lst[0], lst[1] = lst[1], lst[0]        
    return lst

def rotate(self): 
    lst=list(self.balls)
    lst = lst[1:]+lst[:1]
    return self.balls

输出应该是这样的:

>>> board = MarblesBoard((3,6,7,4,1,0,8,2,5)) 
>>> board 
3 6 7 4 1 0 8 2 5 
>>> board.switch() 
>>> board 
6 3 7 4 1 0 8 2 5 
>>> board.rotate() 
>>> board 
3 7 4 1 0 8 2 5 6 
>>> board.switch() 
>>> board 
7 3 4 1 0 8 2 5 6

但是,当我使用切换或旋转时,它会减少调用原始球列表。不知道如何解决这个问题。

最佳答案

您实际上并没有修改 self.balls,只是返回修改后的列表。

如果您想让方法基本相同,并继续使用元组,您可以更改 switch() 的定义,以实际将更改写入 self.balls 通过执行以下操作:

  def switch(self):
      lst=list(self.balls)
      lst[0], lst[1] = lst[1], lst[0]  
      self.balls = tuple(lst)

同样,您可以将 rotate() 更改为如下所示:

  def rotate(self): 
      lst=list(self.balls)
      lst = lst[1:]+lst[:1]
      self.balls=tuple(lst)

关于python - 气泡排序开关和旋转挑战,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52940093/

相关文章:

python - 使用 beautifulsoup 抓取 XML 元素属性

python - 用 $ 正则表达式前缀字母

Python argparse : Mutually exclusive group where one or the other are required

python random.setstate(), seed() - 是否保证跨实现的结果相同?

java - Collections.emptyList() 和 Collections.EMPTY_LIST 有什么区别

Java - 转换为未知类型

python - 属性错误: module 'networkx' has no attribute 'Graph' in vs code

python - 皮卡没有属性日志

python - 使用什么库从图像中提取文本 (OCR)?

Python 优化 : Choosing between dictionary or list of list