第7章

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第7章相关的知识,希望对你有一定的参考价值。

7-1:

dict.update()

7-2:

大多数Python对象可以作为键,但它们必须是可哈希的(hashable)。对于只包括像数字和字符串这样的不可变参数的元组,可以作为字典中的键。对于像列表这样的可变类型不可以作为键。原因在于,解释器调用哈希函数,根据字典中键的值来计算存储数据的位置,如果键是可变对象,它的值可改变,如果键发生变化,哈希函数会映射到不同的地址来存储数据,如果这样的情况发生,哈希函数就不可能可靠地存储或获取相关的数据。

7-3:

(a)

adict = {m:1, n:2, a:7, b:8}
for eachKey in sorted(adict):
    print eachKey

(b)

adict = {m:1, n:2, a:7, b:8}
for eachKey in sorted(adict):
    print eachKey, adict[eachKey]

 (c)

adict = {n:2, b:8,m:1, a:7}
values = adict.values()
values.sort()
for item in values:
    for a in adict:
        if adict[a] == item:
            print a, adict[a]
            x = a
            break
    adict.pop(x)

7-4:

def list2dict(l1, l2):
    return dict(zip(l1, l2))

7-5:

(a)

#!/usr/bin/env python

import time

db = {}

def newuser():
    prompt = login desired: 
    while True:
        name = raw_input(prompt)
        if db.has_key(name):
            prompt = name taken, try another: 
            continue
        else:
            break
    pwd = raw_input(passwd: )
    db[name] = [pwd, time.asctime()]

def olduser():
    name = raw_input(login: )
    pwd = raw_input(passwd: )
    passwd = db.get(name)[0]
    if passwd == pwd:
        print welcome back, name
        oldtime = db[name][1][11:16]
        newtime = time.asctime()[11:16]
        if ((float(oldtime[0:2])*60+float(oldtime[3:5])) - (float(newtime[0:2])*60+float(newtime[3:5]))) / 60 <= 4:
            print "You already logged in at: <%s>" % db[name][1]
        db[name][1] = time.asctime()
    else:
        print login incorrect

def showmenu():
    prompt = """
(N)ew User Login
(E)xisting User Login
(Q)uit

Enter choice: """

    done = False
    while not done:

        chosen = False
        while not chosen:
            try:
                choice = raw_input(prompt).strip()[0].lower()
            except (EOFError, KeyboardInterrupt):
                choice = q
            print \nYou picked: [%s] % choice
            if choice not in neq:
                print invalid option, try again
            else:
                chosen = True

        if choice == q: done = True
        if choice == n: newuser()
        if choice == e: olduser()

if __name__ == __main__:
    showmenu()

(b)

 1 #!/usr/bin/env python
 2 
 3 import time
 4 
 5 db = {}
 6 
 7 def newuser():
 8     prompt = login desired: 
 9     while True:
10         name = raw_input(prompt)
11         if db.has_key(name):
12             prompt = name taken, try another: 
13             continue
14         else:
15             break
16     pwd = raw_input(passwd: )
17     db[name] = [pwd, time.asctime()]
18 
19 def olduser():
20     name = raw_input(login: )
21     pwd = raw_input(passwd: )
22     passwd = db.get(name)[0]
23     if passwd == pwd:
24         print welcome back, name
25         oldtime = db[name][1][11:16]
26         newtime = time.asctime()[11:16]
27         if ((float(oldtime[0:2])*60+float(oldtime[3:5])) - (float(newtime[0:2])*60+float(newtime[3:5]))) / 60 <= 4:
28             print "You already logged in at: <%s>" % db[name][1]
29         db[name][1] = time.asctime()
30     else:
31         print login incorrect
32 
33 def manage():
34     prompt = """
35 (D)elete a User
36 (V)iew all username and password
37 (Q)uit
38 
39 Enter choice: """
40     while True:
41         ans = raw_input(prompt).strip()[0].lower()
42         if ans not in dvq:
43             print invalid option, try again
44             continue
45         else:
46             if ans == d:
47                 print There are all users in this database
48                 for item in db.keys():
49                     print item
50                 u = raw_input(Enter user name you want to delete: )
51                 if u in db.keys():
52                     p = raw_input(To delete this account, you must know that its password ->)
53                     if db[u][0] == p:
54                         db.pop(u)
55                         print delete succeed!
56                     else:
57                         print invalid password, delete failed
58                 else:
59                     print %s is an invalid username % u
60 
61             elif ans == v:
62                 print There is all username and password
63                 for key, item in db.items():
64                     print key, item[0]
65 
66             else:
67                 break
68 
69 def showmenu():
70     prompt = """
71 (N)ew User Login
72 (E)xisting User Login
73 (M)anage
74 (Q)uit
75 
76 Enter choice: """
77 
78     done = False
79     while not done:
80 
81         chosen = False
82         while not chosen:
83             try:
84                 choice = raw_input(prompt).strip()[0].lower()
85             except (EOFError, KeyboardInterrupt):
86                 choice = q
87             print \nYou picked: [%s] % choice
88             if choice not in nemq:
89                 print invalid option, try again
90             else:
91                 chosen = True
92 
93         if choice == q: done = True
94         if choice == n: newuser()
95         if choice == e: olduser()
96         if choice == m: manage()
97 
98 if __name__ == __main__:
99     showmenu()

(c~g):稍后更新

7-6:

print Welcome to stock portfolio database system
print there are 4 column data you should input with each line
print [stock ticker symbol, number of shares, purchase price, current price]
print input each item separate with whitespace, end eachline with enter, end all with ctrl+c
all = []
try:
    while True:
        userin = raw_input(->).split( )
        one = []
        for item in userin:
            one.append(float(item))
        all.append(one)
except KeyboardInterrupt:
    pass
print
print please select one column to sort this table
prompt = """
(S)tock ticker symbol
(N)umber of shares
(P)urchase price
(C)urrent price

select one: 
"""
print prompt
while True:
    select = raw_input().strip().lower()
    adict = {}
    if select == s:
        temp = []
        for item in all:
            if item[0] in temp:
                print error, please select one column which element is unique.
                break
            temp.append(item[0])
        else:
            for item in all:
                adict[item[0]] = item
            for key in sorted(adict):
                print key, adict[key]
            break
        continue
    elif select == n:
        temp = []
        for item in all:
            if item[1] in temp:
                print error, please select one column which element is unique.
                break
            temp.append(item[1])
        else:
            for item in all:
                adict[item[1]] = item
            for key in sorted(adict):
                print key, adict[key]
            break
        continue
    elif select == p:
        temp = []
        for item in all:
            if item[2] in temp:
                print error, please select one column which element is unique.
                break
            temp.append(item[2])
        else:
            for item in all:
                adict[item[2]] = item
            for key in sorted(adict):
                print key, adict[key]
            break
        continue
    elif select == c:
        temp = []
        for item in all:
            if item[3] in temp:
                print error, please select one column which element is unique.
                break
            temp.append(item[3])
        else:
            for item in all:
                adict[item[3]] = item
            for key in sorted(adict):
                print key, adict[key]
            break
        continue

7-7:

adict = {a:1, b:2, c:hello, d:world}
bdict = {}
for key, value in adict.items():
    bdict[value] = key
print bdict

上述解决方法是有破坏性的,如果两个键所对应的值相等,那么得到的新字典中,以原来相等的值作为的键,只能对应最新的一个原来的键,之前的被覆盖掉了。所以,更好的解决方案是,将有相同值的键放入一个列表中作为对应新列表的键的值:

稍后更新

7-8:

try:
    print Input some employee name and number, separate with whitespace, end up with ctrl+c
    resource = {}
    while True:
        userin = raw_input(->).split( )
        resource[userin[0]] = userin[1]
except KeyboardInterrupt:
    pass
print
for eachKey in sorted(resource):
    print eachKey, resource[eachKey]

附加题:

try:
    print Input some employee name and number, separate with whitespace, end up with ctrl+c
    resource = {}
    while True:
        userin = raw_input(->).split( )
        resource[userin[0]] = userin[1]
except KeyboardInterrupt:
    pass
bdict = {}
for key, value in resource.items():
    bdict[int(value)] = key
print
for eachKey in sorted(bdict):
    print eachKey, bdict[eachKey]

7-9:

(a)

def tr(srcstr, dststr, string):
    if (len(srcstr) != len(dststr)) or (srcstr not in string):
        print error
        return
    for item in range(len(string)):
        if string[item] == srcstr[0] and (item <= len(string) - len(srcstr)):
            if string[item:item+len(srcstr)] == srcstr:
                string = string[:item] + dststr + string[item+len(srcstr):]
    return string

(b)

def tr(srcstr, dststr, string, cs = True): # cs means case sensitive
    if not cs:
        srcstr = srcstr.lower()
        dststr = dststr.lower()
        string = string.lower()
    if (len(srcstr) != len(dststr)) or (srcstr not in string):
        print error
        return
    for item in range(len(string)):
        if string[item] == srcstr[0] and (item <= len(string) - len(srcstr)):
            if string[item:item+len(srcstr)] == srcstr:
                string = string[:item] + dststr + string[item+len(srcstr):]
    return string

(c)

def tr(srcstr, dststr, string, cs = True): # cs means case sensitive
    if not cs:
        srcstr = srcstr.lower()
        dststr = dststr.lower()
        string = string.lower()
    if srcstr not in string:
        print error
        return
    for item in range(len(string)):
        if string[item] == srcstr[0] and (item <= len(string) - len(srcstr)):
            if string[item:item+len(srcstr)] == srcstr: 
                string = string[:item] + dststr + string[item+len(srcstr):] +   * (len(srcstr) - len(dststr))
    return string.strip()

7-10:

(a)

def rot13(c):
    if 65 <= ord(c) <= 90:
        if ord(c) <= 77:
            return chr(ord(c) + 13)
        elif ord(c) > 77:
            return chr(64 + ord(c) + 13 - 90)
    elif 97 <= ord(c) <= 122:
        if ord(c) <= 109:
            return chr(ord(c) + 13)
        elif ord(c) > 109:
            return chr(96 + ord(c) + 13 - 122)
    else:
        return c

(b)

#!/usr/bin/env python
def rot13(c):
    if 65 <= ord(c) <= 90:
        if ord(c) <= 77:
            return chr(ord(c) + 13)
        elif ord(c) > 77:
            return chr(64 + ord(c) + 13 - 90)
    elif 97 <= ord(c) <= 122:
        if ord(c) <= 109:
            return chr(ord(c) + 13)
        elif ord(c) > 109:
            return chr(96 + ord(c) + 13 - 122)
    else:
        return c

user = raw_input(Enter string to rot13: )
print You string to en/decrypt was: [%s]. % user
rots = ""
for item in user:
    rots += rot13(item)
print The rot 13 string is: [%s] % rots

7-11:

见“答案7-2”

7-12:

(a)由不同元素构成的总体称为集合,它们具有确定性,互异性和无序性。

(b)Python中的集合是一组无序排列的可哈希的值。

 7-13:

import random
N = random.randint(1, 10)
count = 0
A = set()
while count < N:
    A.add(random.randint(0, 9))
    count += 1
N = random.randint(1, 10)
count = 0
B = set()
while count < N:
    B.add(random.randint(0, 9))
    count += 1
print A =, A
print B =, B
print A|B =, (A|B)
print A&B =, (A&B)

7-14:

import random
N = random.randint(1, 10)
count = 0
A = set()
while count < N:
    A.add(str(random.randint(0, 9)))
    count += 1
N = random.randint(1, 10)
count = 0
B = set()
while count < N:
    B.add(str(random.randint(0, 9)))
    count += 1
print A =, A
print B =, B
print How do you think A|B and A&B (separate each item with whitespace)?
for item in range(3):
    aorb = set(raw_input(A|B: ).split( ))
    aandb = set(raw_input(A&B: ).split( ))
    if (aorb == A|B) and (aandb == A&B):
        print right!
        break
    else:
        print wrong, please alter your answer
        print aorb
        print aandb
else:
    print The answer is:
    print A|B: , (A|B)
    print A&B: , (A&B)

附加题:

import random
N = random.randint(1, 10)
count = 0
A = set()
while count < N:
    A.add(str(random.randint(0, 9)))
    count += 1
N = random.randint(1, 10)
count = 0
B = set()
while count < N:
    B.add(str(random.randint(0, 9)))
    count += 1
print A =, A
print B =, B

print How do you think A|B and A&B (separate each item with whitespace)?
for item in range(3):
    aorb = set(raw_input(A|B: ).split( ))
    aandb = set(raw_input(A&B: ).split( ))
    if (aorb == A|B) and (aandb == A&B):
        print right!
        break
    else:
        print wrong, please alter your answer
        print aorb
        print aandb
else:
    print The answer is:
    print A|B: , (A|B)
    print A&B: , (A&B)

ss = A - B
print There is, ss, please judge whether is a subset of set A: (y/n)?
for i in range(3):
    judge = raw_input(->).strip()[0].lower()
    if judge == y:
        print right!
        break
    else:
        wrong, please alter your answer
else:
    print This is a subset of set A

7-15:

print please input 2 sets, for each item separate with whitespace, for each set end with enter:
a = set(raw_input(set A: ).split( ))
b = set(raw_input(set B: ).split( ))
print select an operator: in, not in, &, |, ^, <, <=, >, >=, ==, !=
o = raw_input(->)
if o == in:
    print A in B =, (a in b)
elif o == not in:
    print A not in B =, (a not in b)
elif o == &:
    print A & B =, (a & b)
elif o == |:
    print A | B =, (a | b)
elif o == ^:
    print A ^ B =, (a ^ b)
elif o == <:
    print A < B :, (a < b)
elif o == <=:
    print A <= B :, (a <= b)
elif o == >:
    print A > B :, (a > b)
elif o == >=:
    print A >= B :, (a >= b)
elif o == ==:
    print A == B :, (a == b)
elif o == !=:
    print A != B :, (a != b)

 

以上是关于第7章的主要内容,如果未能解决你的问题,请参考以下文章

第7章 复用类

python AdaBoost的示例代码。参考:机器学习在行动第7章。

JavaScript编程艺术-第7章代码汇总

第 7 章 异常处理结构代码测试与调试

7. 第 7 章 类和对象简介

)