python - user input - set

ittechlab
ittechlab used Ask the Experts™
on
i want to write a python code where user input a number and i want to insert in between the right place.

for example user input 35, i want to insert between 30 and 40.

a = int(input("Enter a number: "))
s1 = set([10,20,30,40,50])
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
This is not possible if you want to use the set type. Set does not preserve the order of arguments. Using a list in the set([10, 20, 30, 40, 50]) is just a convention. You can also use a tuple (immutable), but it would look syntactically slightly confusing -- like set((10, 20, 30, 40, 50)) -- because of the doubled parentheses. Or, at least, it it would be more error prone -- even though the error would be revealed very soon.

So, you may want to use the list without converting it to the set type.

Assuming that the list is sorted, you can traverse the list in a loop and search for the index of the leftmost value that is greater (or greater-or-equal) than the inserted value. Then you can use the list.insert() method to insert it.

Unless it is a homework (to write such loop), it is better to use the standard Python module bisect to search for the position. The module even implements the handy function bisect.insort_left(a, x, lo=0, hi=len(a)), that does exactly what you may want. (Here a is the list used as an array, x is the inserted value. The other two arguments are optional.)
Top Expert 2014
Commented:
If you have a relatively small list, you can do something like this:
s1 = [10,20,30,40,50]
s1.insert(s1.index(max([x for x in s1 if x < 35]))+1,35)
s1
[10, 20, 30, 35, 40, 50]

Open in new window

For large lists, follow the pepr recommendation and use bisect.  
Note that bisect assumes your list is in sorted order.  You can use the sorted() function to accomplish that.
ittechlabLinux Support

Author

Commented:
I tried using list.

l1 = [10,20,30,40,50]
index = 0
n=15

for e in l1:
    if e < n:
        index += 1
    else:
        break

print l1.index(e)

l1.insert(l1.index(e),n)

print l1
There is a bug in your solution. If the inserted value is greater than all of the existing, it will place it to the wrong position. Study and try the following code:
#!python2


lst = [10, 20, 30, 40, 50]
n = 15

# Use the enumerate() function to get both the element and the index
# of the element. You need not to calculate it on your own.
insertion_done = False      # see the comment below
for i, e in enumerate(lst):
    # Do something only when the tested element should not be skipped.
    if e >= n:
        print i             # just for the information
        lst.insert(i, n)
        insertion_done = True
        break

# It can happen that the inserted value was not found in the list.
# You have to add the extra code to solve the special case. It can be done
# various ways. Here, the flag that is set if the element was already
# inserted is used. (Try to insert 55 in your case.)
if not insertion_done:
    lst.append(n)

print 'First solution:', lst


# If it is not the learning case, it is always a good idea to use a library
# that already implements the functionality.
import bisect

lst = [10, 20, 30, 40, 50]
n = 15
bisect.insort_left(lst, n)

print 'Second solution:', lst

# In many cases (if the code is potentially be used repeatedly], it is a good idea
# to wrap the functionality as your function. Later, you may enhance the function
# body implementation, and it still will be called the same way -- the rest of
# code will not be changed.
def my_insort_left(lst, n):
    insertion_done = False
    for i, e in enumerate(lst):
        if e >= n:
            lst.insert(i, n)
            insertion_done = True
            break
    if not insertion_done:
        lst.append(n)
# End of the function definition.


lst = [10, 20, 30, 40, 50]
n = 15
my_insort_left(lst, n)
print 'Wrapped to the function:', lst

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial