zoukankan      html  css  js  c++  java
  • 大爽Python入门教程 47 答案

    大爽Python入门公开课教案 点击查看教程总目录

    1 检查长度

    实现一个函数check_any_match_size(words, size)
    检查一个由字符串构成的列表words
    是否存在字符串长度符合指定尺寸size
    任意一个符合尺寸即可返回True,否则返回False
    运行时示例如下

    >>> check_any_match_size(['lion', 'deer', 'bear'], 5)
    False
    >>> check_any_match_size(['lion', 'deer', 'sheep'], 5)
    True
    

    答案代码示例

    def check_any_match_size(words, size):
        for word in words:
            if len(word) == size:
                return True
    
        return False
    

    2 生成n以内的素数

    实现一个函数show_all_prime(n)
    返回所有大于等于2,小于n的素数。
    运行时示例如下

    >>> show_all_prime(10)
    [2, 3, 5, 7]
    >>> show_all_prime(20)
    [2, 3, 5, 7, 11, 13, 17, 19]
    

    答案代码示例

    def is_prime(num):
        for i in range(2, num):
            if num % i == 0:
                return False
    
        return True
    
    
    def show_all_prime(n):
        res = []
        for i in range(2, n):
            if is_prime(i):
                res.append(i)
    
        return res
    

    3 去重

    实现一个函数get_no_repeat(lst)
    接受一个整数组成的列表lst
    返回一个新的列表,其中包含lst中的元素,但剔除掉了重复项。

    >>> get_no_repeat([1,3,5,1,2])
    [1, 3, 5, 2]
    >>> get_no_repeat([2,3,4,2,3,2,4])
    [2, 3, 4]
    

    答案代码示例

    def get_no_repeat(lst):
        res = []
        for item in lst:
            if item not in res:
                res.append(item)
    
        return res
    

    4 计算重复字符

    实现一个函数get_repeat_str(s1, s2)
    接受两个字符串s1, s2
    返回一个新的字符串。
    返回的字符串由s1s2中的所有相同字符(去除重复)构成,且顺序遵循s1的顺序。

    >>> get_repeat_str("abcba", "adae")
    "a"
    >>> get_repeat_str("lihua", "zhangsan")
    "ha"
    

    答案代码示例

    def get_repeat_str(s1, s2):
        res = ""
        for c in s1:
            if c in s2:
                if c not in res:
                    res += c
    
        return res
    
  • 相关阅读:
    Apache Solr入门教程(初学者之旅)
    Codeforces 631 (Div. 2) E. Drazil Likes Heap 贪心
    Codeforces 631 (Div. 2) D. Dreamoon Likes Sequences 位运算^ 组合数 递推
    Codeforces 631 (Div. 2) C. Dreamoon Likes Coloring 思维or构造
    python中的类型转换
    MVC3.0在各个版本IIS中的部署
    get和post的区别
    Vue和React对比
    谈谈你对web标注和W3c的理解和认识
    js中的undefined 和null
  • 原文地址:https://www.cnblogs.com/BigShuang/p/15573934.html
Copyright © 2011-2022 走看看