Fork me on GitHub
晴宝

吃饱好减肥


  • 首页

  • 分类

  • 归档

  • 标签

  • 关于

leetcode之100. 相同的树

发表于 2019-01-31 | 分类于 leetcode
字数统计 243 字 | 阅读时长 1 分钟

题目描述:

给定两个二叉树,编写一个函数来检验它们是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

示例 1:

1
2
3
4
5
6
7
8
> 输入:       1         1
> / \ / \
> 2 3 2 3
>
> [1,2,3], [1,2,3]
>
> 输出: true
>

示例 2:

1
2
3
4
5
6
7
8
> 输入:      1          1
> / \
> 2 2
>
> [1,2], [1,null,2]
>
> 输出: false
>

示例 3:

1
2
3
4
5
6
7
8
> 输入:       1         1
> / \ / \
> 2 1 1 2
>
> [1,2,1], [1,1,2]
>
> 输出: false
>
阅读全文 »

leetcode之88. 合并两个有序数组

发表于 2019-01-31 | 分类于 leetcode
字数统计 221 字 | 阅读时长 1 分钟

题目描述:

给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。

说明:

  • 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
  • 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。

示例:

1
2
3
4
5
6
> 输入:
> nums1 = [1,2,3,0,0,0], m = 3
> nums2 = [2,5,6], n = 3
>
> 输出: [1,2,2,3,5,6]
>
阅读全文 »

leetcode之83. 删除排序链表中的重复元素

发表于 2019-01-31 | 分类于 leetcode
字数统计 187 字 | 阅读时长 1 分钟

题目描述:

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

1
2
3
> 输入: 1->1->2
> 输出: 1->2
>

示例 2:

1
2
3
> 输入: 1->1->2->3->3
> 输出: 1->2->3
>
阅读全文 »

leetcode之70. 爬楼梯

发表于 2019-01-31 | 分类于 leetcode
字数统计 227 字 | 阅读时长 1 分钟

题目描述:

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注意:给定 n 是一个正整数。

示例 1:

1
2
3
4
5
6
> 输入: 2
> 输出: 2
> 解释: 有两种方法可以爬到楼顶。
> 1. 1 阶 + 1 阶
> 2. 2 阶
>

示例 2:

1
2
3
4
5
6
7
> 输入: 3
> 输出: 3
> 解释: 有三种方法可以爬到楼顶。
> 1. 1 阶 + 1 阶 + 1 阶
> 2. 1 阶 + 2 阶
> 3. 2 阶 + 1 阶
>
阅读全文 »

leetcode之69. x 的平方根

发表于 2019-01-31 | 分类于 leetcode
字数统计 219 字 | 阅读时长 1 分钟

题目描述:

实现 int sqrt(int x) 函数。

计算并返回 x 的平方根,其中 x 是非负整数。

由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。

示例 1:

1
2
3
> 输入: 4
> 输出: 2
>

示例 2:

1
2
3
4
5
> 输入: 8
> 输出: 2
> 说明: 8 的平方根是 2.82842...,
> 由于返回类型是整数,小数部分将被舍去。
>
阅读全文 »

leetcode之67. 二进制求和

发表于 2019-01-31 | 分类于 leetcode
字数统计 485 字 | 阅读时长 2 分钟

题目描述:

给定两个二进制字符串,返回他们的和(用二进制表示)。

输入为非空字符串且只包含数字 1 和 0。

示例 1:

1
2
3
> 输入: a = "11", b = "1"
> 输出: "100"
>

示例 2:

1
2
3
> 输入: a = "1010", b = "1011"
> 输出: "10101"
>
阅读全文 »

leetcode之66. 加一

发表于 2019-01-31 | 分类于 leetcode
字数统计 655 字 | 阅读时长 3 分钟

题目描述:

给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。

最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。

你可以假设除了整数 0 之外,这个整数不会以零开头。

示例 1:

1
2
3
4
> 输入: [1,2,3]
> 输出: [1,2,4]
> 解释: 输入数组表示数字 123。
>

示例 2:

1
2
3
4
> 输入: [4,3,2,1]
> 输出: [4,3,2,2]
> 解释: 输入数组表示数字 4321。
>
阅读全文 »

Numpy

发表于 2019-01-23 | 分类于 Python
字数统计 188 字 | 阅读时长 1 分钟

Numpy 里的数据结构和Python不同

Numpy Array只存一个Type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Numpy Array只存一个Type
python_list = ['string', 3, 3.2]
print(python_list)

import numpy as np
np_list1 = np.array([1, 2, 3, 4.0])
np_list2 = np.array([1, 2, 3], dtype = 'int')
print(np_list1)
np_list2[0] = 2.33333
print("2.33333 is trunated to %d" %np_list2[0])

# 输出如下所示:
"""
['string', 3, 3.2]
[1. 2. 3. 4.]
2.33333 is trunated to 2
"""

创建办法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import numpy as np

zero_list = np.zeros(5, dtype = int)
one_matrix = np.ones((2, 2), dtype = float)
same_entry_matrix = np.full((1, 2), 2.333)
mean = 0
sd = 1
normal_number_matrix = np.random.normal(mean, sd, (3, 3))
print(zero_list)
print(one_matrix)
print(same_entry_matrix)
print(normal_number_matrix)

# 输出如下所示:
"""
[0 0 0 0 0]
[[1. 1.]
[1. 1.]]
[[2.333 2.333]]
[[-0.16545138 -0.310813 -1.08602781] # 随机的
[ 1.99551174 0.19482657 -0.30166058]
[ 0.60243205 -1.3135839 1.87655078]]
"""

start = 0
end = 10
step = 2
print(type(np.arange(start, end, step)) )

# 输出如下所示:
"""
<class 'numpy.ndarray'>
"""

Python基础知识

发表于 2019-01-21 | 分类于 Python
字数统计 3.9k 字 | 阅读时长 18 分钟

Python 简介

Python 由 Guido van Rossum(龟叔) 于 1989 年年底出于某种娱乐目的而开发。

Python 2 or 3

2008 年 12 月,Python 发布了 3.0 版本(也常常被称为 Python 3000,或简称 Py3k)。Python 3.0 是一次重大的升级,为了避免引入历史包袱, Python 3.0 没有考虑与 Python 2.x 的兼容 。这样导致很长时间以来,Python 2.x 的用户不愿意升级到 Python 3.0,这种割裂一度影响了 Python 的应用。毕竟大势不可抵挡,开发者逐渐发现 Python 3.x 更简洁、更方便。现在,绝大部分开发者已经从 Python2.x 转移到 Python 3.x,但有些早期的 Python 程序可能依然使用了 Python 2.x 语法。
2020年1月1日,Python2正式推出历史舞台。 宣布不在对Python2进行更新。
因此,不管是Python新手还是老手,新开发的Python程序都需要用Python 3进行开发。

Python 的特点

Python 是一种 面向对象 、 解释型 、 弱类型 的脚本语言,它也是一种功能强大而完善的通用型语言。

  • 面向对象

  • 解释型

  • 弱类型

    Python的设计哲学是 “优雅”、“明确”、“简单” ,如果之前你使用过其他的语言,再来使用Python,一
    定会被它的简洁、优雅所震惊。相比其他编程语言(比如 Java),Python 代码非常简单,上手非常容
    易。比如我们要完成某个功能,如果用 Java 需要 100 行代码,但用 Python 可能只需要 20 行代码,这是 Python 具有巨大吸引力的一大特点。
    我们以 输出1-10之间的所有偶数 为例进行说明Python代码的简洁:
    python代码

    1
    2
    >   res = [ i for i in rangge(1, 11) if i % 2 == 0]
    >

Java代码

1
2
3
4
5
6
>   for(int i=1; i<=10; i++){
> if (i%2 == 0) {
> System.out.println(i);
> }
> }
>

《Java编程思想》的作者Bruce Eckel这样评价Python:“ life is short you need python ”

Python 的两大特色是清晰的语法和可扩展性 :

  • Python 的语法非常清晰,它甚至不是一种格式自由的语言。例如,它要求 if 语句的下一行必须向
    右缩进,否则不能通过编译。
  • Python 的可扩展性体现为它的模块,Python 具有脚本语言中最丰富和强大的类库(这些类库被形
    象地称为“batteries included ,内置电池”),这些类库覆盖了文件 I/O、GUI、网络编程、数据库访问、文本操作等绝大部分应用场景

    此外,Python 的社区也很发达,即使一些小众的应用场景,Python 往往也有对应的开源模块来提供解决方案。
    Python 作为一门解释型的语言,它天生具有跨平台的特征,只要为平台提供了相应的 Python 解释器,
    Python 就可以在该平台上运行。

    解释型语言几乎天然是跨平台的
    

    Python 自然也具有解释型语言的一些弱点 :

  1. 速度慢:Python 程序比 Java、C、C++ 等程序的运行效率都要慢。
  2. 源代码加密困难:不像编译型语言的源程序会被编译成目标程序,Python 直接运行源程序,因此
    对源代码加密比较困难。

应用领域

在世界编程语言排行榜中, Python最近几年一直霸占到前三的地位,并且还有一直上升的趋势:
Python目前几乎在所有的应用领域都有所成就,可以编程语言界的 全栈语言 :
云计算 :云计算最火的语言, 典型应用OpenStack
大数据 :几乎所有的大数据组件都开发Python接口,如PySpark
Web开发 :众多优秀的WEB框架,众多大型网站均为Python开发,Youtube, 知乎, 豆瓣等等, 典型
WEB框架有Django、Flask等。
科学计算 : 数据分析工具:NumPy, SciPy, Pandas, Matplotlib等
人工智能 : 深度学习:TensorFlow、PyTorch、PandlePandle
系统运维 :Python脚本,Ansible等
桌面界面开发 :PyQT, WxPython,TkInter
嵌入式开发 :MicroPython
网络爬虫 : 著名的爬虫框架Scrapy, BeautifulSoup, Requests等库

Python 安装

Python or Anconda?

Python官网:https://www.python.org
Anaconda官网:https://www.anaconda.com

Anaconda

Anaconda就是可以便捷获取包且对包能够进行管理,同时对环境可以统一管理的发行版本。Anaconda
包含了conda、Python在内的超过180个科学包及其依赖项。
Anaconda具有如下特点:

  • 开源

  • 安装过程简单

  • 高性能使用Python和R语言

  • 免费的社区支持

    其特点的实现主要基于Anaconda拥有的:

    • conda包

    • 环境管理器

    • 1,000+开源库

安装方式选择

离网环境 : 离网环境下使用Anaconda进行安装
联网环境 :

  • Windows : 使用Anaconda进行安装
  • Linux :使用python原生包进行安装
  • Mac :使用Python原生包进行安装

Python 库安装

Python Package Index:https://pypi.org

联网安装

1、安装最新库

1
pip install XXX

2、安装执行版本库

1
pip install xxx==version

3、升级库到最新版本

1
pip install —upgrade XXX

4、卸载库

1
pip uninstall XXX

联网加速

由于 pip 默认使用 Python 的官方源 pypi.python.org/pypi ,导致我们经常使用pip装包时速度过慢
或者无法安装(请求超时)等问题,所以国内用户建议使用 pip 国内源。
目前常用的 pip 国内源有:
豆瓣:http://pypi.douban.com/simple(推荐)
清华:http://pypi.tuna.tsinghua.edu.cn/simple

Windows 配置

新建 %HOME%\pip\pip.ini 文件,内容如下:

1
2
3
4
5
[global]
index-url = https://pypi.douban.com/simple
trusted-host = pypi.douban.com
disable-pip-version-check = true
timeout = 120

Linux配置

创建 ~/.pip 目录 ,新建 ~/.pip/pip.conf 文件,内容如下:

1
2
3
4
5
6
7
[global]
timeout =6000
index-url =http://pypi.douban.com/simple/
[install]
use-mirrors =true
mirrors =http://pypi.douban.com/simple/
trusted-host =pypi.douban.com

离线安装

需要在 https://pypi.org 上查找自己需要的库进行安装。

whl包安装

注意:选对 Python版本
numpy-1.19.1-cp38-cp38-manylinux1_x86_64.whl
cp38代表python 3.8
x86_64代表64位操作系统

1
pip install xxx.whl

tar/zip 包安装

此方式适配所有 python 版本

1
2
3
unzip numpy-1.19.1.zip
cd numpy-1.19.1
python setup.py install

Python 虚拟环境

Conda常用命令

1
2
3
conda list # 查看安装了哪些包
conda env list # 查看当前存在哪些虚拟环境
conda update conda # 更新当前conda

创建虚拟环境

1
conda create -n your_env_name python=x.x

your_env_name: 虚拟环境的名字
x.x :python版本,如 3.6

激活虚拟环境

1
conda activate your_env_name

退出虚拟环境

1
conda deactivate

删除虚拟环境

1
2
conda remove -n your_env_name --all # 删除所有
conda remove -n your_env_name package_name # 删除虚拟环境中的包

生成 requirements.txt

python 项目如何在另一个环境上重新构建项目所需要的运行环境依赖包?

生成 requirements.txt,有两种方式。

单虚拟环境

1
pip freeze > requirements.txt

为什么只适用于单虚拟环境?因为这种方式,会将环境中的依赖包全都加入,如果使用的全局环
境,则下载的所有包都会在里面,不管是不时当前项目依赖的。

使用 pipreqs

1
2
3
4
# 安装
pip install pipreqs
# 在当前目录生成
pipreqs . --encoding=utf8 --force

–force 强制执行,当 生成目录下的requirements.txt存在时覆盖。
这种方式,只生成当前项目下的依赖

Python基础语法

Boolean and its Opeations

1
2
3
4
5
6
7
8
9
10
11
# Boolean and its Operations
print(type(True))
print(type(False))
print(type(None))

# 输出如下所示:
"""
<class 'bool'>
<class 'bool'>
<class 'NoneType'>
"""

And Or

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# and or
B = True
A = False

print(B and True)
print(A or B)
print(not B)
print(not A)
print(B and (not A))

# 输出如下所示:
"""
True
True
False
True
True
"""

Expressions can evaluate to a boolean value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Expressions can evaluate to a boolean value
print(3 >= 2)
print(2 >= 2)
print(A is A)
print(A is B)
print(3 != 2)

# 输出如下所示:
"""
True
True
True
False
True
"""

Integer and floats

1
2
3
4
5
6
7
8
9
# Integer and floats
print(type(3))
print(type(3.0))

# 输出如下所示:
"""
<class 'int'>
<class 'float'>
"""

Numerical operations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Numerical operations
import math

print(3 / 2)
print(5 // 2)
print(3 % 2)
print(float(3))
print(pow(2, 3))
print(math.ceil(3.4))
print(math.floor(3.4))
print(round(3.1415926, 2))

# 输出如下所示:
"""
1.5
2
1
3.0
8
4
3
3.14
"""

String

  • strings are useful because they are immutable(它们不可变)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# String
Introduction = 'Today is 2019-01-21'
print(Introduction)
print(str(3))
print(int('3'))
print(str("b'AS"))

# String Method
A = 'abc'
print(A.capitalize())
print(A.upper())
print(A.find('b'))
print(A.find('d'))

# String formatting
s = 'My name is Tom'
name = 'Tomas'
age = 25
score = 98.532421
print('hello, my name is %s and I am %d years old\n \ I scored %f on my midterm'%(name, age, score))
print('hello, my name is %s and I am %d years old\n \
I scored %.2f on my midterm'%(name, age, score))

# 输出如下所示:
"""
Today is 2019-01-21
3
3
b'AS

Abc
ABC
1
-1

hello, my name is Tomas and I am 25 years old
\ I scored 98.532421 on my midterm
hello, my name is Tomas and I am 25 years old
I scored 98.53 on my midterm
"""

List

  • Mutable(可变的)
  • Iterable
  • Sequence Type
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# List 
# Create and Modify list
A = []
A.append(1)
A
# List index and Slicing
# length = n, start from 0 and end at (n-1)
A = [1, 2, 3, 4, 5, 6]
print(len(A))
print(A[0])
A[0] = 100
print(A[0])
A[1:4]
print(A[1:4]) # 不会输出索引4的数

# What exactly is "iterable"?
for item in A[2:5]:
print(item)
A = [1, 2]
A.append('2')
print(A)
A[0] = 's'
print(A)
print(list('abc') )

# 输出如下所示:
"""
6
1
100
[2, 3, 4]

3
4
5
[1, 2, '2']
['s', 2, '2']
['a', 'b', 'c']
"""

Method and Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Method
A = list((2, 1, 3))
print(A)
A.sort(reverse = True) # A的值发生了改变
print(A)
# Function
print(sorted(A)) # A的值没有改变
print(A)

# 输出如下所示:
"""
[2, 1, 3]
[3, 2, 1]
[1, 2, 3]
[3, 2, 1]
"""

Tuple

  • Similar to list 和list类似
  • But it is immutable(hashable) 但它是不可变的 support for hash(), a built-in function
  • Can have repeated value可以有重复的元素
  • Sequence Type
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# Tuple
# Create Tuple
A = tuple([1, 2, 3, 2])
print(A)
print(A[0])
print(A[2:4])
print(A[:4])
print(A[::])
print(A[:-1])
B = tuple([1, 2, 3, 4])
print(B[::-1])

A[0] = 's'
print(A)

C = tuple()
print(C)
C = 1,
print(C)
D = (1)
print(type(D))


# 输出如下所示:
"""
(1, 2, 3, 2)
1
(3, 2)
(1, 2, 3, 2)
(1, 2, 3, 2)
(1, 2, 3)
(4, 3, 2, 1)

A[0] = 's'
TypeError: 'tuple' object does not support item assignment

()
(1,)
<class 'int'>
"""

Set

  • Unordered 没有顺序
  • Contain hashable elements( so it is again immutable) 里面的元素必须是hashable
  • No repetition 没有重复
  • Not a sequence type
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Set
A = set([1, 1, 2])
B = set(['Michal', 'Betty'])
print(A)
print(len(A))
print(B)
print(len(B))

C = set([1], [2])
print(C)

# Set Arithmetics
A = set([1, 2, 3])
B = set([3, 4, 5])
print('A intersects B')
print(A & B)
print('A unions B')
print(A | B)
print('in A not in B')
print(A - B)
print('add 5 into A')
A.add(5)
print(A)
print('new A after adding 5')
print(A)
print('remove 2 in A')
A.remove(2)
print(A)
print('new A after reoving 2')
print(A)

# 输出如下所示:
"""
{1, 2}
2
{'Michal', 'Betty'}
2

C = set([1], [2])
TypeError: set expected at most 1 arguments, got 2

A intersects B
{3}
A unions B
{1, 2, 3, 4, 5}
in A not in B
{1, 2}
add 5 into A
{1, 2, 3, 5}
new A after adding 5
{1, 2, 3, 5}
remove 2 in A
{1, 3, 5}
new A after reoving 2
{1, 3, 5}
"""

Common operations on List, Set, Tuple

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Use tuple for demonstration here
A = (1, 2, 3)
print(len(A))

for item in A:
print(item)

print(1 in A)

# 输出如下所示:
"""
3
1
2
3
True
"""

Dictionary

  • Very fast for look up( O(1) compared to O(N) in list) 非常快
  • Mapping Type (think of “Map” as “Match”) #### Keys
  • Arbitary values 任意值
  • Must be hashable(i.e. Immutable, will explain later) 必须是不变的
  • We may also call them “index”(pandas) 有时候也称为index #### Values
  • No restrictions, can be mutable 没有限制
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Dictionary
def simple_function(a, b, c):
print(a)
print(b)
print(c)

simple_function(1, 2, 3)
simple_function(c = 3, a = 1, b = 2)
simple_function(1, c = 3, b = 2)

# 输出如下所示:
"""
1
2
3
1
2
3
1
2
3
"""

#### Create List 创建list
midterm1 = {'Michael': 98, 'Betty': 96}
print(midterm1)

final = dict() # 一个空字典
print(final)

midterm2 = dict(Michael = 98, Betty = 96)
print(midterm2)

midterm3 = dict([('Michael', 98), ('Betty', 96)])
print(midterm3)

print(midterm1 == midterm2 == midterm3)

midterm4 = dict([('Michael', 98), ('Betty', 96), ('Michael', 90)])
print(midterm4)

midterm1['Michael'] = 97
print(midterm1)

for key in midterm1:
print(key)

print(midterm1.keys())
print(midterm1.values())

# 输出如下所示:
{'Michael': 98, 'Betty': 96}
{}
{'Michael': 98, 'Betty': 96}
{'Michael': 98, 'Betty': 96}
True
{'Michael': 90, 'Betty': 96}
{'Michael': 97, 'Betty': 96}
Michael
Betty
dict_keys(['Michael', 'Betty'])
dict_values([97, 96])

Ranges

  • Start 开始
  • Stop 结束
  • Step 步的大小
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Ranges
print(list(range(10)))
print(list(range(0, 10, 3)))
print(list(range(0, -10, -1)))
print(list(range(0)))
print(list(range(1, 0)))

r = range(10)
print(5 in r)
print(r[1])

# 输出如下所示:
"""
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 3, 6, 9]
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
[]
[]
True
1
"""

Hashable

  • map name strings to 15 integers
  • red = a collision
  • think of them as many buckets
  • theoretically more than one items in every single bucket, but we say the look up is O(1)
1
2
3
4
5
6
7
8
9
# Hashable
print(hash('apple'))
print(hash(((1, -1, 0), (1, 0, 0), (1, 0, -1))))
print(hash(((1, 0, -1), (1, 0, 0), (1, -1, 0))))

# 输出如下所示:
-4061574024490551516
-697649482279922733
-697649482279922733

Loop and Conditionals

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# If Statement
name = 'Kesci'
if name == 'Kesci':
print(name)

tool = 'Klab'
if tool != 'Kesci':
print(tool)

# Use Good Grammar for Efficiency
# if if if
# if elif else
number = 10
def print_silly(x):
if number == 10:
print('checking the first one')
print('equal to 10')
if number <= 10:
print('checking the second one')
print('no less than 10')
if number >= 10:
print('checking the third one')
print('no more than 10')

def print_clever(x):
if number == 10:
print('checking the first one')
print('equal to 10')
elif number <= 10:
print('checking the second one')
print('no less than 10')
elif number >= 10:
print('checking the third one')
print('no more than 10')

print_silly(10)
print_clever(10)


# 输出如下所示:
"""
Kesci
Klab

checking the first one
equal to 10
checking the second one
no less than 10
checking the third one
no more than 10

checking the first one
equal to 10
"""

# For Loop
# When you know when to stop 当你知道你什么时候停止
count = 0
for number in range(10):
count = count + number
print(count)

# 输出如下所示:
"""
0
1
3
6
10
15
21
28
36
45
"""

# While loop
# Interchangeable with for loop 可以和for loop互换
# Must use this one if you don't know when to stop 当你不知道什么时候停下来
# Easy to have bug( forever looping) if you forget to modify your condition 容易有bug
unknown_condition = 100
my_number = 10
while my_number < unknown_condition:
my_number = my_number + 10
print(my_number)

print('I am out of while loop now')
print(my_number)

# 输出如下所示:
"""
20
30
40
50
60
70
80
90
100
I am out of while loop now
100
"""

# Nest your if statement in your loops:
# Use indentation
unknown_condition = 100
my_number = 0
while my_number < unknown_condition:
if my_number % 2 == 0:
my_number = my_number + 10
print(my_number)
else:
my_number = my_number + 5
print(my_number)

print('I am out of while loop now')
print('my_number is %d in the end'%my_number)

# 输出如下所示:
"""
10
20
30
40
50
60
70
80
90
100
I am out of while loop now
my_number is 100 in the end
"""

2-D List, List Aliasing, Shallow or Deep Copy

  • Where we get most bugs
  • You think you get a new list, but you are getting the same one in reality “牵一发动全身” “一改全改了”
  • When you are copying a list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
A = [1,2]
B = A[:]
print(B)

print(B is A)

A = [[1,2,3],[4,5,6]]
B = A[:]
print(A)
print(B)

B[1][2] = 100
print(B)

print(A)

print(A is B)
print(A[0] is B[0])
print(A[1] is B[1])

# 输出如下所示:
"""
[1, 2]
False
[[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 100]]
[[1, 2, 3], [4, 5, 100]]
False
True
True
"""

[[1, 2, 3], [4, 5, 100]]
[[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 100]]
# We call B a shallow copy of A, to make a deep copy,
# we need to use the copy.deepcopy function
import copy
A = [[1,2,3],[4,5,6]]
B = copy.copy(A)
B[1][2] = 100
print(A) # same as [:]

A = [[1,2,3],[4,5,6]]
B = copy.deepcopy(A)
B[1][2] = 100
print(A)
print(B)

# 输出如下所示:
"""
[[1, 2, 3], [4, 5, 100]]
[[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 100]]
"""

Python操作数据库

安装

1
pip install mysqlclient

导入依赖包

1
import MySQLdb

建立数据库连接

1
2
3
4
5
6
7
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='root',
db ='django_study',
)

获取游标

1
2
# 通过获取到的数据库连接conn下的cursor()方法来创建游标。
cur = conn.cursor()

通过游标执行SQL

1
2
3
4
5
6
7
8
9
10
11
12
# 创建数据表,通过游标cur 操作execute()方法可以写入纯sql语句。通过execute()方法中写入sql语句
来对数据进行操作
cur.execute("create table student(id int ,name varchar(20),class varchar(30),age
varchar(10))")
# 插入一条数据
cur.execute("insert into student values('1','Tom1','3 year 2 class','9')")
# conn.commit()方法在提交事物,在向数据库插入一条数据时必须要有这个方法,否则数据不会被真正的
插入。
conn.commit()
# 查询数据
cur.execute("select * from student")
resultOne = cur.fetchone()

关闭连接

1
2
3
4
# cur.close() 关闭游标
cur.close()
# conn.close()关闭数据库连接
conn.close()

剑指Offer之和为S的连续正数序列

发表于 2019-01-18 | 分类于 剑指Offer
字数统计 695 字 | 阅读时长 2 分钟

题目描述:

小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!

输出描述:

1
2
> 输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
>
阅读全文 »
1…121314…16
晴宝宝

晴宝宝

151 日志
10 分类
18 标签
GitHub
© 2017 - 2021 晴宝宝
由 Hexo 强力驱动
主题 - NexT.Muse