codecademy 代码学习1


1. Write a function called censor that takes two strings, text and word, as input. It should return the text with the word you chose replaced with asterisks.
For example: censor("this hack is wack hack", "hack") 
should return  "this **** is wack ****"
Assume your input strings won't contain punctuation or upper case letters.
The number of asterisks you put should correspond to the number of letters in the censored word.
 code:
def censor(text,word):
   new_lst=[]
    for w in text.split():
       print (w)
        if w==word:
            new_lst.append('*'*len(word))
        else:
            new_lst.append(w)
    return(' '.join(new_lst))
2. Define a function called count that has two arguments called sequence and item. Return the number of times the item occurs in the list.
For example: count([1,2,1,1], 1) should return 3 (because 1 appears 3 times in the list).
code:
def count(sequence,item):
    count=0
    for i in sequence:
        if i==item:
            count=count+1
    return count

3. Define a function called purify that takes in a list of numbers, removes all odd numbers in the list, and returns the result.
For example, purify([1,2,3]) should return [2].
code:
def purify(nums):
    new_list=[]
    for i in nums:
        if i%2==0:
            new_list.append(i)
    return new_list
4.remove_duplicates    
Write a function  remove_duplicates  that takes in a list and removes elements of the list that are the same.
For example:  remove_duplicates([1,1,2,2])  
should return  [1,2] .
code:
import copy
def remove_duplicates(lis):
    new_list=copy.deepcopy(lis)
    res=[]
    for li in new_list:
        if li not in res:
            res.append(li)
    return res
remove_duplicates([4,5,5,4])
5.median let's write a function to find the median of a list.The median is the middle number in a sorted sequence of numbers.
code:
def median(ls):     new_ls=sorted(ls)     if len(ls)%2==1:         median=sorted(ls)[(len(ls)-1)/2]     else:         median=(new_ls[(len(ls)-2)/2]+new_ls[len(ls)/2])/2.0     return median median([4,5,5,4]) 

你可能感兴趣的:(python,python,codecademy)