zoukankan      html  css  js  c++  java
  • 找工作时写过的部分代码

    def getinput(tinput,k):
        size=len(tinput)
        if size==0 or k>size:
            return []
        array=sort(tinput,size)
        return array[:k]
    def sort(array,size):
        for i in range(int(size/2-1),-1,-1):
            array=adjust(array,i,size-1)#
        for j in range(size-1,-1,-1):
            temp=array[j]
            array[j]=array[0]
            array[0]=temp
            array=adjust(array,0,j-1)
        return array
    
    def adjust(array,start,end):
        temp=array[start]
        i=start*2+1
        while i<=end:
            if i+1<end and array[i+1]>array[i]:
                i+=1
            if array[i]<temp:
                break
            array[start]=temp
            start=i
            i=start*2+1
        array[start]=temp
        return array
    选择排序
    def choose_sort(r):
        length=len(r)
        for i in range(length):
            minmum=i
            for j in range(i+1,length):
                if lis[minmum]>lis[j]:
                    minmum=j
            if i!=minmum:
                swap(i,minmum)
    快速排序
    def quicksort(r):
      if (low<=high):
        div=partion(r,0,len(r))
        quicksort(r,0,div-1)
        quicksort(r,div+1,len(r))
    def partion(r,low,high):
       lis=r
       key=lis[low]
       while low<high:
            while low<high and lis[high]>=key:
                hight-=1
            swap(low,high)
            while low<high and lis[low]<=key:
                low+=1
            swap(low,high)
        return low
        
        
        
        key=lis[low]
        while low<high:
            while low<high and lis[high]<key:
                high-=1
            swap(low,high)
            while low<high and lis[low]>key:
                low+=1
            swap(low,high)
            
    归并排序
    def  merge_sort(arr,temp,s,end):
        temp=[None for i in range(len(arr))]
        if s<end:
            mid=int((s+end)/2)
            merge_sort(arr,temp,s,mid)
            merge_sort(arr,temp,mid+1,end)
            merge(arr,temp,s,mid,end)
    def merge(arr,temp,s,m,end):
        i=s
        j=m+1
        t=0
        while(i<=m and j<=end):
            if arr[i]<=arr[j]:
                temp[t]=arr[i]
                i+=1
            else:
                temp[t]=arr[j]
                j+=1
            t+=1
        while(i<=m):
            temp[t]=arr[i]
            t+=1
            i+=1
        while(j<=end):
            temp[t]=arr[j]
            t+=1
            j+=1
        t=0
        while(s<=end):
            arr[s]=temp[t]
            s+=1
            t+=1
    def merge_sort(arr,temp,s,end):
        temp=[None for i in range(len(arr))]
        if s<end:
            mid=int((s+end)/2)
            merge_sort(arr,temp,s,mid)
            merge_sort(arr,temp,mid+1,end)
            merge(arr,temp,s,mid,end)
    def merge(arr,temp,s,m,end):
        i=s
        j=m+1
        t=0
        while(i<=m and j<=end):
            if arr[i]<=arr[j]:
                temp[t]=arr[i]
                i+=1
            else:
                temp[t]=arr[j]
                j+=1
            t+=1
        while(i<=m):
            temp[t]=arr[i]
            t+=1
            i+=1
        while(j<=end):
            temp[t]=arr[j]
            t+=1
            j+=1
        t=0
        while(s<=end):
            arr[s]=temp[t]
            s+=1
            t+=1
    
            
    import tensorflow as tf
    class TextCnn:
        def __init__(self,sequence_length,num_classes,embedding_size,filter_sizes,num_filters,l2_reg_lambda=0.0,attention_dim=100,use_attention=True):
            self.embedded_chars=tf.placeholder(tf.float32,[None,sequence_length,embedding_size],name='embedded_chars')
            self.input_y=tf.placeholder(tf.float32,[None,num_classes],name='input_y')
            self.dropout_keep_prob=tf.placeholder(tf.float32,name='dropout_keep_prob')
            self.sequence_length=sequence_length
            self.embedding_size=embedding_size
            l2_loss=tf.constant(0.0)
            if use_attention:
                self.attention_hidden_dim=attention_dim
                self.attention_W=tf.Variable(tf.random_uniform([self.embedding_size,self.attention_hidden_dim],0.0,1.0),name='attention_W')
                self.attention_U=tf.Variable(tf.random_uniform([self.embedding_size,self.attention_hidden_dim],0.0,1.0),name='attendion_U')
                self.attention_V=tf.Variable(tf.random_uniform([self.attention_hidden_dim,1],0.0,1.0),name='attention_V')
                self.output_att=list()
                with tf.name_scope('attention'):
                    input_att=tf.split(self.embedded_chars,self.sequence_length,axis=1)
                    for index,x_i in enumerate(input_att):
                        x_i=tf.reshape(x_i,[-1,self.embedding_size])
                        c_i=self.attention(x_i,input_att,index)
                        inp=tf.concat([x_i,c_i],axis=1)
                        self.output_att.append(inp)
                    input_conv = tf.reshape(tf.concat(self.output_att,axis=1),[-1,self.sequence_length,self.embedding_size*2],name='input_convolution')
                self.input_conv_expanded=tf.expand_dims(input_conv,-1)
            else:
                self.input_conv_expanded=tf.expand_dims(self.embedded_chars,-1)
            dim_input_conv=self.input_conv_expanded.shape[-2].value
            pooled_outputs=[]
            for i,filter_size in enumerate(filter_sizes):
                with tf.name_scope('conv-maxpool-%s'%filter_size):
                    filter_shape=[filter_size,dim_input_conv,1,num_filters]
                    W=tf.Variable(tf.truncated_normal(filter_shape,stddev=0.1),name='W')
                    b=tf.Variable(tf.constant(0.1,shape=[num_filters]),name='b')
                    conv=tf.nn.conv2d(self.input_conv_expanded,W,strides=[1,1,1,1])
                    padding=VALID
                    name='convolution')
                    h=tf.nn.relu(tf.nn.bias_add(conv,b),name='relu')
                    pooled=tf.nn.max_pool(h,ksize=[1,sequence_length-filter_size+1,1,1],strides=[1,1,1,1],padding='valid',name='pool')
                    pooled_outputs.append(pooled)
            num_filters_total=num_filters*len(filter_sizes)
            self.h_pool=tf.concat(pooled_outputs,3)
            self.h_pool_flat=tf.reshape(self.h_pool,[-1,num_filters_total])
            with tf.name_scope('dropout'):
                self.h_drop=tf.nn.dropout(self.h_pool_flat,self.dropout_keep_prob)
            with tf.name_scope('output')
                W = tf.get_variable('W',shape=[num_filters_total,num_classes],initializer=tf.contrib.layers.xavier_initialzer())
                b=tf.Variable(tf.constant(0.1,shape=[num_classes]),name='b')
                l2_loss+=tf.nn.l2_loss(W)
                l2_loss+=tf.nn.l2_loss(b)
                self.scores=tf.nn.xw_plus_b(self.h_drop,W,b,name='scores')
                self.predictions=tf.argmax(self.scores,1,name='predictions')
                self.probabilities=tf.nn.sigmoid(self.scores,name='probabilities')
            with tf.name_scope('loss):
                losses=tf.nn.sigmoid_cross_entropy_with_logits(logits=self.scores,labels=self.input_y)
                self.loss=tf.reduce_mean(losses)+l2_reg_lambda*l2_loss
            with tf.name_scope('accuracy'):
                correct_predictions=tf.equal(self.predictions,tf.argmax(self.input_y,1))
                self.accuracy=tf.reduce_mean(tf.cast(correct_predictions,'flot'),name'accuracy')
        def attention(self,x_i,x,index):
            e_i=[]
            c_i=[]
            for output in x:
                output=tf.reshape(output,[-1,self.embedding_size])
                atten_hidden=tf.tanh(tf.add(tf.matmul(x_i,self.attention_W),tf.matmul(output,self.attention_U)))
                e_i_j=tf.matmul(atten_hidden,self.attention_V)
                e_i.append(e_i_j)
            e_i=tf.concat(e_i,axis=1)
            alpha_i=tf.nn.softmax(e_i)
            alpha_i=tf.split(alpha_i,self.sequence_length,1)
            for j,(alpha_i_j,output) in enumerate(zip(alpha_i,x):
                if j==index:
                    continue
                else:
                    output=tf.reshape(output,[-1,self.embedding_size])
                    c_i_j=tf.multiply(alpha_i_j,output)
                    c_i.append(c_i_j)
            c_i=tf.reshape(tf.concat(c_i,axis=1),[-1,self.sequence_length-1,self.embedding_size])
            c_i=tf.reduce_sum(c_i,1)
            return c_i
                
    #KMP
    def getnextarray(t):
        next=[-1,0]
        for i in range(2,len(t)):
            next.append(0)
        for j in range(2,len(t)):
            k=next[j-1]
            while k!=-1:
                if t[j-1]==t[k]:
                    next[j]=k+1
                else:
                    k=next[k]
                next[j]=0
        return next
    def kmpalg(s,t):
        next=getnextarray(t)
        i=0
        j=0
        while i<len(s) or j<len(t):
            if j==-1 or s[i]==t[j]:
                i+=1
                j+=1
            else:
                j=next[j]
        if j==len(t):
            return i-j
        else:
            return -1
        
    #计算base的exponent次方    
    def Power(self, base, exponent):
            # write code here
            if base==0:#若底为0,返回0
                return 0
            sum=1#注意要初始化一个存储计算结果的变量,不能直接对base进行叠乘,因为直接叠乘会改变base的大小
            if exponent>0:#次方大于0,正常操作
                for i in range(exponent):
                    sum=sum*base
                return sum
            elif exponent==0:#次数等于0,返回1
                return 1
            else:#次数小于0,先将次数取反,最后返回的是求完积之后的倒数
                exponent=-(exponent)
                for i in range(exponent):
                    sum=sum*base
                return 1.0/sum
    #调整数组顺序使奇数位于偶数前面
    def reOrderArray(self, array):
            # write code here
            #ood,even=[],[]#新建两个列表,分别存储奇数、偶数
            #
            #for a in array:#数组可以通过循环依次得到各个元素
             #   if a%2==0:
             #       even.append(a)
             #   else:
              #      ood.append(a)
            #return ood+even
            for i in range(1,len(array)):
                if (array[i]%2)!=0 and i!=0:
                    temp=array[i]
                    j=i-1
                    while j>=0 and (array[j]%2)==0:
                        array[j+1]=array[j]
                        j-=1
                    array[j+1]=temp
            return array
            
    #链表中倒数第k个节点
    def FindKthToTail(self, head, k):
            # write code here
            #方法一:先遍历一遍得到链表长度,再遍历到第n-k+1个节点即为倒数第k个节点
            #方法二:设置两个指针,一个先走k-1步,然后另一个指针开始走,两个始终相差k-1,直到前面的指针走到
            #最后一个节点输出后面指针指向的节点
            if head==None or k==0:
                return None
            
            else:
                bef=head
                for i in range(k-1):#注意先走k-1步,由于range从0开始,先走一步的时候要k-1!!!!!!!!
                    if bef.next!=None:
                        bef=bef.next
                    else:
                        return None
                after=head
                while bef.next!=None:
                    bef=bef.next
                    after=after.next
                return after    
        
    
    def Merge(pHead1,pHead2):
            dummy=ListNode(0)
            pHead=dummy
            while pHead1 and pHead2:
                if pHead1.val>=pHead2.val:
                    dummy.next=pHead2
                    pHead2=pHead2.next
                else:
                    dummy.next=pHead1
                    pHead1=pHead1.next
                dummy=dummy.next
                
            if pHead1:
                dummy.next=pHead1
            if pHead2:
                dummy.next=pHead2
            return pHead.next
    
    def Merge(self, pHead1, pHead2):
                # write code here
                dummy = ListNode(0)
                pHead = dummy
    
                while pHead1 and pHead2:
                    if pHead1.val >= pHead2.val:
                        dummy.next = pHead2
                        pHead2 = pHead2.next
                    else:
                        dummy.next = pHead1
                        pHead1 = pHead1.next
    
                    dummy = dummy.next
    
                if pHead1:
                    dummy.next = pHead1
                if pHead2:
                    dummy.next = pHead2
    
                return pHead.next
        
    def Merge(self, pHead1, pHead2):
            # write code here
            ListNode mergenode=null
            ListNode current=null
            while pHead1!=null and pHead2!=null: 
                 if pHead1.val<=pHead2.val:
                        if mergenode==null:
                            mergenode=current=pHead1
                        else:
                            current.next=pHead1
                        pHead1=pHead1.next
                 else:
                    if mergenode==null:
                            mergenode=current=pHead2
                        else:
                            current.next=pHead2
                        pHead2=pHead2.next
            return mergenode    
    
    ListNode Merge(ListNode list1,ListNode list2):
                if list1==None:
                    return list2
                if list2==None:
                    return list1
                if list1.val<list2.val:
                    res=list1
                    res.next=Merge(list1.next,list2)
                elif list1.val>list2.val:
                    res=list2
                    res.next=Merge(list1,list2.next)
                return res
        
    def HasSubtree(proot1,proot2):
            result=False
            if proot1!=None and proot2!=None:
                if proot1.val==proot2.val:
                    result=doestree(proot1,proot2)
                if not result:
                    result=Has(proot1.left,proot2)
                if not result:
                    result=Has(proot1.right,proot2)
    def doestree(proot1,proot2):
        if proot2==None:
            return True
        if proot1==None:
            return False
        if proot1.val!=proot2.val:
            return False
        return does()and does()
                
    char *strcpy(char *strDes,const char *string)
    {
    if(string==NULL &&strDes==NULL)
    {return NULL;
    }
    char* address=strDes
    while(*string!=''){
    *(strDes++)=*(string++);
    }
    *strDes='';
    return address
    }    
        
    #二叉搜索树的后序遍历序列    
    def VerifySquenceOfBST(self, sequence):
            if sequence==None or len(sequence)==0:
                return None
            node=sequence[-1]
            length=len(sequence)
            for i in range(length):
                if sequence[i]>node:
                    break
            for j in range(i):
                if sequence[j]>node:
                    return False
            for j in range(i,length):
                if sequence[j]<node:
                    return False
            left=True
            if i>0;
                left=VerifySquenceOfBST(sequence[:i])
            right=True
            if i<length-1:
                right=VerifySquenceOfBST(sequence[i:-1])
            return left and right
        
    def FindPathMain(root,path,currentSum):
            currentSum+=root.val
            path.append(root)
            isLeaf=(root.left==None and root.right==None)
            if currentSum==expectNumber and isLeaf:
                onePath=[]
                for node in path:
                    onePath.append(node.val)
                result.append(onepath)
            if currentSum<expectNumber:
                if root.left:
                    FindPathMain(root.left,path,currentSum)
                if root.right:
                    FindPathMain(root.right,path,currentSum)
            path.pop()
        
    def FindPathMain(root,path,currentSum):
            currentSum+=root.val
            path.append(root)
            if currentSum==expect:
                onepath=[]
                for i in path:
                    onepath.append(i)
                result.append(onePath)
            elif currentSum<expect:
                if root.left:
                    FindPathMain(root.left,path,currentSum)
                if root.right:
                    FindPathMain(root.left,path,currentSum)
            path.pop()
            
    #字符串的排列
    def Permutation(ss):
            if not ss:#若为空
                return []
            res=[]
            helper(ss,res,'')
            return sorted(list(set(res)))
    def helper(ss,res,path):
        if not ss:#ss若为空,将得到的path存入结果res
            res.append(path)
        else:
            for i in range(len(ss)):
                helper(ss[:i]+ss[i+1:],res,path+ss[i])
    
    #连续子数组的最大和
    def FindGreatestSumOfSubArray(self, array):
            # write code here
            n = len(array)
            dp = [ i for i in array]#dp存储历史上的和的最大值 先对dp初始化为数组元素
            for i in range(1,n):
                #不断对数组元素依次求和,遇到比前面的和更大的元素,更换max为该元素;否则一直求和,并记录每次求和结果
                dp[i] = max(dp[i-1]+array[i],array[i])
             
            return max(dp)#最后返回求和过程中的最大值 
                
    sum=array[0]
            res=-0xffffffff
            for i in range(1,len(array)):
                sum=sum+array[i]
                if sum<0:
                    if res<(sum-array[i]):
                        res=sum-array[i]
                    sum=0
                else:
                    if sum>res:
                        res=sum
            return res
    
      max_sum = array[0]
            pre_sum = 0
            for i in array:
                if pre_sum < 0:
                    pre_sum = i
                else:
                    pre_sum += i
                if pre_sum > max_sum:
                    max_sum =  pre_sum
            return max_sum        
        
    #丑数
    def choushu(index):
            ind=1
            res=[1]
            x=y=z=0
            while ind<index:
                minnum=min(2*res[x],3*res[y],5*res[z])
                res.append(minnum)
                if minnum<=2*res[x]:
                    x+=1
                if minnum<=3*res[y]:
                    y+=1
                if minnum<=5*res[z]:
                    z+=1
                ind+=1
            return minnum
    
    #归并排序
    def merge_sort(arr,temp,s,end):
        temp=[None for i in range(len(arr))]
        if s<end:
            mid=(s+end)//2
            merge_sort(arr,temp,s,mid)
            merge_sort(arr,temp,mid+1,end)
            merge(arr,temp,s,mid,end)
    def merge(arr,temp,s,m,end):
        i=s
        j=m+1
        t=0
        while (i<=m and j<=end):
            if arr[i]<arr[j]:
                temp[t]=arr[i]
                i+=1
            else:
                temp[t]=arr[j]
                j+=1
            t+=1
        while i<=m:
            temp[t]=arr[i]
            i+=1
            t+=1
        while j<=end:
            temp[t]=arr[j]
            j+=1
            t+=1
        for i in range(end):
            arr[i]=temp[i]
    
    
    def FindFirstCommonNode(self, pHead1, pHead2):
            # write code here
            #两个链表第一个公共节点之后的节点都是重复的,
            #所以从链尾开始查找,找到最后一个两个链表相同的节点
            nodes=[]
            while pHead1:
                nodes.append(pHead1)
                pHead1=pHead1.next
            id=0
            while pHead2:
                if pHead2.val==nodes[id].val:
                    return pHead2
                pHead2=pHead2.next
                id+=1
    def GetNumberOfK(self, data, k):
            # write code here
            if self.endk(data,k,0,len(data)-1)==-1:#表示data中没有k
                return 0
            else:
                return self.endk(data,k,0,len(data)-1)-self.firstk(data,k,0,len(data)-1)+1
            #注意最后要加1,才是k的个数
        #下面两个函数 是一样的,只是一个找第一个一个找最后一个,其中的一些判断条件不同
        #找到第一个k出现的位置
        def firstk(self,data,k,first,end):
            if first>end:#递归终止条件,返回-1
                return -1
            #二分查找
            mid=int((first+end)/2)
            middata=data[mid]
            if middata==k:
                if (mid>0 and data[mid-1]!=k)or mid==0:#若mid在大于0的时候对应的前一个位置的值不是k,或者此时mid=0
                    return mid#找到第一个位置的k
                else:
                    end=mid-1
            elif middata<k:
                first=mid+1
            elif middata>k:
                end=mid-1
            return self.firstk(data,k,first,end)#每次递归要传入查找的范围
        #找到最后一个k出现的位置
        def endk(self,data,k,first,end):
            if first>end:
                return -1
            mid=int((first+end)/2)
            middata=data[mid]
            if middata==k:
                if (mid+1<(len(data)) and data[mid+1]!=k)or mid==(len(data)-1):
                    return mid#找到第一个位置的k
                else:
                    first=mid+1
            elif middata<k:
                first=mid+1
            elif middata>k:
                end=mid-1
            return self.endk(data,k,first,end)
            
    #把字符串转成整数
    def str2num(s):
        slist=['1','2','3','4','5','6','7','8','9','0']
        fuhao=['-','+']
        first=0
        sum=0
        direct=0#未被赋值,即没有符号
        for i in s:
            if i not in slist and i not in fuhao:
                return 0
            if first==0 and i in fuhao:#第一个位置
                first=1
                if i=='-':
                    direct=-1
                else:
                    direct=1
            else:
                sum=sum*10+i
        if direct==0:
            direct=1
        return direct*sum
    
    def isNumeric(self, s):
            '''
            # write code here
            length=len(s)
            #需要判断的三种符号
            hase=False
            hasdot=False
            hassigh=False
            if length<=0:
                return False
            else:
                for i in range(length):#对每个元素依次判断
                    if s[i]=='e' or s[i]=='E':
                        if hase:#若已经有了e或E则false
                            return False
                        else:#若之前没有,则记录为True
                            hase=True
                            if i==length-1:#e的位置不能是最后一个
                                return False
                    elif s[i]=='.':
                        if hasdot or hase:
                            return False
                        else:
                            hasdot=True#不能用==,之前用错了!!!!
                            if hase:#若已经有了e,后面不能有.
                                return False
                    elif s[i]=='+' or s[i]=='-':#+-可以出现在e后面,或者第一个位置(直接判断其位置不行吗?)
                        if hassigh:#注意!!!!!!!这个地方,判断条件是如果之前出现过+-
                            if s[i-1]!='e' and s[i-1]!='E':
                                return False
                        else:#没有e的话,+-只能出现在开头   注意!!这里判断的不是是否有e而是之前是否有符号位出现过
                            hassigh=True
                            if i!=0 and s[i-1]!='e' and s[i-1]!='E':#若+-不在第一个位置或者不在e后面
                                return False
                    elif s[i]<'0' or s[i]>'9':
                        return False
                    #不能在循环中返回,否则在判断第一个元素后就会返回,不再继续比较
                    #else:
                        #return True
                return True
    
    #序列化和反序列化二叉树
    '''def Serialize(self, root):
                self.s = ''
                self.sarializeCore(root)
                return self.s
    
        def sarializeCore(self,root):
                if root is None:
                    self.s += "#,"
                    return
                self.s += str(root.val)+","
                self.sarializeCore(root.left)
                self.sarializeCore(root.right)
                return self.s#这句没有也可
    
        def Deserialize(self, s):
                    if s is None:
                        return None
                    if len(s)==1 and s[0]=="#":
                        return None
                    self.index = 0
                    s= s.split(',')
                    root = self.DeserializeCore(s)
                    return root
    
        def DeserializeCore(self,s):
    
                    t = s[self.index]
                    if t.isdigit():
                        root = TreeNode(int(t))
                        self.index +=1
                        left = self.DeserializeCore(s)
                        right = self.DeserializeCore(s)
                        root.left = left
                        root.right = right
                        return root#这个地方必须有,没有就没构建出来节点
                    elif t =="#":
                        self.index+=1
                        return None
                        '''
        def Serialize(self,root):
            self.s=''
            self.sarializeCore(root)
            return self.s
        def sarializeCore(self,root):
            if root is None:
                self.s+='#,'#注意要加逗号分隔
                return self.s
            self.s+=str(root.val)+','#注意要加逗号分隔,将数字转为str
            self.sarializeCore(root.left)
            self.sarializeCore(root.right)
        def Deserialize(self,s):
            if s is None:
                return None
            if len(s)==1 and s[0]=='#':
                return None
            self.index=0
            s=s.split(',')
            root=self.DeserializeCore(s)
            return root
        def DeserializeCore(self,s):
            t=s[self.index]
            if t.isdigit():
                root=TreeNode(int(t))#注意转为int
                self.index+=1
                left=self.DeserializeCore(s)
                right=self.DeserializeCore(s)
                root.left=left
                root.right=right
                return root
            elif t=='#':
                self.index+=1
                return None
        
    #疯狂游戏笔试题:n个数之间的大于等于有多少种可能
    #c语言代码
    
    #include <stdio.h>
    int main(){
    int n;
    while(scanf("%d",&n)!=EOF){
    int i,j,count2[19],count[19]={0};
    int sum=0;
    count[1]=1;
    count[2]=2;
    for(i=3;i<=n;i++){
    for(j=2;j<=i;j++){
    count2[j]=(count[j]+count[j-1])*j;
    }
    for(j=2;j<=i;j++){
    count[j]=count2[j];}
    }
    for(i=1;i<=n;i++){
    sum+=count[i];
    }
    }
    return 0;
    }
    
    
    #堆排序
    def msort():
      array=[1,2,3,4]
      size=len(array)
      array=sort(array,size)
      return array
    def sort(array,size):
      for i in range(int(size/2)-1,-1,-1):
        adjust(array,i,size-1)
      for i in range(size-1,-1,-1):
        temp=array[0]
        array[0]=array[i]
        array[i]=temp
        adjust(array,0,i-1)
    def adjust(array,start,end):
        temp=array[start]
        i=2*start+1
        while i<=end:
            if i+1<=end and array[i+1]<array[i]:
                i=i+1#注意要初始化一个存储计算结果的变量,不能直接对base进行叠乘,因为直接叠乘会改变base的大小
            if array[i]>temp:
                break
            array[start]=array[i]
            start=i
            i=2*start+1
        array[start]=temp
    
    
    #快排
    def sort():
       lis=[1,2,3,4]
       qsort(lis,0,len(lis)-1)
    def qsort(lis,low,high):
        if low<high:
            key=partion(lis,low,high)
            qsort(lis,low,key-1)
            qsort(lis,key+1,high)
    def partion(lis,low,high):
        keynum=lis[low]
        while low<high:
            while low<high and lis[high]>=keynum:
                high-=1
            swap(lis[high],lis[low])
            while low <high and lis[low]<=keynum:
                low+=1#注意要初始化一个存储计算结果的变量,不能直接对base进行叠乘,因为直接叠乘会改变base的大小
            swap()
        return low
    
    #字符串的排列
    def code27(s):
        if len(s)==1:
            return s[1]
        res=[]
        for i in range(len(s)):
            l=code27(s[:i]+s[i+1:])
            for m in l:
                res.append(s[i]+m)
        return res
    def permutation(s):
        word=list(s)
        return list(sorted(set(code27(word))))
        
    #归并排序
    def merge_sort(arr,temp,s,end):
        temp=[None for in in range(len(arr))]
        if s<end:
            mid=int((s+end)/2)
            merge_sort(arr,temp,s,mid)#先分割
            merge_sort(arr,temp,mid+1,end)
            merge(arr,temp,s,mid,end)#然后合并
        return arr
    def merge(arr,temp,s,mid,end):
        t=0#未被赋值,即没有符号
        i=s
        j=mid+1
        while i<=mid and j<=end:
            if arr[i]<arr[j]:
                temp[t]=arr[i]
                i+=1
            else:
                temp[t]=arr[j]
                j+=1
            t+=1
        while i<mid:
            temp[t]=arr[i]
            t+=1
            i+=1
        while j<end:
            temp[t]=arr[j]
            t+=1
            j+=1
        t=0
        while(s<=end):
            arr[s]=temp[t]
            s+=1#注意要初始化一个存储计算结果的变量,不能直接对base进行叠乘,因为直接叠乘会改变base的大小
            t+=1
        
    #堆排序
    def sort(data):
        size=len(data)
        for i in range(size//2-1,-1,-1):
            adjust(data,i,size-1)
        for i in range(size-1,-1,-1):
            temp=data[0]
            data[0]=data[i]
            data[i]=temp
            adjust(data,0,i-1)
    def adjust(data,start,end):
        temp=data[start]
        i=start*2+1#注意要初始化一个存储计算结果的变量,不能直接对base进行叠乘,因为直接叠乘会改变base的大小
        while i<=end:
            if i+1<=end and data[i+1]<data[i]:
                i=i+1
            if data[i]>temp:
                break
            data[start]=data[i]
            start=i
            i=start*2+1
        data[start]=temp
        
    #快速排序
    def quiksort(data,low,high):
        if low<high:
            key=choose(data,low,high)
            quiksort(data,low,key)
            quiksort(data,key+1,high)
    def choose(data,low,high):
        keyvalue=data[low]
        while low<high:
            while low<high and data[high]>=keyvalue:
                high-=1#注意要初始化一个存储计算结果的变量,不能直接对base进行叠乘,因为直接叠乘会改变base的大小
            temp=data[low]
            data[low]=data[high]
            data[high]=temp
            while low<high and data[low]<=keyvalue:
                low+=1
            temp=data[low]
            data[low]=data[high]
            data[high]=temp
        return low
        
    #快排
    def sort(data,low,high):
        if low<high:
            key=qsort(data,low,high)
            sort(data,low,key)
            sort(data,key+1,high)
    def qsort(data,low,high):
        i=low
        key=data[low]
        while low<high:
            while low<high and data[high]>=key:
                high-=1#注意要初始化一个存储计算结果的变量,不能直接对base进行叠乘,因为直接叠乘会改变base的大小
            swap()
            while low<high and data[low]<=key:
                low+=1
            swap()
            
        return low
    #归并排序
    def `msort(data,low,high):
        temp=[None for i in range(len(data)]
        if low<high:
            mid=(low+high)//2
            msort(data,low,mid)
            msort(data,mid+1,high)
            merge(data,temp,low,mid,high)
    def merge(data,temp,low,mid,high):
        i=low
        j=mid+1
        t=0
        while i<=mid and j<=high
           
           if data[i]<=data[j]:
                temp[t]=data[i]
                t+=1#注意要初始化一个存储计算结果的变量,不能直接对base进行叠乘,因为直接叠乘会改变base的大小
                i+=1
           else:
                temp[t]=data[j]
                t+=1
                j+=1
        while i<=mid:
            temp[t]=data[i]
            t+=1
            i+=1#注意要初始化一个存储计算结果的变量,不能直接对base进行叠乘,因为直接叠乘会改变base的大小
        while j<=high:
            temp[t]=data[j]
            t+=1
            j+=1
    
        t=0    
        while s<=high:
            data[s]=temp[t]
            s+=1
            t+=1
    #堆排序
    def duisort(data):
        for i in range(len(data)//2+1,-1,-1):
            adjust(data,i,len(data)-1)
        for i in range(len(data)-1,-1,-1):
            temp=data[0]
            data[0]=data[j]
            data[j]=temp
            adjust(data,0,j-1)
    def adjust(data,s,end):
        temp=data[s]
        i=s*2+1
        while i<=end:
            if i+1<end and data[i+1]<data[i]:
                i+=1
            if data[i]>temp:
                break
            data[s]=data[i]
            s=i
            i=s*2+1
            
        data[s]=temp
    
    
    
    
    
    
    
            
            
            
            
  • 相关阅读:
    ubuntu 制做samba
    《Programming WPF》翻译 第4章 前言
    《Programming WPF》翻译 第4章 3.绑定到数据列表
    《Programming WPF》翻译 第4章 4.数据源
    《Programming WPF》翻译 第5章 6.触发器
    《Programming WPF》翻译 第4章 2.数据绑定
    《Programming WPF》翻译 第4章 1.不使用数据绑定
    《Programming WPF》翻译 第5章 7.控件模板
    《Programming WPF》翻译 第5章 8.我们进行到哪里了?
    《Programming WPF》翻译 第5章 5.数据模板和样式
  • 原文地址:https://www.cnblogs.com/kjkj/p/11751111.html
Copyright © 2011-2022 走看看