Python 平衡点问题
1.平衡点问题
平衡点:比如int[] numbers = {1,3,5,7,8,25,4,20}; 25前面的总和为24,25后面的总和也是24,25这个点就是平衡点;假如一个数组中的元素,其前面的部分等于后面的部分,那么这个点的位序就是平衡点
要求:返回任何一个平衡点
方法:平衡点两边的数求和相等,也就是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为支配数,0,1,4分别为支配点;
要求:返回任何一个支配点
如果某数是支配点,那么它一定在排序后的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
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步