+ 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
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
+ 2
Erlénio.RS , it's typo bro his question is how to extract integer from a string faster then O(n)
+ 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))
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.
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/