python实现贪心算法经典案例

均分纸牌问题

python实现贪心算法经典案例_第1张图片
python代码:

# 贪心算法实现均分纸牌问题
import numpy as np

def avg_Card(cards_list):
    avg = np.mean(cards_list)
    for i in range(len(cards_list)-1):
        cards_list[i+1] = cards_list[i+1] + cards_list[i] - avg
        cards_list[i] = avg
    print(cards_list)

cards = [9, 8, 17, 6]
avg_Card(cards)

最大整数问题

# 贪心算法实现最大整数问题

def int2str(data_list):
    # 数字转字符串
    data = []
    for i in data_list:
        data.append(str(i))
    return data

def greedy(data):
# 贪心算法
    for i in range(len(data)):   # 类似冒泡排序,每次循环确定一个最适合放在前面的数
        for j in range(i+1, len(data)):
            if data[i]+data[j] < data[j]+data[i]:
                temp = data[i]
                data[i] = data[j]
                data[j] = temp
    return data

data = [7,121,12,123]
data = int2str(data)
l = greedy(data)
result = ''
for i in l:
    result += i
print(result)

参考:贪心算法及几个经典例子

你可能感兴趣的:(数据结构与算法,贪心算法,数据结构)