给一个正整数,如果是偶数,则减半;如果是奇数,则变为它的三倍加一。直到变为一停止。
对于所有正整数经过足够多次变换最终总能达到1。
#!/usr/bin/env python # -*- coding: utf-8 -*- def collatz(number): while(number != 1): if number % 2 == 0: number = number // 2 print(number) else: number = 3 * number + 1 print(number) if __name__ == '__main__': try: # 输入一个大于0的整数 number = abs(int(input("Enter a number:"))) if number != 0: collatz(number) else: print("Pointless!") except: print("Input error!")
用列表:
#!/usr/bin/env python # -*- coding: utf-8 -*- def collatz(number): numbers = [] while(number != 1): if number % 2 == 0: number //= 2 else: number = 3 * number + 1 numbers.append(number) return numbers if __name__ == '__main__': number = raw_input("Enter a number:") if number.isdigit() and int(number) != 0: number = int(number) numbers = collatz(number) print(numbers) else: print("Input error!")