AlmostThere
AlmostThere

Reputation: 647

Looping through two lists, comparing one list against the other and return values

I have two lists that I want to compare. I want to loop through list one values and compare it to the values in list two. Im looking to return either 1, 0, or -1 based on if the value in list one is less than or equal to the value in list two.

For example, the value of 2 from list one would be assigned a value of 0 because it is greater than 0 and less than 3 from list two.

list_one = [0,2,5,0,3,7]
list_two = [0,3]

#loop through list one values
for j in list_one:
    #loop through list two values
    for k in list_two:
        
        if float(j) <= k:
            value = 1
            break            
        elif float(j) <= k:
            value = 0 
            break
        else:
            value = -1
            
    print(value)

Actual Outcome:

1
1
-1
1
1
-1

Expected Outcome:

1
0
-1
1
0
-1

Upvotes: 1

Views: 228

Answers (2)

Joseph Brennan
Joseph Brennan

Reputation: 1

#Logic errors aside, the biggest mistake in this code sample is your confusing use of #list_two. Clearly list_two must be a 2-element list: [min, max]. Any other structure #would be difficult to understand. Keep it as a list if you prefer but at the outset #decode list_two as follows:""

 min_val = list_two[0]
 max_val = list_two[1]

#Then loop j through list_one and apply this logic:

if j < min_val:
    value = 1
elif j > max_val:
    value = -1
else:
    value = 0

#So basically lose the second loop (the k loop). And definitely remove the float() #references.

Upvotes: 0

Tharun K
Tharun K

Reputation: 1180

There were a few issues in your logic, I have changed them in the code attached below

list_one = [0,2,5,0,3,7]
list_two = [0,3]

#loop through list one values
for j in list_one:
    #loop through list two values
    value=0
    for k in list_two:
        
        if float(j) <= k:
            value += 1
            break            
        elif float(j) == k:
            value += 0 
            break
        else:
            value += -1
            
        if value > 1:
            value = 1
        elif value < -1:
            value = -1
            
    print(value)

Let me know if this fixes it for you, the problem statement wasn't very clear, I have modified this code according to my interpretation of the problem statement

Upvotes: 2

Related Questions