如果没有奇数,则返回列表中最大的奇数无

时间:2017-07-01 14:31:58

标签: python list

这里有一个问题,我在那里做的功课,不正确。

def largest_odd_times(L):         """假设L是一个非空的整数列表             返回出现奇数的L的最大元素             L中的时间。如果不存在这样的元素,则返回None"""

    # Your code here

例如,如果 •largest_odd_times([2,2,4,4])返回None •largest_odd_times([3,9,5,3,5,3])返回9

from collections import Counter
        L = [3, 3, 2, 0, 9]
        def largest_odd_times(L):
            """ Assumes L is a non-empty list of ints
                Returns the largest element of L that occurs an odd number 
                of times in L. If no such element exists, returns None """
            L.sort(reverse=True)
            counted = Counter(L).items()
            for x in counted:
                if x[1] % 2 == 1:
                    return x[0]
            return None


    Test: largest_odd_times([3, 2])
    my output:2, correct output 3
    Test: largest_odd_times([3, 3, 2, 0])
    myoutput,0 correct output 2 
    Test: largest_odd_times([6, 8, 6, 8, 6, 8, 6, 8, 6, 8])
    My output, none, correct output 8
    Test: largest_odd_times([2, 4, 5, 4, 5, 4, 2, 2])
    my output 5, correct 4

    What wrong in this code, explanation of  where I went wrong and what should have done and fixing will be really great.
    Thank you.

3 个答案:

答案 0 :(得分:0)

这是一个更简单的方法:

from collections import Counter

def largest_odd_times(l):

    d = Counter(l)

    #d now stores: {8: 5, 6: 5}

    numbers = [a for a, b in d.items() if b%2 != 0]

    if len(numbers) > 0:
       return max(numbers)

    else:
       return None


print(largest_odd_times([6, 8, 6, 8, 6, 8, 6, 8, 6, 8]))

输出:

8

答案 1 :(得分:0)

也许简洁的列表理解可以实现你想要的。列表推导实际上返回一个包含出现次数的元组,后面跟着列表中出现奇数次数最多的数字。

a = [2, 2, 3, 4, 1, 5, 6, 2, 3, 4, 5]
r = max([(a.count(v),v) for v in a if a.count(v) % 2])[1]
print(r)
2

答案 2 :(得分:0)

这就是我做的事情

def largest_odd_times(L):     “””     L是列表,返回发生奇数次的L的最大元素     '''

try:
    m = max(L) #finds largest element in list

except ValueError: # if there is none (eg. empty list)
    return None
count = L.count(m)  # how many times does the max element occur

if count%2 == 1 :  # check if its odd
    return m
else:
    L = [x for x in L if x != m]  # if it's not odd, remove all instances
    return largest_odd_times(L)