m0_64542878 2022-11-24 07:47 采纳率: 85.7%
浏览 50
已结题

用python判断构成三角形

编写类,寻找最大周长的三角形。要求输入一个正整数列表,返回由列表中的三个数值组成的有效三角形的最大周长。如果所有的数值组合都不能构成有效三角形,则返回 0。输入输出示例及效果如下图:【参考代码行数:27行】
提示:(1)能构成三角形的条件为,任意两边之和大于第三边,任意两边之差的绝对值小于第三边;
(2)获取固定位数数字排列组合方法,如下面是获取3位数字排列组合的用法。
from itertools import combinations, permutations
print(list(permutations([1, 2, 3,4], 3))) # 有序排列
print(list(combinations([1, 2, 3,4], 3))) # 无序排列
代码参考:

img

运行预览:

img

img

  • 写回答

6条回答

  • honestman_ 2022-11-24 08:38
    关注
    from itertools import combinations, permutations
    
    
    class Summ():
        def __init__(self, alist):
            self.alist = alist
    
        def get_ret(self):
            is_true = False
            ret_dic = {}
            for num in list(permutations(self.alist, 3)):
                if num[0] + num[1] > num[2] and abs(num[0] - num[1]) < num[2]:
                    ret_dic[sum(num)] = num
                    is_true = True
            if not is_true:
                print('所以组合都不能构成有效三角形')
            else:
                ret_dic = sorted(ret_dic.items(), key=lambda x:x[0])
                print(f'最大周长为:{ret_dic[0][0]};三边长度分别为:{ret_dic[0][1][0]}{ret_dic[0][1][1]}{ret_dic[0][1][2]}')
    
    
    if __name__ == '__main__':
        numlist = input('输入列表:').split()
        numlist = [int(temp) for temp in numlist]
        summ = Summ(numlist)
        ret = summ.get_ret()
        # print(f'{ret} -> numlist[{ret[0]}]+numlist[{ret[1]}]={target}')
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • 於黾 2022-11-24 08:07
    关注

    这题根本不需要排列,用排列还要再考虑周长大小问题,反而麻烦
    1.先把输入存进list里,n=list(eval(input().replace(' ',',')))
    2.按从大到小排序,n.sort(reverse=True)
    3.循环for i in renge(n-2)
    每次取i,i+1,i+2三个判断是否能构成三角形,只要能构成,那肯定是最大的三角形
    4.既然已经排序过了,判断的时候判断n[i]>n[i+1]+n[i+2]即可,不需要排列组合

    评论 编辑记录
  • 阿_旭 2022-11-24 08:37
    关注
    
    # -*- coding: utf-8 -*-
    
    
    from itertools import combinations, permutations
    
    
    class judge_triangle:
        def __init__(self, alist):
            self.alist = alist
            self.max_length = 0
            self.tmp = []
    
    
        def is_triangle(self, list1):
            a, b ,c = list1
            if (a+b>c) and (a+c>b) and (b+c>a):
                return True
            else:
                return False
    
        def all_combinations(self, list1):
            # 返回所有3个数组合
            return list(combinations(list1, 3))
    
        def cal_perimeter(self, list1):
            # 计算周长
            return sum(list1)
    
        def return_max(self, list1):
            # 返回最大周长
            for each in self.all_combinations(list1):
                if self.is_triangle(each):
                    perimeter = self.cal_perimeter(each)
                    if perimeter >= self.max_length:
                        self.max_length = perimeter
                        self.tmp.append(each)
            return self.max_length, self.tmp
    
        def main(self):
            perimeter, comb = self.return_max(self.alist)
            if perimeter == 0:
                print('所有组合都不能构成有效三角形')
            else:
                print("最大周长为: {};三边长度分别为: {}".format(perimeter, comb))
    
    a = judge_triangle([6,7,10,20,32,1])
    a.main()
    
    a = judge_triangle([1,2,7])
    a.main()
    
    

    img

    展开全部

    评论
  • 游一游走一走 2022-11-24 08:41
    关注
    from itertools import permutations, combinations
    
    
    def check_ok(all_sanbian):
        result = True
        # 能构成三角形的条件为,任意两边之和大于第三边,任意两边之差的绝对值小于第三边
        for i in list(permutations(all_sanbian, 3)):
            if not (i[0] + i[1] > i[2] and abs(i[0] - i[1]) < i[2]):
                result = False
                break
        return result
    
    
    class SanJiaoXing:
        def __init__(self, alist):
            self.alist = alist
    
        def get_max(self):
            result = None
            data = None
            for i in list(combinations(self.alist, 3)):
                if check_ok(i):
                    temp = sum(i)
                    if result is None or temp > result:
                        result = temp
                        data = i
            return result, data
    
    
    if __name__ == '__main__':
        alist = input('输入整数列表:').split()
        # alist = '6 7 10 20 32 1'.split()
        # alist = '1 4 7'.split()
        alist = [int(temp) for temp in alist]
        get_max = SanJiaoXing(alist).get_max()
        if get_max[0] is None:
            print('所有组合都不能构成有效三角形')
        else:
            print(f'最大周长为:{get_max[0]} 三边长度分别为:{get_max[1][0]}{get_max[1][1]}{get_max[1][2]}')
    

    展开全部

    评论 编辑记录
  • 7*24 工作者 2022-11-24 08:43
    关注
    
    
    from itertools import combinations
    userInput = input('输入一组以空格隔开的正整数列表:')  # 6 7 10 20 32 1 14
    info = [ int(i) for i in userInput.split() ]   #  [6, 7, 10, 20, 32, 1, 14]
    result = {  }
    for item in list( combinations( info,3 ) ):
        if ( item[0] + item[1] > item[2] ) and ( abs(item[0] - item[1]) < item[2] ):
            sum = item[0] + item[1] + item[2]
            if sum not in result.keys():
                result[sum] = [ item ]
            else:
                result[sum].append(item)
    
    max_perimeter = max( result.keys() )
    data = result.get( max( result.keys() ) )
    if len(data) == 1:
        print('最大周长为:{},三边长分别为:{}'.format(  max_perimeter,  '、'.join( list( map( lambda x:str(x),data[0] ) ) )     ))
    else:
        for i in data:
            print('最大周长为:{},三边长分别为:{}'.format(max_perimeter,   '、'.join( list( map( lambda x:str(x),i ) ) )   ))
    
    评论
  • 程序媛一枚~ Python领域新星创作者 2022-11-24 09:05
    关注

    img

    
    from itertools import combinations
    
    import math
    
    
    # print(list(permutations([1, 2, 3, 4], 3)))  # 有序排列
    # print(list(combinations([1, 2, 3, 4], 3)))  # 无序排列
    
    
    class Triangle(object):
        alist = None
    
        def __init__(self, alist):
            self.alist = alist
    
        def largestTriangle(self):
            res = []
            self.alist.sort()
            # 对边长升序排序进行无序组合,因此最后一组能构成三角形的值,周长一定是最大的
            for val in combinations(self.alist, 3):
                # class tuple转list
                l = [x for x in val]
                # 判断是否能构成三角形
                if (l[0] + l[1] > l[2] and l[0] + l[2] > l[1] and l[1] + l[2] > l[0]
                        and math.fabs(l[0] - l[1]) < l[2] and math.fabs(l[0] - l[2]) < l[1] and math.fabs(l[1] - l[2]) < l[
                            0]):
                    res.append([sum(l), l])
            return res
    
    
    # list = [6, 7, 10, 20, 32, 1]
    # list = [1, 4, 7]
    list = list(map(int, input("输入列表:").split()))
    val = Triangle(list)
    res = val.largestTriangle()
    if (len(res) == 0):
        print("所有组合都不能构成有效三角形")
    else:
        print("最大周长:%d,三边长度分别为:%d、%d、%d" % (res[-1][0], res[-1][1][0], res[-1][1][1], res[-1][1][2]))
    

    展开全部

    评论
收起5条回答
编辑
预览

报告相同问题?

问题事件

  • 系统已结题 12月1日
  • 已采纳回答 11月24日
  • 赞助了问题酬金15元 11月24日
  • 创建了问题 11月24日
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部