import itertools
# 有序
print(list(itertools.permutations([1, 2, 3, 4], 2)))
# [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
# 无序
print(list(itertools.combinations([1, 2, 3, 4], 2)))
# [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
a=[1,3,5]
b=[1,2,3]
set(a) & set(b) #交集
set(a) | set(b) #并集
set(a) - set(b) #差集(得到的结果是set([5]))
1)一个list里面取n个值(无序,组合):
import copy
def combine(l, n):
answers = []
one = [0] * n
def next_c(li=0, ni=0):
if ni == n:
answers.append(copy.copy(one))
return
for lj in range(li, len(l)): # python2 和python3一个用range,一个用xrange
one[ni] = l[lj]
next_c(lj + 1, ni + 1)
next_c()
return answers
list = [1, 2, 3, 4, 5]
sublists = combine(list, 3)
输出的结果为():
[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]
2)一个list里面取n个值(有序,排列,此处以n = 3为例):
list = [1, 2, 3, 4, 5]
sublists = []
for i in range(len(list)):
for j in range(len(list)):
if j == i:
continue
else:
for k in range(len(list)):
if k == j or k == i:
continue
else:
sublists.append([list[i], list[j], list[k]])
输出的结果为():
[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 2], [1, 3, 4], [1, 3, 5], [1, 4, 2], [1, 4, 3], [1, 4, 5], [1, 5, 2], [1, 5, 3], [1, 5, 4], [2, 1, 3], [2, 1, 4], [2, 1, 5], [2, 3, 1], [2, 3, 4], [2, 3, 5], [2, 4, 1], [2, 4, 3], [2, 4, 5], [2, 5, 1], [2, 5, 3], [2, 5, 4], [3, 1, 2], [3, 1, 4], [3, 1, 5], [3, 2, 1], [3, 2, 4], [3, 2, 5], [3, 4, 1], [3, 4, 2], [3, 4, 5], [3, 5, 1], [3, 5, 2], [3, 5, 4], [4, 1, 2], [4, 1, 3], [4, 1, 5], [4, 2, 1], [4, 2, 3], [4, 2, 5], [4, 3, 1], [4, 3, 2], [4, 3, 5], [4, 5, 1], [4, 5, 2], [4, 5, 3], [5, 1, 2], [5, 1, 3], [5, 1, 4], [5, 2, 1], [5, 2, 3], [5, 2, 4], [5, 3, 1], [5, 3, 2], [5, 3, 4], [5, 4, 1], [5, 4, 2], [5, 4, 3]]
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
dp[n]=dp[n−1]+dp[n−2]
# -*- coding:utf-8 -*-
class Solution:
def jumpFloor(self, number):
# write code here
'''
n = 1 : 1
n = 2 : 1+1 = 2
n = 3 : dp[n-2]+dp[n-1]
'''
if number == 1 or number == 2:
return number
dp = [1,2]
for i in range(number-2):
dp.append(dp[-1]+dp[-2])
return dp[-1]
# -*- coding: utf-8 -*-
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print dictionary
"""
输出:
{'a': 1, 'c': 3, 'b': 2}
"""
print(dictionary['a'])
list=range(1,n+1)
>>> a = '1232'
>>> a[::-1]
'2321'
list1[::2] #每隔一个元素取一个
如list1 = [1,2,3,4,5,6], 则list1[::2] = [1,3,5]