Python_week1 学习笔记

References

《Python Week2》, Department of Development, EESAST, THU
https://www.runoob.com/python3/python3-data-type.html
https://www.runoob.com/python3/python3-number.html
https://www.runoob.com/python3/python3-string.html
https://blog.csdn.net/qq_41088475/article/details/107944558
https://www.runoob.com/python3/python3-loop.html
https://www.runoob.com/python3/python3-conditional-statements.html
https://www.runoob.com/python3/python3-errors-execptions.html
https://www.runoob.com/python3/python3-tuple.html
https://www.runoob.com/python3/python3-list.html
https://www.runoob.com/python3/python3-dictionary.html
https://www.runoob.com/python3/python3-set.html

课前问题

a) What’s the fundamental and intrinsic difference between Python and C++?
Which one is faster? How to run Python/C++ code in command line?
(You don’t need to actually run them though)
b) Install Python.
• For Windows users, you can install Anaconda or install a WSL (Windows subsystem for Linux).
• For MacOS users, Anaconda is also supported in MacOS, or you can
switch your MacOS default Python version according to this page.
While the official Anaconda site is given, it’s also important to switch
Anaconda/pip source, because download speed of default source is too
slow. See Tsinghua mirror site for Anaconda installation help and pip
usage help.
Python version 3.7 or higher is recommended.
(Hint: There’s a DETAILED install instruction in the hyperlinks of Anaconda and WSL! Please follow them exactly.)
Open your terminal (Anaconda terminal or MacOS terminal) and type
python to verify your installation.
c) (Optional) Configure your editor if you prefer to use one. Visual Studio
Code, PyCharm or jupyter notebook is recommended.
d) Learn basic data types, e.g. int, str, float, bool, and assignment statement.
Which is iterable and which is not?
e) Learn basic control flows in Python, e.g. for loop of iterable objects, while
loop, if/else, try-except-finally and so on.
f) Learn basic data structures in Python, e.g. tuple, list, dict, set and so on.
Which is immutable and which is not?
g) Learn slice and operations of iterable objects, e.g. reverse, split, append,
pop and so on.
h) (Optional) Python build-in functions, e.g. range, len, reverse, enumerate,
slice, isinstance and so on.

尝试解答

d) Learn basic data types, e.g. int, str, float, bool, and assignment statement. Which is iterable and which is not?
# int, float, bool, complex: bool中0/1可以直接做整型相加减
x = 5 + 4    # 9
x = 4.3 - 2  # 2.3
x = 3 * 7    # 21
x = 2 / 4    # 0.5
x = 2 // 4   # 0
x = 17 % 3   # 2
x = 2 ** 5   # 32
del var_a, var_b  # 可删除
abs(x)
fabs(x)           # import math
ceil(x)           # 上入整数, import math
exp(x)            # import math
floor(x)          # 下舍整数, import math
log(x)            # 自然对数, import math
log10(x)          # import math
max(x1, x2,...)
min(x1, x2,...)
modf(x)           # 返回小数部分和整数部分, import math
pow(x, y)         # import math
round(x [,n])     # 四舍五入
sqrt(x)           # import math
acos(x)           # import math
asin(x)           # import math
atan(x)           # import math
atan2(y, x)       # import math
cos(x)            # import math
sin(x)            # import math
tan(x)            # import math
hypot(x, y)       # sqrt(x*x + y*y), import math
degrees(x)        # import math
radians(x)        # import math
pi, e             # import math
choice(seq)                          # import random
randrange ([start,] stop [,step])    # import random
random()                             # import random
seed([x])                            # import random
shuffle(lst)                         # 序列随机排序, import random
uniform(x, y)                        # 在[x, y]内随机产生一个实数, import random

# str: Python中没有字符类型,且字符串无法改变,且均为Unicode字符
str = 'Runoob'
print (str)        
print (str[0:-1])                             # 输出第一个到倒数第二个的所有字符
print (str[0])       
print (str[2:5])                              # 输出从第三个开始到第五个的字符    [start:end:step] <==> for (i = start; i < end; i = i + step)
print (str[2:])                               # 输出从第三个开始的后的所有字符
print (str * 2)                               # 输出字符串两次,也可以写成 print (2 * str)
print (str + "TEST")                          # 连接字符串
print('Ru\noob')
print(r'Ru\noob')                             # 直接输出原始字符串,不考虑转义字符
print("line1 \
... line2 \
... line3")                                   # line1 line2 line3
print ("我叫 %s 今年 %d 岁!" % ('小明', 10))   # 我叫 小明 今年 10 岁!
para_str = """这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( \t )。
也可以使用换行符 [ \n ]。
"""

# iterable: list, str, tuple, dict, file, xrange
e) Learn basic control flows in Python, e.g. for loop of iterable objects, while loop, if/else, try-except-finally and so on.
# for loop of iterable objects
for <variable> in <sequence>:
    <statements>
else:
    <statements>

# while loop
while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
# simple while
while (flag): print ('欢迎访问菜鸟教程!')

# if/else
if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3

# try-except-finally
# try-except
while True:
    try:
        x = int(input("请输入一个数字: "))
        break
    except ValueError:
        print("您输入的不是数字,请再次尝试输入!")
# try-except(...,...,...)
except (RuntimeError, TypeError, NameError):
    pass
# try-except-except-...
try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise
# try-except-else
for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()
# try-except-finally
try:
    runoob()
except AssertionError as error:
    print(error)
else:
    try:
        with open('file.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)
finally:
    print('这句话,无论异常是否发生都会执行。')
f) Learn basic data structures in Python, e.g. tuple, list, dict, set and so on. Which is immutable and which is not?
# tuple
tup1 = ('Google', 'Runoob', 1997, 2000)
tup3 = "a", "b", "c", "d"
tup1 = (50)               # type(tup1) == <class 'int'>
tup1 = (50,)              # type(tup1) == <class 'tuple'>
tup3 = tup1 + tup2        # 可拼接
del tup                   # 可删除
len(tuple) 
max(tuple)
min(tuple)
tuple(iterable)
(1, 2, 3) + (4, 5, 6)             # (1, 2, 3, 4, 5, 6)
('Hi!',) * 4                      # ('Hi!', 'Hi!', 'Hi!', 'Hi!')
3 in (1, 2, 3)                    # True
for x in (1, 2, 3): print (x,)    # 1 2 3

# list
list1 = ['Google', 'Runoob', 1997, 2000]
del list[2]       # 可删除
x[0][1]           # 可嵌套
len(list)
max(list)
min(list)
list(seq)         # 元组转换为列表
list.append(obj)
list.count(obj)
list.extend(seq)  # 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
list.index(obj)
list.insert(index, obj)
list.pop([index=-1])
list.remove(obj)
list.reverse()
list.sort( key=None, reverse=False)
list.clear()
list.copy()
[1, 2, 3] + [4, 5, 6]                    # [1, 2, 3, 4, 5, 6]
['Hi!'] * 4                              # ['Hi!', 'Hi!', 'Hi!', 'Hi!']
3 in [1, 2, 3]                           # True
for x in [1, 2, 3]: print(x, end=" ")    # 1 2 3

# dict: <key>可为数字、字符串、元组(不可为列表)
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8                 # 可更新
dict['School'] = "docs"         # 可直接添加
del dict['Name']                # 可删除
del dict
len(dict)
str(dict)                       # 输出字典,以可打印的字符串表示
type(variable)
radiansdict.clear()
radiansdict.copy()                         # 浅复制
radiansdict.fromkeys(seq[, value])         # 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
radiansdict.get(key, default=None)
key in dict
radiansdict.items()                        # 以列表返回可遍历的(键, 值) 元组数组
radiansdict.keys()                         # 返回一个迭代器,可以使用 list() 来转换为列表
radiansdict.values()
radiansdict.setdefault(key, default=None)  # 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
radiansdict.update(dict2)
pop(key[,default])
popitem()

# set
a = set('abracadabra')                              # {'a', 'r', 'b', 'c', 'd'}
b = set('alacazam')                                 # {'c', 'm', 'z', 'l', 'a'}
a - b                                               # {'r', 'd', 'b'}
a | b                                               # {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
a & b                                               # {'a', 'c'}
a ^ b                                               # {'r', 'd', 'b', 'm', 'z', 'l'}
a = {x for x in 'abracadabra' if x not in 'abc'}    # {'r', 'd'}
s.add(x)
s.update(x)                                   # 参数可以是列表,元组,字典等
s.remove(x)
s.discard(x)                                  # 如果元素不存在,不会发生错误
s.pop()
s.clear()
s.copy()
s.difference(x)  
s.difference_update(x)                        # 直接更新s
s.intersection(set1, set2 ... etc)
s.intersection_update(set1, set2 ... etc)
s.isdisjoint(x)
s.issubset(x)
s.issuperset(x)
s.symmetric_difference(x)
s.symmetric_difference_update(x)
s.union(set1, set2...)
len(s)
x in s

# immutable: tuple

课后任务

Two Sum

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i] + nums[j] == target:
                    return i,j

String Compression

class Solution:
    def compressString(self, S: str) -> str:
        if not S:
            return ""
        s1 = S
        l1 = len(s1)
        s2 = ''
        tmp = s1[0]
        tmp1 = 1

        for i in range(1,l1):
            if s1[i] != tmp:
                s2 = s2 + tmp + str(tmp1)
                tmp = s1[i]
                tmp1 = 1
            else:
                tmp1 = tmp1 + 1
        
        s2 = s2 + tmp + str(tmp1)
        if len(s2) < l1:
            return s2
        else:
            return s1

Restore IP Addresses

class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        l = len(s)
        ans = ""
        anslist = []

        def dfs(tmp, now):
            nonlocal ans
            if tmp > 3:
                if now >= l:
                    return
                if l - 1 - now > 2:
                    return
                if (l - 1 > now) and (s[now] == '0'):
                    return
                tmpint = int(s[now:l])
                if tmpint <= 255:
                    ans = ans + s[now:l]
                    anslist.append(ans)
                return

            for i in range(now, l):
                if i - now > 2: 
                    break
                if (i > now) and (s[now] == '0'):
                    break
                if int(s[now:i+1]) > 255:
                    break
                tmpans = ans
                ans = ans + s[now:i+1] + '.'
                dfs(tmp + 1, i + 1)
                ans = tmpans

        dfs(1,0)
        return anslist

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值