不断记录python常见习题,不断寻求更多更好的解决办法。持续更新中.....
练习:
1. list两两元素交换位置,如[1,2,3,4,5,6] 执行后为 -> [2,1,4,3,6,5]
第一种实现方式,比较原始:
l = [1,2,3,4] l1 = l[::2] l2 = l[1::2] print l1 print l2 c = [ ] for i in range( max ( len(l1), len(l2) ) ): print i if l2: c.append(l2[i]) if l1: c.append(l1[i]) print c
2. 打乱有序序列l
#!/usr/bin/python # -*- coding: UTF-8 -*- from random import shuffle l = list(range(10)) shuffle(l) print l
3. 一个支持各种操作符的类
#!/usr/bin/python # -*- coding: UTF-8 -*- import math import itertools class Vector(object): typecode = 'd' def __init__(self, components): self._components = [float(i) for i in components] def __repr__(self): return 'Vector({})'.format(list(self._components)) def __str__(self): return str(tuple(self)) def __len__(self): return len(self._components) def __getitem__(self, item): return self._components[item] def __getattr__(self, item): cls = type(self) def __iter__(self): return iter(self._components) def __eq__(self, other): return tuple(self) == tuple(other) def __abs__(self): return math.sqrt(sum(x * x for x in self)) def __neg__(self): return Vector(-x for x in self) def __pos__(self): return Vector(x for x in self) def __add__(self, other): pairs = itertools.izip_longest(self, other, fillvalue=0.0) return Vector(a + b for a, b in pairs) if __name__ == '__main__': vector2 = Vector(range(5)) print vector2 == range(5) print abs(vector2) print str(vector2) print repr(vector2) print -vector2 print +vector2 print vector2+Vector(range(2))
4. 列表操作,属于列表内部的重新组合
"""
给定一个字符串列表`strlist`和整数`k`。
请编写函数`func`,它返回字符串列表中`k`个相邻字符串中最长的第一个。
示例:
func(["this", "is", "an", "example"], 1) --> "example"
func(["this", "is", "another", "example"], 1) --> "another"
func(["this", "is", "another", "example"], 2) --> "anotherexample"
假设字符串列表的长度为`n`,如果`n = 0`或`k > n`或`k <= 0`则返回空字符串。
示例:
func([], 1) --> ""
func(["this", "is", "an", "example"], 5) --> ""
func(["this", "is", "an", "example"], 0) --> ""
"""
#!/usr/bin/env python # -*- coding: utf-8 -*- def func(strlist, k):
if strlist == [] or len(strlist) < k:
return ''
new_list = [strlist[num:num + k] for num in range(len(strlist) - k + 1)]
l = [''.join(n) for n in new_list]
l_num = [len(nu) for nu in l]
return l[l_num.index(max(l_num))]
5. 列表操作,属于从一个list中抽取所有特性的子list。
"""
给定一个仅包含整数,且按照大小顺序排好序的列表,列表内不存在重复的整数。
实现一个函数,将列表格式化为由`,`(逗号)分隔的字符串;如果相邻的整数(至少3个)是
连续的(值相差1为连续),则将这几个相邻的整数格式化为由`-`(减号)分隔、左右分别为
起始和终止位整数的字符串。
示例:
func([-6,-3,-2,-1,0,1,3,4,5,7,8,9,10,11,14,15,17,18,19,20]) --> '-6,-3-1,3-5,7-11,14,15,17-20'
func([-3,-2,-1,2,10,15,16,18,19,20]) --> '-3--1,2,10,15,16,18-20'
特殊情况示例:
func([]) --> ''
"""
def func(args): if len(args) == 0: return '' li = [] flag = 0 args_index = 0 while args_index < len(args): args_index_value = args[args_index] if args_index+1 == len(args): li.append(str(args_index_value)) break for args_back_value in args[args_index+1:]: if args_index_value-args_back_value+flag == -1: flag += 1 else: if flag >= 2: args_index += flag li.append(str(args_index_value)+'-'+str(args[args_index])) else: li.append(str(args_index_value)) flag = 0 args_index += 1 break return ','.join(li)
6. 合并两个有序列表
list_1 = [1,2,3,4] list_2 = [3,5,7,8] list_merge = list_1 + list_2 print sorted(list_merge)
7. 获取list的交集、差集、并集等,思路先把list转换成集合,集合操作后转换回list
list_1 = [1, 2, 3, 4] list_2 = [3, 5, 7, 8] print list(set(list_1) & set(list_2)) print list(set(list_1)|set(list_2)) print list(set(list_1) - set(list_2))
8. tuple与list之间的互相转换
tp = ('a', 'b', 'c') li = ['a', 'b', 'c'] print list(tp) print tuple(li)
9.
"""
你控制着你的游戏角色在地图上行走,每走一步都会消耗1点体力。
编写一个函数为你的角色规划行进路线,在不改变原有行进顺序的情况下,用最节省体力的方式到达目的地。
示例:
func(["NORTH", "SOUTH", "EAST"]) --> ["EAST"]
向"NORTH"行进后立即向"SOUTH"行进,"NORTH"和"SOUTH"是相反的方向,所以["NORTH", "SOUTH"]是可以减省掉的。
func(["EAST", "WEST", "WEST", "WEST"]) --> ["WEST", "WEST"]
向"EAST"行进后立即向"WEST"行进,"EAST"和"WEST"是相反的方向,所以["EAST", "WEST"]是可以减省掉的。
特殊情况说明:
func(["NORTH", "WEST", "EAST", "SOUTH"]) --> func(["NORTH", "SOUTH"]) --> []
["WEST", "EAST"]减省掉后,行进路线变成了["NORTH", "SOUTH"],可以进一步减省掉。
func(["NORTH", "WEST", "SOUTH", "EAST"]) --> ["NORTH", "WEST", "SOUTH", "EAST"]
["NORTH", "WEST"], ["WEST", "SOUTH"], ["SOUTH", "EAST"]任意两组相邻的方向,都不是相反的方向,所以不能减省掉。
"""
def func(directions): tmp = '' for index, li in enumerate(directions): if tmp == '': tmp = li else: if tmp == 'NORTH' and li == 'SOUTH' or tmp == 'SOUTH' and li == 'NORTH' or tmp == 'EAST' and li == 'WEST' or tmp == 'WEST' and li == 'EAST': tmp = '' directions = func(directions[:index - 1] + directions[index + 1:]) else: tmp = li return directions
10 正则相关
"""
请实现一个函数来对目标字符串进行校验,使其满足以下全部条件:
* 不少于6个字符
* 包含至少一个小写字母
* 包含至少一个大写字母
* 包含至少一个数字
* 只能包含大小写字母和数字
示例:
func("12ABcd") --> True
func("12ABc") --> False
func("12ABCD") --> False
func("12abcd") --> False
func("ABCdef") --> False
func("12AB cd") --> False
"""
import re def func(string): if len(string)< 6: return False if not string.isalnum(): return False if string.isdigit(): return False if string.isalpha(): return False if len(re.findall(r'd+', string)) == 0 : return False if not re.match(r'(?=.*[a-z])', string): return False if not re.match(r'(?=.*[A-Z])', string): return False return True
11. 有一个长度是101的数组,存在1~100的数字,有一个是重复的,找出重复出来
import random l = list(range(100)) random.shuffle(l) random_num = random.randint(0, 99) l.insert(random_num, random_num) print([num for num in l if l.count(num) == 2]) print([(index, num) for index, num in enumerate(l) if l.count(num) == 2])