1

So I have a need to have a while loop that runs so long as the maximum value from list1 is greater than the minimum value from list2. Right now, I have this:

    count=0
    list1= mine
    list2= friend
    while max(list1)>min(list2):
        count+=1
        list1= list1.remove(max(list1))
        list2= list2.remove(min(list2))
    return count

However, the function cannot be called because it says the object is non-iterable. Can someone please tell me how to fix this?

Thank you so very much

0

3 Answers 3

2

list.remove does not return the list, so once you remove the first value, you assign to the list1 and list2 variables non iterable objects, simply change

list1= list1.remove(max(list1))
list2= list2.remove(min(list2))

to

list1.remove(max(list1))
list2.remove(min(list2))
Sign up to request clarification or add additional context in comments.

Comments

2

list.remove() modifies the list in place and returns None, so after the first iteration both list1 and list2 will be None. Just remove the assignment from your remove lines:

while max(list1)>min(list2):
    count+=1
    list1.remove(max(list1))
    list2.remove(min(list2))

Comments

1

Problem is, list.remove returns None. While you can easely solve this by replacing list1=list1.remove(...), may I propose you other solution which

  • do not modify list1, list2, since this can lead to a buggy code;
  • is a bit faster, since list.remove is not very effective

Suggested code:

import timeit
from itertools import izip_longest

def via_remove(l1, l2):
    count = 1
    while max(l1)>min(l2):
        count+=1
        l1.remove(max(l1))
        l2.remove(min(l2))
    return count

def with_itertools(l1, l2):
    c = 1
    for l1_max, l2_min in izip_longest(sorted(l1, reverse=True), sorted(l2)):
        if l1_max <= l2_min:
            break
        c += 1
    return c

print timeit.timeit('from __main__ import via_remove; via_remove(range(1000), range(1000))', number=100)
7.82893552113

print timeit.timeit('from __main__ import with_itertools; with_itertools(range(1000), range(1000))', number=100)
0.0196773612289

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.