python新手 dict习题求解By using a dict,write a method only_once(a) that takes a list,a,as an argument and returns a list containing the elements of a that occur exactly once.For full marks,elements should appear in the same order as their first

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/12 12:59:10
python新手 dict习题求解By using a dict,write a method only_once(a) that takes a list,a,as an argument and returns a list containing the elements of a that occur exactly once.For full marks,elements should appear in the same order as their first

python新手 dict习题求解By using a dict,write a method only_once(a) that takes a list,a,as an argument and returns a list containing the elements of a that occur exactly once.For full marks,elements should appear in the same order as their first
python新手 dict习题求解
By using a dict,write a method only_once(a) that takes a list,a,as an argument and returns a list containing the elements of a that occur exactly once.For full marks,elements should appear in the same order as their first occurrence in a.
# set up a dict mapping words onto how many times they occur
freq = dict()
for w in varney:
freq[w] = 0
for w in varney:
freq[w] = freq[w] + 1
test:a
[9,-14,-11,11,14,1,11,10,3,9,10,11,-8,14,-9,-1,0,-8,-4,-6,6,-9,5,13,14,-2,-3,-10,-6,4]
>>> only_once(a)
[-14,-11,1,3,-1,0,-4,6,5,13,-2,-3,-10,4]
ps:当输入的a在百万级在1秒内算出长度就可以了.len(once_only(a))
368013

python新手 dict习题求解By using a dict,write a method only_once(a) that takes a list,a,as an argument and returns a list containing the elements of a that occur exactly once.For full marks,elements should appear in the same order as their first
import random
import time

def mklist(size):
    return map(lambda x: random.randint(0,size), xrange(size))

def only_once_dict(a):
    d, l = dict(), []
    for x in a:
        if x not in d:
            d[x] = x
            l.append(x)
    return l

def only_once_set(a):
    s, l = set(), []
    for x in a:
        if x not in s:
            s.add(x)
            l.append(x)
    return l

t0 = time.time()
a = mklist(1000000)
t1 = time.time()
len(list(only_once_dict(a)))
t2 = time.time()
len(list(only_once_set(a)))
t3 = time.time()
print "generate usage", t1 - t0
print "only_once_dict", t2 - t1
print "only_once_set", t3 - t2
>python -u "baidu.py"
generate usage 2.64109396935
only_once_dict 0.612596035004
only_once_set 0.607508182526
>Exit code:0    Time:3.981