Upload
moke
View
48
Download
6
Embed Size (px)
DESCRIPTION
School of Computer and Information Science Southwest Forestry University 201 3 . 9. Introduction to Computer Programming. 计算机编程导论. 西南林业大学 计算机与信息学院 201 3 . 9. Review. Chapter 1 sequential programming Use computers to solve problems Essentials of program design Flow chart - PowerPoint PPT Presentation
Citation preview
Introduction to Computer
ProgrammingSchool of Computer and Information Science
Southwest Forestry University
2013.9
计算机编程导论
西南林业大学计算机与信息学院
2013.9
Review
Chapter 1 sequential programming• Use computers to solve problems• Essentials of program design– Flow chart– Program running– Problem-solving process
• Sequential programming
复习
第 1 章 顺序程序设计– 用计算机解决问题的方法– 程序设计要素• 流程图• 程序运行过程• 解决问题的过程
– 顺序程序设计
Chapter 2 Using Array
• Array are frequently used in storing data in program design. Almost every kind of programming language provides a array data structure, such as C and Basic provide one-dimensional, multi-dimensional array.
• Python provides the richest, the most flexible, and the most powerful forms in program design.
• This chapter describes the array structures (lists, tuples, dictionaries) in Python, and how to use them to achieve simple and powerful programs.
第 2 章 使用序列
• 序列是程序设计中经常用到的数据存储方式,几乎每一种程序设计语言都提供了表格数据结构,如 C 和 Basic 中的一维、多维数组等。
• Python 提供的序列类型在所有程序设计语言中是最丰富,最灵活,也是功能最强大的。
• 本章介绍使用 Python 中常用的序列结构(列表、元组、字典)来实现一些简单而又功能强大的程序。
2.1 Array Problem
[Q2-1] Data sorting• Description: Read 5 data from the
keyboard, output in ascending order.• Solutions 1: Use five variables to store
data, compare and sort.
2.1 序列问题
【问题 2-1 】 数据排序问题• 问题描述:由用户从键盘输入五个数据,按升
序排序后输出。 • 解决方案一:用五个变量来存储输入的五个数
据,再用一一比较和交换来达到排序的目的。
2.1 序列问题问题 2-1 程序:#data sort Ques2_1_0.py
x1 = input(' 请输入第 1 个元素 :')x2 = input(' 请输入第 2 个元素 :')x3 = input(' 请输入第 3 个元素 :')x4 = input(' 请输入第 4 个元素 :')x5 = input(' 请输入第 5 个元素 :')
# 将前两个元素排好序if x1>x2: x1,x2=x2,x1 # 将前三个元素排好序if x1>x3: x1,x2,x3=x3,x1,x2elif x2>x3: x2,x3=x3,x2
# 将前四个元素排好序 if x1>x4: x1,x2,x3,x4=x4,x1,x2,x3elif x2>x4: x2,x3,x4=x4,x2,x3elif x3>x4: x3,x4=x4,x3
# 将前五个元素排好序 if x1>x5: x1,x2,x3,x4,x5=x5,x1,x2,x3,x4elif x2>x5: x2,x3,x4,x5=x5,x2,x3,x4elif x3>x5: x3,x4,x5=x5,x3,x4elif x4>x5: x4,x5=x5,x4
# 输出排序结果print(x1,x2,x3,x4,x5)
2.1 Array Problem
Shortcoming of Solution 1:• Need to define many variables to store
data• The program is not complex, but tedious,
error-prone• When sorting more data, such as 50, the
programming becomes intolerable• When sorting even more data, such as
1000, it will be ridiculous to write a program in this way.
2.1 序列问题
解决方案一存在的问题:• 需要定义多个变量来存储数据• 程序虽不复杂,但很繁琐,写起来容易出错• 当待排序数据达到一定量,如 50 个时,这样
的编程方式变得无法忍受• 当待排序数据达到一定量,如 1000 个时,这
样的程序无法编,无法看……
2.1 Array Problem
Solution 2:Use List
Analysis:
• Input ten data, and store them in a list
• Use python's sort () method to sort the list data and output. 结束
输出排序后的结果
开始
用 sort( ) 方法对列表中数据进行排序
输入 10 个数据存放在列表中
图 2-1 数据排序流程图
2.1 序列问题
解决方案二:使用列表
分析:• 将用户输入的十个数
据存放到一个列表中• 用 python 的 sort( )
方法对列表中数据进行排序后输出。
结束
输出排序后的结果
开始
用 sort( ) 方法对列表中数据进行排序
输入 10 个数据存放在列表中
图 2-1 数据排序流程图
2.1 序列问题问题 2-2 程序: #data sort:Ques2_1.py
data_list=[ ] # 初始化一个空列表
# 循环十次,输入十个数字放到列表中for integer in range(10): x=input(' 请输入第 '+str(integer+1)+' 个元
素: ') data_list=data_list+[x]
print ' 排序前数据: ',data_list
# 用 sort 方法对列表中的数据进行排序data_list.sort()
print ' 排序后数据: ',data_list
方案二优点:• 不管数据量多大,只用定义一
个列表变量• 程序简单,程序代码量不随数
据量变大而增加• 程序可以调用 Python 内置函
数来实现排序……
2.1 序列问题输入及程序运行结果:请输入第 1 个元素: 54请输入第 2 个元素: 23请输入第 3 个元素: 67请输入第 4 个元素: 84请输入第 5 个元素: 41请输入第 6 个元素: 68请输入第 7 个元素: 34请输入第 8 个元素: 56请输入第 9 个元素: 98请输入第 10 个元素: 61排序前数据: ['54', '23', '67', '84', '41', '68', '34', '56', '98', '61']排序后数据: ['23', '34', '41', '54', '56', '61', '67', '68', '84', '98']
2.1 Array Problem
[Q2-2] Dictionary problem• Description: Find keyword explained.• Analysis: some words are stored in the
dictionary, the key is the first letter of the word, the value is the explanation of the word. The user enters a valid letter, the program queries the corresponding word and output it. If the input is out of range, the program ends.
2.1 序列问题
【问题 2-2 】 查字典问题 • 问题描述:根据用户输入的关键字的简写查询
相应名称解释。• 分 析:将一些程序设计中常用名称存放在
字典中,键是其英文的第一个字母,值是该名称的解释。由用户输入要查询的名称的英语第一个字母,若在合法的范围内则进行查询、输出,若不在范围内则结束程序。
2.1 序列问题
算法流程图:
开始
定义字典
结束
图 2-2 查字典流程图
输入 a~e 范围内的字母
输出查字典的结果
2.1 序列问题问题 2-2 程序:#Dictionary Search:Ques2_2.py
# 定义字典dic={"a":"algorithm ,算法,解决一种问题的大致步
骤 ","b":"bug ,臭虫,程序里的错误 ","c":"compile ,编译,把用高级程序语言写的程序转换成低级语言 ","d":"debugging ,除虫,找到及移除程序设计错误的过程 ","e":"exception ,异常,执行错误的另一个名称 "}
# 输入要查询的关键字以便进行字典查询keyword=raw_input(' 请输入要查询的名词关键字( a ~
e ) :')
# 输入 a ~ e 之间的关键字则进行查询,否则结束程序while keyword>='a' and keyword<='e': print dic[keyword] keyword=raw_input(' 请输入要查询的名词关键字( a ~ e
) :')
2.1 序列问题
输入及程序运行结果:请输入要查询的名词关键字( a ~ e ): b
bug ,臭虫,程序里的错误请输入要查询的名词关键字( a ~ e ): d
debugging ,除虫,找到及移除程序设计错误的过程
请输入要查询的名词关键字( a ~ e ): x
>>>
2.2 Array BasicsArray: A series of values, which are usually
related to, and in a certain order.Array c :•Include 12 integer elements•Use Array : Array name +[position number]•The position of the first element is 0, c[0]•The second element is c[1]•The i-th element is c[i-1]Array can also be accessed from the rear:•The last element is c[-1]•Penultimate 2 is c[-2]Position number — also known as "the subscript" or "Index"
2.2 序列基础知识序列:一系列连续值,它们通常是相关的,并且按一定
顺序排列。序列 c :•12 个整数元素•引用元素:序列名+ [位置编号 ]•第 1 个元素的位置编号为 0 , c[0]•第 2 个元素是 c[1]•第 i 个元素是 c[i-1] 序列也可以从尾部访问 :•最后一个元素是 c[-1]•倒数第 2 个是 c[-2]•倒数第 i 个元素是 c[-i]位置编号——也称“下标”或“索引” ,是整数或整数表达式。
2.3 ListList: A list is an ordered set of values, where each
value is identified by an index.• The elements of a list can be any type• Each data in the list called an element• All its elements are separated by commas and placed
in the bracket "[" and "]"List of examples:• [10, 20, 30, 40] #All the elements are integer data• ['crunchy frog', 'ram bladder', 'lark vomit'] #All the elements are strings• ['spam', 2.0, 5, [10, 20]] #The list contains a string
element, a floating-point type element, an integer elements and a list
2.3 列表列表:• 是 Python 中内置数据类型,是一个元素的有序集合• 一个列表中的数据类型可以各不相同• 列表中的每一个数据称为元素• 其所有元素用逗号分割并放在一对中括号“ [” 和“ ]” 中列表举例:• [10, 20, 30, 40] # 所有元素都是整型数据的列表• ['crunchy frog', 'ram bladder', 'lark vomit'] # 所有
元素都是字符串的列表• ['spam', 2.0, 5, [10, 20]] # 该列表中包含
了一个字符串元素、一个浮点类型元素、一个整型元素和一个列表类型元素
2.3 List(1) Create: use the "=" to assign a list to a variable.For example:
>>> a_list = ['a', 'b', 'mpilgrim', 'z', 'example']
(2) Read elements We can access an element in the list by using the variable
name and an index number. Pay attention to the list of the first elements of a serial number 0.
For example:
>>> print(a_list[2])
mpilgrim
Note: If a list has n elements, then the valid range is from -n to n-1, when the index number x is negative, indicating that the counting starts from the right, and the actual index number of the element is n + x .
2.3 列表( 1 )创建列表:使用“ =” 将一个列表赋值给变量。例如:>>> a_list = ['a', 'b', 'mpilgrim', 'z', 'example']( 2 )读取元素 用变量名加元素序号(放中括号中)即可访问列表中某个元素,注意列表的第一个元素序号为 0 。
例如:>>> print(a_list[2])mpilgrim注意:若一个列表有 n 个元素,则访问元素的合法序号范
围是 -n ~ n-1 ,当序号 x为负时,表示从右边计数,其访问的元素实际为序号为 n+x 的元素。
2.3 列表例如:>>> print(a_list[-1])example>>> print(a_list[-5])a>>> print(a_list[-7])Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> print(a_list[-7])IndexError: list index out of range>>> print(a_list[5])Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> print(a_list[5])IndexError: list index out of range
a_list = ['a', 'b', 'mpilgrim', 'z', 'example']
2.3 List(3) Slices• Use a range of indexes to intercept any
part of the list to get a new list.• The first number represents the slice start
position, and the second number represents the slice cutoff (but does not contain) position.
For example:>>> print(a_list[1:3])['b', 'mpilgrim']>>> print(a_list[1:-1])['b', 'mpilgrim', 'z']
a_list = ['a', 'b', 'mpilgrim', 'z', 'example']
2.3 列表
( 3 )列表切片 可以使用列表序号对来截取列表中的任何部分从而
得到一个新列表。序号对中第一个序号表示切片开始位置,第二个序号表示切片截止(但不包含)位置。
例如:>>> print(a_list[1:3])
['b', 'mpilgrim']
>>> print(a_list[1:-1])
['b', 'mpilgrim', 'z']
2.3 列表注意:当切片的左索引为 0 时可缺省,当右索引为列表长度时也可缺省。例如:>>> print(a_list[:3])['a', 'b', 'mpilgrim']>>> print(a_list[3:])['z', 'example']>>> print(a_list[:])['a', 'b', 'mpilgrim', 'z', 'example']
a_list = ['a', 'b', 'mpilgrim', 'z', 'example']
2.3 List(4) Adding elementsMethod 1: Use the "+" and a new list attached to
the tail of the original list;>>> a_list = [1]>>> a_list = a_list + ['a', 2.0]>>> a_list[1, 'a', 2.0 ]Method 2: Using append () method adds a new
element to the end of the list;>>> a_list.append(True)>>> a_list[1, 'a', 2.0, True ]
2.3 列表( 4 )增加元素方法一:使用“ +” 将一个新列表附加在原列表的尾部;>>> a_list = [1]
>>> a_list = a_list + ['a', 2.0]
>>> a_list
[1, 'a', 2.0]
方法二:使用 append( ) 方法向列表尾部添加一个新元素;
>>> a_list.append(True)
>>> a_list
[1, 'a', 2.0, True]
2.3 List
Method 3: Use the extend () method to add a list at the tail of the original list;
>>> a_list.extend(['x', 4])>>> a_list[1, 'a', 2.0, True, 'x', 4 ]
Method 4: Use the insert () method to add an element into the list anywhere.
>>> a_list.insert(0, 'x')>>> a_list['x', 1, 'a', 2.0, True, 'x', 4]
2.3 列表方法三:使用 extend( ) 方法将一个列表添加在原列表
的尾部;>>> a_list.extend(['x', 4])>>> a_list[1, 'a', 2.0, True, 'x', 4]
方法四:使用 insert( ) 方法将一个元素插入到列表的任意位置。
>>> a_list.insert(0, 'x')>>> a_list['x', 1, 'a', 2.0, True, 'x', 4]
2.3 List(5) Search• Use count ( ) method to calculate the number
of an element in the list;>>> a_list.count('x')2
• Use ”in” Operator checking whether an element is in the list;
• >>> 3 in a_listFalse>>> 2.0 in a_listTrue
a_list = ['x', 1, 'a', 2.0, True, 'x', 4]
2.3 列表( 5 )检索元素使用 count( ) 方法计算列表中某个元素出现的次数;>>> a_list.count('x')2
使用 in 运算符返回某个元素是否在该列表中;>>> 3 in a_listFalse>>> 2.0 in a_listTrue
2.3 列表• Use the index () method to return the exact
location of an element in the list;• 使用 index() 方法返回某个元素在列表中的准确位置;
>>> a_list.index('x')0>>> a_list.index(5)Traceback (most recent call last): File "<pyshell#33>", line 1, in <module> a_list.index(5)ValueError: 5 is not in list
a_list = ['x', 1, 'a', 2.0, True, 'x', 4]
2.3 List(6) Delete an element When adding or removing elements, the
list will automatically expand or shrink. The list will never have gaps.
Method 1: Use the “del” statement to delete the elements at a particular location
>>> del a_list[1]>>> a_list['x', 'a', 2.0, True, 'x', 4]
a_list = ['x', 1, 'a', 2.0, True, 'x', 4]
2.3 列表
( 6 )删除元素 当向列表中添加或删除元素时,列表将自动
拓展或收缩,列表中永远不会有缝隙。
方法一:使用 del 语句删除某个特定位置的元素>>> del a_list[1]
>>> a_list
['x', 'a', 2.0, True, 'x', 4]
2.3 列表Method2: Use
“remove()” method to remove an element with a particular value
方法二:使用remove 方法删除某个特定值的元素
>>> a_list.remove('x')>>> a_list['a', 2.0, True, 'x', 4]>>> a_list.remove('x')>>> a_list['a', 2.0, True, 4]>>> a_list.remove('x')Traceback (most recent call last): File "<pyshell#51>", line 1, in
<module> a_list.remove('x')ValueError: list.remove(x): x not
in list
a_list = ['x', 'a', 2.0, True, 'x', 4]
2.3 列表Method three: Use pop() method to pop out the element at the
specified location. The last element is popped out if no parameters given.
方法三:使用 pop(参数 ) 方法来弹出(删除)指定位置的元素,缺省参数时弹出最后一个元素。
>>> a_list.pop( )4>>> a_list['a', 2.0, True]>>> a_list.pop(1)2.0>>> a_list['a', True]>>> a_list.pop(1)True>>> a_list['a']
>>> a_list.pop( )'a'>>> a_list[ ]>>> a_list.pop( )Traceback (most recent call last): File "<pyshell#61>", line 1, in <module> a_list.pop( )IndexError: pop from empty list
2.3.3 Function of the list1. cmp( )Format : cmp(List1 , List2)Function : Compare the two lists , returns
1 when the first list is greater than the second, on the contrary returns -1, when the two elements of the list is the same returns 0
2. len( )Format : len(List)Function : Returns the number of elements
in the list
2.3.3 列表常用函数
1. cmp( )格式: cmp( 列表 1 ,列表 2)功能:对两个列表进行比较,若第一个列表大于
第二个,则结果为 1 ,相反则为 -1 ,元素完全相同则结果为 0 。
2. len( )格式: len( 列表 )功能:返回列表中的元素个数。
2.3.3 Function of the list>>> list1=[123,'xyz']>>> list2=[123,'abc']>>> cmp(list1,list2)1>>> list2=[123,'z']>>> cmp(list1,list2)-1>>> list2=list1>>> cmp(list1,list2)0>>> len(list1)2
2.3.3 Function of the list
3. max( ),min( )
Format : max(List), min(List)
Function : Return the largest or smallest element in the list
>>>
str_l=['abc','xyz','123']
>>> num_l=[123,456,222]
>>> max(str_l)
'xyz'
>>> min(str_l)
'123'
>>> max(num_l)
456
>>> min(num_l)
123
2.3.3 列表常用函数
3. max( ) 和 min( )
格式: max( 列表 ), min( 列表 )
功能:返回列表中的最大或最小元素。
>>>
str_l=['abc','xyz','123']
>>> num_l=[123,456,222]
>>> max(str_l)
'xyz'
>>> min(str_l)
'123'
>>> max(num_l)
456
>>> min(num_l)
123
2.3.3 Function of the list
4. sorted( )
reversed( )
Format :sorted(List), reversed(List)
Function : Sorting or Reverse
>>> list=[1,4,3,6,9,0,2]
>>> for x in reversed(list):
print x,
2 0 9 6 3 4 1
>>> sorted(list)
[0, 1, 2, 3, 4, 6, 9]
>>> sorted(list,reverse=True)
[9, 6, 4, 3, 2, 1, 0]
2.3.3 列表常用函数
4. sorted( ) 和reversed( )
格式: sorted( 列表 ), reversed( 列表 )
功能:前者的功能是对列表进行排序,默认是按升序排序,还可在列表的后面增加一个 reverse参数,其等于 True则表示按降序排序;后者的功能是对列表进行逆序。
>>> list=[1,4,3,6,9,0,2]
>>> for x in reversed(list):
print x,
2 0 9 6 3 4 1
>>> sorted(list)
[0, 1, 2, 3, 4, 6, 9]
>>> sorted(list,reverse=True)
[9, 6, 4, 3, 2, 1, 0]
2.3.3 Function of the list5. sum( )
Format : sum(List),
Function : Summing the numerical list of elements
>>> sum(list)
25
>>> sum(str_l)
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
sum(str_l)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
2.3.3 列表常用函数5. sum( )
格式: sum( 列表 )
功能:对数值型列表的元素进行求和运算,对非数值型列表运算则出错。
>>> sum(list)
25
>>> sum(str_l)
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
sum(str_l)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
书面作业
1.习题 2.1
2.习题 2.2
上机作业
1. 将本章课件中涉及的所有源程序在Python下输入、调试并运行;
2. 将本章课件中所有的交互式命令在Python 的 IDLE 中调试;
3. 将前面两个书面作业的程序上机调试、运行。