美文网首页
python作业第二题 Superpowers

python作业第二题 Superpowers

作者: 瀚0000056 | 来源:发表于2018-08-18 21:45 被阅读0次

    Superpowers

    COMP9021, Session 2, 2018

    描述

    1. 要求输入一行整数,数字之间可以有任意空格,这些整数来代表英雄们的力量值,每人一个力量值,有正有负,英雄力量值可以被翻转数值的相反数,如-1反转为1,7翻转为-7
    2. 要求输入一个非负整数 nb_of_switches,最大不超过上一行的英雄数量,该数量代表对英雄的翻转数量
    3. 求得一下数值
      1. 求得英雄们翻转次数为nb_of_switches的最大力量值,每个英雄们可以翻转任意次数(包括不翻转,翻转1次,1次以上),如nb_of_switches为3,英雄力量序列为(4,-3,1,2,-7),则可达到的最大力量值为4+3-1+2+7=15
      2. 求得英雄们翻转次数为nb_of_switches的最大力量值,每个英雄们可以最多翻转一次,(完全不翻转、翻转1次),如nb_of_switches为3,英雄力量序列为(4,-3,1,2,-7),则可达到的最大力量值仍未15,nb_of_switches为5,英雄力量序列为(-7, 1, 2, 3, 4),则最大力量值为7-1-2-3-4=-3
      3. 求得英雄们翻转次数为nb_of_switches的最大力量值,被翻转的英雄们必须是连续的nb_of_switches个,例如序列为(4, -3, 1, 2, -7),nb_of_switches为3,则最大值为4 − 3 − 1 − 2 + 7=5
      4. 求得英雄们被翻转后可得的最大力量值,翻转方法为翻转连续的英雄,数量不限(可以不翻转)例如,序列为( 1 2 3 4 5),最大值为15
    def first_power(heros, nb_of_switches):
        for _ in range(nb_of_switches):
            min_ = min(heros)
            pos = heros.index(min_)
            heros[pos] = 0-min_
        s = 0
        for hero in heros:
            s = s + hero
        print('Possibly flipping the power of the same hero many times, the greatest achievable power is %d.' % (s))
    
    def second_power(heros, nb_of_switches):
        switchded_heros = list()
        for _ in range(nb_of_switches):
            min_ = min(heros)
            switchded_heros.append(0-min_)
            heros.remove(min_)
        s = 0
        for hero in heros:
            s = s+hero
        for hero in switchded_heros:
            s = s+hero
        print('Flipping the power of the same hero at most once, the greatest achievable power is %d. ' % (s))
    
    def third_power(heros, nb_of_switches,powerlist,isprint):
        for i in range(len(heros)-nb_of_switches+1):
            current = 0
            s = 0
            for pos in range(len(heros)):
                if (i+current == pos) and (current < nb_of_switches):
                    s = s+(0-heros[pos])
                    current += 1
                else:
                    s = s+heros[pos]
            powerlist.append(s)
        max_ = max(powerlist)
        if isprint:  
            print('Flipping the power of nb_of_flips many consecutive heroes, the greatest achievable power is %d. '%(max_))
    
    
    def fourth_power(heros):
        powerlist = list()
        for i in range(len(heros)+1):
            third_power(heros,i,powerlist,False)
        max_ = max(powerlist)
        print('Flipping the power of arbitrarily many consecutive heroes, the greatest achievable power is %d. '%(max_))
    
    

    相关文章

      网友评论

          本文标题:python作业第二题 Superpowers

          本文链接:https://www.haomeiwen.com/subject/zpkqiftx.html