Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can I count every item in a list by a specific range? Also, why the last item in my output is not sorted?

I have written a code to receive the user input as a list.

def lst_data():
    lst = []
    total = int(input('Number of Data: '))
    for number in range(0, total):
        user_data = int(input('Enter the Data: '))
        lst.sort()
        lst.append(user_data)
    print(lst)

the output is:

[50, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61, 62, 63, 64, 65, 68, 70, 70, 71, 72, 73, 74, 75, 76, 77, 79, 79, 80, 80, 81, 82, 84, 86, 87, 88, 89, 89, 90, 91, 83]

The next step I want to do is count every item on that list by every 6 numbers like 50-55 = ???, 56-61 = ???, 62-67 =???, and so on.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve been trying with:

counter =  0
for i in last:
    if 50 < i < 55:
    counter += 1

print(counter)

it works but I have to repeat the code over and over and value in the "if statement" has to be from the user input

how can i figure this out? and I want to check if there is any way to make my code simpler

>Solution :

I think this is what you’re trying to do:

def count(lo, hi, _list):
    return sum(lo <= e <= hi for e in _list)

nd = int(input('Number of data items: '))
data = []

for _ in range(nd):
    datum = int(input('Enter datum: '))
    data.append(datum)

lo = int(input('Enter low range value: '))
hi = int(input('Enter high range value: '))

print(f'There are {count(lo, hi, data)} items in the range {lo}-{hi}')

Example:

Number of data items: 5
Enter datum: 2
Enter datum: 1
Enter datum: 3
Enter datum: 5
Enter datum: 6
Enter low range value: 1
Enter high range value: 5
There are 4 items in the range 1-5

Note:

There is no reason to sort the list

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading