函數模塊字符串列表

函數python

'''算法

定義一個函數要使用def語句,依次寫出函數名、括號、括號中的參數和冒號,而後在縮進塊中編寫函數體,函數的返回值用return語句返回編程

定義函數: def f(a,b):
服務器

                         return a + bapp

參數能夠賦默認值好比 a=0, b=0,參數也能夠這樣寫: def f(*args),即爲參數可爲任意值,例如:dom

def f (*args):ide

        total = 0函數

  for val in args:ui

    total += valspa

    return total 

my_list = [1, 3, 5, 10, 20]

print(f(*mylist))               (把列表看成可變參數傳到函數裏面,要加*號,即把列表裏面的元素進行操做)

 

'''

模塊

'''

from 模塊名 import 制定的函數

關鍵字:from, import, as

做用域-LEGB(local, enclose, global, build- in)    全局變量最好不要用

a = 100

def f():

    global a

    a = 200

    b = 'hello'

        def g():

            nonlocal b

            b = 'good'   

 

'''

字符串

內存管理

'''

 

棧-變量-地址-對象的引用

堆-真正的對象

id()

is

靜態區

(給服務器寫程序,避免內存泄漏,防止崩潰)(python才用自動垃圾回收)

例子:

import sys
list1 = [0]* 10
list2 = list1
list3 = list2
print(sys.getsizeof(list1))
print(sys.getrefcount(list1))
del list2
del list3     
print(sys.getrefcount(list1)) 

 

'''

列表

'''

生成式的語法:mylist = [x ** 2 for x in range(1, 10)]       (計算速度慢可是內存佔用少)

mylist = mylist + [20, 30]

刪除元素: del,remove

取出列表一部分- 切片(起始位置,終止位置,步長)

列表排序: sort, 排好序的新列表:sorted

tuple和list 很是類似(獲取元素的方法是同樣的)可是tuple一旦初始化後就不能修改

'''

'''

生成器

經過列表生成式,咱們能夠直接建立一個列表,可是受內存限制,列表容量確定是有限的,並且建立一個包含一百萬個元素的列表,不只佔用很大的儲存空間,若是咱們僅僅須要訪問前面幾個元素,那後面絕大多數的元素佔用的空間都白白浪費了。因此若是列表元素能夠按照某種方法推算出來,那麼咱們是否能夠在循環中不斷推算出後續的元素呢?這樣就沒必要建立完整的list,從而節省大量的空間。在python中,一邊循環一邊計算的的機制,被稱爲生成器:generator

L = [x ** x for x in range(10)]

g = (x * x for x in range(10))

建立L和g的區別僅在於最外層的[]和(),L 是一個list,而g是一個generator。generator保存的是算法,每次調用next(g),就計算出下一個值,直到計算到最後一個元素,沒有更多的元素時,拋出 StopIteration的錯誤。

斐波拉契數列用函數打印出來:

def fib(max):

    n,a,b = 0,0,1

    while n < max:

        print(b)

        a,b = b, a + b

        n = n +1 

    return 'done' 

'''

'''

迭代器

能夠直接做用於for循環的數據類型有:list,tuple,dict,set,str等,一類是generator,包括生成器和帶yield的generator function,這些能夠直接做用於for循環的對象稱爲可迭代對象:Iterable。

''' 

類和實例

'''

面向對象最重要的概念就是類(class)和實例(instance),類是抽象的模版,好比Student類,而實例是根據類建立出來的一個個具體的‘對象’,每一個對象都擁有相同的方法,但各自的數據有可能不一樣。因爲類能夠起到模版的做用,所以,能夠在建立實例的時候,把一些咱們認爲必須綁定的屬性強制填寫進去,經過定義一個特殊的函數‘__init__’方法,在建立實例的時候,就把name,score等屬性綁定上去

class Student(object):

 

    def __init__(self, name, score):

        self.name = name

        self.score = score

注意到__init__方法的第一個參數永遠是self,表示建立實例自己,所以在__init__方法內部,就能夠把各類屬性綁定到self,由於self就指向建立的實例自己。有了__init__方法,在建立實例的時候,就不能穿入空參數了,必須傳入與__init__方法匹配的參數,可是self不須要傳參,python解釋器會自動把實例變量傳進去。

面向對象編程的一個重要特色就是數據封裝,在student類中,每一個實例就擁有各自的name和score這些數據,咱們能夠經過函數來訪問這些數據,好比打印一個學生的成績:

 

    def print_score(std):

...     print('%s: %s' % (std.name, std.score))

...

>>> print_score(bart)

Bart Simpson: 59

可是,既然student實例自己就擁有這些數據,要訪問這些數據,就沒有必要從外面的函數去訪問,能夠直接在student類的內部定義訪問數據的函數,這樣就把‘數據’給封裝起來了。這些封裝數據的函數是和student類自己是關聯起來的,咱們稱之爲類的方法:

 

class Student(object):

 

    def __init__(self, name, score):

        self.name = name

        self.score = score

 

    def print_score(self):

        print('%s: %s' % (self.name, self.score))

咱們從外部看student類,就只須要知道,建立實例須要給出name和score,而如何打印,都在student類內部定義的,這些數據和邏輯被封裝起來了,調用很容易,但殊不知道內部實現的細節。

封裝的另外一個好處是,能夠給student類增長新的方法,好比get_grade:

 

class Student(object):

    ...

 

    def get_grade(self):

        if self.score >= 90:

            return 'A'

        elif self.score >= 60:

            return 'B'

        else:

            return 'C'

小結:類是建立實例的模版,而實例則是一個個具體的對象,各個實例擁有的數據都相互獨立,互不影響;

方法就是與實例綁定的函數,和普通函數不一樣,方法能夠直接訪問實例數據;

經過在實例上調用方法,咱們就直接操做了對象內部的數據,但無需知道方法內部的實現細節;

和靜態語言不一樣,python容許對實例變量綁定任何數據,也就是說,對於兩個實例變量,雖然它們都是同一個類的不一樣實例,但擁有的變量名稱均可能不一樣。

 

 

'''

例題:

 

1.約瑟夫環問題(30我的,有15個基督徒,數到9的人踢出去,最後剩下15個全是基督徒,問非基督徒的位置)

 

 

def main():
    person = [True] * 30   #表示30我的都活着
    counter = 0            # counter = 15 中止循環
    index = 0              #第幾我的在報數
    number = 0
    while counter < 15:
        if person[index]:
            number += 1
            if number == 9:
                person[index] = False
                counter += 1
                number = 0
        index += 1
        if index >= len(person):
            index = 0
    for p in person:
        print('基督徒' if p else '不是基督徒', end=' ')



if __name__ == '__main__':
    main()
2.用元組找出一個list裏面第二大的數
def second_max(x):
    (m1, m2) = (x[0], x[1]) if x[0] > x[1] else (x[1], x[0])
    for index in range(2, len(x)):
        if x[index] > m1:
            m2 = m1
            m1 = x[index]
        elif m1 > x[index] > m2:
            m2 = x[index]
    return m2

def main():
    my_list = [35,79,99,92,90,50,60,70,40,10,22,99,99]
    print(second_max(my_list))

if __name__ == '__main__':
    main()

 3.設計一個函數,傳入三個參數:年月日。返回傳入的年月日是這一年的第幾天

def is_leap_year(y):
     if y % 4 == 0 and y % 100 !=0 or y % 400 == 0:
         return True
         return False

def which_day(year, month, day):
     days_of_month = [
     [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
     [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
     ][is_leap_year(year)]                                   # 經過是不是閏年來返回bool值,bool值可返回0或者1
     total = 0
     for index in range(month - 1):
         total += days_of_month[index]
         return total + day


 if __name__ == '__main__':
     print(which_day(1908,11,28))
     print(which_day(1908,3, 8))
     print(which_day(1981,12,31))
Vi
def is_leap_year(y):
if y % 4 == 0 and y % 100 !=0 or y % 400 == 0:
return True
return False

def which_day(year, month, day):
days_of_month = [
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
][is_leap_year(year)] # 經過是不是閏年來返回bool值,bool值可返回0或者1
total = 0
for index in range(month - 1):
total += days_of_month[index]
return total + day


if __name__ == '__main__':
print(which_day(1908,11,28))
print(which_day(1908,3, 8))
print(which_day(1981,12,31))
ew Code

 4.生成一個楊輝三角,給行數(例如10),生成楊輝三角

def triangle():
    n = [1]
    while True:
        yield n
        n.append(0)
        n = [n[i - 1] + n[i] for i in range(len(n))]

def num_triangle():
    n = 0
    for t in triangle():
        print(t)
        n = n + 1
        if n == 10:
            break


if __name__ == '__main__':
    num_triangle()

5. 給定一個成績列表,去掉最高分和最低分,求平均值

def main():
    names = ['劉備', '張飛', '趙雲', '關羽', '諸葛亮', '曹操', '馬超']
    score_list = []
    total = 0
    for name in names:

        score = input('請輸入%s的成績:' %name)
        score_list.append(score)
        min_score = max_score = score_list[0]
    for score in score_list:
        if score > max_score:
            max_score = score
        elif score < min_score:
            min_score = score
            total += int(score)
    score_list.remove(max_score)
    score_list.remove(min_score)

    print('平均成績是:%.1f' %(total/len(score_list)))

if __name__ == '__main__':
    main()

6. 雙色球- 6個紅色球(1~33)和1個藍色球(1~16)

from random import randrange, randint


def display(balls):
    for index, ball in enumerate(balls):
        if index == len(balls) - 1:
            print('|', end = ' ')
        print('%02d' %ball, end = ' ')
    print()


def random_select():
    red_balls = list(range(1, 34))
    selectd_balls = []
    for _ in range(6):
        index = randrange(0, len(red_balls))
        selectd_balls.append(red_balls[index])
        del red_balls[index]
    selectd_balls.sort()
    selectd_balls.append(randint(1,16))
    return selectd_balls


def main():
    n = int(input('機選幾注?'))

    for _ in range(n):
        display(random_select())


if __name__ == '__main__':
    main()

7. 十階樓梯,小孩走可能一次走一級,或者兩級也或者三級,問最多有多少走法

def foo(n):

    if n < 0:
        return 0
    elif n == 0:
        return 1
    return foo(n-1) + foo(n - 2) + foo(n - 3)
if __name__ == '__main__':
     print(f(100))
     print(foo(10))

 

8. 猜數字

from random import randint


def main():
    user_input = int(input("please input the number you want computer guess>>>:"))
    counter = 0
    low = 1
    high = 100
    money = 1000
    while True:
        guess = randint(low, high)
        print(guess)
        counter += 1
        if user_input == guess:
            print("congratulation, computer guess right")
            print("total guess:", counter)
            money += 200
            print("computer has: ", money)
            if money < 500:
               print(" computer you are fucking stupid!!!!")
            quit()
        elif user_input > guess:
            low = guess + 1
            print("computer guess a higher number")
            money -= 100
        else:  # user_input < guess
            high = guess - 1
            print("computer guess a lower number:")
            money -= 100


if __name__ == '__main__':
    main()
相關文章
相關標籤/搜索