Python函数设置变量意外

时间:2019-05-24 13:00:16

标签: python python-3.x sorting python-3.6

我正在尝试编写排序函数程序,但是在我不应该更改randomdata变量的地方遇到了问题。

以下代码将无法运行,因为合并排序导致randomdata毫无明显原因地处于2d列表中...

感谢python为什么这样做的任何帮助!

from random import randint
from math import ceil

size = int(input("Sample size: "))
maximum = int(input("Range of numbers: "))

randomdata = [randint(0, maximum) for _ in range(size)]
print("DATA", randomdata)


def bubble(data):
    comparisons = 0
    length = len(data)
    for _ in range(length - 1):
        for i in range(length - 1):
            if data[i] > data[i+1]:
                hold = data[i]
                del data[i]
                data.insert(i+1, hold)
            comparisons += 1
    return comparisons, data

def mergefunction(data1, data2):
    if type(data1) != type([]):
        data1 = [data1]
    if type(data2) != type([]):
        data2 = [data2]
    comparisons = 0
    merged = list()
    while len(data1) > 0 and len(data2) > 0:
        #print("DATA 1", data1)
        #print("DATA 2", data2)
        if data1[0] < data2[0]:
            merged.append(data1[0])
            del data1[0]
        else:
            merged.append(data2[0])
            del data2[0]
        comparisons += 1
    merged += data1
    merged += data2
    #print("COMPS", comparisons)
    #print("SORT", merged)
    return comparisons, merged

def merge(data):
    comparisons = 0
    while len(data) > 1:
        #print("DATA", data)
        for i in range(0, ceil(len(data)/2), 1):
            #print("I", i)
            try:
                compadd, merged = mergefunction(data[i], data[i+1])
                del data[i], data[i]
                data.insert(i, merged)
                comparisons += compadd
            except IndexError:
                pass
    return comparisons, data[0]

def insrt(data):
    sorteddata = [-10000000]
    comparisons = 0
    for item in data:
        print("ITEM", item)
        for i in range(len(sorteddata)):
            #print(item, sorteddata[i])
            if item > sorteddata[i]:
                sorteddata.insert(i+1, item)
                comparisons += 1
                break
            comparisons += 1
    del sorteddata[0]
    print(sorteddata)
    return comparisons, sorteddata

print("="*10,"BUBBLE","="*10)
print("RANDOM", randomdata)
comps, data = bubble(randomdata)
print("COMPARISONS", comps)
print("SORTED DATA", data)

print("="*10,"MERGE","="*10)
print("RANDOM", randomdata)
comps, data = merge(randomdata)
print("COMPARISONS", comps)
print("SORTED DATA", data)

print("="*10,"INSERT","="*10)
print("RANDOM", randomdata)
comps, data = insrt(randomdata)
print("COMPARISONS", comps)
print("SORTED DATA", data)

Python 3.6.1 抱歉,此代码中充斥着调试器...

1 个答案:

答案 0 :(得分:2)

当您执行comps, data = bubble(randomdata)时,您会将randomdata的引用传递给bubble(),因为randomdatalist,这意味着是可变的,然后您在data中对bubble()所做的所有更改都反映在randomdata中。您需要使用randomdata的副本。类似于:data = data[:]内的bublle()