python Learning Basics Day06 (P61~~74)

b station Dane python class study notes

P61 Python Basics-6.1 Course Content Review

1. Review day05

"""
    day05 review
    container
        common operation
        string:Immutable  store coded value  sequence
        the list:variable  storage variable     sequence
            basic operation
                1.create:[data]   list(container)
                2.Locating: Index  slice
                    # Get a slice of elements from a list to form a new list
                    variable = list name[slice]
                    # modify an element
                    list name[slice] = variable
                3.delete:
                    del list name[index/slice]
                    list name.remove(element)
                    remove multiple elements from a list,It is recommended to delete in reverse order.
                4.Increase:
                    list name.append(element)
                    list name.insert(index,element)
                5. iterate over all elements
                    the following code
"""
# iterate over all elements
list01 = [3, 4, 4, 5, 6]
# print list
# print(list01)
# Forward
for item in list01:
    print(item)

# reverse (index)
# 3  2  1  0
for i in range(len(list01) - 1, -1, -1):
    print(list01[i])

# -1 -2 -3 -4
for i in range(-1, -len(list01) - 1, -1):
    print(list01[i])

P62 Python Basics-6.2 Calculation of the minimum value of homework analysis

1. Calculate the minimum value

"""
    Calculate the minimum value in a list(Do not use min)
"""
list01 = [43, 54, 5]
min_value = list01[0]
for i in range(1, len(list01)):
    if min_value > list01[i]:
        min_value = list01[i]
print(min_value)

memory map

P63 Basics of Python-6.3 Analysis of homework lottery problems

1. Lottery Problem 1

4. lottery Double color ball:
red ball:6 one, 1 -- 33 Integers between cannot be repeated
 blue ball:1 one, 1 -- 16 integer between
(1) Randomly generate a lottery ticket[6 1 red ball 1 blue ball].
import random

list_ticket = []

# 6 non-repeating red balls
while len(list_ticket) < 6:
    random_number = random.randrange(1, 33)
    # If the nonce is not present, it is stored.
    if random_number not in list_ticket:
        list_ticket.append(random_number)
# 1 blue ball
list_ticket.append(random.randrange(1, 16))

print(list_ticket)

2. Lottery Problem 2

"""
(2) Buy a lottery ticket in the console
 hint:
    "Please enter the first red ball number:"
    "Please enter the second red ball number:"
    "number is not in range"
    "number has been repeated"
    "Please enter the basketball number:"
"""
# 6 non-repeating red ball numbers within the range of 1--33
list_ticket = []
while len(list_ticket) < 6:
    number = int(input("Please enter the No.%d red ball numbers:" % (len(list_ticket) + 1)))
    if number < 1 or number > 33:
        print("number is not in range")
    elif number in list_ticket:
        print("number has been repeated")
    else:
        list_ticket.append(number)

# 1 basketball number within the range of 1--16
while len(list_ticket) < 7:
    number = int(input("Please enter the basketball number:"))
    if 1 <= number <= 16:
        list_ticket.append(number)
    else:
        print("number is not in range")

print(list_ticket)

P64 Python Basics-6.4 List Comprehensions and Exercises

definition:

Convert an iterable to a list using the easy method.

grammar:

variable = [expression for variable in iterable]
variable = [expression for variable in iterable if condition]

illustrate:

If the boolean value of the if truth expression is False, the data produced by the iterable will be discarded.

Sample code:

# Add all the elements in list01 to list02 after adding 1.
list01 = [5, 56, 6, 7, 7, 8, 19]
# list02 = []
# for item in list01:
#     list02.append(item + 1)
list02 = [item + 1 for item in list01]
print(list02)
# Add 1 to the elements greater than 10 in list01 and store them in list02.
# list02 = []
# for item in list01:
#     if item >10:
#         list02.append(item + 1)
list02 = [item + 1 for item in list01 if item > 10]

practise:

'''
# Exercise: Use range to generate numbers between 1--10, and store the square of the number in list01
# Store all odd numbers in list01 into list02
# Store all even numbers in list01 into list03
# Increment all even numbers greater than 5 in list01 and store them in list04
'''
# list01 = []
# for item in range(1, 11):
#     list01.append(item ** 2)

list01 = [item ** 2 for item in range(1, 11)]

# list02 = []
# for item in list01:
#     if item % 2 == 1:
#         list02.append(item)
list02 = [item for item in list01 if item % 2 == 1]

list03 = [item for item in list01 if item % 2 == 0]

# list04 = []
# for item in list01:
#     if item % 2 == 0 and item > 5:
#         list04.append(item + 1)
list04 = [item + 1 for item in list01 if item % 2 == 0 and item > 5]
print(list04)

P65 Python Basics-6.5 Introduction to Tuples

1. Definition

  1. An immutable sequence container consisting of a sequence of variables.
  2. Immutable means that once created, elements cannot be added/deleted/modified.

2. Memory diagram of list expansion principle

P66 Python Basics-6.6 Basic operations of tuples

Create an empty tuple:

tuple name = ()
tupleName = tuple()

Create non-empty tuples:

tuple name = (20,)
tuple name = (1, 2, 3)
tuple name = 100,200,300
tupleName = tuple( iterable object)

Get element:

index, slice

Iterate over tuples:

Forward:
for variable name in list name:
	The variable name is the element
	Reverse:
for index name in range(len(list name)-1,-1,-1):
	Yuanzu name[index name]is the element

sample code

# 1. Create a tuple
# null
tuple01 = ()

# has a default value of
tuple01 = (1, 2, 3)

# list --> tuple
tuple01 = tuple(["a", "b"])
print(tuple01)
# tuple --> list
list01 = list(tuple01)
print(list01)

# If the tuple has only one element
# tuple02 = (100)
# print(type(tuple02))# int

tuple02 = (100,)
print(type(tuple02))  # int

# cannot change
# tuple02[0] = 10

# 2. Get elements (index slice)
tuple03 = ("a", "b", "c", "d")
e01 = tuple03[1]
print(type(e01))  # str

e02 = tuple03[-2:]
print(type(e02))  # tuple

# You can directly assign tuples to multiple variables
tuper04 = (100, 200)
a, b = tuper04
print(a)
print(b)

# 3. Traversing elements
# Forward
for item in tuper04:
    print(item)

# reverse
# 1  0
for i in range(len(tuper04) - 1, -1, -1):
    print(tuper04[i])

P67 Python Basics-6.7 Using Tuples to Optimize Code

1. The role of tuples

  1. Both tuples and lists can store a series of variables. Since the list reserves memory space, elements can be added.
  2. Tuples will allocate memory on demand, so if the number of variables is fixed, it is recommended to use tuples because they take up less space.
  3. application:
    The essence of variable exchange is to create tuples: x, y = y, x
    The essence of the format string is to create tuples: "Name: %s, Age: %d" % ("tarena", 15)

2. Tuple optimization code exercise 1

"""
    practise:Complete the following functions with the help of tuples.
"""
# month = int(input("Please enter the month:"))
#
# if month < 1 or month > 12:
#     print("Input error")
# elif month == 2:
#     print("28 days")
# elif month == 4 or month == 6 or month == 9\
#         or month == 11:
#     print("30 days")
# else:
#     print("31 days")

# Method 1:
# month = int(input("Please enter the month:"))
#
# if month < 1 or month > 12:
#     print("Input error")
# elif month == 2:
#     print("28 days")
# elif month in (4,6,9,11):
#     print("30 days")
# else:
#     print("31 days")

# Method 2:
month = int(input("Please enter the month:"))
if month < 1 or month > 12:
    print("typo")
else:
    # Store the days of the month into a tuple
    day_of_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
    print(day_of_month[month - 1])

P68 Python Basics-6.8 Practice of converting dates to days

"""
    practise:Enter the date in the console(Month Day),Calculate the day of the year.
    Example: March 5th
         1 number of days in month + 2 number of days in month + 5

         5 August 8
         1 number of days in month + 2 number of days in month +3 number of days in month + 4 number of days in month+ 8
"""
day_of_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
month = int(input("Please enter the month"))
day = int(input("Please enter day:"))
# method one:
# # Accumulate the number of days in the previous months
total_day = 0
for i in range(month - 1):
    total_day += day_of_month[i]
# Accumulate the number of days in the month
total_day += day
print("is this year's first%d sky." % total_day)

# Method Two:
# Accumulate the number of days in the previous months
total_day = sum(day_of_month[:month - 1])
total_day += day
print("is this year's first%d sky." % total_day)

P69 Python Basics-6.9 Introduction to Dictionaries

1. Definition

  1. A mutable map container consisting of a sequence of key-value pairs.
  2. Mapping: one-to-one correspondence, and each record is unordered.
  3. Keys must be unique and immutable (string/number/tuple), values ​​have no restrictions.

Dictionary memory map

Dictionaries are the fastest lookups of all containers. Its internal storage is planned according to the hash algorithm. The general understanding is that the stored data is divided into several areas, and the desired location can be quickly located according to the hash algorithm.
But the disadvantage is that it consumes memory space. That is, exchanging space for time.

P70 Python Basics-6.10 Basic operations of dictionaries

1. Create a dictionary:

DictionaryName = {key1: value1, key2: value2}
dictionary_name = dict(iterable object)

2. Add/modify elements:

grammar:
dictionaryName[key] = data
illustrate:
Key does not exist, create record.
If the key exists, modify the mapping relationship.

3. Get elements:

variable = dictionary name[key] # error if no key

Fourth, traverse the dictionary:

for key name in dictionary name:
	dictionary name[key name]

for key name, value name in dictionary name.items():
statement

5. Delete elements:

del dictionary name[key]

6. Example code

# 1. create
# null
dict01 = {}
dict01 = dict()
# Defaults
dict01 = {"wj":100,"zm":80,"zr":90}
dict01 = dict([("a","b"),("c","d")])
print(dict01)

# 2. Find elements (find value according to key)
print(dict01["a"])
# If the key does not exist, an error will occur when searching.
if "qtx" in dict01:# if key exists
    print(dict01["qtx"])

# 3. Modify the element (the key existed before)
dict01["a"] = "BB"

# 4. Add (the key did not exist before)
dict01["e"] = "f"

# 5. delete
del dict01["a"]

print(dict01)
# 6. Traverse (get all elements in the dictionary)

# Traversing the dictionary to get the key
for key in dict01:
    print(key)
    print(dict01[key])

# Traversing the dictionary to get the value
for value in dict01.values():
    print(value)

# Traverse the dictionary to get the key value pair key value (tuple).
# for item in dict01.items():
#     print(item[0])
#     print(item[1])

for k,v in dict01.items():
    print(k)
    print(v)

P71 Python Basics-6.11 Commodity Information Entry and Printing Practice

1. Dictionary Exercise 1

"""
    exercise 1:Cyclic entry of product information in the console(name,unit price).
       If the name enters a null character,then stop the entry.
         Print all the information line by line.
"""
dict_commodity_info = {}
while True:
    name = input("Please enter a product name:")
    if name == "":
        break
    price = int(input("Please enter the unit price of the product:"))
    dict_commodity_info[name] = price

for key,value in dict_commodity_info.items():
    print("%s The unit price of the product is%d"%(key,value))

P72 Python Basics-6.12 Student Information Entry and Printing Practice

1. Exercise: Dictionaries nested lists

# Exercise 2: Cyclic input of student information (name, age, grade, gender) in the console.
# If the name enters an empty character, it will stop entering.
# Print all the information line by line.
"""
# Dictionaries embedded lists:
{
    "Zhang Wuji":[28,100,"male"],
}
"""
dict_student_info = {}
while True:
    name = input("Please type in your name:")
    if name == "":
        break
    age = int(input("Please enter your age:"))
    score = int(input("Please enter grades:"))
    sex = input("Please enter gender:")
    dict_student_info[name] = [age, score, sex]

# print all student information
for name,list_info in dict_student_info.items():
    print("%s is the age of%d,result is%d,gender is%s"%(name,list_info[0],list_info[1],list_info[2]))

2. Exercise: Dictionaries nested dictionaries

"""
# Dictionaries inside dictionaries:
{
    "Zhang Wuji":{"age":28,"score":100,"sex":"male"},
}
"""
dict_student_info = {}
while True:
    name = input("Please type in your name:")
    if name == "":
        break
    age = int(input("Please enter your age:"))
    score = int(input("Please enter grades:"))
    sex = input("Please enter gender:")
    dict_student_info[name] = {"age": age, "score": score, "sex": sex}

for name, dict_info in dict_student_info.items():
    print("%s is the age of%d,result is%d,gender is%s" %
          (name, dict_info["age"],
           dict_info["score"], dict_info["sex"]))

3. Exercise: list nested dictionary

"""
# List embedded dictionary:
[
    {"name":"Zhang Wuji","age":28,"score":100,"sex":"male"},
]
"""
list_student_info = []
while True:
    name = input("Please type in your name:")
    if name == "":
        break
    age = int(input("Please enter your age:"))
    score = int(input("Please enter grades:"))
    sex = input("Please enter gender:")
    dict_info = {"name": name, "age": age, "score": score, "sex": sex}
    list_student_info.append(dict_info)

for dict_info in list_student_info:
    print("%s is the age of%d,result is%d,sex is%s" % (dict_info["name"], dict_info["age"], dict_info["score"], dict_info["sex"]))
# Get the first student information
dict_info = list_student_info[0]
print("The first entry is:%s,age is%d,result is%d,gender is%s" % (dict_info["name"], dict_info["age"], dict_info["score"], dict_info["sex"]))

P73 Python Basics-6.13 Summary of Dictionary and List Comparison

1. Summary

"""
Summarize:
   Store multiple student information(Name,age,score,gender)in many ways

1. exercise05 dictionary embedded list:
{
    "Zhang Wuji":[28,100,"male"],
}
2. exercise06 Dictionaries within dictionaries:
{
    "Zhang Wuji":{"age":28,"score":100,"sex":"male"},
}
3. exercise07 list embedded dictionary:
[
    {"name":"Zhang Wuji","age":28,"score":100,"sex":"male"},
]
4. list inside list
[
    ["Zhang Wuji",28,100,'male'],
]
"""

2. Selection strategy

Selection strategy: According to specific needs, combined with advantages and disadvantages, comprehensive consideration(the lesser of two evils).
    dictionary:
        Advantages: Get the value according to the key, and the reading speed is fast;
           Code readability is higher than lists(Get by key vs get by index).
        Disadvantages: large memory usage;
           Get the value only according to the key,not flexible.
    list:
        Pros: according to the index/Slicing, more flexible access to elements.
             Compared with dictionaries, it takes up less memory.
        Disadvantages: Obtained by index, if there is a lot of information, the readability is not high.

P74 Python Basics-6.14 Entering multiple people's favorite exercises and assigning homework

1. Method 1

"""
practise:Enter multiple preferences of multiple people in the console,Enter a null character to stop.
For example:Please type in your name:
    Please enter the first preference:
    Please enter the second preference:
    ...
    Please type in your name:
    ...
   Finally, print all preferences of everyone on the console.
[
    {"Mowgli":[Zhao Min,Zhou Zhiruo,Xiao Zhao]}
]
"""
list_person_bobby = []
while True:
    name = input("Please type in your name:")
    if name == "":
        break
    dict_person = {name:[]}
    list_person_bobby.append(dict_person) 
    while True:
        bobby = input("Please enter preferences:")
        if bobby == "":
            break
        dict_person[name].append(bobby)

2. Method 2

"""
{
    "Mowgli":[Zhao Min,Zhou Zhiruo,Xiao Zhao]
}
"""
dict_person_bobby = {}
while True:
    name = input("Please type in your name:")
    if name == "":
        break
    dict_person_bobby[name] = []
    while True:
        bobby = input("Please enter preferences:")
        if bobby == "":
            break
        dict_person_bobby[name].append(bobby)

for name, list_bobby in dict_person_bobby.items():
    print("%s like:" % name)
    for item in list_bobby:
        print(item)

Tags: Python

Posted by newrehmi on Thu, 09 Mar 2023 08:18:01 +0530