From 3aa99f495c44f4f44ce0871559e24bec9f1fe549 Mon Sep 17 00:00:00 2001 From: LSGOMYP Date: Tue, 14 Jul 2020 23:39:31 +0800 Subject: [PATCH] =?UTF-8?q?program=E8=AF=BE=E7=A8=8B=E5=86=85=E5=AE=B9?= =?UTF-8?q?=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Python-Language/01. 变量、运算符与数据类型.md | 14 +-- .../{15. 位运算.md => 02. 位运算.md} | 35 ++++++- .../{02. 条件语句.md => 03. 条件语句.md} | 4 +- .../{03. 循环语句.md => 04. 循环语句.md} | 51 +++++++++- .../{04. 异常处理.md => 05. 异常处理.md} | 25 ++++- Python-Language/{05. 列表.md => 06. 列表.md} | 57 ++++++++++- Python-Language/{06. 元组.md => 07. 元组.md} | 25 ++++- .../{07. 字符串.md => 08. 字符串.md} | 48 ++++++++- Python-Language/{08. 字典.md => 09. 字典.md} | 51 +++++++++- Python-Language/{09. 集合.md => 10. 集合.md} | 9 +- Python-Language/{10. 序列.md => 11. 序列.md} | 8 +- ...Lambda表达式.md => 12. 函数与Lambda表达式.md} | 11 ++- .../{12. 类与对象.md => 13. 类与对象.md} | 33 ++++++- .../{13. 魔法方法.md => 14. 魔法方法.md} | 24 +++-- Python-Language/{14. 模块.md => 15. 模块.md} | 31 +++++- ...7. datetime模块.md => 16. datetime模块.md} | 55 ++++++++++- ...件与文件系统.md => 17. 文件与文件系统.md} | 97 ++++++++++++------- Python-Language/res/test.txt | 4 + readme.md | 2 +- 19 files changed, 504 insertions(+), 80 deletions(-) rename Python-Language/{15. 位运算.md => 02. 位运算.md} (88%) rename Python-Language/{02. 条件语句.md => 03. 条件语句.md} (99%) rename Python-Language/{03. 循环语句.md => 04. 循环语句.md} (83%) rename Python-Language/{04. 异常处理.md => 05. 异常处理.md} (92%) rename Python-Language/{05. 列表.md => 06. 列表.md} (90%) rename Python-Language/{06. 元组.md => 07. 元组.md} (93%) rename Python-Language/{07. 字符串.md => 08. 字符串.md} (93%) rename Python-Language/{08. 字典.md => 09. 字典.md} (89%) rename Python-Language/{09. 集合.md => 10. 集合.md} (95%) rename Python-Language/{10. 序列.md => 11. 序列.md} (93%) rename Python-Language/{11. 函数与Lambda表达式.md => 12. 函数与Lambda表达式.md} (95%) rename Python-Language/{12. 类与对象.md => 13. 类与对象.md} (97%) rename Python-Language/{13. 魔法方法.md => 14. 魔法方法.md} (96%) rename Python-Language/{14. 模块.md => 15. 模块.md} (94%) rename Python-Language/{17. datetime模块.md => 16. datetime模块.md} (91%) rename Python-Language/{16. 文件与文件系统.md => 17. 文件与文件系统.md} (91%) create mode 100644 Python-Language/res/test.txt diff --git a/Python-Language/01. 变量、运算符与数据类型.md b/Python-Language/01. 变量、运算符与数据类型.md index b43f5af..16c1a05 100644 --- a/Python-Language/01. 变量、运算符与数据类型.md +++ b/Python-Language/01. 变量、运算符与数据类型.md @@ -106,7 +106,7 @@ print((1 > 3) or (3 < 5)) # True `<<`|左移 |4 << 2,表示整数 4 按位左移 2 位 `>>`|右移 |4 >> 2,表示整数 4 按位右移 2 位 -++按位非操作 ~++ +按位非操作 ~ ```python ~ 1 = 0 @@ -114,7 +114,7 @@ print((1 > 3) or (3 < 5)) # True ``` -++按位与操作 &++ +按位与操作 & ```python 1 & 1 = 1 @@ -123,7 +123,7 @@ print((1 > 3) or (3 < 5)) # True 0 & 0 = 0 ``` -++按位或操作 |++ +按位或操作 | ```python 1 | 1 = 1 @@ -132,7 +132,7 @@ print((1 > 3) or (3 < 5)) # True 0 | 0 = 0 ``` -++按位异或操作 ^++ +按位异或操作 ^ ```python 1 ^ 1 = 0 @@ -144,7 +144,7 @@ print((1 > 3) or (3 < 5)) # True -++按位左移操作 <<++ +按位左移操作 << 【例子】`num << i` 将`num`的二进制表示向左移动`i`位所得的值。 ```c @@ -154,7 +154,7 @@ print((1 > 3) or (3 < 5)) # True 01 01 10 00 -> 88 ``` -++按位右移操作 >>++ +按位右移操作 >> 【例子】`num >> i` 将`num`的二进制表示向右移动`i`位所得的值。 ```c @@ -525,7 +525,7 @@ print('hello world') ``` -【例子】,`item`值与`'another string'`两个值之间用`sep`设置的参数`&`分割。由于`end`参数没有设置,因此默认是输出解释后换行,即`end`参数的默认值为`\n`。 +【例子】`item`值与`'another string'`两个值之间用`sep`设置的参数`&`分割。由于`end`参数没有设置,因此默认是输出解释后换行,即`end`参数的默认值为`\n`。 ```python diff --git a/Python-Language/15. 位运算.md b/Python-Language/02. 位运算.md similarity index 88% rename from Python-Language/15. 位运算.md rename to Python-Language/02. 位运算.md index 633da4b..b563e3a 100644 --- a/Python-Language/15. 位运算.md +++ b/Python-Language/02. 位运算.md @@ -2,7 +2,7 @@ ## 1. 原码、反码和补码 -二进制有三种不同的表示形式:原码、反码和补码,++计算机内部使用补码来表示++。 +二进制有三种不同的表示形式:原码、反码和补码,计算机内部使用补码来表示。 原码:就是其二进制表示(注意,有一位符号位)。 @@ -197,10 +197,11 @@ a 并 b -> a | b a 差 b -> a & (~b) ``` - --- 整数在内存中是以补码的形式存在的,输出自然也是按照补码输出。 +【例子】C#语言输出负数 + ```c class Program { @@ -241,4 +242,32 @@ print(0xfffffffd) # 4294967293 所以为了获得负数(十进制表示)的补码,需要手动将其和十六进制数`0xffffffff`进行按位与操作,再交给`bin()`进行输出,得到的才是负数的补码表示。 --- -**练习题**: \ No newline at end of file +**练习题**: + +leetcode 习题 136. 只出现一次的数字 + +给定一个**非空**整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。 + +尝试使用位运算解决此题。 + +题目说明: + +```python +""" +Input file +example1: [2,2,1] +example2: [4,1,2,1,2] + +Output file +result1: 1 +result2: 4 +""" + + + +class Solution: + def singleNumber(self, nums: List[int]) -> int: + + # your code here +``` + diff --git a/Python-Language/02. 条件语句.md b/Python-Language/03. 条件语句.md similarity index 99% rename from Python-Language/02. 条件语句.md rename to Python-Language/03. 条件语句.md index 527ac03..23c2212 100644 --- a/Python-Language/02. 条件语句.md +++ b/Python-Language/03. 条件语句.md @@ -9,6 +9,7 @@ if expression: - if 语句的 `expr_true_suite` 代码块只有当条件表达式 `expression` 结果为真时才执行,否则将继续执行紧跟在该代码块后面的语句。 - 单个 if 语句中的 `expression` 条件表达式可以通过布尔操作符 `and`,`or`和`not` 实现多重条件判断。 +【例子】 ```python if 2 > 1 and not 2 > 3: print('Correct Judgement!') @@ -134,6 +135,5 @@ assert 3 > 7 # AssertionError ``` ---- -**练习题**: + diff --git a/Python-Language/03. 循环语句.md b/Python-Language/04. 循环语句.md similarity index 83% rename from Python-Language/03. 循环语句.md rename to Python-Language/04. 循环语句.md index 0d15378..4118076 100644 --- a/Python-Language/03. 循环语句.md +++ b/Python-Language/04. 循环语句.md @@ -48,7 +48,6 @@ while string: # d ``` - --- ## 2. while - else 循环 @@ -57,7 +56,7 @@ while 布尔表达式: 代码块 else: 代码块 -``` +``` 当`while`循环正常执行完的情况下,执行`else`输出,如果`while`循环中执行了跳出循环的语句,比如 `break`,将不执行`else`代码块的内容。 @@ -320,7 +319,7 @@ while True: print("大了,大了") else: if guess == secret: - print("你是小哥哥心里的蛔虫吗?") + print("你这样懂小哥哥的心思啊?") print("哼,猜对也没有奖励!") break else: @@ -552,3 +551,49 @@ while count > 0: --- **练习题**: +1、编写一个Python程序来查找那些可以被7除以5的整数的数字,介于1500和2700之间。 + +```python +# your code here + + + +``` + +2、龟兔赛跑游戏 + +题目描述: + +话说这个世界上有各种各样的兔子和乌龟,但是研究发现,所有的兔子和乌龟都有一个共同的特点——喜欢赛跑。于是世界上各个角落都不断在发生着乌龟和兔子的比赛,小华对此很感兴趣,于是决定研究不同兔 子和乌龟的赛跑。他发现,兔子虽然跑比乌龟快,但它们有众所周知的毛病——骄傲且懒惰,于是在与乌龟的比赛中,一旦任一秒结束后兔子发现自己领先t米或以 上,它们就会停下来休息s秒。对于不同的兔子,t,s的数值是不同的,但是所有的乌龟却是一致——它们不到终点决不停止。 + +然而有些比赛相当漫长,全程观看会耗费大量时间,而小华发现只要在每场比赛开始后记录下兔子和乌龟的数据——兔子的速度v1(表示每秒兔子能跑v1 米),乌龟的速度v2,以及兔子对应的t,s值,以及赛道的长度l——就能预测出比赛的结果。但是小华很懒,不想通过手工计算推测出比赛的结果,于是他找 到了你——清华大学计算机系的高才生——请求帮助,请你写一个程序,对于输入的一场比赛的数据v1,v2,t,s,l,预测该场比赛的结果。 + +输入: + +输入只有一行,包含用空格隔开的五个正整数v1,v2,t,s,l,其中(v1,v2< =100;t< =300;s< =10;l< =10000且为v1,v2的公倍数) + +输出: + +输出包含两行,第一行输出比赛结果——一个大写字母“T”或“R”或“D”,分别表示乌龟获胜,兔子获胜,或者两者同时到达终点。 + +第二行输出一个正整数,表示获胜者(或者双方同时)到达终点所耗费的时间(秒数)。 + +------ + +样例输入: + +10 5 5 2 20 + +样例输出 + +D
+4 + +```python +# your code here + + + +``` + + \ No newline at end of file diff --git a/Python-Language/04. 异常处理.md b/Python-Language/05. 异常处理.md similarity index 92% rename from Python-Language/04. 异常处理.md rename to Python-Language/05. 异常处理.md index 10ab215..59cf587 100644 --- a/Python-Language/04. 异常处理.md +++ b/Python-Language/05. 异常处理.md @@ -291,4 +291,27 @@ except NameError: --- -**练习题**: \ No newline at end of file +**练习题**: + +1、猜数字游戏 + +题目描述: + +电脑产生一个零到100之间的随机数字,然后让用户来猜,如果用户猜的数字比这个数字大,提示太大,否则提示太小,当用户正好猜中电脑会提示,"恭喜你猜到了这个数是......"。在用户每次猜测之前程序会输出用户是第几次猜测,如果用户输入的根本不是一个数字,程序会告诉用户"输入无效"。 + +(尝试使用try catch异常处理结构对输入情况进行处理) + +获取随机数采用random模块。 + +![](https://img-blog.csdnimg.cn/20200714230819193.png) + +```python +# your code here + + + + + +``` + + \ No newline at end of file diff --git a/Python-Language/05. 列表.md b/Python-Language/06. 列表.md similarity index 90% rename from Python-Language/05. 列表.md rename to Python-Language/06. 列表.md index f122ecc..d6e3cd4 100644 --- a/Python-Language/05. 列表.md +++ b/Python-Language/06. 列表.md @@ -483,7 +483,6 @@ print(x) - --- **参考文献**: - https://www.runoob.com/python3/python3-tutorial.html @@ -491,4 +490,58 @@ print(x) - https://mp.weixin.qq.com/s/DZ589xEbOQ2QLtiq8mP1qQ --- -**练习题**: \ No newline at end of file +**练习题**: + +1、列表操作练习 + +列表lst 内容如下 + +lst = [2, 5, 6, 7, 8, 9, 2, 9, 9] + +请写程序完成下列操作: + +1. 在列表的末尾增加元素15 +2. 在列表的中间位置插入元素20 +3. 将列表[2, 5, 6]合并到lst中 +4. 移除列表中索引为3的元素 +5. 翻转列表里的所有元素 +6. 对列表里的元素进行排序,从小到大一次,从大到小一次 + +2、修改列表 + +问题描述: + +lst = [1, [4, 6], True] + +请将列表里所有数字修改成原来的两倍 + +3、leetcode 852题 山脉数组的峰顶索引 + +如果一个数组k符合下面两个属性,则称之为山脉数组 + +数组的长度大于等于3 + +存在$i$,$i$ >0 且$i<\operatorname{len}(k)-1$, 使得$$\mathrm{k}[0]<\mathrm{k}[1]<\ldots<\mathrm{k}[\mathrm{i}-1]<\mathrm{k}[\mathrm{j}]>\mathrm{k}[\mathrm{i}+1] \ldots>\mathrm{k}[\operatorname{len}(\mathrm{k})-1]$$ + +这个$i$就是顶峰索引。 + +现在,给定一个山脉数组,求顶峰索引。 + +示例: + +输入:[1, 3, 4, 5, 3] + +输出:True + +输入:[1, 2, 4, 6, 4, 5] + +输出:False + +```python +class Solution: + def peakIndexInMountainArray(self, A: List[int]) -> int: + + # your code here +``` + + \ No newline at end of file diff --git a/Python-Language/06. 元组.md b/Python-Language/07. 元组.md similarity index 93% rename from Python-Language/06. 元组.md rename to Python-Language/07. 元组.md index 81a505c..dd87b1c 100644 --- a/Python-Language/06. 元组.md +++ b/Python-Language/07. 元组.md @@ -166,4 +166,27 @@ print(a, b) # 1 2 ``` --- -**练习题**: \ No newline at end of file +**练习题**: + +1、元组概念 + +写出下面代码的执行结果和最终结果的类型 + +```python +(1, 2)*2 +(1, )*2 +(1)*2 +``` + +分析为什么会出现这样的结果. + +2、拆包过程是什么? + +```python +a, b = 1, 2 +``` + +上述过程属于拆包吗? + +可迭代对象拆包时,怎么赋值给占位符? + diff --git a/Python-Language/07. 字符串.md b/Python-Language/08. 字符串.md similarity index 93% rename from Python-Language/07. 字符串.md rename to Python-Language/08. 字符串.md index e02540f..2984f78 100644 --- a/Python-Language/07. 字符串.md +++ b/Python-Language/08. 字符串.md @@ -393,4 +393,50 @@ print('%010d' % 5) # 0000000005 - https://mp.weixin.qq.com/s/DZ589xEbOQ2QLtiq8mP1qQ --- -**练习题**: \ No newline at end of file +**练习题**: + +1、字符串函数回顾 + +- 怎么批量替换字符串中的元素? +- 怎么把字符串按照空格进⾏拆分? +- 怎么去除字符串⾸位的空格? + +2、实现isdigit函数 + +题目要求 + +实现函数isdigit, 判断字符串里是否只包含数字0~9 + +```python +def isdigit(string): + """ + 判断字符串只包含数字 + :param string: + :return: + """ + # your code here + pass +``` + +3、leetcode 5题 最长回文子串 + +给定一个字符串 `s`,找到 `s` 中最长的回文子串。你可以假设 `s` 的最大长度为 1000。 + +示例: + +输入: "babad" + +输出: "bab" + +输入: "cbbd" + +输出: "bb" + +```python +class Solution: + def longestPalindrome(self, s: str) -> str: + + # your code here +``` + + \ No newline at end of file diff --git a/Python-Language/08. 字典.md b/Python-Language/09. 字典.md similarity index 89% rename from Python-Language/08. 字典.md rename to Python-Language/09. 字典.md index 1079bd3..c97b5d3 100644 --- a/Python-Language/08. 字典.md +++ b/Python-Language/09. 字典.md @@ -328,7 +328,56 @@ print("更新字典 dict : ", dic) # 更新字典 dict : {'Sex': 'female', 'Age': 8, 'Name': 'Lsgogroup'} ``` - --- **练习题**: +1、字典基本操作 + +字典内容如下: + +```python +dic = { + 'python': 95, + 'java': 99, + 'c': 100 + } +``` + +用程序解答下面的题目 + +- 字典的长度是多少 +- 请修改'java' 这个key对应的value值为98 +- 删除 c 这个key +- 增加一个key-value对,key值为 php, value是90 +- 获取所有的key值,存储在列表里 +- 获取所有的value值,存储在列表里 +- 判断 javascript 是否在字典中 +- 获得字典里所有value 的和 +- 获取字典里最大的value +- 获取字典里最小的value +- 字典 dic1 = {'php': 97}, 将dic1的数据更新到dic中 + +2、字典中的value + +有一个字典,保存的是学生各个编程语言的成绩,内容如下 + +``` +data = { + 'python': {'上学期': '90', '下学期': '95'}, + 'c++': ['95', '96', '97'], + 'java': [{'月考':'90', '期中考试': '94', '期末考试': '98'}] + } +``` + +各门课程的考试成绩存储方式并不相同,有的用字典,有的用列表,但是分数都是字符串类型,请实现函数`transfer_score(score_dict)`,将分数修改成int类型 + +```python + +def transfer_score(data): + # your code here + + +``` + + + \ No newline at end of file diff --git a/Python-Language/09. 集合.md b/Python-Language/10. 集合.md similarity index 95% rename from Python-Language/09. 集合.md rename to Python-Language/10. 集合.md index 5975933..7b1969d 100644 --- a/Python-Language/09. 集合.md +++ b/Python-Language/10. 集合.md @@ -330,7 +330,6 @@ print(b) - --- **参考文献**: - https://www.runoob.com/python3/python3-tutorial.html @@ -338,4 +337,10 @@ print(b) - https://mp.weixin.qq.com/s/DZ589xEbOQ2QLtiq8mP1qQ --- -**练习题**: \ No newline at end of file +**练习题**: + +1. 怎么表示只包含⼀个数字1的元组。 +2. 创建一个空集合,增加 {‘x’,‘y’,‘z’} 三个元素。 +3. 列表['A', 'B', 'A', 'B']去重。 +4. 求两个集合{6, 7, 8},{7, 8, 9}中不重复的元素(差集指的是两个集合交集外的部分)。 +5. 求{'A', 'B', 'C'}中元素在 {'B', 'C', 'D'}中出现的次数。 \ No newline at end of file diff --git a/Python-Language/10. 序列.md b/Python-Language/11. 序列.md similarity index 93% rename from Python-Language/10. 序列.md rename to Python-Language/11. 序列.md index 1f68aa7..f6b3707 100644 --- a/Python-Language/10. 序列.md +++ b/Python-Language/11. 序列.md @@ -180,4 +180,10 @@ print(list(a2)) # [4, 5, 6] ``` --- -**练习题**: \ No newline at end of file +**练习题**: + +1. 怎么找出序列中的最⼤、⼩值? +2. sort() 和 sorted() 区别 +3. 怎么快速求 1 到 100 所有整数相加之和? +4. 求列表 [2,3,4,5] 中每个元素的立方根。 +5. 将[‘x’,‘y’,‘z’] 和 [1,2,3] 转成 [(‘x’,1),(‘y’,2),(‘z’,3)] 的形式。 \ No newline at end of file diff --git a/Python-Language/11. 函数与Lambda表达式.md b/Python-Language/12. 函数与Lambda表达式.md similarity index 95% rename from Python-Language/11. 函数与Lambda表达式.md rename to Python-Language/12. 函数与Lambda表达式.md index bc61bca..88ad37c 100644 --- a/Python-Language/11. 函数与Lambda表达式.md +++ b/Python-Language/12. 函数与Lambda表达式.md @@ -463,7 +463,6 @@ import sys sys.setrecursionlimit(1000) ``` - --- ## 2. Lambda 表达式 @@ -599,7 +598,6 @@ print(apply_to_list(lambda x: sum(x) / len(x), lst)) # 3.0 ``` - --- **参考文献**: - https://www.runoob.com/python3/python3-tutorial.html @@ -609,5 +607,12 @@ print(apply_to_list(lambda x: sum(x) / len(x), lst)) --- **练习题**: -1. [利用python解决汉诺塔问题?](https://mp.weixin.qq.com/s?__biz=MzIyNDA1NjA1NQ==&mid=2651010966&idx=1&sn=57c9c6a05cfeaafc6bb88eaee54550a3&chksm=f3e3500ec494d918edc37c3e23997d0fc330152029e7140b82437f453ec9e7bf8d0c500a500d&token=523711417&lang=zh_CN#rd) +1. 怎么给函数编写⽂档? +2. 怎么给函数参数和返回值注解? +3. 闭包中,怎么对数字、字符串、元组等不可变元素更新。 +4. 分别根据每一行的首元素和尾元素大小对二维列表 a = [[6, 5], [3, 7], [2, 8]] 排序。(利用lambda表达式) +5. 利用python解决汉诺塔问题? +> 有a、b、c三根柱子,在a柱子上从下往上按照大小顺序摞着64片圆盘,把圆盘从下面开始按大小顺序重新摆放在c柱子上,尝试用函数来模拟解决的过程。(提示:将问题简化为已经成功地将a柱上面的63个盘子移到了b柱) + +![](https://img-blog.csdnimg.cn/20200714232535813.png) \ No newline at end of file diff --git a/Python-Language/12. 类与对象.md b/Python-Language/13. 类与对象.md similarity index 97% rename from Python-Language/12. 类与对象.md rename to Python-Language/13. 类与对象.md index afce973..c2d2af7 100644 --- a/Python-Language/12. 类与对象.md +++ b/Python-Language/13. 类与对象.md @@ -154,7 +154,6 @@ b.kick() # 我叫球B,该死的,谁踢我... ``` - --- ## 3. Python 的魔法方法 @@ -850,4 +849,34 @@ print(cc.x) # 2 - https://www.jianshu.com/p/9fb316cbf42e --- -**练习题**: \ No newline at end of file +**练习题**: + +1、以下类定义中哪些是类属性,哪些是实例属性? + +2、怎么定义私有⽅法? + +3、尝试执行以下代码,并解释错误原因: + +```python +class C: + def myFun(): + print('Hello!') + c = C() + c.myFun() +``` + +4、按照以下要求定义一个游乐园门票的类,并尝试计算2个成人+1个小孩平日票价。 + +要求: +- 平日票价100元 +- 周末票价为平日的120% +- 儿童票半价 + +```python +class Ticket(): + # your code here + + +``` + + \ No newline at end of file diff --git a/Python-Language/13. 魔法方法.md b/Python-Language/14. 魔法方法.md similarity index 96% rename from Python-Language/13. 魔法方法.md rename to Python-Language/14. 魔法方法.md index cbe4eba..dd09ce5 100644 --- a/Python-Language/13. 魔法方法.md +++ b/Python-Language/14. 魔法方法.md @@ -245,7 +245,6 @@ print('%r' %today) # datetime.date(2019, 10, 11) - --- ## 2. 算术运算符 @@ -335,7 +334,6 @@ print(divmod(8, 2)) # (4, 0) - `__xor__(self, other)`定义按位异或操作的行为:`^` - `__or__(self, other)`定义按位或操作的行为:`|` - --- ## 3. 反算术运算符 @@ -388,7 +386,6 @@ print(1 + b) # -2 - `__ixor__(self, other)`定义赋值按位异或操作的行为:`^=` - `__ior__(self, other)`定义赋值按位或操作的行为:`|=` - --- ## 5. 一元运算符 - `__neg__(self)`定义正号的行为:`+x` @@ -396,7 +393,6 @@ print(1 + b) # -2 - `__abs__(self)`定义当被`abs()`调用时的行为 - `__invert__(self)`定义按位求反的行为:`~x` - --- ## 6. 属性访问 @@ -526,9 +522,9 @@ print(c2.count) ``` - `__len__(self)`定义当被`len()`调用时的行为(返回容器中元素的个数)。 -- `__getitem(self, key)`定义获取容器中元素的行为,相当于`self[key]`。 -- `__setitem(self, key, value)`定义设置容器中指定元素的行为,相当于`self[key] = value`。 -- `__delitem(self, key)`定义删除容器中指定元素的行为,相当于`del self[key]`。 +- `__getitem__(self, key)`定义获取容器中元素的行为,相当于`self[key]`。 +- `__setitem__(self, key, value)`定义设置容器中指定元素的行为,相当于`self[key] = value`。 +- `__delitem__(self, key)`定义删除容器中指定元素的行为,相当于`del self[key]`。 【例子】编写一个可改变的自定义列表,要求记录列表中每个元素被访问的次数。 @@ -747,4 +743,16 @@ for each in libs(100): --- **练习题**: -1. [利用 Python 做一个简单的定时器类。](https://mp.weixin.qq.com/s?__biz=MzIyNDA1NjA1NQ==&mid=2651011380&idx=1&sn=e2fb4ad1b9734e8f104c267d4cd36b33&chksm=f3e35eacc494d7ba417701f2f9b6bd2133e921bef5ed3b798a6aa87d35919dfdd26156491e83&token=523711417&lang=zh_CN#rd) \ No newline at end of file + +1、上面提到了许多魔法方法,如`__new__`,`__init__`, `__str__`,`__rstr__`,`__getitem__`,`__setitem__`等等,请总结它们各自的使用方法。 + +2、利用python做一个简单的定时器类 + +要求: + +- 定制一个计时器的类。 +- `start`和`stop`方法代表启动计时和停止计时。 +- 假设计时器对象`t1`,`print(t1)`和直接调用`t1`均显示结果。 +- 当计时器未启动或已经停止计时时,调用`stop`方法会给予温馨的提示。 +- 两个计时器对象可以进行相加:`t1+t2`。 +- 只能使用提供的有限资源完成。 \ No newline at end of file diff --git a/Python-Language/14. 模块.md b/Python-Language/15. 模块.md similarity index 94% rename from Python-Language/14. 模块.md rename to Python-Language/15. 模块.md index fcf15db..1e60fec 100644 --- a/Python-Language/14. 模块.md +++ b/Python-Language/15. 模块.md @@ -48,7 +48,6 @@ hello.hi() # Hi everyone, I love lsgogroup! hi() # NameError: name 'hi' is not defined ``` - --- ## 3. 导入模块 @@ -200,7 +199,6 @@ print(const.__name__) 所以,`if __name__ == '__main__'`的意思是:当 .py 文件被直接运行时,`if __name__ == '__main__'`之下的代码块将被运行;当 .py 文件以模块形式被导入时,`if __name__ == '__main__'`之下的代码块不被运行。 - --- ## 5. 搜索路径 @@ -223,7 +221,6 @@ print(sys.path) 搜索路径是在 Python 编译或安装的时候确定的,安装新的库应该也会修改。搜索路径被存储在 `sys` 模块中的 `path` 变量中。 - --- ## 6. 包(package) @@ -343,4 +340,30 @@ from sound.effects import * - https://blog.csdn.net/u010820857/article/details/85330778 --- -**练习题**: \ No newline at end of file +**练习题**: + +1、怎么查出通过 from xx import xx导⼊的可以直接调⽤的⽅法? + +2、了解Collection模块,编写程序以查询给定列表中最常见的元素。 + +题目说明: + +输入:language = ['PHP', 'PHP', 'Python', 'PHP', 'Python', 'JS', 'Python', 'Python','PHP', 'Python'] + +输出:Python + +```python +""" +Input file +language = ['PHP', 'PHP', 'Python', 'PHP', 'Python', 'JS', 'Python', 'Python','PHP', 'Python'] + +Output file +Python +""" +def most_element(language): + """ Return a list of lines after inserting a word in a specific line. """ + + # your code here + + +``` \ No newline at end of file diff --git a/Python-Language/17. datetime模块.md b/Python-Language/16. datetime模块.md similarity index 91% rename from Python-Language/17. datetime模块.md rename to Python-Language/16. datetime模块.md index 6aafe71..4a02f6e 100644 --- a/Python-Language/17. datetime模块.md +++ b/Python-Language/16. datetime模块.md @@ -2,7 +2,6 @@ datetime 是 Python 中处理日期的标准模块,它提供了 4 种对日期和时间进行处理的类:**datetime**、**date**、**time** 和 **timedelta**。 - --- ## 1. datetime类 @@ -281,7 +280,6 @@ print(dt // 7 + 1) # 40 - --- ## 3. time类 @@ -329,7 +327,6 @@ dt = datetime.datetime.combine(date, datetime.time.min) print(dt) # 2019-10-02 00:00:00 ``` - --- ## 4. timedelta类 @@ -411,3 +408,55 @@ print(td.total_seconds()) # 8035200.0 --- **练习题**: + +1、假设你获取了用户输入的日期和时间如`2020-1-21 9:01:30`,以及一个时区信息如`UTC+5:00`,均是`str`,请编写一个函数将其转换为timestamp: + +题目说明: + +```python +""" + +Input file +example1: dt_str='2020-6-1 08:10:30', tz_str='UTC+7:00' +example2: dt_str='2020-5-31 16:10:30', tz_str='UTC-09:00' + +Output file +result1: 1590973830.0 +result2: 1590973830.0 +""" + + +def to_timestamp(dt_str, tz_str): + # your code here + pass +``` + +2、编写Python程序以选择指定年份的所有星期日。 + +题目说明: + +```python +""" + +Input file + 2020 + +Output file + 2020-01-05 + 2020-01-12 + 2020-01-19 + 2020-01-26 + 2020-02-02 + ----- + 2020-12-06 + 2020-12-13 + 2020-12-20 + 2020-12-27 + """ + +def all_sundays(year): + # your code here + +``` + + \ No newline at end of file diff --git a/Python-Language/16. 文件与文件系统.md b/Python-Language/17. 文件与文件系统.md similarity index 91% rename from Python-Language/16. 文件与文件系统.md rename to Python-Language/17. 文件与文件系统.md index e04f25c..22a7a46 100644 --- a/Python-Language/16. 文件与文件系统.md +++ b/Python-Language/17. 文件与文件系统.md @@ -16,15 +16,15 @@ :---:|--- 'r' | 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。 'w' | 打开一个文件只用于写入。
如果该文件已存在则打开文件,并从开头开始编辑。
即原有内容会被删除。
如果该文件不存在,创建新文件。 -'x' | 排他模式,新建一个文件,如果该文件已存在则会报错。 +'x' | 写模式,新建一个文件,如果该文件已存在则会报错。 'a' | 追加模式,打开一个文件用于追加。
如果该文件已存在,文件指针将会放在文件的结尾。
也就是说,新的内容将会被写入到已有内容之后。
如果该文件不存在,创建新文件进行写入。 -'b' | 以二进制模式打开文件 -'t' | 以文本模式打开(默认) +'b' | 以二进制模式打开文件。一般用于非文本文件,如:图片。 +'t' | 以文本模式打开(默认)。一般用于文本文件,如:txt。 '+' | 可读写模式(可添加到其它模式中使用) -【例子】打开一个文件,并返回文件对象,如果该文件无法被打开,会抛出`OSError`。 +【例】打开一个文件,并返回文件对象,如果该文件无法被打开,会抛出`OSError`。 ```python f = open('将进酒.txt') @@ -59,7 +59,7 @@ for each in f: - `fileObject.close()` 用于关闭一个已打开的文件。关闭后的文件不能再进行读写操作, 否则会触发`ValueError`错误。 -【例子】 +【例】 ```python f = open("将进酒.txt") print('FileName:', f.name) # FileName: 将进酒.txt @@ -68,7 +68,7 @@ f.close() - `fileObject.read([size])` 用于从文件读取指定的字符数,如果未给定或为负则读取所有。 -【例子】 +【例】 ```python f = open('将进酒.txt', 'r') line = f.read(20) @@ -80,7 +80,7 @@ f.close() - `fileObject.readline()`读取整行,包括 "\n" 字符。 -【例子】 +【例】 ```python f = open('将进酒.txt', 'r') line = f.readline() @@ -91,7 +91,7 @@ f.close() - `fileObject.readlines()`用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 `for... in ...` 结构进行处理。 -【例子】 +【例】 ```python f = open('将进酒.txt', 'r') lines = f.readlines() @@ -119,7 +119,7 @@ f.close() - `fileObject.tell()`返回文件的当前位置,即文件指针当前位置。 -【例子】 +【例】 ```python f = open('将进酒.txt', 'r') line = f.readline() @@ -134,7 +134,7 @@ f.close() - `offset`:开始的偏移量,也就是代表需要移动偏移的字节数,如果是负数表示从倒数第几位开始。 - `whence`:可选,默认值为 0。给 `offset` 定义一个参数,表示要从哪个位置开始偏移;0 代表从文件开头开始算起,1 代表从当前位置开始算起,2 代表从文件末尾算起。 -【例子】 +【例】 ```python f = open('将进酒.txt', 'r') line = f.readline() @@ -152,7 +152,7 @@ f.close() - `fileObject.write(str)`用于向文件中写入指定字符串,返回的是写入的字符长度。 -【例子】 +【例】 ```python f = open('workfile.txt', 'wb+') print(f.write(b'0123456789abcdef')) # 16 @@ -166,7 +166,7 @@ print(f.read(1)) # b'd' 如果文件打开模式带`b`,那写入文件内容时,`str`(参数)要用`encode`方法转为`bytes`形式,否则报错:`TypeError: a bytes-like object is required, not 'str'`。 -【例子】 +【例】 ```python str = '...' # 文本 = Unicode字符序列 @@ -178,7 +178,7 @@ str = b'...' # 相当于 byte[] ``` -【例子】 +【例】 ```python f = open('将进酒.txt', 'r+') @@ -208,7 +208,7 @@ f.close() - `fileObject.writelines(sequence)`向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符`\n`。 -【例子】 +【例】 ```python f = open('test.txt', 'w+') seq = ['小马的程序人生\n', '老马的程序人生'] @@ -229,7 +229,7 @@ f.close() 关键词 with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行它的清理方法。 -【例子】 +【例】 ```python try: f = open('myfile.txt', 'w') @@ -245,7 +245,7 @@ finally: 这段代码执行完毕后,就算在处理过程中出问题了,文件 f 总是会关闭。 -【例子】 +【例】 ```python try: with open('myfile.txt', 'w') as f: @@ -257,7 +257,6 @@ except OSError as error: # 出错啦!not readable ``` - --- # 2. OS 模块中关于文件/目录常用的函数 @@ -270,7 +269,7 @@ except OSError as error: - `os.getcwd()`用于返回当前工作目录。 - `os.chdir(path)`用于改变当前工作目录到指定的路径。 -【例子】 +【例】 ```python import os @@ -281,9 +280,9 @@ os.chdir(path) print("目录修改成功 : %s" % os.getcwd()) # 目录修改成功 : C:\ ``` -- `os.listdir(path)`返回`path`指定的文件夹包含的文件或文件夹的名字的列表。 +- `listdir (path='.')`返回`path`指定的文件夹包含的文件或文件夹的名字的列表。 -【例子】 +【例】 ```python import os @@ -295,7 +294,7 @@ for item in dirs: - `os.mkdir(path)`创建单层目录,如果该目录已存在抛出异常。 -【例子】 +【例】 ```python import os @@ -308,7 +307,7 @@ os.mkdir(r'.\C\A') # FileNotFoundError - `os.makedirs(path)`用于递归创建多层目录,如果该目录已存在抛出异常。 -【例子】 +【例】 ```python import os os.makedirs(r'.\E\A') @@ -316,7 +315,7 @@ os.makedirs(r'.\E\A') - `os.remove(path)`用于删除指定路径的文件。如果指定的路径是一个目录,将抛出 `OSError`。 -【例子】 +【例】首先创建`.\E\A\text.txt`文件,然后进行删除。 ```python import os @@ -327,7 +326,7 @@ print("目录为: %s" % os.listdir(r'.\E\A')) - `os.rmdir(path)`用于删除单层目录。仅当这文件夹是空的才可以, 否则, 抛出 `OSError`。 -【例子】 +【例】首先创建`.\E\A`目录,然后进行删除。 ```python import os @@ -338,7 +337,7 @@ print("目录为: %s" % os.listdir(r'.\E')) - `os.removedirs(path)`递归删除目录,从子目录到父目录逐层尝试删除,遇到目录非空则抛出异常。 -【例子】 +【例】首先创建`.\E\A`目录,然后进行删除。 ```python import os @@ -349,19 +348,19 @@ print("目录为: %s" % os.listdir(os.getcwd())) - `os.rename(src, dst)`方法用于命名文件或目录,从 `src` 到 `dst`,如果 `dst` 是一个存在的目录, 将抛出 `OSError`。 -【例子】 +【例】把test.txt文件重命名为test2.txt。 ```python import os print("目录为: %s" % os.listdir(os.getcwd())) -os.rename("test", "test2") +os.rename("test.txt", "test2.txt") print("重命名成功。") print("目录为: %s" % os.listdir(os.getcwd())) ``` - `os.system(command)`运行系统的shell命令(将字符串转化成命令) -【例子】 +【例】先自行创建一个a.py的文件,然后由shell命令打开。 ```python import os @@ -377,7 +376,7 @@ os.system('calc') # 打开计算器 - `os.linesep`当前平台使用的行终止符(win下为`\r\n`,Linux下为`\n`) - `os.name`指代当前使用的操作系统(包括:'mac','nt') -【例子】 +【例】 ```python import os @@ -394,7 +393,7 @@ print(os.name) # nt - `os.path.split(path)`分割文件名与路径,返回`(f_path,f_name)`元组。如果完全使用目录,它会将最后一个目录作为文件名分离,且不会判断文件或者目录是否存在。 - `os.path.splitext(path)`分离文件名与扩展名,返回`(f_path,f_name)`元组。 -【例子】 +【例】 ```python import os @@ -418,7 +417,7 @@ print(os.path.splitext(r'C:\test\lsgo.txt')) # ('C:\\test\\lsgo', '.txt') - `os.path.getmtime(file)`返回指定文件的最新的修改时间 - 浮点型秒数,可用time模块的`gmtime()`或`localtime()`函数换算 -【例子】 +【例】 ```python import os import time @@ -443,7 +442,7 @@ print(time.localtime(os.path.getctime(file))) - `os.path.samefile(path1,path2)`判断path1和path2两个路径是否指向同一个文件 -【例子】 +【例】 ```python import os @@ -470,7 +469,7 @@ pickle模块中最常用的函数为: - `file`:文件名称。 -【例子】 +【例】 ```python import pickle @@ -505,8 +504,36 @@ fr.close() # {0: [1, 2, 3, 4], 1: ('a', 'b'), 2: {'c': 'yes', 'd': 'no'}} ``` - --- **参考文献**: - https://www.runoob.com/python3/python3-tutorial.html -- https://www.bilibili.com/video/av4050443 \ No newline at end of file +- https://www.bilibili.com/video/av4050443 + +--- +**练习题**: + +1、打开中文字符的文档时,会出现乱码,Python自带的打开文件是否可以指定文字编码?还是只能用相关函数? + +2、编写程序查找最长的单词 + +输入文档: res/test.txt + +题目说明: + +```python +""" + +Input file + test.txt + +Output file + ['general-purpose,', 'object-oriented,'] + +""" +def longest_word(filename): + # your code here + pass + +``` + + \ No newline at end of file diff --git a/Python-Language/res/test.txt b/Python-Language/res/test.txt new file mode 100644 index 0000000..cb2a56c --- /dev/null +++ b/Python-Language/res/test.txt @@ -0,0 +1,4 @@ +What is Python language? +Python is a widely used high-level, general-purpose, interpreted, dynamic programming language.Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in +languages such as C++ or Java. +Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles.It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with Python. \ No newline at end of file diff --git a/readme.md b/readme.md index 0ed8827..4f22d74 100644 --- a/readme.md +++ b/readme.md @@ -2,7 +2,7 @@ 主要包括: -- Python编程语言 +- [Python编程语言](https://github.com/datawhalechina/team-learning-program/tree/master/Python-Language) - 数据结构与算法