animado31
animado31

Reputation: 3

How to create a function to output ranges for a list (in python)

I need to create a function that inputs a list of integers and outputs a count of one of three ranges. I know there are easier ways to do it, but this is the way it needs to be done for this project.

let's say the ranges need to be: (x < 10, 10 <= x < 100, x >= 100)

So far I've tried...

list = (1, 2, 10, 20, 50, 100, 200)
low = 0
mid = 0
high = 0
final_list = list()

def func(x):
    if x < 10:
        low = low + 1
    elif x < 100:
        mid = mid + 1
    else:
        high = high + 1

for i in range(len(list)):
    x  = func(list[i])
    final_list.append(x)

This is the best I've been able to come up with, but obviously it's not correct. Again, I realize there are easier ways to accomplish this, but the created function and for loop are required for this specific problem.

So... any ideas?

Upvotes: 0

Views: 85

Answers (2)

wheeled
wheeled

Reputation: 36

Or another way, depending on what you need to use the counters for:

my_list = (1, 2, 10, 20, 50, 100, 200)
# renamed the variable so it does not shadow the builtin list() type


def main():
    # created a function main() to allow the counters to be available to func() as nonlocal variables
    low = 0
    mid = 0
    high = 0
    final_list = list()

    def func(x):  # embedded func() in main()
        nonlocal low, mid, high  # declared the counters as nonlocal variables in func()
        if x < 10:
            low += 1
        elif x < 100:
            mid += 1
        else:
            high += 1

    for x in my_list:  # simplified the iteration over my_list
        func(x)
        final_list.append(x)  # final_list is just a copy of my_list - may not be necessary
    print(low, mid, high)  # to display the final values of the counters


main()

Upvotes: 1

Prune
Prune

Reputation: 77850

You have two problems:

  • Your function doesn't return anything
  • Your accumulators (counts) are separated from your loop

Move the loop inside the function:

def func(values):

    low = 0
    mid = 0
    high = 0

    for x in values:

        if x < 10:
            low = low + 1
        elif x < 100:
            mid = mid + 1
        else:
            high = high + 1

    return low, mid, high


print(func([1, 2, 10, 20, 50, 100, 200]))

Output:

(2, 3, 2)

Upvotes: 1

Related Questions