Home > front end >  How to stop my loop from ending at the end of i
How to stop my loop from ending at the end of i

Time:03-16

The prompt is:

Using PyCharm, under lab8, under Directory exercise, create a Python file called more_loops.py. Write a function, nbrs_greater that accepts 2 integer lists as parameters, and returns a list of integers that indicates how many integers in the second list are greater than each integer in the first list. For example: nbrs_greater([3, 4, 1, 2, 7], [10, 1, 4, 2, 5, 3]) returns [3, 2, 5, 4, 1]

And my code is working sometimes, but when I enter:

nbrs_greater([20, 5, 1, 6], [1, 4, 8, 12, 16])

It won't continue past 6 and returns [0, 3, 4] instead of [0, 3, 4, 3] because there are three values for which 6 is greater than in list 2.

Here is my original code--------

def nbrs_greater(list_1, list_2):
    final_list = []
    list_count = []
    list_greater = []
    number_of_greater = 0
    for i in list_1:
        for j in list_2:
            if i < j:
                list_greater.append(i)
                number_of_greater  = 1
            if i > max(list_2):
                list_count.append(0)
    for k in list_greater:
        count_list_var = list_greater.count(k)
        list_count.append(count_list_var)
    for h in list_count:
        if h not in final_list:
            final_list.append(h)
    if len(final_list) == 0:
        final_list.append(0)
    return final_list


print(nbrs_greater([20, 5, 1, 6], [1, 4, 8, 12, 16]))

CodePudding user response:

You're making this much more complicated than it needs to be. You don't need a list of each number that's greater in order to get the count. You can use the sum() function to get a count.

def nbrs_greater(list_1, list_2):
    final_list = []
    for i in list_1:
        greater_count = sum(j > i for j in list_2)
        final_list.append(greater_count)
    return final_list

CodePudding user response:

At here if h not in final_list: you mean final_list has not same num,so it won't apear two '3'.The different count numbers can be ok.

  • Related