zoukankan      html  css  js  c++  java
  • 习题练习4

    习题1

      编写函数,对单词中的字母实现下操作:

        根据参数设置,将单词中的字母转化为大写或者小写

        返回转化之后的单词

    def convert(word, low=True):
        if low:
            return word.lower()
        else:
            return word.upper()
    
    w = "Physics"
    
    print(convert(w))
    print(convert(w, low=False))

    习题2

      编写函数,计算平面直角坐标系中两点的距离,函数的参数是两点的坐标

      编写函数,判断某字符串中是否含有指定集合中的字母

    def distance(pa, pb):
        import math
        lst = [(x-y)**2 for x, y in zip(pa, pb)]
        d = math.sqrt(sum(lst))
        return d
    
    pa = (1, 2)
    pb = (3, 4)
    print('d=', distance(pa, pb))

    习题3

      在字典中有get方法,但是列表中没有。编写函数,对列表实现类似字典中get方法的功能

    def get_by_index_1(lst, i, value=None):
        if i < len(lst):
            return lst[i]
        else:
            return value
    
    lst = [1, 2, 3]
    while True:
        try:
            idx = int(input('input index of list:'))
        except ValueError:
            print("Index should be int.")
            continue
        value = input('input value:')
    
        if value != 'q':
            r1 = get_by_index_1(lst, idx, value)
            print(r1)
        else:
            break

    习题4

      假设有文件名:py10.py,py2.py,py1.py,py14.py,编写对文件名进行排序的函数

    import re
    
    def select_numbers(s):
        pieces = re.compile(r'(d+)').split(s)
        pieces[1::2] = map(int, pieces[1::2])
        return pieces
    
    def sort_filename(filename):
        return sorted(filename, key=select_numbers)
    
    files = ['py10.py', 'py2.py', 'py1.py', 'py14.py']
    result = sort_filename(files)
    print(files)
    print(result)
  • 相关阅读:
    XPath在python中的高级应用
    Python中 sys.argv[]的用法简明解释
    python format
    爬虫解析:XPath总结
    c#attribute特性
    .net随笔--不好归类的
    windows系统操作
    linux学习
    visual studio各种新建项目和新建项简介
    自定义界面和控件--基础
  • 原文地址:https://www.cnblogs.com/zhaop8078/p/11785171.html
Copyright © 2011-2022 走看看