Python入门(实验)

来源:互联网 发布:百度人口迁徙数据 编辑:程序博客网 时间:2024/05/17 00:01

在自己的电脑上安装Anaconda,用conda create创建一个3.6版本的environment。今后我们的程序都在这个环境下执行。

  • https://repo.continuum.io/archive/?spm=5176.100239.blogcont109288.14.H9Tlkq
  • 包含Anaconda往期版本的清华大学镜像
    https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/
  • Anaconda官网
    https://www.anaconda.com/download/#_windows’

上网查询,并且自己在jupyter notebook上实验,看看python3.6当中有哪些常用的数据类型。

  • 安装Anaconda,把jupyter notebook的路径配置到系统环境变量PATH中,在命令行窗口pip install jupyter,安装好之后直接在命令行窗口jupyter notebook就可以了

用range创建一个list,命名为variable numbers,这个list从100到0,间隔为8。结果应该长下面这样:([100,92,84,76,68,60,52,44,36,28,20,12,4])

numbers=range(100,0,-8)list(numbers)>>>[100, 92, 84, 76, 68, 60, 52, 44, 36, 28, 20, 12, 4]

用if-elif-else语句判断某个年龄是未成年(=60)。

age=12if age>60:    print('old man!')elif age>30:    print('middle age!')else:    print('juvenile!')  >>>juvenile!

用list comprehension把我们前面的numbers每个数字都变成它的平方。

#列表推导式[num**2 for num in numbers]>>>[10000, 8464, 7056, 5776, 4624, 3600, 2704, 1936, 1296, 784, 400, 144, 16]

用for语句构建一个fibonacci数列,只需要前十个数字即可。

a=0;b=1;c=1print(c)for i in range(9):    c=a+b;a=b;b=c    print(c)>>>11235813213455

随机写下六个人的名字,构成一个list。

names=['Lilei','Tom','Jane','July','Xiaoming','Young']print(names)>>>['Lilei', 'Tom', 'Jane', 'July', 'Xiaoming', 'Young']

把这个list变成一个dict,按照顺序给这些名字编号,号码从1开始。key是名字,value是编号。

#value是键,key是值。。。print(dict(enumerate(names)))>>>{0: 'Lilei', 1: 'Tom', 2: 'Jane', 3: 'July', 4: 'Xiaoming', 5: 'Young'}
names_dic={}for i,name in enumerate(names):    names_dic[name]=iprint(names_dic)>>>{'Jane': 2, 'Tom': 1, 'July': 3, 'Lilei': 0, 'Young': 5, 'Xiaoming': 4}

函数练习

1.Define a function max() that takes two numbers as arguments and returns the largest of them.Use the if-then-else construct available in Python.(It is true that Python has the max() function built in, but writing it yourself is nevertheless a good exercise)

def max(a,b):    if a==b:        return a    elif a>b:        return a    else:        return b#testmax(1,2)>>>2

2.Define a function max_of_three() that takes three numbers as arguments and returns the largest of them.

def max_of_three(a,b,c):    if a==b:        if a==c or a>c:            return a        else:            return c    elif a>b:        if a>c:            return a        else:            return c    else:        if b>c:            return b        else:            return c#testmax_of_three(4,2,1) >>>4      
def max_of_three(a,b,c):    return(max(max(a,b),c))#testmax_of_three(3,5,4)>>>5

3.Define a function sum() and a function multiply() that sums and multiplies(respectively) all the numbers in a list of numbers. For example, sum([1,2,3,4]) should return 10, and multiply([1,2,3,4]) should return 34

def sum(num_list):    su=0    for i in range(len(num_list)):        su=num_list[i]+su    return su#testnl=[1,5,9];sum(nl)>>>15
def multiply(num_list):    mult=1    for i in num_list:        mult=i*mult    return mult#returnnl=[1,5,9];multiply(nl)>>>45

4.Define a function reverse() that computes the reversal of a string. For example, reverse(‘I am testing’) should return the string ‘gnitset ma I’.

def reverse(str_pre):    str_aft=[]    for zifu in list(reversed(list(str_pre))):        str_aft.append(zifu) ###    return ''.join(str_aft)#testsp='I am testing'reverse(sp)>>>'gnitset ma I'

5.Write a function is_member() that takes a value(i.e. a number,string,etc)x and a list of values a, and returs True if x is a member of a,False otherwise.(Note that this is exactly what the in operator does,but for the sake of the exercise you should pretend Python did not have this operator).

def is_member(a,x):    if type(x)==list:        if a in x:            print('True')        else:            print('False')    else:        print('x must be a list!')#testis_member('Li','Lily')>>>x must be a list!

6.Define a function overlapping() that takes two lists and returns True if they have at least one member in common,False otherwise. You may use your is_member() function, or the in operator, but for the sake of the exercise, you should(also) write it using two nested for-loops.

def overlapping(A,B):    if (type(A)==list) and (type(B)==list):        C=[]        for a in A:            for b in B:                if a==b:                    C.append('True')                else:                    C.append('False')    else:        print('the two arguments must be both lists!')    print(C)    return is_member('True',C)#testoverlapping([1,3],[2,5])>>>['False', 'False', 'False', 'False']False

7.Define a function generate_n_chars() that takes an integer n and a character c and returns a string, n characters long, consisting only of c:s. For example, generate_n_chars(5, ‘x’) should return the string ‘xxxxx’. (Python is unusual in that you can actually write an expression 5* ‘x’ that will evaluate to ‘xxxxx’. For the sake of the exercise you should ignore that the problem can be solved in this manner).

def generate_n_chars(a,c):    if (type(a)==int) and (type(c)!=int) and (type(c)!=float):        return a*c    else:        print('a must be int,c should not be a number!')#testgenerate_n_chars(5,'zx') >>>'zxzxzxzxzx'

8.Define a procedure histogram() that takes a list of integers and prints a histogram to the screen. For example, histogram([4,9,7]) should print the following:

 **** ********* *******
def histogram(alist):    if type(alist)==list:        for i in alist:            if type(i)==int:                print(generate_n_chars(i,'*'))            else:                print('the member in alist must be an int!')    else:        print('alist must be a list!')#testhistogram(['1',8,6])>>>the member in alist must be an int!**************

9.The function max() from exercise 1 and the function max_of_three() from exercise 2 will only work for two and three numbers,respectively. But suppose we have a much larger number of numbers, or suppose we cannot tell in advance how many they are? Write a function max_in_list() that takes a list of numbers and returns the largest one.

def max_in_list(numlist):    if type(numlist)==list:        fi=numlist[0]        for i in numlist:            if (type(i)==int) or (type(i)==float):                M=max(fi,i)                fi=M            else:                print('the member in alist must be an int!')    else:        print('alist must be a list!')     return M#testmax_in_list([1,20,29,40,300])>>>300

10.Write a program that maps a list of words into a list of integers representing the lengths of the cooresponding words.

def length1(wordlist):    for i in wordlist:        print(i, 'has a length of' ,len(i))#testlength1(['July','Tom'])>>>July has a length of 4Tom has a length of 3
def length(wordlist):    mp={}    for i in wordlist:        mp[i]=len(i)    return mp#testlength(['July','Tom','Newton'])>>>{'July': 4, 'Newton': 6, 'Tom': 3}

11.Write a function find_longest_word() that takes a list of words and returns the length of the longest one.

def find_longest_word(wordslist):    val_list=list(length(wordslist).values())    maxlength=max_in_list(val_list)    for word in wordslist:        if len(word)==maxlength:            print(word)        else:            pass#testfind_longest_word(['July','Tom','Newton','Xiaohe'])>>>NewtonXiaohe

12.Write a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n.

def filter_long_words(wordslist,n):    val_list=list(length(wordslist).values())    maxlength=max_in_list(val_list)    for word in wordslist:        if n>maxlength or n==maxlength:            print('n is larger than the longest number!')            break        elif len(word)>n:            print(word)        else:            pass#testfilter_long_words(['July','Tom','Newton'],3)>>>JulyNewton

13.Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Python dictionary. Try it with something like char_freq(‘abbabcbdbabdbdbabababcbcbab’)

def char_freq(char):    if type(char)==str:        char_dic={}        char_list=list(char)        #set返回的数据类型?        char_set=list(set(char_list))        for j in char_set:            char_dic[j]=0        for i in char_list:            char_dic[i] +=1    return char_dic#testchar_freq('abcbdbc')>>>{'a': 1, 'b': 3, 'c': 2, 'd': 1}

14.Define a simple “spelling correction” function correct() that takes a string and sees to it that 1) two or more occurrences of the space character is compressed into one, and 2) inserts an extra space after a period if the period is directly followed by a letter. E.g. correct("This is very funny and cool.Indeed!") should return “This is very funny and cool. Indeed!” Tip: Use regular expressions!

15.Using the higher order function reduce(), write a function max_in_list() that takes a list of numbers and returns the largest one. Then ask yourself: why define and call a new function, when I can just as well call the reduce() function directly?

#reduce()函数也是Python内置的一个高阶函数。reduce()函数接收的参数和 map()类似,一个函数 f,一个list,#但行为和 map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。def f(x,y):    if x==y or x>y:        return x    else:        return yfrom functools import reducereduce(f,[1,2,3,5,4])>>>5
#max_in_list()函数见第9题def max_in_list(numlist):    if type(numlist)==list:        fi=numlist[0]        for i in numlist:            if (type(i)==int) or (type(i)==float):                M=max(fi,i)                fi=M            else:                print('the member in alist must be an int!')    else:        print('alist must be a list!')     return M#testmax_in_list([1,20,29,40,300])>>>300

16.Write a program that maps a list of words into a list of integers representing the lengths of the corresponding words. Write it in three different ways: 1) using a for-loop, 2) using the higher order function map(), and 3) using list comprehensions.

# 1)见第10题函数def length(wordlist):    mp={}    for i in wordlist:        mp[i]=len(i)    return mp#testlength(['July','Tom','Newton'])>>>{'July': 4, 'Newton': 6, 'Tom': 3}
#map高阶函数def f(x,y):    return (x,y)l1=['Tom','July','Newton']l2=[len(i) for i in l1]print(list(map(f,l1,l2)))>>>[('Tom', 3), ('July', 4), ('Newton', 6)]
#列表推导式namelist=['Tom','July','Newton'][(name,len(name))  for name in namelist]>>>[('Tom', 3), ('July', 4), ('Newton', 6)]

Somewhat harder exercises

17.A sentence splitter is a program capable of splitting a text into sentences. The standard set of heuristics for sentence splitting includes (but isn’t limited to) the following rules:

Sentence boundaries occur at one of “.” (periods), “?” or “!”, except that

  1. Periods followed by whitespace followed by a lower case letter are not sentence boundaries.

  2. Periods followed by a digit with no intervening whitespace are not sentence boundaries.

  3. Periods followed by whitespace and then an upper case letter, but preceded by any of a short list of titles are not sentence boundaries. Sample titles include Mr., Mrs., Dr., and so on.

  4. Periods internal to a sequence of letters with no adjacent whitespace are not sentence boundaries (for example, www.aptex.com, or e.g).

  5. Periods followed by certain kinds of punctuation (notably comma and more periods) are probably not sentence boundaries.

  6. Your task here is to write a program that given the name of a text file is able to write its content with each sentence on a separate line. Test your program with the following short text:

    Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. Did he mind? Adam Jones Jr. thinks he didn't. In any case, this isn't true... Well, with a probability of .9 it isn't.

    The result should be:

    Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it.Did he mind?Adam Jones Jr. thinks he didn't.In any case, this isn't true...Well, with a probability of .9 it isn't.

7.Your task in this exercise is as follows:

Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Generate a string with N opening brackets (“[“) and N closing brackets (“]”), in some arbitrary order.

Examples:

[] OK ][ NOT OK
[][] OK ][][ NOT OK
[[][]] OK []][[] NOT OK

s=input('type several [ and ]:')dictbase={'[':0,']':0}if s.count('[')!=s.count(']'):    print("'[' and ']'have different number")else:    for i in s:        if i=='[':            dictbase['[']+=1        elif (i==']') & (dictbase[']']<dictbase['[']):            dictbase[']']+=1        else:            pass#print("'['and']'count:",dictbase)if (dictbase['[']==dictbase[']']) & (dictbase['[']!=0):    print("OK!")elif dictbase['[']!=0:    print("NOT OK!")else:    pass
原创粉丝点击