Avatar of ittechlab
ittechlab
Flag 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])
Python

Avatar of undefined
Last Comment
pepr

8/22/2022 - Mon
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
aikimark

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
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
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck