user11876616
user11876616

Reputation:

Beginner Python question: trouble converting list objects to integers

This code is causing a

TypeError: 'list' object cannot be interpreted as an integer.

It was working before adding user inputs. The code returns a count of how many times the number overlaps with the range of the input number pairs. Thanks in advance!

user_input_1 = input("Enter the first pair here: ")
lst1 = [int(i) for i in user_input_1.split(" ") if i.isdigit()]

user_input_2 = input("Enter the second pair here: ")
lst2 = [int(i) for i in user_input_2.split(" ") if i.isdigit()]

user_input_3 = input("Enter the third pair here: ")
lst3 = [int(i) for i in user_input_3.split(" ") if i.isdigit()]

user_input_4 = input("Choose a center number: ")
number = int(user_input_4)


mainlist = [[lst2], [lst2], [lst3]]

def count_overlapping(mainlist, number): 
    count = 0
    for element in mainlist:
        if number in range(element[0], element[-1]) or number == element[0] or number == element[-1]:
            count += 1
    return count    

print(count_overlapping(mainlist, number))

Upvotes: 1

Views: 57

Answers (2)

kederrac
kederrac

Reputation: 17322

the mainlist is a list of lists of lists, you should use:

mainlist = [lst2, lst2, lst3]

also, you may improve your function count_overlapping (assuming that your inputs has pairs of numbers/2 numbers):

def count_overlapping(mainlist, number):
    return sum(1 for [a, b] in mainlist if number >= a and number <= b)

Upvotes: 0

Eric Truett
Eric Truett

Reputation: 3010

You have an extra level of lists that you don't need, so when you think you are getting an int value, you are still getting a list.

Change mainlist = [[lst2], [lst2], [lst3]] to mainlist = [lst2, lst2, lst3]

mainlst = [[lst1], [lst2], [lst3]]
[[[1, 2, 3, 4, 5, 6, 7, 8, 9]],
 [[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]],
 [[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]]

mainlst = [lst1, lst2, lst3]                                                                                     
[[1, 2, 3, 4, 5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]

Upvotes: 1

Related Questions