Python-[--001--]-Python涉及的算法题

第一题:将 a = [1,1,1,2,2,3,3,3,4,5,6,6,6,7,8,8]转化为c = [1,1,2,2,3,3,4,5,6,6,7,8]

分析:对出现相同元素次数大于2的进行处理

a = [1,1,1,2,2,3,3,3,4,5,6,6,6,7,8,8]
# c = [1,1,2,2,3,3,4,5,6,6,7,8]
b = []
for i in a:

    if b.count(i) < 2:

        b.append(i)

print(b)

第二题:找出字符串中重复的内容

f = "asklabassk"
def find_distinct(string):

l1 = []
ff = [i for i in string]
for i in ff:
if ff.count(i) > 1:
        l1.append(i)

return
(set(l1))
f = "asklabassk" 
res
= find_distinct(f)
print(res)
--------------------------
{'s', 'a', 'k'}

第三题:统计字符串中元素出现的次数

def count_each_char_1(string):
    res = {}
    for i in string:
        if i not in res:
            res[i] = 1
        else:
            res[i] += 1
    return res


print(count_each_char_1('aenabsascd'))

------------------------------
{'a': 3, 'e': 1, 'n': 1, 'b': 1, 's': 2, 'c': 1, 'd': 1}

 第四题:一个txt文档中的英文单词,统计每个单词出现的次数,并倒叙排列

t.txt

test,add touch test aaa hehe . add add test test

代码

d = {}
with open("test.txt",'r') as f:

    for line in f:

        line = line.replace(","," ")
        line = line.replace("."," ")
        line = line.replace("!"," ")

        # 将所有内容去除空格,输出一个列表['test', 'add', 'touch', 'test', 'aaa', 'hehe', 'add', 'add', 'test', 'test']
        str_lines = line.split()

        print(str_lines)

        for str in str_lines:

            if str in d.keys():

                d[str] += 1

            else:
                d[str] = 1

print(d.items())
result = sorted(d.items(),key=lambda k:k[1],reverse=True)
print(result)

输出

[('test', 4), ('add', 3), ('touch', 1), ('aaa', 1), ('hehe', 1)]

 第五题:求出列表中某元素出现的次数大于列表的一半长度的元素

a = [1,1,1,2,2,6,6,6,6,6,6,6]
s = set()
for i in a:

    if a.count(i)>int(len(a)/2):

        s.add(i)


print(list(s))

——————————————————————————
[6]

 第六题:找出两个列表中相同的元素和不同弄的元素

l5 = [1,2,3,4,5,6]
l6 = [2,3,4,7,8,9]
l7 = [i for i in l5 if i in l6]               # [2, 3, 4]
l8 = [i for i in (l5+l6) if i not in l7]      # [1, 5, 6, 7, 8, 9]
print(l7)
print(l8)
# 第二种方法
print(set(l5)&set(l6))   # [2, 3, 4]
print(set(l5)^set(l6))   # {1, 5, 6, 7, 8, 9}

第七题:如何删除list里面的重复的元素并保证顺序并不变化

l3 = [1,5,5,3,6,6,7,35,7,6,6,88.44,33,5]
l4 = []
for i in l3:

    if i not in l4:
        l4.append(i)

print(l4)    # [1, 5, 3, 6, 7, 35, 88.44, 33]

第八題:生成等差数列

l2 = list(range(8,100,12))
print(l2)   # [8, 20, 32, 44, 56, 68, 80, 92]

第九题:一行代码求1-1000的和

s1 = sum(range(1,1000))
print(s1)      # 499500
# 第二种方法
from functools import reduce
s2 = reduce(lambda x,y:x+y,range(1,1000))
print(s2)

第十题:生成奇数数列

"""
用一行代码生成奇数数列
"""
l1 = [2*i+1 for i in range(10)]
print(l1)   # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

 

posted @ 2020-08-05 17:44  旅行没有终点  阅读(266)  评论(0编辑  收藏  举报