简体   繁体   English

在Python中计算排序和列表理解

[英]Counting sort and list comprehension in Python

I have problem with understand how to resolve error in my code. 我在了解如何解决代码中的错误时遇到问题。 Here it comes: 它来了:

def counting_sort(some_list, max=100000):
    licznik = [0] * (max+1) 
    for x in some_list:
        licznik[x] = licznik[x]+1
    i=0
    for x in range(max+1):
        for y in range(licznik[x]):
            some_list[i]=x 
            i=i+1 
    return some_list.reverse()

def gen(number, b=100000):
    some_list = []
    return [some_list.append(random.randint(0, b)) for x in xrange(number)]

domain = [10000, 25000, 50000, 100000, 200000, 300000, 400000, 500000, 750000, 1000000]
for element in domain:
    print 'Results for: ' + str(element) + ' elements:'
    for j in range(0, 10):
        temp_list = gen(element)
        start = time.time()
        counting_sort(temp_list)
        end = time.time() - start
        print end

This is problem with line: 这是行的问题:

for x in some_list:
            licznik[x] = licznik[x]+1

I guess that it should be resolved by list comprehension, but I have no idea how to transform it this way. 我想应该通过列表理解来解决它,但是我不知道如何以这种方式进行转换。 Any helping advice? 有帮助的建议吗? Thanks for advance. 感谢前进。

You are filling some_list with None values in your function gen . 您正在使用gen函数中的None值填充some_list Change the line 换线

return [some_list.append(random.randint(0, b)) for x in xrange(number)]

to: 至:

return [(random.randint(0, b)) for x in xrange(number)]

Your gen function is wrong... list.append returns None and modifies somelist in place, change to: 您的gen函数是错误的... list.append返回None并在适当位置修改somelist ,更改为:

def gen(number, b=100000):
    return [random.randint(0, b) for x in xrange(number)]

To demonstrate: 展示:

some_list = []
print [some_list.append(10) for _ in xrange(5)]
# [None, None, None, None, None]
print some_list
# [10, 10, 10, 10, 10]

And you're returning the list of None s. 您将返回None的列表。

You are trying to use a None value as a key to the list licznik on line 5. 您试图将None值用作第5行上的licznik列表的键。

If you modify your Gen function to this, it should work. 如果您将Gen函数修改为此,它将起作用。

def gen(number, b=100000):
    return [(random.randint(0, b)) for x in xrange(number)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM