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]) 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值