• Python 笔记


    1,冒泡算法:

    def bubble(items):
        if len(items) <= 1:
            return items
        for index in range(len(items)-1,0,-1):
            flag = False
            for sub_index in range(index):
                if items[sub_index] > items[sub_index + 1]:
                    items[sub_index],items[sub_index + 1] = items[sub_index + 1], items[sub_index]
                    flag = True
            if flag == False:
                break 
        return items

     2,有一个整数数组,请求出两两之差绝对值最小的值,只要得出最小值即可,不需要求出是哪两个数。

    c=min(abs(i-j) fori in a for j in b)
    

      这里有一个技巧,[abs(i-j) for i in a for j inb]会生成一个list,使用大量的存储空间,而(abs(i-j) for i in a for j inb)则产生一个生成器。

    3,写一个函数,检查字符是否是整数,如果是,返回其整数值。(或者:怎样只用4行代码编写出一个从字符串到长整形的函数?)

    a=input("输入一组字符:")
    if a.isdigit():
        a=int(a)
        print(a)

    4,给出一个函数来输出一个字符串的所有排列。

    #方法一:递归
    def perms(elements):
        if len(elements) <=1:
            yield elements
        else:
            for perm in perms(elements[1:]):
                for i in range(len(elements)):
    
                    yield perm[:i] + elements[0:1] + perm[i:]
    
    for item in list(perms('nice')):
        print(item)
    #方法二:
    from itertools import permutations
    a="nice"
    for element in list(itertools.permutations(a, 4)):
        print(''.join(element))

     5,将一个list形式的字符串转换为list数据形式

    a = "[1,2,3]"
    from ast import literal_eval
    a = literal_eval(a)  # list形式字符串转换为list
    -------------------------------
    eval(a)

      

  • 相关阅读:
    Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
    学习笔记之DBeaver
    Leetcode 103. Binary Tree Zigzag Level Order Traversal
    Leetcode 94. Binary Tree Inorder Traversal
    本周学习小结(15/07
    面试总结之算法
    Leetcode 160. Intersection of Two Linked Lists
    KindEditor富文本编辑框和BeautifulSoup的基本使用
    报障系统之权限管理
    报障系统之博客主页及后台管理
  • 原文地址:https://www.cnblogs.com/gaigaige/p/8024326.html
Copyright © 2020-2023  润新知