Link to home
Start Free TrialLog in
Avatar of ittechlab
ittechlabFlag for Canada

asked on

python - user input - set

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])
Avatar of pepr
pepr

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.)
SOLUTION
Avatar of aikimark
aikimark
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ittechlab

ASKER

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
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial