作业帮 > 英语 > 作业

python新手 dict习题求解

来源:学生作业帮 编辑:搜狗做题网作业帮 分类:英语作业 时间:2024/07/31 14:20:14
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习题求解
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
再问: 真的很谢谢你能帮我解答。但是你看下要求重复的元素一个也不要输出出来。只输出独一无二的。 你写的其实是我这的第一题。。这个我会。谢谢你能帮我再看一下吗?
再问: 很谢谢你帮我。你在看下要求按顺序输出独一无二的数。重复的数不要输出。你写的是我的第一题我会。能再改改吗?谢谢。
再答: 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:
        d[x] = d.get(x, 0)+1
        if d[x]==1:
            l.append(x)
    return [n for n in l if d[n]==1]
 
def tester():
    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]
    b = list(only_once_dict(a))
    if b == [-14, -11, 1, 3, -1, 0, -4, 6, 5, 13, -2, -3, -10, 4]:
        print "OK"
    else:
        print "Function Fail."

tester()

t0 = time.time()
a = mklist(1000000)
t1 = time.time()
print len(list(only_once_dict(a)))
t2 = time.time()
print "generate usage", t1 - t0
print "only_once_dict", t2 - t1

#~ >python -u "only_once.py"
#~ OK
#~ 367667
#~ generate usage 2.71760296822
#~ only_once_dict 1.1097869873
#~ >Exit code: 0    Time: 3.992时间要求上稍逊