基础算法

## 算法

------

```python
def num():
    return [lambda x: i * x for i in range(4)]   
    #return [lambda x i=i: i * x for i in range(4)]
    #return (lambda x : i * x for i in range(4))
if __name__ == '__main__':
    print([m(2) for m in num()])
```

两数之和

```python
def get_index_num(l, target):
    """
    
    :param l: 传入的列表
    :param target: 求下标值的和
    :return: 值的下标
    """
    num_index = {}
    for i, num in enumerate(l):
        num_index[num] = i
        j = num_index.get(target - num)
        if j is not None and j != i:
            return [j, i]
if __name__ == '__main__':
    l = [2, 7, 6, 9]
    target = 9
    g = get_index_num(l, target)
    print(g)
    

```

判断字符串有无重复的字符

```python
def str(a):
    """

    :param a: 要验证的字符串
    :return: 返回的要求
    """
    str = sorted(a)
    length = len(a) - 1
    for i in range(length):
        if str[i] == str[i + 1]:
            return False
    return True


if __name__ == '__main__':
    a = 'asda'
    s = str(a)
    print(s)
```

反转数字的三种情况

```python
def reveser_num(num):
    """
    
    :param num: 要判断的数字
    :return: 返回处理的结果
    """
    if num == 0:
        return num
    elif num > 0:
        return int(str(num)[::-1])
    else:
        return -reveser_num(-num)

if __name__ == '__main__':
    num = 300
    r = reveser_num(num)
    print(r)
```

判断列表中重复的数字

```python
def get_num(li):
    """

    :param li:要判断的列表
    :return:返回有重复的数字
    """
    lists = []
    num_dict = {}
    for i in li:
        if num_dict.get(i, ''):
            lists.append(str(i))
        num_dict[i] = 1
    lists = list(set(lists))
    return ''.join(lists)


if __name__ == '__main__':
    li = [4, 3, 4, 5, 2, 3]
    g = get_num(li)
    print(g)
```

反转列表

```python
def reverse_list(l):
    """

    :param l: 要操作的列表
    :return: 返回结果
    """
    new_list = []
    for i in range(len(l)):
        new_list.append(l[-i - 1])
    return new_list


if __name__ == '__main__':
    list = [1, 2, '', 9]
    print(reverse_list(list))
```

实现字符串内部单个反转

```python
"Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc" 

def reveser_str(s):
    """

    :param s:要操作的字符串
    :return:返回结果
    """
    s = ' '.join(s.split(' ')[::-1])[::-1]
    return s



if __name__ == '__main__':
    s =  "Let's take LeetCode contest"
    print(reveser_str(s))
```

一个小球从一百米的地方下落 第十次的离地距离 和 总路程

```python
def ball(num):
    """

    :param num: 第一次下落距离
    :return: 返回第十次的总和
    """
    num = 100
    num2 = num/2
    for i in range(1,11):
        print(i)
        num += 2 * num2
        num2 /= 2
    return num,num2


if __name__ == '__main__':
    num = 100
    print(ball(num))

冒泡排序
def Bubble(l):
"""
:params l:要操作的列表
:return: 返回排序的列表
"""
for i in range(len(l) - 1):
for j in range(len(l) - i - 1):
if l[j] > l[j + 1]:
l[j], l[j + 1] = l[j + 1], l[j]
return l


if __name__ == '__main__':
list = [1, 5, 6, 7, 9, 6, 3]
print(Bubble(list))
```

 

posted on 2020-07-06 18:42  mldsh  阅读(156)  评论(0编辑  收藏  举报

导航