Python Forum
Determine if string is integer
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Determine if string is integer
#11
Here is my proposal, using a deterministic finite automaton
def isinteger(x):
    D = {(0, ' '): 0, (0, '+'): 1, (0, '-'): 1, (0, '.'): 2,
        (1, ' '): 1, (1, '.'): 2, (2, '0'): 4,
        (3, '.'): 4, (3, ' '): 5, (4, '0'): 4, (4, ' '): 5,
        (5, ' '): 5,}
    s = 0
    for c in x:
        if (s, c) in D: s = D[(s, c)]
        elif c in '0123456789':
            if s in (0, 1, 3): s = 3
            else: return False
        else: return False
    return s > 2
Reply
#12
(Oct-15-2019, 07:19 AM)DeaD_EyE Wrote: You can reimplenent the wheel or trust Python.

Or you can do the actual assignment. Your solution fails the assignment because it returns True for 1.000013. The assignment isn't "can this string be converted to an integer," it's "does this string represent an integer."
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#13
@DeaD_EyE - agree, but the assignment precludes the use of try...except which is the reason for my rant.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Using an integer to manipulate a string/text variable rexyboy2121 1 1,703 Apr-22-2020, 01:37 AM
Last Post: michael1789
  Converting String to Integer Python Johnny1998 5 3,013 Aug-02-2019, 08:13 PM
Last Post: Johnny1998

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020