python面试常用算法

展开嵌套的list

def spread_list(lst):
    '''
    >>> spread_list([1, 3,[5, 6, [9, 10], [11,[12, [13, 14]]], 15]])
    [1, 3, 5, 6, 9, 10, 11, 12, 13, 14, 15]
    '''
    return sum([spread_list(x) if type(x) is list else [x] for x in lst],[])
    # [[1], [3], [[5], [6], [[9], [10]], [[11], [[12], [[13], [14]]]], [15]]]
print(spread_list([1, 3,[5, 6, [9, 10], [11,[12, [13, 14]]], 15]]))

艾氏筛法求质数

import itertools
def _odd_iter():
    n =1
    # while True:
    #   n = n+2
    #   yield n
    return itertools.count(3,2)
def not_divisable(n):
    return lambda x:x %n>0

def primes():
    yield 2
    it = _odd_iter()
    while True:
        n = next(it)
        yield n
        it = filter(not_divisable(n),it)
p = primes()
for t in range(10):
    print(next(p))

求大于n的最小整数

import math
def get_prime_than(n):

    if isprime(n+1):
        return n+1
    return get_prime_than(n+1)

def isprime(m):
    if m <=1:
        return False
    for i in range(2,int(math.sqrt(m))+1):
        if m % i == 0:
            return False
    return True

# l1 = filter(isprime,range(2,100))
# print(list(l1))
print(get_prime_than(101))
def bubble_sort2(ary):
    n = len(ary)
    for i in range(n):
        flag = True                   #标记
        for j in range(1,n-i):
            if  ary[j-1] > ary[j] :
                ary[j-1],ary[j] = ary[j],ary[j-1]
                flag = False
        if flag :                   #全排好序了,直接跳出
            break
    return ary

不用循环和条件打印1~1000

import sys
sys.setrecursionlimit(1005)
def printnum(n):
    print(n);
    return (n-1000) and printnum(n+1);
printnum(1)

不同范围的随机数转换

def Rand3():
    x = -1
    while not 0 <= x < 3:
        x = Rand5()
    return x
def Rand7():
    x = -1
    while not 0 <= x < 21:
        x = Rand5() * 5 + Rand5()
    return x % 7

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

原理:通过排序倒序找到每一个值last,通过sum大小判断放入small_list中,这其中有可能某个list先添加满,所以要判断length

def diff(sorted_list, length):
    if not sorted_list:
        return (([],[]))
    last = sorted_list[-1]
    big_list, small_list = diff(sorted_list[:-1],length)
    big_list_sum = sum(big_list)
    small_list_sum = sum(small_list)
    if big_list_sum > small_list_sum:
        if len(small_list) >= length:
            big_list.append(last)
        else:
            small_list.append(last)
        return ((big_list, small_list))
    else:
        if len(big_list) >= length:
            small_list.append(last)
        else:
            big_list.append(last)
        return ((small_list, big_list))
        
a = [1,13,4,9]
b = [3,44,800,700]
c= []
c.extend(a)
c.extend(b)
p = sorted(c,reverse=True)
w = diff(p, len(a))
print(w)

链表相加进位

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = ListNode(0)
        l = head
        carry = 0
        while l1 or l2 or carry:
            v1 = v2 = 0
            if l1:
                v1 = l1.val
                l1 = l1.next
            if l2:
                v2 = l2.val
                l2 = l2.next
            carry, val = divmod(v1+v2+carry, 10)
            l.next = ListNode(val)
            l = l.next
        return head.next

链表成对调换

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    # @param a ListNode
    # @return a ListNode
    def swapPairs(self, head):
        if head != None and head.next != None:
            next = head.next
            head.next = self.swapPairs(next.next)
            next.next = head
            return next
        return head

合并两个有序列表

def loop_merge_sort(l1, l2):
    tmp = []
    while len(l1) > 0 and len(l2) > 0:
        if l1[0] < l2[0]:
            tmp.append(l1[0])
            del l1[0]
        else:
            tmp.append(l2[0])
            del l2[0]
    tmp.extend(l1)
    tmp.extend(l2)
    return tmp

交叉链表求交点

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
def node(l1, l2):
    length1, lenth2 = 0, 0
    # 求两个链表长度
    while l1.next:
        l1 = l1.next
        length1 += 1
    while l2.next:
        l2 = l2.next
        length2 += 1
    # 长的链表先走
    if length1 > lenth2:
        for _ in range(length1 - length2):
            l1 = l1.next
    else:
        for _ in range(length2 - length1):
            l2 = l2.next
    while l1 and l2:
        if l1.next == l2.next:
            return l1.next
        else:
            l1 = l1.next
            l2 = l2.next

你可能感兴趣的:(python面试常用算法)