zoukankan      html  css  js  c++  java
  • python学习之——元组中两数相加之和等于某数

    #题目:数组中找出两个元素之和 等于给定的整数
    
    # 思路:
    # 1、将数组元素排序;
    # 2、array[i]与a[j](j的取值:i+1到len_array-1) 相加;
    # 3、如两两相加<整数继续,如=整数则输出元素值;
    # 4、如>则直接退出,i+1 开始下一轮相加比较
    
    def addData(array, sumdata):
       
        temp_array = array
        temp_sumdata = sumdata
        print "sumdata: %d" %temp_sumdata
    
    # 如array中没有负数,则可以先将 >sumdata 的数删掉
    # 为了避免长度变化问题,可将<sumdata的数赋值给另一array
    #    temp_array = []
    #    len_temp_array2 = len(temp_array2)
    #    for i in range(0,len_temp_array2):
    #        if temp_array2[i] < temp_sumdata:
    #            temp_array.append(temp_array2[i])
          
        sorted(temp_array)
        
        len_temp_array = len(temp_array)
    
    # 计数符合条件的组数
        num = 0
        
        for i in range(0, len_temp_array-1):
            for j in range(i+1, len_temp_array):
                if temp_array[i] + temp_array[j] < temp_sumdata:
                    continue
                elif temp_array[i] + temp_array[j] == temp_sumdata:
                    num += 1
                    print "Group %d :" % num
                    print "下标:%d, 元素值: %d" %(i, temp_array[i])
                    print "下标:%d, 元素值: %d" %(j, temp_array[j])
                else:
                    break
        
    if __name__=="__main__":
        test_array = [-1,1,2,3,4,5,6,7,8]
        test_sumdata = 6
        addData(test_array, test_sumdata)
  • 相关阅读:
    VirtualBox 给虚拟机绑定IP
    【转】 wget 命令用法详解
    [转]python -m SimpleHTTPServer
    longene QQ 安装目录
    查看mininet交换机中的流表
    aircrack-ng 字典破解WPA / WPA2
    Win7 64 安装Visual Studio 2010和SQL Server 2008 R2
    Floodlight 防火墙是如何起作用的
    小米2000万买域名mi.com
    Windows JDK环境变量的配置
  • 原文地址:https://www.cnblogs.com/cloverclt/p/4761989.html
Copyright © 2011-2022 走看看