首页 > 其他分享 >CS50P: 9. Et Cetera

CS50P: 9. Et Cetera

时间:2024-08-05 23:18:27浏览次数:7  
标签:Cetera __ meow int CS50P print Et main def

set

python’s documentation of set

  • 类型

  • 数学上的集合,没有重复元素

Q: 统计有多少个不同名house

way1--list

students = [
    {"name": "Hermione", "house": "Gryffindor"},
    {"name": "Harry", "house": "Gryffindor"},
    {"name": "Ron", "house": "Gryffindor"},
    {"name": "Draco", "house": "Slytherin"},
    {"name": "Padma", "house": "Ravenclaw"},
]
houses = []
for student in students:
    if student["house"] not in houses:
        houses.append(student["house"])
for house in sorted(houses):
    print(house)

line 8 等价于 houses = list()

way2--set

set 自动删除重复元素

houses = set()
for student in students:
   houses.add(student["house"])

Global Variables 全局变量

access

所有的函数都可以访问的变量,同C,对应 local variable

balance = 0
def main():
    print("Balance:", balance)
    deposit(100)
    withdraw(50)
    print("Balance:", balance)
def deposit(n):
    balance += n
def withdraw(n):
    balance -= n
if __name__ == "__main__":
    main()

报错 UnboundLocalError: cannot access local variable 'balance' where it is not associated with a value

global variable 可以访问,不能修改

line 8 的 balance 变量会被认为是 local variable

interact--global

def deposit(n):
    global balance
    balance += n
def withdraw(n):
    global balance
    balance -= n

函数内加上 global xxx 指示 xxx 是全局变量

object-oriented programming

class Account:
    def __init__(self):
        self._balance = 0    # instance variable

    @property
    def balance(self):
        return self._balance
    
    def deposit(self, n):
        self._balance += n
    
    def withdraw(self, n):
        self._balance -= n

def main():
    account = Account()
    print("Balance:", account.balance)
    account.deposit(100)
    account.withdraw(50)
    print("Balance:", account.balance)

if __name__ == "__main__":
    main()

_ 可以提醒自己其他地方不能 touch 这个 class 中的 function,比如 main 中不能有 account.balance = 1000

class 中的 balance 可以在其中的函数中修改,因为有 self 参数

Constants

常量不可修改,通常大写并放在最前,但是python不知道是个常量,主要提醒自己不要修改大写变量

MEOWS = 3
for _ in range(MEOWS):
    print("meow")

OOP:

class Cat:
    MEOWS = 3   # class constant
    def meow(self):
        for _ in range(Cat.MEOWS):
            print("meow")
cat = Cat()     # instantiate a cat
cat.meow()      # let cat meow

Type Hints

dynamic language,不用写变量的类型,python会自动识别

python’s documentation of Type Hints

mypy

测试并保证变量使用合理

在终端运行 mypy meow.py ,会显示错误(程序员可以忽略错误),根据提示修改即可

mypy's own documentation

变量类型

def meow(n):
    for _ in range(n):
        print("meow")
number = input("Number: ")
meow(number)

报错:line 4 接收到的是字符

修改代码2.0:

def meow(n: int):

: inttype hint ,表示 n 应该是 int 型变量。

修改代码3.0:

def meow(n: int):
    for _ in range(n):
        print("meow")
number: int = int(input("Number: "))
meow(number)

函数返回值提示

思想:函数尽量要有返回值

def meow(n: int) -> str:
    return "meow\n" * n
number: int = int(input("Number: "))
meows: str = meow(number)
print(meows, end="")

line 1: 是一个 hint ,提示我们函数默认返回类型为 str (可以是 None )

Docstrings

python’s documentation of docstrings

左右三个引号指示本函数的作用

def meow(n: int) -> str:
    """Meow n times."""
    return "meow\n" * n

给函数写说明文档

def meow(n: int) -> str:
    """
    Meow n times.
    
    :param n: Number of times to meow
    :type n: int
    :raise TypeError: If n is not an int
    :return: A string of n meows, one per line
    :rtype: str
    """
    return "meow\n" * n

通过第三方库 Sphinx 可以生成 PDF 文档或网页

Argparse

python’s documentation of argparse

sys

想用command-line输入,键入 python3 meows.py -n 3

import sys
if len(sys.argv) == 1:
    print("meow")
elif len(sys.argv) == 3 and sys.argv[1] == "-n":
    n = int(sys.argv[2])
    for _ in range(n):
        print("meow")
else:
    print("usage: meow.py")

-n 常常表示后面的数字是次数

字母前用 - ,单词前用 --

使用很多 if 来分情况,参数位置严格

argparse

a library that handles all the parsing of complicated strings of command-line arguments

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-n")
args = parser.parse_args()

for _ in range(int(args.n)):
    print("meow")

An object called parser is created from an ArgumentParser class.

That class’s add_argument method is used to tell argparse what arguments we should expect from the user when they run our program.

The parser’s parse_args method 相当于解析 sys.argv ,在终端中键入的所有参数都传给 args

Finally, running the parser’s parse_args method ensures that all of the arguments have been included properly by the user.

. 引用一个 object 里的 property,args.n-n 后输入的数字

--h

python3 meows.py -h--help 查看帮助信息

-n N 表示需要在 -n 后输入数字作参数

更清楚的版本:

parser = argparse.ArgumentParser(description="Meow like a cat")
parser.add_argument("-n", help="number of times to meow")

default, type

import argparse
parser = argparse.ArgumentParser(description="Meow like a cat")
parser.add_argument("-n", default=1, help="number of times to meow", type=int)
args = parser.parse_args()
for _ in range(args.n):
    print("meow")

line 3:

  • default=1 默认 N 为 1
  • type=int 会把参数按照数字处理(本来是str),line 5 就不用 int()

Unpacking

Q:把一个list中的元素作为函数的参数?

def total(galleons, sickles, knuts):
    return (galleons * 17 + sickles) * 29 + knuts
coins = [100, 50, 25]
print(total(coins[0], coins[1], coins[2]), "Knuts")

List就像packed with values,我们现在unpack list into multiple things

*

list 变量前加 * 得到单个值

print(total(*coins), "Knuts")

a * unpacks the sequence of the list of coins and passes in each of its individual elements to total

传参次序

def total(galleons, sickles, knuts):
    return (galleons * 17 + sickles) * 29 + knuts
print(total(galleons=100, sickles=50, knuts=25), "knuts")

标明 galleons=100 后,参数可以不按顺序传递

**

dict 变量前加 * 得到键值对

coins = {"galleons": 100, "sickles": 50, "knuts": 25}
print(total(**coins), "knuts")

效果等价于 ⬆️

args & kwargs

args

*args 表示可以接收未知数目的参数,args are positional arguments

def f(*args, **kwargs):
    print("Positional:", args)
f(100, 50, 25)

结果为 Positional: (100, 50, 25)

kwargs

kwargs are named/keyword arguments

def f(*args, **kwargs):
    print("Named:", kwargs)
f(galleons=100, sickles=50, knuts=25)

结果为 Named: {'galleons': 100, 'sickles': 50, 'knuts': 25} ,一个 dict

ps. 主要是 ***argskwargs 可以换名字

print

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

回顾print函数,*objects 表示可以接收任意数量的参数

map

Q: 把一句话以大写输出

def main():
    yell("This is CS50")
def yell(phrase):
    print(phrase.upper())
if __name__ == "__main__":
    main()

有返回值

def main():
    yell(["This", "is", "CS50"])
def yell(words):
    uppercased = list()
    for word in words:
        uppercased.append(word.upper())
    print(*uppercased)
if __name__ == "__main__":
    main()
def main():
    yell("This", "is", "CS50")
def yell(*words):
    uppercased = list()
    for word in words:
        uppercased.append(word.upper())
    print(*uppercased)

此时的yell很像print

map

python’s documentation of map

apply some function to every element of some sequence like a list 对序列中的每个元素进行映射

map(function, iterable, ...)
def main():
    yell("This", "is", "CS50")
def yell(*words):
    uppercased = map(str.upper, words)
    print(*uppercased)  # unpack

str class中的upper function,注意没有 () ,map 会 call

List Comprehensions

List comprehensions allow you to create a list on the fly in one elegant one-liner.

list comprehensions

line 4 等价:

uppercased = [word.upper() for word in words]

对每个参数,.upper() 都会作用在它们身上

if condition

Q:筛选出住在Gryffindor的学生

students = [
    {"name": "Hermione", "house": "Gryffindor"},
    {"name": "Harry", "house": "Gryffindor"},
    {"name": "Ron", "house": "Gryffindor"},
    {"name": "Draco", "house": "Slytherin"},
]
gryffindors = [
    student["name"] for student in students if student["house"]=="Gryffindor"
]
for gryffindor in sorted(gryffindors):
    print(gryffindor)

gryffindors = [] 中的一整串是列表中的元素

filter

python’s documentation of filter

上述问题的另一种实现--filter

Using Python’s filter function allows us to return a subset of a sequence for which a certain condition is true

def is_gryffindor(s):
    return s["house"] == "Gryffindor"
gryffindors = filter(is_gryffindor, students)
for gryffindor in sorted(gryffindors, key=lambda s: s["name"]):
    print(gryffindor["name"])

filter( , ) 的第一个参数为函数(返回值是True or False),将会作用于序列的每个元素;第二个参数是序列

另一种传递函数的方法:

gryffindors = filter(lambda s: s["house"] == "Gryffindor", students)

Dictionary Comprehensions

Q: 已知学生名单,建立包含名字和房子的list

students = ["Hermione", "Harry", "Ron"]
gryffindors = []
for student in students:
    gryffindors.append({"name": student, "house": "Gryffindor"})
print(gryffindors)

line 2 ~4 等价于:

gryffindors = [{"name": student, "house": "Gryffindor"} for student in students]

进一步优化:

students = ["Hermione", "Harry", "Ron"]
gryffindors = {student: "Gryffindor" for student in students}
print(gryffindors)

key是name,value都是Gryffindor

{'Hermione': 'Gryffindor', 'Harry': 'Gryffindor', 'Ron': 'Gryffindor'}

enumerate

python’s documentation of enumerate

Q:为输出编号

way 1

students = ["Hermione", "Harry", "Ron"]
for i in range(len(students)):
    print(i + 1, students[i])
1 Hermione
2 Harry
3 Ron

way 2

enumerate(iterable, start=0)

同时返回元素和index

for i, student in enumerate(students):
    print(i + 1, student)

Generators and Iterators

python’s documentation of generators.

python’s documentation of iterators.

Q: 数羊

def main():
    n = int(input("What's n? "))
    for i in range(n):
        print(sheep(i))
def sheep(n):
    return "

标签:Cetera,__,meow,int,CS50P,print,Et,main,def
From: https://www.cnblogs.com/chasetsai/p/18344227

相关文章

  • LeetCode 1631. Path With Minimum Effort
    原题链接在这里:https://leetcode.com/problems/path-with-minimum-effort/description/题目:Youareahikerpreparingforanupcominghike.Youaregiven heights,a2Darrayofsize rowsxcolumns,where heights[row][col] representstheheightofcell (row,c......
  • [Violet 6]故乡的梦 题解
    前言题目链接:Hydro&bzoj。题意简述无向联通图给出起点终点,多次询问删边后最短路,或报告不连通。\(n,m,q\leq2\times10^5\)。题目分析首先想到,如果删掉的边不是原来最短路的边,那么最短路不会发生变化。因此我们只需考虑删除了原来在最短路上的边。不妨把原先最短路任......
  • kubernetes-存储卷与持久化详解
    目录背景volume介绍emptyDirHostPathNFSconfigMapSecretPersistentVolume介绍PV回收策略PV访问策略基于nfs或nas创建pv创建hostpath类型的pvPV的状态PersistentVolumeClaim创建pvc与pv进行绑定使用pvc动态存储storageclass创建目录nfs添加授权目录创建yaml背景容器部署过程中一......
  • day32【LeetCode力扣】541. 反转字符串 II
    day32【LeetCode力扣】541.反转字符串II1.题目描述给定一个字符串s和一个整数k,从字符串开头算起,每计数至2k个字符,就反转这2k字符中的前k个字符。如果剩余字符少于k个,则将剩余字符全部反转。如果剩余字符小于2k但大于或等于k个,则反转前k个字符,其余字符......
  • 跳转语句(return,break,continue,goto,throw)
    跳转语句Java中的跳转语句允许你控制程序的流程,主要有以下几种:return:从方法返回一个值,并退出当前方法。break:跳出当前的循环(for、while或do-while)。continue:跳过当前循环的剩余部分,开始下一次循环迭代。goto:跳转到程序中的指定标签位置(Java7引入的有限形式)。throw:抛出......
  • Profibus转EtherCAT协议转换网关(通讯配置方法)
    如何实现Profibus网络和EtherCAT网络的连接互通?不少朋友对此存有疑问,作者在此统一作出回复。实际上,捷米特JM-DPM-ECT这款设备能够有效地解决这一问题。接下来,作者将为大家详尽地介绍该设备的功能、参数以及配置方式。一,设备主要功能捷米特JM-DPM-ECT是自主研发的一款Profibu......
  • CANopen从站转Profinet从站协议转换网关(通讯配置方法)
    如何实现CANopen网络和Profinet网络的连接互通?不少朋友对此存有疑问,作者在此统一作出回复。实际上,捷米特JM-PN-COP这款设备能够有效地解决这一问题。接下来,作者将为大家详尽地介绍该设备的功能、参数以及配置方式。一、功能概述1.1设备简介捷米特JM-PN-COP是PN(Profinet)......
  • Jetson Orin nano 安装ubuntu22.04
    最近项目需要给底盘部署建图以及定位导航,底盘用的是Jetsonorinnano,用的是Ros2humble版本的机器人操作系统,由于humble版本的系统只支持ubuntu22.04,所以需要在orinnano上重新烧录ubuntu22.04,但是这个版本的系统跟之前的有些不一样,也踩了很多坑,查阅了官网的相关资料后,已经......
  • Profibus主站转EtherCAT协议转换网关(通讯配置方法)
    如何实现Profibus网络和EtherCAT网络的连接互通?不少朋友对此存有疑问,作者在此统一作出回复。实际上,捷米特JM-DPM-ECT这款设备能够有效地解决这一问题。接下来,作者将为大家详尽地介绍该设备的功能、参数以及配置方式。一,产品主要功能捷米特JM-DPM-ECT是自主研发的一款Profibu......
  • WPF locate discreted points via periodically and set transparency via the alpha,
    //xaml<Windowx:Class="WpfApp229.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mi......