0

I'm working on some code in which I read in the following binary numbers:

0000
0001
1000
1001
00000000
0000000
000000
00000
0000

And part of the code reads in input such that s = input(). I then call the function accepts(s), which has the following definition:

def accepts(str_input):
    return accept_step(states[0], str_input, 0)  # start in q0 at char 0

The accept_step function is defined as:

def accept_step(state, inp, pos):
    if pos == len(inp):  # if no more to read
        return state.is_final_state   # accept if the reached state is final state
    c = inp[pos]    # get char
    pos += 1
    try:
        nextStates = state.transitions[c]
    except():
        return False    # no transition, just reject

    # At this point, nextStates is an array of 0 or
    # more next states.  Try each move recursively;
    # if it leads to an accepting state return true.
    """
    *** Implement your recursive function here, it should read state in nextStates
    one by one, and run accept_step() again with different parameters ***
    """
    for state in nextStates:
        if accept_step(state, inp, pos): #If this returns true (recursive step)
            return True
    return False    # all moves fail, return false


"""
 Test whether the NFA accepts the string.
 @param in the String to test
 @return true if the NFA accepts on some path
"""

I get this error:

    if pos == len(inp):  # if no more to read
TypeError: object of type 'int' has no len()

I have already tried using str(s) (conversion), such as in input(str(s)) and accepts(str(s)), but to no avail.

It seems that for whatever reason, my input text is being read in as integers, and not as strings.

I would like to read my input in as strings and not integers, and be able to use the len() property of strings to execute my program. Could someone please point me in the right direction, and explain to me why my input is read in as integers and not strings? I thought if I specifically wanted integer input, I would have to use something like int(input())?

1 Answers1

-1

Python attempts to assume the type of the variable that is input. In this case it believes that you are entering integers. So try str() around the input during assignment.

s = str(input())
accepts(s)

For example some tests in Python3:

>>> a = 1001
>>> isinstance(a, int)
Returns: True

>>> b = '1001'
>>> isinstance(b, int)
Returns: False

>>> c = str(1001)

>>> isinstance(c, int)
Returns: False

>>> isinstance(c, str)
Returns: True

>>> len(c)
Returns: 4
Alex
  • 1
  • 1