Python题目练习(二)

1.如何实现对python列表去重,并保持原来顺序

li = [1,2,5,3,1,6,3,8,0,3,2,4]
l = []
for i in li:
    if i not in l:
        l.append(i)
print(l)
方法一
li = [1,2,5,3,1,6,3,8,0,3,2,4]
l = list(set(li))
l.sort(key=lambda i:li.index(i))
print(l)

# 先去重,再按照li的索引进行排序
方法二
li = [1,2,5,3,1,6,3,8,0,3,2,4]

from collections import OrderedDict
d = OrderedDict
d = d.fromkeys(li)
print(list(d.keys()))

# 用有序字典进行去重排序
方法三

 

2.请给出二分查找的python示例代码

def search(li,i,start=0,end=None):
    if end == None:end = len(li) - 1
    if start <= end:
        mid = (end - start) // 2 + start
        if i < li[mid]:end = mid - 1
        elif i > li[mid]:start = mid + 1
        else:return '在该列表的第%s个数'%(mid + 1)
        return search(li,i,start,end)
    else:return '该列表没有这个数'
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
print(search(l,42))
View Code
def select(l,aim,start = 0,end = None):
    if end == None:
        end = len(l)
    if start > end:
        return '列表没有该元素'
    mid = (end - start) // 2 + start
    if aim > l[mid]:
        return select(l,aim,mid + 1,end)
    elif aim < l[mid]:
        return select(l,aim,start,mid - 1)
    else:
        return aim,mid
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
print(select(l,42))
View Code

 

3.现有两元组(('a','b')),(('c','d')),请使用匿名函数生成列表[{'a':'c'},{'b':'d'}]

#方法一:
print(list(map(lambda t:{t[0]:t[1]},zip(('a','b'),('c','d')))))

#方法二:
test = lambda t1,t2:[{i:j} for i,j in zip(t1,t2)]
print(test(('a','b'),('c','d')))
View Code

 

4.用python实现'九九乘法表'(用两种不同的方式实现)

#方法一:
for j in range(1,10):
    i = 1
    l = []
    while i <= j:
        sum = i * j
        l.append('%d * %d = %d'%(i,j,sum))
        i += 1
    print('  '.join(l))
    
#方法二:
j = 1
while j < 10:
    i = 1
    s = ''
    while i <= j:
        sum = i * j
        s += '{} * {} = {}  '.format(i,j,sum)
        i += 1
    print(s)
    j += 1
View Code

 

5.三级菜单(可显示下级菜单,按q退出,按b返回)

menu = {
    '北京': {
        '海淀': {
            '五道口': {
                'soho': {},
                '网易': {},
                'google': {}
            },
            '中关村': {
                '爱奇艺': {},
                '汽车之家': {},
                'youku': {},
            },
            '上地': {
                '百度': {},
            },
        },
        '昌平': {
            '沙河': {
                '老男孩': {},
                '北航': {},
            },
            '天通苑': {},
            '回龙观': {},
        },
        '朝阳': {},
        '东城': {},
    },
    '上海': {
        '闵行': {
            "人民广场": {
                '炸鸡店': {}
            }
        }
View Code
l = [menu]
while True:
    ret = l[-1]  #取列表最后一个元素
    for k in ret:
        print(k)
    choice = input('请选择地点(按B/b返回,按Q/q退出):')
    if choice in ret and ret[choice]:
        l.append(ret[choice])  #添加到列表末尾
    elif choice.upper() == 'B' and len(l) > 1:
        l.pop()  #删除列表末尾的元素
    elif choice.upper() == 'Q':
        break
列表增加删除法
def menu_tree(menu):
    while True:
        for k in menu:
            print(k)
        choice = input('请选择地点(按B/b返回,按Q/q退出):')
        if choice.upper() == 'B' or choice.upper() == 'Q':
            return choice
        elif choice in menu and menu[choice]:
            ret = menu_tree(menu[choice])
        if ret == 'Q': return 'q'
 menu_tree(menu)
递归函数法

 

6.哥德巴赫偶数拆分质数,请拆分100-120之间的哥德巴赫数。

def prime_num(n):
    m = n ** 0.5
    i = 2
    while i < m+1:
        if n % i == 0:
            return False
        i += 1
    return True
for i in range(100,121):
    a = 2
    while a <= i/2:
        b = i - a
        ret1 = prime_num(a)
        ret2 = prime_num(b)
        if ret1 == True and ret2 == True:
            print('%d = %d + %d'%(i,a,b))
        a += 1
View Code

 

7.设计一个计算器,计算'1 - 2 * (   (60-30 +(-40/5)   * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'的结果

import re
def main(express):
    express = express.replace(' ','')  #对表达式去空格
    while True:
        express_bracket = re.search('\([^(]+?\)',express)  #循环寻找带括号的式子
        if express_bracket:
            express_bracket = express_bracket.group()
            result = real_express(express_bracket)  #调用real_express函数
            express = express.replace(express_bracket,result,1)  #把式子替换成计算结果
        else:break
    return real_express(express)  #调用real_express函数
def real_express(express):
    while True:
        real_exp = re.search('\d+\.?\d*[*/]-?\d+\.?\d*',express)  #循环寻找乘法/除法式子
        if real_exp:
            real_exp = real_exp.group()
            final_num = mul_div(real_exp)  #调用mul_div函数
            express = express.replace(real_exp,final_num,1)  #把式子替换成计算结果
        else:break
    express = deal_symbol(express)  #对式子处理符号
    num_l = re.findall('-?\d+\.?\d*',express)  #匹配式子的所有数字
    sum = 0
    for num in num_l:
        sum += float(num)  #将所有数字相加
    return str(sum)
def mul_div(express):
    if '*' in express:  #判断是否是乘法式子
        a,b = express.split('*')
        return str(float(a) * float(b))
    if '/' in express:  #判断是否是除法式子
        a,b = express.split('/')
        return str(float(a) / float(b))
def deal_symbol(express):  #处理符号
    if '--' in express:express = express.replace('--','+')
    if '-+' in express:express = express.replace('-+','-')
    if '+-' in express:express = express.replace('+-','-')
    if '++' in express:express = express.replace('++','+')
    return express
express =  '1 - 2 * (   (60-30 +(-40/5)   * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
print(main(express))
View Code
import re
def math(dic):
    x,y = float(dic['x']),float(dic['y'])
    if dic['mark'] == '*':return x * y
    elif dic['mark'] == '/':return x / y
    elif dic['mark'] == '+':return x + y
    else:return x - y
def suansu(re_str):
    ret = re.search('(?P<x>\d+\.?\d*)(?P<mark>[*/])(?P<y>-?\d+\.?\d*)',re_str)
    try:
        while True:
            re_str = re_str.replace(ret.group(),str(math(ret.groupdict())))
            if '++' in re_str:re_str = re_str.replace('++','+')
            if '--' in re_str:re_str = re_str.replace('--','+')
            ret = re.search('(?P<x>\d+\.?\d*)(?P<mark>[*/])(?P<y>-?\d+\.?\d*)', re_str)
    except AttributeError:pass
    ret = re.search('(?P<x>-?\d+\.?\d*)(?P<mark>[+-])(?P<y>-?\d+\.?\d*)',re_str)
    try:
        while True:
            re_str = re_str.replace(ret.group(),str(math(ret.groupdict())))
            ret = re.search('(?P<x>-?\d+\.?\d*)(?P<mark>[+-])(?P<y>-?\d+\.?\d*)', re_str)
    except AttributeError:return re_str
def main(user_inp):
    while True:
        if not re.search('\([^(]+?\)',user_inp):
            return suansu(user_inp)
        else:
            for i in re.findall('\([^(]+?\)',user_inp):
                user_inp = user_inp.replace(i,suansu(i.replace('(','').replace(')','')))
while True:print(main(input('>>:').replace(' ','')))
View Code 
 1 import re
 2 def math(x, y, z):
 3     if y in ['*', '/', '+', '-']: return eval(f'{x} {y} {z}')
 4 def deal_express(express, reg, flag=''):
 5     while True:
 6         ret = re.search(f'({flag}\d+\.?\d*)({reg})(-?\d+\.?\d*)', express)
 7         if ret: express = express.replace(ret.group(), str(math(ret.group(1), ret.group(2), ret.group(3))))
 8         else: return express
 9 def count(re_str):
10     return deal_express(deal_express(re_str, '[*/]'), '[+-]', '-?')
11 def main(user_inp):
12     while True:
13         ret = re.search('\([^(]+?\)', user_inp)
14         if ret: user_inp = user_inp.replace(ret.group(), count(ret.group())[1: -1], 1)
15         else: return count(user_inp)
16 while True: print(main(input('>>:').replace(' ', '')))
16行代码实现

 

8.请用python函数实现n次登陆功能

def login(n,i = 1):
    name = input('请输入用户名:').strip()
    pwd = input('请输入密码:').strip()
    if name == 'alex' and pwd == '123':return '登陆成功'
    elif i == n:return '您的账户已经被锁定'
    else:
        print('登陆失败,你还有%s次机会'%(n - i))
        i += 1
        return login(n,i)
print(login(3))
View Code

 

9.有两个序列a,b,大小都为n,序列元素的值任意整形数,无序;要求:通过交换a,b中的元素,使[序列a元素的和]与[序列b元素的和]之间的差最小。

a = [1,3,5,8,3,24,53,11,34,56]
b = [6,51,32,45,65,77,88,99,34,44]
x = y = 0
min = abs(sum(a) - sum(b))
while x < len(a):
    while y < len(b):
        a[x],b[y] = b[y],a[x]
        tmp = abs(sum(a) - sum(b))
        if min > tmp:min = tmp
        else:a[x],b[y] = b[y],a[x]
        y += 1
    x += 1
    y = 0
print(min)
View Code
def change(a,b,x=0):
    y = 0
    num = abs(sum(a) - sum(b))
    while y < len(b):
        a[x],b[y] = b[y],a[x]
        tmp = abs(sum(a) - sum(b))
        if num > tmp:num = tmp
        else:a[x],b[y] = b[y],a[x]
        y += 1
    x += 1
    if x < len(a):return change(a,b,x)
    return a,b,num
View Code
def change(a,b):
    x = y = 0
    num = abs(sum(a) - sum(b))
    while x < len(a):
        while y < len(b):
            a[x],b[y] = b[y],a[x]
            tmp = abs(sum(a) - sum(b))
            if num > tmp:num = tmp
            else:a[x],b[y] = b[y],a[x]
            y += 1
        y = 0
        x += 1
    return a,b,num
View Code

 

10.一个列表含有相同键的字典合并

题目
方法一
方法二
方法三

 

11.给两个字符串s和t,判断t是否为s的重新排列后组成的单词,s='anagram',t='nagaram',return True;s='rat',t='car',return False;

def check(s, t):
    li = [k for k in s]
    try:
        for w in t:
            li.remove(w)
    except Exception as exc:
        print(exc)
        return False
    if len(li) == 0:
        return True
    else:
        return False
方法一
def check(s, t):
    dic1, dic2 = {}, {}
    for k in s:
        if k in dic1:
            dic1[k] += 1
        else:
            dic1 = {k: 0}
    for w in t:
        if w in dic2:
            dic2[w] += 1
        else:
            dic2 = {w: 0}
    if dic1 == dic2:
        return True
    else:
        return False
方法二

 

12.给定一个m*n的二维列表,查找一个数是否存在。列表有下列特性:每一行的列表从左到右已经排序好;每一行第一个数比上一行最后一个数大;[[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]

def search(li, k):
    if k > li[-1][-1]:
        return False
    for item in li:
        if k == item[-1]:
            return True
        elif k < item[-1]:
            if k in item:
                return True
            else:
                return False
    return False
View Code

 

13.给定一个列表和一个整数,设计算法找到两个数的下标,使得两个数之和为给定的整数。例:列表[1,2,5,4]与目标整数3,1+2=3,结果为(0, 1).

def find(li, k):
    ret = []
    for i in range(len(li)):
        for j in range(i + 1, len(li)):
            if li[i] + li[j] == k:
                ret.append((i, j))
    return ret
View Code

 

posted @ 2017-11-08 20:01  Coufusion  阅读(416)  评论(0编辑  收藏  举报