Python3解《劍指》問題:“遇到奇數移至最前,遇到偶數移至最後”
阿新 • • 發佈:2018-07-13
tail mov ber range __name__ 內置函數 self tuple !=
[本文出自天外歸雲的博客園]
我做了兩種解法,一種是利用python內置函數,另一種是自定義與數字相關的類與函數。
‘‘‘ 解法1:利用python中與列表相關的內置函數 ‘‘‘ def move_numbers(numbers: list, new_numbers=[]): while len(numbers) > 0: if numbers[0] % 2 == 0: number = numbers.pop(0) new_numbers.append(number) else: number = numbers.pop(0) new_numbers.insert(0, number) print(new_numbers) ‘‘‘ 解法2:自定義與數字相關的類與函數 ‘‘‘ class Numbers: header = None tail = None numbers = None class Number: def __init__(self, value): self.value = value self.next= None def __init__(self, *args): self.numbers = tuple([Numbers.Number(arg) for arg in args]) self.install(self.numbers) def install(self, args: tuple): for i in range(len(args)): number = args[i] if i == 0 and len(args) > 1: number.next= args[i + 1] self.header = number if i > 0 and i < len(args) - 1: number.next = args[i + 1] if i == len(args) - 1 and len(args) > 1: self.tail = number def show(self): subs = [] index = self.header while index: subs.append(index.value) index = index.next print(subs) def move(self): index = self.header new_header = None for i in range(len(self.numbers)): _next = index.next if index.value % 2 == 0: index.next = None self.tail.next = index self.tail = index if index.value % 2 != 0 and i != 0: if new_header: index.next = new_header new_header = index else: new_header = index new_header.next = self.header self.header = new_header index = _next ‘‘‘ 題目: 遇到奇數移動到最前面 遇到偶數移動到最後面 ‘‘‘ if __name__ == ‘__main__‘: # 解法1 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] move_numbers(numbers) # 解法2 numbers = Numbers(1, 2, 3, 4, 5, 6, 7, 8, 9, 0) numbers.move() numbers.show()
Python3解《劍指》問題:“遇到奇數移至最前,遇到偶數移至最後”