Python 平衡点问题

1.平衡点问题 
平衡点:比如int[] numbers = {1,3,5,7,8,25,4,20}; 25前面的总和为2425后面的总和也是2425这个点就是平衡点;假如一个数组中的元素,其前面的部分等于后面的部分,那么这个点的位序就是平衡点 
要求:返回任何一个平衡点

方法:平衡点两边的数求和相等,也就是sum(lsit)减去这个数之后再除以2等于这个数某一边的数求和

用一个变量来累加这个数左边的那一部分序列


[python] view plain copy
def fore(list_):  
    sum = sum(list_)  
    balance = 0  
    for num in numbers:  
        if balance < (sum-num)/2:  
            balance += num  
        else:  
            break  
    if balance == (sum-num)/2:  
        print("the balanced number is:{0}".format(num))  
    else:  
        print("balanced number not found!")  
  
if __name__ == '__main__':  
    numbers = [1,3,5,7,8,25,4,20]  
    fore(numbers)  
[python] view plain copy
>>> ================================ RESTART ================================  
>>>   
the balanced number is:25  


2.支配点问题: 
支配数:数组中某个元素出现的次数大于数组总数的一半时就成为支配数,其所在位序成为支配点;比如int[] a = {3,3,1,2,3};3为支配数,014分别为支配点; 
要求:返回任何一个支配点

如果某数是支配点,那么它一定在排序后的list最中间,更多详情http://hi.baidu.com/ruclin/item/f2706f26b1d2db140975086b


[python] view plain copy
def dominate_point(lst):  
    b = sorted(a)  
    candidate_donimate = b[int(len(b)/2)]  
    num = 0  
    for val in b:  
        if val == candidate_donimate:  
            num +=1  
    if num>= int(len(b)/2):  
        for i in range(len(a)):  
            if candidate_donimate == a[i]:  
                print("{0} is dominate point, the first sequence number is{1}"  
                      .format(candidate_donimate, i))  
                break  
    else:  
        print("no dominate point!")  
  
if __name__ == '__main__':  
    a = [3,3,1,2,3]  
    dominate_point(a)   
[python] view plain copy
>>> ================================ RESTART ================================  
>>>   
3 is dominate point, the first sequence number is0 

参考:
http://blog.csdn.net/michellechouu/article/details/27576515

posted @ 2017-08-30 19:13  hzxPeter  阅读(890)  评论(0)    收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示