面試常見程序題python版——持續更新中

希爾排序

https://blog.csdn.net/MoreWindows/article/details/6668714

#coding:utf8
#歸併排序
#合併兩個有序數組ab 到c
def merge(a,b):
    i=j=0
    c=[]
    while i<len(a)and j<len(b):
        if a[i]<b[j]:
            c.append(a[i])
            i+=1
        else:
            c.append(b[j])
            j+=1
    while i<len(a):
        c.append(a[i])
        i+=1
    while j<len(b):
        c.append(b[j])
        j+=1
    return c
def mergeSort(lists):
    if len(lists)<=1:
        return lists
    mid=len(lists)/2
    left=mergeSort(lists[:mid])
    right=mergeSort(lists[mid:])
    return merge(left,right)
a = [4, 7, 8, 3, 5, 9]
print mergeSort(a)

 

# coding:utf8
# #冒泡排序
def bubble_sort(lists):
    count=len(lists)
    for i in range(0,count):
        for j in range(i,count):
            if lists[i]>lists[j]:
                t=lists[i]
                lists[i]=lists[j]
                lists[j]=t
    return lists
lists=[2,4,6,7,9]
print lists
#鏈表打印
def traversal(head):
    curNode=head
    while curNode is not None:
        print curNode.data
        curNode=curNode.next

#binary二分查找
def binary_find(find,lists):
    low=0
    high=len(lists)
    while low<=high:
        mid=(low+high)/2
        if lists[mid]==find:
            return mid
        elif lists[mid]>find:
            high=mid-1
        else:
            low=mid+1
    return -1
lists=[2,4,6,7,9]
print binary_find(9,lists)
#字符串逆序
s="hello"
li=list(s)
li.reverse()
print "".join(li)
#字典按value值逆序
d = {'a':1,'b':4,'c':2}
print sorted(d.items(),key=lambda x:x[1],reverse=False)
#快速排序
def partition(v,left,right):
    key=v[left]
    low=left
    high=right
    while low<high:
        while (low<high)and(v[high]>=key):
            high -=1
        v[low]=v[high]
        while (low<high)and(v[low]<=key):
            low +=1
        v[high]=v[low]
        v[low]=key
    return low
def quick_sort(v,left,right):
    if left<right:
        p=partition(v,left,right)
        quick_sort(v,left,p-1)
        quick_sort(v,p+1,right)
        return v
v=[2,1,8,4,5,6]
v1=quick_sort(v,0,len(v)-1)
print v1

操作1:m=s ;s=s+s

操作2:s=s+m

初始化:s="a";m=s

給定一個字符串長度n最少需要幾次操作才能獲得最後的結果

測試用例:n=4 返回2

number = int(raw_input("Enter a number: "))
def test(number):

    r = []
    while number != 1:

        for i in range(1, number + 1):
            if (number % i) == 0 and i != 1:
                number = number / i
                if number == 1:
                    # print " %d" %i
                    r.append(i)
                else:
                    # print " %d*" %i,
                    r.append(i)
                break
    count = 0
    count1 = 0
    count2 = 0
    for i in r:
        if i == 2:
            count += 1
        elif i == 3:
            count1 += 2
        else:
            count2 += (i-1)
    return (count+count1+count2)
test(number)

思路:將兩個字符串a,b轉換成列表,以第二個字符串b的長度作爲滑動窗口的長度進行滑動,將結果以字典形式存起來,key值是a列表下標,value值就是滑動窗口在a列表上獲得的長度爲len(b_list)子列表.

#KMP字符串匹配。給你兩個字符串,尋找其中一個字符串是否包含另一個字符串,如果包含,返回包含的起始位置
def ngrams(input,n):
    output = {}
    for i in range(len(input)-n+1):
        output.setdefault(i,input[i:i+n])#{i:[]}
    return output
def find(a,b):
    a_list=list(a)
    b_list=list(b)
    n=len(b_list)
    a_dict=ngrams(a_list,n)
    for k,v in a_dict.items():
        if v==b_list:
            return k
        else:
            continue
    return -1
a=raw_input("a:")
b=raw_input("b:")
k=find(a,b)
print k

樹的路徑

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        paths=[]
        if not root:return paths
        leftPaths,rightPaths=[],[]
        leftPaths=self.binaryTreePaths(root.left)
        rightPaths=self.binaryTreePaths(root.right)
        for path in leftPaths:
            print path
            a=str(root.val)+"->"+str(path)
            paths.append(a)
        for path in rightPaths:
            a = str(root.val) + "->" + str(path)
            paths.append(a)
        if(len(paths)==0):
            paths.append(""+str(root.val))
        return paths

翻轉鏈表

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if not pHead or not pHead.next:
            return pHead
        head=pHead
        pre=None
        while head:
            Next=head.next
            head.next=pre
            pre=head
            head=Next
        return pre
#遞歸版本字符串反轉
def func(s):
    if len(s) <1:
        return s
    return func(s[1:])+s[0]
#非遞歸
str[::-1]

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章