python学习入门(2)---

发布时间:2017-6-29 9:34:36编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"python学习入门(2)---",主要涉及到python学习入门(2)---方面的内容,对于python学习入门(2)---感兴趣的同学可以参考一下。

思想

  • 穷举法
  • 猜测-检验
  • 二分法
  • 分而治之

函数

函数体定义方式

def 
<function name> (<formal parameters>):
    <function body>

docstring用于描述一个函数的功能

def myFunction(argument):
   ""'''
   Docstring goes here. Explain what type argument(s) should have, and what your function
   is going to return.
   """

   < Code for`这里写代码片` your function (the body of the function) goes here >

hint

1.
f函数的定义如下

def f(x, y):
   x + y - 2
   return None

运行如下代码段 :
1)

print(f)

运行结果为

function

2)

print(f(1,2))

运行结果为

None

函数体的应用- - -异常处理

二分法寻找根

code1

def findRoot1(x, power, epsilon):
    low = 0
    high = x
    ans = (high+low)/2.0
    while abs(ans**power - x) > epsilon:
        if ans**power < x:
            low = ans
        else:
            high = ans
        ans = (high+low)/2.0
    return ans

##print findRoot1(25.0, 2, .001)
##print findRoot1(27.0, 3, .001)
##print findRoot1(-27.0, 3, .001)
so can't find cube root of negative number

code2

def findRoot2(x, power, epsilon):
    if x < 0 and power%2 == 0:
        return None
    # can't find even powered root of negative number
    low = min(0, x)
    high = max(0, x)
    ans = (high+low)/2.0
    while abs(ans**power - x) > epsilon:
        if ans**power < x:
            low = ans
        else:
            high = ans
        ans = (high+low)/2.0
    return ans

##print findRoot2(25.0, 2, .001)
##print findRoot2(27.0, 3, .001)
##print findRoot2(-27.0, 3, .001)
##
##print findRoot2(0.25, 2, .001)
##print findRoot2(-0.125, 3, .001)
# can't find even powered root of negative number

code3

def findRoot3(x, power, epsilon):
    if x < 0 and power%2 == 0:
        return None
    low = min(-1.0, x)
    high = max(1.0, x)
    ans = (high+low)/2.0
    while abs(ans**power - x) > epsilon:
        if ans**power < x:
            low = ans
        else:
            high = ans
        ans = (high+low)/2.0
    return ans

print findRoot3(25.0, 2, .001)
print findRoot3(27.0, 3, .001)
print findRoot3(-27.0, 3, .001)

print findRoot3(0.25, 2, .001)
print findRoot3(-0.125, 3, .001)

调用另外文件中的函数

(1)定义外部函数circle.py

# circle.py
# From Lecture 4, Modules

pi = 3.14159

def area(radius):
    return pi*(radius**2)

def circumference(radius):
    return 2*pi*radius

(2)引用外部函数

import circle

(3)使用外部函数
在cmd中使用 . 这个符号

circle.radius
circle.area(3)
circle.circumference(3)

String

index和find

index和find都是返回索引,但二者之间是有一定的区别的,具体参考

递归

1.计算 a^b

迭代

def iterPower(base, exp):
    '''
    base: int or float.
    exp: int >= 0

    returns: int or float, base^exp
    '''
    result = 1
    while exp > 0:
        result *=base
        exp -= 1
    return result

递归

def recurPower(base, exp):
    '''
    base: int or float.
    exp: int >= 0

    returns: int or float, base^exp
    '''
    # Your code here
    if exp==0:
        return 1
    else:
        return base*recurPower(base,exp-1)

2.计算a,b的最大公约数

迭代

def gcdIter(a, b):
    '''
    a, b: positive integers

    returns: a positive integer, the greatest common divisor of a & b.
    '''
    testValue = min(a, b)

    # Keep looping until testValue divides both a & b evenly
    while a % testValue != 0 or b % testValue != 0:
        testValue -= 1

    return testValue

递归

def gcdRecur(a, b):
    '''
    a, b: positive integers

    returns: a positive integer, the greatest common divisor of a & b.
    '''
    if a<b:
        t=a
        a=b
        b=t
    if(b==0):
        return a
    else:
        return gcdRecur(b,a%b)

3.Tower of Hanio

递归

def printMove(fr, to):
    print('move from ' + str(fr) + ' to ' + str(to))

def Towers(n, fr, to, spare):
#终止条件:只有一个物体,直接从from移动到to
    if n == 1:
        printMove(fr, to)
    else:
    #3步:
    #(1)将n-1个物体由from移动到spare,借助to
    #(2)将1个物体由from移动到to,借助spare
    #(3)将n-1个物体由spare移动到to,借助from
        Towers(n-1, fr, spare, to)
        Towers(1, fr, to, spare)
        Towers(n-1, spare, to, fr)

4.Fibonacci

def fib(x):
    """assumes x an int >= 0
       returns Fibonacci of x"""
    assert type(x) == int and x >= 0
    if x == 0 or x == 1:
        return 1
    else:
        return fib(x-1) + fib(x-2)

5.非数字应用- - -回文串的判定

分析

预处理

1.将所有的字符都变为小写模式
2.删除所有的空格和标点符号

终止条件

若字符为1个或者0个,那么它为回文字符串

递归条件

如果首字符和尾字符相同,那么如果字符串为回文结构等价于中间的字符串为回文字符串

代码

def isPalindrome(s):

    def toChars(s):
        s = s.lower()
        ans = ''
        for c in s:
            if c in 'abcdefghijklmnopqrstuvwxyz':
                ans = ans + c
        return ans

    def isPal(s):
        if len(s) <= 1:
            return True
        else:
            return s[0] == s[-1] and isPal(s[1:-1])

    return isPal(toChars(s))

6.求出字符串的长度

迭代

def lenIter(aStr):
    '''
    aStr: a string

    returns: int, the length of aStr
    '''
    # Initialize a variable to hold our final count
    count = 0

    # Iterate over each character in the string, counting each one
    for char in aStr:
        count += 1
    return count

递归

def lenRecur(aStr):
    '''
    aStr: a string

    returns: int, the length of aStr
    '''
    # Your code here
    if(aStr==''):
        return 0
    else:
        return 1+lenRecur(aStr[1:])

7.判定字符是否在字符串中出现

前提条件:字符串为有序列

分析

终止条件

1.当len(aStr)==0 时,返回False
2.当 aStr长度为1 且aStr与char不同时,返回False

递归条件

1.test the middle character of a string against the character you’re looking for (the “test character”). If they are the same,return False
2.If they’re not the same, check if the test character is “smaller” than the middle character.
If so, we need only consider the lower half of the string;
3.otherwise, we only consider the upper half of the string. (Note that you can compare characters using Python’s < function.)

代码

def isIn(char, aStr):
    '''
    char: a single character
    aStr: an alphabetized string

    returns: True if char is in aStr; False otherwise
    '''
    # Your code here
    mid=len(aStr)/2
    if aStr=='':
        return False
    elif len(aStr)==1 and char!=aStr:
       return False
    else:
        if char==aStr[mid]:
            return False
        elif char<aStr[mid]:
            return isIn(char,aStr[0:mid])
        else:
            return isIn(char,aStr[mid+1:])

全局变量

全局变量可以适用于全局

def fibMetered(x):
    #每次都说明numCalls是一个全局变量
    global numCalls
    numCalls += 1
    if x == 0 or x == 1:
        return 1
    else:
        return fibMetered(x-1) + fibMetered(x-2)


def testFib(n):
    for i in range(n+1):
    #全局变量使用之前设置为0
        global numCalls
        numCalls = 0
        print('fib of ' + str(i) + ' = ' + str(fibMetered(i)))
        print('fib called ' + str(numCalls) + ' times')

对象

复合数据类型

  • Tuples(元祖)
  • Lists(列表)
  • Dictionaries(字典)

Tuples

(1)

t1=(1,'two',3)
print(t1)

运行结果为 :

(1,'two',3)

(2)

t2=(t1,'four')

运行结果为 :

((1,'two',3),'four')

contatenation

t1+t2

运行结果为 :

(1,'two',3,(1,'two',3),'four')

Indexing

(1)

(t1+t2)[3]

运行结果为

(1,'two',3)

(2)

(t1+t2)[3:5]

运行结果为 :

((1,'two',3),'four')

strange comma

(1)代码

(3)

运行结果为

3

此时

(3)

的数据类型为int
(2)代码

(3,)

运行结果为

(3,)

此时,

(3,)

的数据类型为 tuple

示例代码- - -取奇数的元素

def oddTuples(aTup):
    '''
    aTup: a tuple

    returns: tuple, every other element of aTup. 
    '''
    # Your Code Here
    a=()
    for i in range(len(aTup)):
        if i%2==0:
            a=a+(aTup[i],)
    return a

注意:

a=a+(aTup[i],)

Lists

形式

看起来与tuple类似:

  • 有序值的序列,每一个值被索引值标识
  • Use [1, 2, 3] rather than (1, 2, 3)
  • Singletons are now just [4] rather than (4, )

与 tuple的区别

Lists可变
tuple, int, float, str不可改变,不能进入并修改其中的元素值
因而 Lists被创建之后可以被修改

概念区分

前提

Techs = ['MIT', 'Cal Tech']
Ivys = ['Harvard', 'Yale', 'Brown']

Consider

Univs= [Techs, Ivys]
Univs1 = [ ['MIT', 'Cal Tech'],['Harvard', 'Yale', 'Brown']]

1.输出内容看起来相同

2.往其中添加对象时,显示出不同性

Techs.append('RPI')
print(Univs) 
Print(Univs1) 

显示结果

Univs = [ ['MIT', 'Cal Tech','RPI'],['Harvard', 'Yale', 'Brown']]
Univs1 = [ ['MIT', 'Cal Tech'],['Harvard', 'Yale', 'Brown']]

原因 :绑定
这里写图片描述

这种现象被称为别名

操作

List的所有操作–python指南

1. Iteration

功能 : 输出每一个单词以及单词中包含的字母

for e in Univs:
    print('Univs contains')
    print(e)
    print('which contains')
    for u in e:
        print('' + u)

2.往List后插入元素

两种方式 :(1)append (2)+

1)append
Techs.append('RPI')

append用于往List后面添加一个对象,会改变原先的列表。

2)+ 序列化

所有元素都在同一水平

flat = Techs + Ivys

结果为:

['MIT','Cal Tech', 'RPI','Harvard','Yale','Brown']

3.remove

L1.remove(e1)

在list中移除某一项

  • Inside for loop,Python keeps track of where it is in listusing internal counter
  • When we mutate a list, we change its length but Python doesn’t update counter

4.Cloning

1.现有问题
L1=[1,2,3,4]
L2=[1,2,4,5]

removeDups函数:

def removeDups (L1, L2):
for e1 in L1:
if e1 in L2:
    L1.remove(e1)

此时,期待的运行结果为

L1=[3,4]

但是,实际情况是

L1=[2,3,4]

不符合预期结果
原因 :
在迭代中,Python 会更新列表元素信息,但是并不会更新计数器

2.更好的解决方案 - - -cloning
def removeDupsBetter(L1, L2):
    L1Start = L1[:]
    for e1 in L1Start:
    if e1 in L2:
        L1.remove(e1)

5.is ==

aList=list(range(1,5))
bList=list(range(1,5))
print(aList==bList)
print(aList is bList)

运行结果
True
False

6.L的元素可以为function

EG1:对每一个x进行多种操作

def applyFuns (L, x):
for f in L:
    print(f(x))

EG2:同一种操作对每一个x进行

# applyToEach

def applyToEach(L, f):
    """assumes L is a list, f a function
       mutates L by replacing each element, e, of L by f(e)"""
    for i in range(len(L)):
        L[i] = f(L[i])


L = [1, -2, 3.4]

def fact(n):
    if n == 1:
        return 1
    else:
        return n*fact(n-1)

def fib(n):
    if n == 0 or n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

applyToEach(L, abs)
print(L)

applyToEach(L, int)
print(L)

applyToEach(L, fact)
print(L)

applyToEach(L, fib)
print(L)

6.map

map类似与List的功能调用,但是可以用于高阶的函数上
(1)

map(abs, [1, -2, 3, -4])

运行结果

[1, 2, 3, 4]

(2)
General form – an n-­‐ary function and n collections of arguments

L1 =[1,28,36]
L2=[2,57,9]    
map(min,L1,L2)    

结果

[1,28,9] 

Dictionaries

键值对

语法

monthNumbers = { ‘Jan’:1, ‘Feb’:2, ‘Mar’:3, 1:’Jan’,2:’Feb’,3:’Mar’}

1)

monthNumbers[1]

return 1


上一篇:hdoj2079 选课时间(题目已修改,注意读题) (母函数)
下一篇:基于centos6.x安装部署superset

相关文章

相关评论

本站评论功能暂时取消,后续此功能例行通知。

一、不得利用本站危害国家安全、泄露国家秘密,不得侵犯国家社会集体的和公民的合法权益,不得利用本站制作、复制和传播不法有害信息!

二、互相尊重,对自己的言论和行为负责。

好贷网好贷款