AI Learning Notes: Several Python Exercise Questions

Keywords: Python Database Programming less

Last article I mentioned the importance of learning programming exercises. Today, I will consolidate some important skills in Python through several exercises.

  1. Filter out values greater than 2 in the dictionary.
#Filter out values of equal or greater than 2
#Note that for Python 2 you will have to use iteritems
d = {"a": 1, "b": 2, "c": 3}
  1. Read the number of words in the input sentence.

  2. The corresponding numbers in a and B want to add and output the results.

#Print out in each line the sum of homologous items from the two sequences

a = [1, 2, 3]
b = (4, 5, 6)
  1. Find the error in the following code.
#Please fix the script so that it returns the user submited first name for the first %s
#and the second name for the second %s

firstname = input("Enter first name: ")
secondname = input("Enter second name: ")
print("Your first name is %s and your second name is %s" % firstname, secondname)
  1. Print out the "LastName" of the third "employee" and add an "employee" of "Albert Bert"
d = {"employees":[{"firstName": "John", "lastName": "Doe"},
                {"firstName": "Anna", "lastName": "Smith"},
                {"firstName": "Peter", "lastName": "Jones"}],
"owners":[{"firstName": "Jack", "lastName": "Petter"},
          {"firstName": "Jessy", "lastName": "Petter"}]}
  1. The output formats of index and item in print a are as follows
    Item 1 has index 0
    Item 2 has index 1
    Item 3 has index 2
a = [1, 2, 3]
  1. Select 6 characters from alphanumeric and symbolic characters and generate 6-bit passwords randomly.
  2. The user is required to enter a username and password. The username cannot be duplicated in the database (database["Mercury", "Venus","Earth","Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"). The password must be greater than five digits and contain both numbers and capital letters.

The above topics are excerpted from Courses on udemy

The answer is as follows:
1. Filter out values greater than 2 in the dictionary

d = {"a": 1, "b": 2, "c": 3}
d = dict((key,value) for key, value in d.items() if value<3)

There are several important points in this topic: (1) the data need to traverse dictionary format, d.items().
(2) Such reconstructed statements are very common in Python. Similarly, we can output a list of less than 3: a = list (key for key, value in D. items () if value < 3)

  1. Read the number of words in the input sentence.
s = input('Please enter: ')
s_list = s.split(' ')
len(s_list)

Several key points of this topic: (1) Several very common methods of dealing with String, such as. split (),. Strip (), and so on. (2) Len () size () type () and other common Python methods.

  1. The corresponding digits in a and B want to add and output the results
a = [1, 2, 3]
b = (4, 5, 6)
print(list(i+j for i,j in zip(a,b)))

The use of zip is very important.

  1. The correct answer is as follows
firstname = input("Enter first name: ")
secondname = input("Enter second name: ")
print("Your first name is %s and your second name is %s" % (firstname, secondname))

You need to use tuples (parentheses) when you have multiple formats of output in Python

  1. Print out the "LastName" of the third "employee" and add an "employee" of "Albert Bert"
d = {"employees":[{"firstName": "John", "lastName": "Doe"},
                {"firstName": "Anna", "lastName": "Smith"},
                {"firstName": "Peter", "lastName": "Jones"}],
"owners":[{"firstName": "Jack", "lastName": "Petter"},
          {"firstName": "Jessy", "lastName": "Petter"}]}

print(d["employees"][2]["firstName"])
d["employees"].append({"firstName": "Albert", "lastName": "Bert"})

The key to this problem is to find out the structure of d, which is a dictionary nested list re-nested dictionary structure.

  1. The output formats of index and item in print a are as follows
    Item 1 has index 0
    Item 2 has index 1
    Item 3 has index 2
a = [1, 2, 3]
for index, item in enumerate(a):
  print("Item s% has index s%\n"%(item, index))

Enumeration of enumerate applications, very important and more examples see (here)[ http://book.pythontips.com/en/latest/enumerate.html]

  1. Select 6 characters from alphanumeric and symbolic characters and randomly generate 6-bit passwords
import ramdon

characters = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
chosen = ramdon.sample("characters",6)
password = "".join(chosen)

This topic has two knowledge points, (1). ramdon, an important library of Python, has been used in random.sample(). (2) string. joint () method.

  1. The user is required to enter a username and password. The username cannot be duplicated in the database (database["Mercury", "Venus","Earth","Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"). The password must be greater than five digits and contain both numbers and capital letters.
database = ["Mercury", "Venus","Earth","Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"]
while True:
    user_name = input("Please enter your user name: ")
    if user_name in database:
        print("The user name is exits, please try again!")
    else:
        break

while True:
    error_msg = []
    psw = input("Please enter your password: ")
    if len(psw)<6:
        error_msg.append( "Password must over 5 characters.")
    if not any(i.isdigit() for i in psw):
        error_msg.append("Password must contain at lease one number")
    if not any(i.isupper() for i in psw):
        error_msg.append("Password must contain at least one uppercase letter")
    if len(error_msg) > 0:
        for i in error_msg:
              print(i)
    else:
     break

There are several knowledge points in this question: (1) the use of while loop statements. (2) Use of if.... In.... (3) The use of I. isDigit () and i.isupper() methods. (4) The use of any ().

Related articles
Reinforcement Learning (RL)
AI Learning Notes: How to Understand Machine Learning
Artificial Intelligence Learning Notes: Basic Concepts and Vocabulary of Artificial Intelligence
Notes on Artificial Intelligence Learning II: Definition Problems

First issue of this article is steemit.com. In order to facilitate reading in the wall, you are welcome to leave a message or visit. My Steemit Homepage

Posted by rikmoncur on Mon, 06 May 2019 11:20:37 -0700