zoukankan      html  css  js  c++  java
  • 查找元素在list中的位置以及折半查询

    问题

    查找某个值在list中的位置


    解决思路

    能够用折半查询的方法解决此问题。


    解决(Python)

    #! /usr/bin/env python
    #coding:utf-8
    
    #折半查找某个元素在list中的位置
    
    def half_search(lst,value,left,right):
        length = len(lst)
        while left<right:
            middle = (right-left)/2
            if lst[middle]>value:
                right = middle-1
            elif lst[middle]<value:
                left = middle+1
            else:
                return middle 
    
    if __name__=="__main__":
        lst=sorted([2,4,5,9])    #折半算法中list要进行排序
        length = len(lst)
        left = 0
        right = length-1
        value =4 
        result = half_search(lst,value,left,right)
        if result:
            print result
        else:
            print "There is no the value that you want to search."

    再思考

    对于上面的折半方法,在python中,能够通过一个函数实现

    lst = sorted([2,4,5,9])    #这里进行排序。主要是为了得到与上面方法一样的结果。其实,list.index()能够针对不论什么list操作,不一定非要排序
    result = lst.index(4)

    此外。假设遇到list中有多个同样的元素。应该怎样将这些元素的位置都查询出来呢?以下的方法是用python实现。

    def find_value_location(lst,value):
        result = [i for i in range(len(lst)) if value==lst[i]]    
        return result

    很多其它用python实现的算法,请看:https://github.com/qiwsir/algorithm

    qiwsir#gmail.com

查看全文
  • 相关阅读:
    [转] DBus学习(一):总体介绍
    [转] DBus学习(四):基础小例子(同步和异步)
    linux系统调用列表
    Quantum Espresso + Phonopy 计算声子过程
    Compile Quantum Espresso (QE)
    Ubuntu 14.04 下创建 svn repository
    Python import 模块导入问题
    修改Ubuntu下ssh登陆时的欢迎信息
    ORNL cadesvirtues上编译 RMG/ Compile RMG on Cadesvirtues at ORNL
    launch images source启动图删除后上下有黑边
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10963759.html
  • Copyright © 2011-2022 走看看