Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an unordered list, let's say:

lst = [12,23,35,54,43,29,65]

and the program will prompt the user to input two numbers, where these two numbers will represent the range.

 input1 = 22
 input2 = 55

therefore, 22 will be the lowest range and 55 will be the largest range. then with these two range, i want to print the values in the list within these range which are:

23
29
35
43
54

Here's my code:

def valRange(input1,input2,l):
n = len(l)
i = 0
upper = input2
lower = input1
while i<n:
    if (lower<=l[i]<=upper):
        l = l[i]
    i+=1
return l

print(valRange(input1,input2,lst))

I'm getting an error saying int object is not subscriptable. Am I comparing it right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
370 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are assigning an integer to variable l (previously it was a list) at line 8.

Then, in next iteration it tries to get i'th element of an integer. Which results in error of course.

Try this;

def valRange(input1,input2,l):
    result = []

    n = len(l)
    i = 0
    upper = input2
    lower = input1
    while i<n:
        if (lower<=l[i]<=upper):
            result.append(l[i])
        i+=1
    return result

print(valRange(input1,input2,lst))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...