Python core Programming Chapter seventh Dictionary, collection exercises

Source: Internet
Author: User
Tags decrypt

#encoding =utf-8
Import Random
#dict. Update (DICT2) a adds the key-value pairs of the dictionary dict2 to the dictionary dict
# 7–1. Dictionary method. Which dictionary method can be used to merge two dictionaries together?
Dict1 = {1: ' W ', 2: ' Y '}
Dict2 = {3: ' t '}
Dict1.update (DICT2)
Print Dict1

# 7–2. The key for the dictionary. We know that the value of the dictionary can be any Python object, what about the key of the dictionary? Please try
# with different types of objects other than numbers and strings as keys to the dictionary, take a look at what types can and cannot be.
# What do you think is the reason for the type of object that cannot be used as a dictionary key?
#字符串, numbers are immutable types and can be
#列表不可以, the elements inside the tuple are strings or numbers, and no other tuples can

# 7–3. Methods for dictionaries and lists.
# (a) Create a dictionary and display the keys in this dictionary in alphabetical order.
Dict3 = {' Please ': ' W ', ' love ': ' Z ', ' Me ': ' Y '}
s= Dict3.keys () #.sort () #获取键的列表
Print S
Print S.sort () #对列表进行排序
Print S
# (b) now displays the keys and values in the dictionary based on the key that has been sorted alphabetically.
For I in S:
Print I,dict3[i]
# (c) Same as (b), but this time it shows the keys and values in the dictionary based on the values of the dictionaries that have been sorted alphabetically. (Note
# meaning: This is generally meaningless for dictionaries and hash tables, since most access and sorting (if needed) are
# based on the dictionary key, just use it as an exercise. )

# 7-4. Build a dictionary. Given a list of two identical lengths, for example, list [1, 2, 3,...] and [' abc ', ' Def ',
# ' Ghi ',...], make a dictionary of all the data in these two lists, like this: {1: ' abc ', 2: ' Def ', 3: ' Ghi ',...}
List1 = [A]
List2 = [' W ', ' z ', ' y ']
Dict4 = {}
For I in range (3):
Dict4[list1[i]] = List2[i]
Print Dict4

# 7-7. Reverses the keys and values in the dictionary. Use a dictionary input, output another dictionary, use the former key to do the value, the former
# value to do the key.
Dict5 = {}
For key in Dict3:
Dict5[dict3[key]]=key
Print Dict3
Print Dict5

# 7-8. Human resources. Create a simple employee name and numbering program. Let the user enter a group of employee names and numbers.
# Your program can provide the ability to sort output by name, the employee name is displayed in front, followed by the corresponding employee number. Additional
# title: Add a feature to output data in the order of employee numbers.
DICT6 ={}
While True:
s = raw_input ("Input name & ID, ' z ' Stop")
if s = = ' Z ':
Break
List = S.split (' & ')
Dict6[list[0]] = list[1]
Print DICT6

print ' Sort by name '
Key = Dict6.keys ()
Key.sort ()
For key in key:
Print Key,dict6[key]

print ' Sort by id '
Dict7 = {}
for key in DICT6:
Dict7[dict6[key]]=key
Key = Dict7.keys ()
Key.sort ()
for key in key:
Print Key,dict7[key]


# 7-9. Translation
# (a) write a character translation program (functionally similar to the TR command in Unix). We call this function tr (), which has
# Three strings to do arguments: source string, Destination string, basic string, syntax is defined as follows:
# def TR (srcstr, DSTSTR, String)
# SRCSTR content is the character set that you intend to "translate", Dsrstr is the character set that is translated, and string is
# The string you intend to perform the translation operation. For example, if srcstr = = ' abc ', DSTSTR = = ' MnO ', string = =
# ' ABCdef ', then the output of TR () will be ' mnodef '. Note here len (srcstr) = = Len (dststr).
# In this exercise you can use the built-in function Chr () and Ord (), but they are not necessarily the solution to the problem
# there are fewer functions.
def tr (srcstr,dststr,string):
Dict4 = {}
For I in range (len (SRCSTR)):
Dict4[srcstr[i]] = Dststr[i]
Print Dict4
If ' a ' in Dict4:
Print dict4[' a ']
str = "
For I in Range (len (string)):
If String[i] in Dict4:
str + = Dict4[string[i]]
Else
str + = String[i]
Print str
# string = String.Replace (SRCSTR,DSTSTR)
# Print String
TR (' abc ', ' MnO ', ' abcdef ')
# (b) Add a marker parameter to this function to handle the case-insensitive translation problem.


# (c) Modify your program so that it can handle the operation of deleting characters. The string srcstr cannot be mapped to a string dststr
# The extra characters in the characters will be filtered out. In other words, these characters do not map to any of the characters in the DSTSTR string, because
# This is filtered out of the word character returned from the function. For example: if srcstr = = ' ABCdef ', dststr = = ' MnO ',
# string = = ' Abcdefghi ', then TR () will output ' Mnoghi '. Note here len (srcstr) >= len (DSTSTR).
def TRC (srcstr,dststr,string):
Dict4 = {}
For I in range (len (SRCSTR)):
If I < Len (DSTSTR):
Dict4[srcstr[i]] = Dststr[i]
Else
Dict4[srcstr[i]] = "
Print Dict4
If ' a ' in Dict4:
Print dict4[' a ']
str = "
For I in Range (len (string)):
If String[i] in Dict4:
str + = Dict4[string[i]]
Else
str + = String[i]
Print str
TRC (' abc ', ' d ', ' abcdef ')
# 7–10. Encryption.
# (a) write a "rot13" translator with the idea of a previous exercise. "Rot13" is an ancient and simple method of encryption,
# It replaces each letter in the alphabet with the 13th letter that follows it. The first half of the alphabet is mapped to the second part,
# The second half of the letter is mapped to the first half, and the case remains the same. For example, ' a ' will be replaced with ' n ' and ' X ' will be substituted for
# change to ' K '; Numbers and symbols are not translated.
Def dict13 ():
Dict = {}
For I in Range (65,78):
DICT[CHR (i)]=CHR (i+13)
DICT[CHR (i+13)] = Chr (i)
j = i + 32
DICT[CHR (j)]=chr (j+13)
DICT[CHR (j+13)] = Chr (j)
Return Dict

Def rot13 ():
string = Raw_input (' Please input/n ')
Dict1 = dict13 ()
str = "
For I in Range (len (string)):
If String[i] in Dict1:
str + = Dict1[string[i]]
Else
str + = String[i]
Print str

ROT13 ()

# (b) Add an application based on your solution that prompts the user to enter a string to be encrypted (this algorithm
# You can also decrypt the encrypted string as follows:
Def dict31 ():
Dict = {}
Dict1 = dict13 ()
For key in Dict1:
Dict[dict1[key]] = key
Return Dict
Def rot31 ():
string = Raw_input (' Please input/n ')
Dict1 = Dict31 ()
str = "
For I in Range (len (string)):
If String[i] in Dict1:
str + = Dict1[string[i]]
Else
str + = String[i]
Print str
Rot31 ()
#% rot13.py
# Enter string to Rot13:this are a short sentence. Your string to En/decrypt is: [This
# is a short sentence.].
# The ROT13 string is: [GUVF VF N Fubeg fragrapr.].
# %
#% rot13.py
# Enter string to ROT13:GUVF VF n Fubeg fragrapr. Your string to En/decrypt was: [GUVF
# VF N Fubeg fragrapr.].
# The ROT13 string is: [This was a short sentence.].
# w = ' What '
# W.lower

# 7–11. Defined. What makes up a valid key in a dictionary? Examples of valid keys and illegal keys in a dictionary.
#键必须是可哈希的 (immutable)
#不允许一个键对应多个值

# 7-12. Defined.
# (a) Mathematically, what is a set?
#由一个或多个元素组成, certainty, mutex, disorder
# (b) What is the definition of a collection type in Python?
#集合对象是一组无序排列的可哈希的值, the members of the collection can do the keys in the dictionary
s = set (' Cheeseshop ') #可变集合
S.add (' z ')
S.update (' Wyt ')
Print S
' K ' in S
t = frozenset (' wyt ') #不可变集合
s = = T
s | T #合集
s&t# intersection
s-t# difference Set
s^t# symmetric differential, belonging to S, belonging to T, not belonging to S and T of the collection
# 7–13. Random number. To modify the code for Exercise 5-17: Use Randint () or Randrange () in the random module
# method generates a random number set: Randomly selected from 0 to 9 (including 9), generating 1 to 10 random numbers. These numbers make up a collection
# A (a can be a mutable collection, or it may not). Similarly, set B is generated by this method. Each time A new collection of A and B is generated, the display
# Results A | B and A & B
Def randomset ():
s = Set (")
N = Random.randint (1,10)
For I in Range (N):
S.add (Random.randint (0,9))
return s
A = Randomset ()
B = Randomset ()
Print A | B
Print A & B
# 7–14. User authentication. Modify the previous exercise to require the user to enter A | B and A & B results and tells the user that he (or
# Her) The answer is correct, not to be a | The results of B and A & B are shown directly. If the user answers the error, allow him (or
# She) modify the solution, and then re-verify the answer that the user entered. If the user submits the answer incorrectly three times, the program displays
# correct results.
# Additional questions: Use your knowledge about the collection to create a potential subset of a collection and ask the user if this potential subset is really
# A subset of the collection that requires the same functionality as the main program to display corrections and answers.
s = set (' 1,2,3,4,5,6 ')
t = set (' 2,3,5,6,1,4 ')
Print type (' 1,2,3,4,5,6 ')
Print S,t
print S = = T

#encoding =utf-8
Import Random

#产生随机集合
Def randomset ():
s = Set (")
N = Random.randint (1,10)
For I in Range (N):
S.add (Random.randint (0,9))
return s
A = Randomset ()
B = Randomset ()
Print A, b
#print a| B,a&b
# A = set ()
# B = set ()
# A.add (1)
# A.add (2)
# B.add (2)
# Print a| B,a&b

#对输入进行处理, go [], Save as Collection
#要考虑输入为空集的处理
#输入格式为 [], turn into ', then set (')
def input_to_set (S1):
Set1 = set ()
If S1! = ' [] ':
U1,U2 = S1.split (' [')
U1,U3 = U2.split ('] ')
List1 = U1.split (', ')

For I in List1:
j = Int (i) #列表中单独字符串转换为数字
Set1.add (j)
#print Set1
Return Set1


i = 0
While I < 3:

str1 = Raw_input (' A | B is: ')
str2 = Raw_input (' A & B is: ')
S1 = Input_to_set (str1)
S2 = Input_to_set (str2)

# print S1 = = a| B
# print S2 = = A&b
if (S1 = = a| B and S2 = = a&b):
print ' correct '
Break
Else
print ' ERROR '
i + = 1
#print I three-time error, output correct answer
if i = = 3:
Print a| B,a&b

Python core Programming Chapter seventh Dictionary, collection exercises

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.