Python3內置容器之例子

1.歸併排序

L1 = [1, 2, 4, 6, 9]
L2 = [2, 3, 5, 7, 8]

L3 = []

for x in L1:
    while len(L2) > 0:
        if x > L2[0]:
            L3.append(L2.pop(0))
        else:
            L3.append(x)
            break
    if len(L2) == 0:
        L3.append(x)
        
L3.extend(L2)
print(L3)

2.按單詞反轉字符串

s = 'I Love You'
tmp = s.split()
s2 = ' '.join(tmp[::-1])
print(s2)

3.找出列表不重複元素並按原來的順序

lst = [1, 2, 1, 3, 1, 2, 5]
lst2 = []

lst3 = []
tmp = []
# count方法
for i in lst:
    if lst.count(i) > 1:
        # 刪除全部i元素
        pass
    else:
        lst2.append(i)

print(lst2)
# in方法
for x in lst:
    if x not in tmp:
        lst3.append(x)
        tmp.append(x)
    else:
        if x in lst3:
            lst3.remove(x)
        
print(lst3)

4.查找一個列表中的最大值

lst = [1, 2, 1, 3, 2, 5,4]
if len(lst) == 0:
    print('List is null.')
else:
    max = lst[0]
    for i in lst:
        if i > max:
            max = i
    print(max)

5.字符串轉化爲數字

# 傳統
s = '-123.12345'
x = 0  # result
sign = 0  # sign of .
loc = 0  # location 
neg = 0  # sign of negative
num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '-']
i = 0
n = 0
m = 0
for i in s:
    if i in num:
        if num.index(i) == 10:
            sign = 1
        elif num.index(i) == 11:
            neg = 1
        else:
            if sign:
                loc +=1
                x = x + num.index(i) * (0.1 ** loc)
            else:
                x = x * 10 + num.index(i)
if neg:
    x *= -1
print(x)
# python
s2 = '-1234.123'
result = 0
mloc = 0
integers, *decimals = s2.split('.')
*nega, integer = integers.partition('-')
if len(decimals) == 0:
    decimal = '0'
else:
    decimal = decimals[0]
for n in integer:
    result = result * 10 + num.index(n)
for m in decimal:
    mloc += 1
    result = result + num.index(m) * (0.1 **mloc)
if len(nega) == 2:
    result *= -1
print(result)

 PS:python

        partition ==> rpartitionapp

6.不適用組合數打印楊輝三角

lst = []

for n in range(1,11): # 從第1行開始,n就是第幾行
    if n == 1:
        lst.append([1])
    elif n == 2:
        lst.append([1, 1])
    else:
        sub_lst = [1]
        for k in range(1, n-1): # 從第0列開始,k從第1列到n-1
            sub_lst.append(lst[n-2][k-1] + lst[n-2][k])
        sub_lst.append(1)
        lst.append(sub_lst) # 增長第n行的列表
        
for s in lst:
    print(' '.join(str(x) for x in s))

7.四則運算的括號匹配

exp = '3 * {3 +[(2 -3) * (4+5)]}'
brackets = (
    ('(', ')'), 
    ('[', ']'), 
    ('{', '}')
)
stack = []
for c in exp:
    if c in (t[0] for t in brackets):
        stack.append(c)
    elif c in (t[1] for t in brackets):
        if len(stack) == 0:
            print('1.error,no enough left brackets {}'.format(c))
            break
        left = [t[0] for t in brackets if c == t[1]]
        if stack.pop() != left[0]:                
            print('2.error,no enough right brackets {}'.format(c))
            break
else:
    if len(stack) == 0:
        print('ok')
    else:
        print('3.error, unnecessary brackets {}'.format(stack))

8.不帶括號的四則運算轉化爲前綴表達式

exp = '2 * 3 + 1 - 4 / 2 * 7 - 1' # 6 +1 - 14 -1 => -8
symbols = {'+': 0, '-': 0, '*': 1, '/': 1}
exp = exp.split()
stack = []
for item in exp:
    if item not in symbols.keys():  # 數字直接入棧
        stack.append(item)
    else:
        while len(stack) > 1 and symbols[stack[-2]] >= symbols[item]:
            # 棧內有元素,且棧內上層符號優先級大於等於入棧符號
            r = stack.pop()
            s = stack.pop()
            l = stack.pop()
            t = {'root':s, 'left':l, 'right':r} #取出上三個,作樹
            stack.append(t) # 入棧
        stack.append(item) #第一個入棧符號,直接入棧|已經作樹,入棧
# 繼續作樹
while len(stack) > 2:
    r = stack.pop()
    s = stack.pop()
    l = stack.pop()
    t = {'root':s, 'left':l, 'right':r}
    stack.append(t)
    
ret = stack.pop()

import pprint
pprint.pprint(ret)

相關文章
相關標籤/搜索