+ 1

How to extract integers from a string

Hi I am trying to extract a string from integer: For example: Given an input: Input = Stal2ling I know I can do this? list = [] for i in Input: try: i = int(i) list.append(i) except: print(i + "is" not an integer") But I think this would be O(n) in time complexity.Is there a way I can make it more efficient. My output should be a list of the integers that are in the string

28th Sep 2021, 3:52 AM
Richard
Richard - avatar
6 Answers
0
I just found out that python has an inbuilt order for numbers and strings. Therefore "2" is less than "e"(all numbers are less than strings even though they are in "" - string form) Therefore it is possible to use binary search. question closed. Thankyou all for your time
28th Sep 2021, 5:57 AM
Richard
Richard - avatar
+ 2
Erlénio.RS , it's typo bro his question is how to extract integer from a string faster then O(n)
28th Sep 2021, 4:50 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 2
Best Way to Get Numbers From String: x=input() lst=[] for i in x: if i.isdigit(): lst.append(i) else: None print(''.join(lst))
28th Sep 2021, 4:58 AM
Sancho Godinho
Sancho Godinho - avatar
0
You're messing around, your problem says something, and your code illustrates something different. If your question is how to extract integers from strings, you can use the code below: userinput = "th6i3fh7" for i in userinput: if i.isdigit(): print("{0} is an integer".format(i)) else: print (i+" is not an integer") If that's what's at issue, extracting strings into integers, in my opinion I think it's impossible, because an integer with characters will never be accepted.
28th Sep 2021, 4:29 AM
Erlénio.RS
Erlénio.RS - avatar
0
You could use binary search instead of linear search. Time complexity would be O(log n) Here is an example of binary search for arrays: https://www.google.com/amp/s/www.geeksforgeeks.org/JUMP_LINK__&&__python__&&__JUMP_LINK-program-for-binary-search/amp/
28th Sep 2021, 4:33 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
0
Richard ,yup and it's not just python,if you convert chars to int numbers will always be smaller, cuz of ASCII...
28th Sep 2021, 6:38 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar