0

I am trying to compare and see if a particular character exists in the string, but when i try to access the character which is in another string, its throws an error 'argument of type 'int' is not iterable'. How do i access the character from a string without causing the error?

    def lengthOfLongestSubstring(self, s: str) -> int:
        longStrLen = 0
        totalStrLen = len(s)

        holderString = ""
        holderString += s[0]
        longStrLen = 0

        for i in range(1,totalStrLen-1):

            if s[i] not in holderString:
                holderString += s[i]
            else:
                if longStrLen < len(holderString):
                    longStrLen = len(holderString)
                holderString = 0

        return longStrLen
TypeError: argument of type 'int' is not iterable at Line 
if s[i] not in holderString:
9
  • 5
    holderString = 0 You've reassigned holderString to an integer, and it's not a string any more. Commented May 24, 2019 at 17:05
  • 1
    Specifically when you check whether the character exists in the string, you set the whole holderstring to 0 when you encounter a duplicate letter. cat will run but caaat will not Commented May 24, 2019 at 17:10
  • Why is this a method? You don't use self anywhere in the body. Commented May 24, 2019 at 17:10
  • What exactly is the function supposed to do? It appears that you just want the index of the first repeated character. Commented May 24, 2019 at 17:11
  • @chepner I would assume due to the inclusion of self it's from a class, but for the minimal reproducible example, the asker (correctly) only provided the nonworking snippet of code Commented May 24, 2019 at 17:14

2 Answers 2

3

Your problem is on this line:

holderString = 0

You reassigned the holderString variable to the integer 0. While strings can be iterated over, integers cannot. You attempt to iterate over the new integer on this line:

if s[i] not in holderString:

which causes the error.

There is a much better way to approach a function that returns the first repeated character though. Simply use the index() method:

def findChar(char, string):
    for c in string:
        if c == char: 
             return string.index(c)
Sign up to request clarification or add additional context in comments.

Comments

0

It appears you only need to count unique characters until you find the first duplicate. You can do that with a set.

def longest_substring(s: str) -> int:
    seen = set()
    for c in s:
        if c in seen:
            break
        seen.add(c)
    return len(seen)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.