python--使用递归优雅实现列表相加和进制转换

咦,好像坚持了一段时间,感觉又有新收获啦。

# coding: utf-8


class Stack:
    def __init__(self):
        self.items = []

    # 是否为空
    def is_empty(self):
        return self.items == []

    # 进栈
    def push(self, item):
        self.items.append(item)

    # 出栈
    def pop(self):
        return self.items.pop()

    # 返回栈顶值,不改变栈
    def peek(self):
        return self.items[len(self.items) - 1]

    # 返回栈长度
    def size(self):
        return len(self.items)


def list_sum(my_list):
    print(my_list)
    if len(my_list) == 1:
        return my_list[0]
    else:
        print(my_list[0], my_list[1:])
        return my_list[0] + list_sum(my_list[1:])


print('=======recursion list add=========')
print(list_sum([1, 3, 5, 7, 9]))

s = Stack()


def to_base_str(num, base):
    base_str = '0123456789ABCDEF'
    div = num // base
    mod = num % base
    s.push(base_str[mod])
    if div == 0:
        res = ''
        while not s.is_empty():
            res += s.pop()
        return res
    else:
        return to_base_str(div, base)


print('=======recursion base trans=========')
print('1456 from 10 to 16: ', to_base_str(1456, 16))
print('32 from 10 to 2: ', to_base_str(32, 2))

输出:

C:\Users\Sahara\.virtualenvs\untitled\Scripts\python.exe D:/test/python_recursion.py
=======recursion list add=========
[1, 3, 5, 7, 9]
1 [3, 5, 7, 9]
[3, 5, 7, 9]
3 [5, 7, 9]
[5, 7, 9]
5 [7, 9]
[7, 9]
7 [9]
[9]
25
=======recursion base trans=========
1456 from 10 to 16:  5B0
32 from 10 to 2:  100000

Process finished with exit code 0

  

猜你喜欢

转载自www.cnblogs.com/aguncn/p/10661024.html