Index out of range in leetcode ide in code for finding the length of the longest substring without repeating characters - python-3.x

This below giving expected output in pycharm and the other side it's getting index out of range in line return length_of_substring[-1] in leetcode.
why it is getting such error?
class Solution:
def lengthOfLongestSubstring(self, string):
unique_list = []
length_of_substring = []
for i in string:
if i not in unique_list:
unique_list.append(i)
else:
length_of_substring.append(len(unique_list))
unique_list.clear()
unique_list.append(i)
length_of_substring.sort()
return length_of_substring[-1]
if __name__ == '__main__':
s = input()
obj = Solution()
result = Solution.lengthOfLongestSubstring(obj, s)
print(result)

First of all: when posting here you should clearly specify (i) the goal of your code and (ii) a self contained minimum example.
In your case it is very difficult to answer your question, because you do not make clear what your code is actually trying to achieve.
Regarding your error message:
Your code does not account for the fact that a string could also consist of only unique elements (e.g. "abcd"). In that case the else clause of your code is never reached and length_of_substring will remain empty. If you then call length_of_substring[-1] it raises an error message.

Related

Checking words using "YNEOS"

In this problem, I take two strings from the user, the first string being s and the second string being t. If t is the reverse of s, I print "YES" else I print "NO".
Here is my code which gives me expected outputs:
s = input()
t = input()
if t == s[::-1]:
print("YES")
else:
print("NO")
But I found another approach that I am curious to understand, but the slicing part is making me confused. Here the code goes:
print("YNEOS"[input()!=input()[::-1]::2])
Trying to find a good explanation, so StackOverflow is what came to my mind before anything else.
Let's first extract the parts of that expression that concern the input/output and the string reversal. We then get this solution:
s = input()
t = input()
trev = t[::-1]
result = "YNEOS"[s != trev::2]
print(result)
The focus of the question is on the expression "YNEOS"[s != trev::2]
Now we get to the "trick" that is performed here. The expression s != trev can be either False or True. This boolean value becomes the first part in the slicing. You'd expect to have the start index of the slice at this position. But the boolean value will also work, as booleans are a subclass of integers, and False is 0 and True is 1. So the above expression evaluates to either:
"YNEOS"[0::2]
or
"YNEOS"[1::2]
The 2 serves as the step, and so "YNEOS"[0::2] will take the characters at indices 0, 2 and 4 ("YES"), while "YNEOS"[1::2] takes the characters at indices 1 and 3 ("NO").
I hope this clarifies it.

canConstruct a memorization dynamic programming problem

I am stating to solve some dynamical programming problem, I came across the problem to solve if a string can be constructed from a list of string.
I have use this following method in python 3.8.
def canConstruct(target,workbank,memo={}):
if (target in memo):
return(memo[target])
if len(target)==0:
return(True)
for i in range (len(workbank)):
pos=target.find(workbank[i])
if (pos != -1):
suffix=target[pos:pos+len(workbank[i])]
out=canConstruct(suffix,workbank,memo)
if (out==True):
memo[target]=True
return(True)
memo[target]=False
return(False)
print(canConstruct('aabbc',['aa','b','c']))
instead of getting true I am getting the error maximum recursion depth exceeded in comparison.
I have checked my recursion limit it is 1000.
Can anyone tell me if I am doing anything wrong.
Thank you in advance.
Ok, there are few pitfalls in your code.
The main issue was, the for loop, because every time it calls the function, it started a new loop, hence the index of i was always one, this was creating the maximum recursion depth error.
The memo parameter, was been redundant to make it as a Dictionary,better in this case as a List.
This suffix=target[pos:pos+len(workbank[i])] had wrong position, it is supposed to be:
suffix = target[len(workbank[idx]):]]
Becase you need to leave behind was is already call and move forward right?
You were doing [0:2] which is 'aa' again. Insted you should do [2:] which is bbc
Solution
Note: I create as I understood the issue, if you expect a different output, please let me know in a comment below.
def canConstruct(target,workbank,memo=[], idx=0):
pos = target.find(workbank[idx])
if pos != -1:
memo.append(True)
idx += 1
try:
suffix = target[len(workbank[idx]):]
canConstruct(suffix,workbank,memo, idx)
except IndexError: # Here we exit the recursive call
pass
else: # In case it did not find string, append False
memo.append(False)
return all(memo) # in order to be True, all item in memo must be True
print(canConstruct('aabbc',['aa','bb','c']))
Output
# True
def canConstruct(target, wordbank, memo=None):
if memo is None:memo={}
if target in memo:return memo[target]
if target == '':return True
for word in wordbank:
if target.startswith(word):
suffix = target.replace(word, '', 1)
if canConstruct(suffix, wordbank, memo) == True:
memo[target] = True
return True
memo[target] = False
return False

Why KeyError raises even the respective key exists?

def countLetter(string):
dic = dict()
for char in string:
dic[char] = (1,dic[char]+1)[char in dic]
print(dic)
countLetter('aabcb')
Here, I'm trying to count the number of times each letter has occured, but the line 4 raises an error.
It raises an KeyError.
The problem is that this line:
dic[char] = (1,dic[char]+1)[char in dic]
is eagerly evaluating dic[char]+1 as part of constructing the tuple to index before you get around to testing if char in dic to select the element of the tuple. So it dies with a KeyError before your test has a chance to prevent the failing lookup. To make it lazy, you could do:
dic[char] = dic[char] + 1 if char in dic else 1
or you could just use a method designed for this to avoid the explicit test:
dic[char] = dic.get(char, 0) + 1
Though this particular pattern is made even simpler with collections.Counter:
import collections
def countLetter(string):
print(collections.Counter(string)) # print(dict(collections.Counter(string))) if it must look like a dict

Writing a function to see how many times a character appears in a set of words

To better help understand the fundamentals, my professor asked people in our class to write a function to see how many times a character appears in a set of words. I am having trouble integrating ord() into the function. Also, I understand that there are easier ways of getting the outcome.
Here is what I have so far:
def function(char):
word = "yes"
for char in word:
ord(char)
return ord(char)
function('y')
I don't get any errors - but I also don't get anything back
That is because you aren't printing anything!
Also, there are issues in your code, first one being the parameter 'char' and the 'char' in the for loop have the same name, that will cause issues.
A small code to find the count of a given letter can be something like this:
def function(word, char):
count = 0
for c in word:
if c == char:
count = count + 1
return count
print (function("yes", 'y'))
return will automatically end a function, and not keep it going.
there are also a lot of variables that you are not using, like the char parameter you passed to your function. when using the for loop, the variable created after for will be reassigned.
try this:
def function():
word = 'yes'
NewList = []
for char in word:
NewList.append(ord(char))
return NewList
print(function())
however what i think would be better:
def function(word):
NewList = []
for char in word:
NewList.append(ord(char))
return NewList
print(function('blahblah'))
also, when simply calling a function from a file, the returned value is not automatically displayed, you must include a call to print

Index out of range - Python

I was programming at CodeWars using Kata, when i got this error:
Traceback:
in
in title_case
IndexError: list index out of range
Here is my code:
def title_case(title, minor_words=1):
string = title.split()
outList = []
if minor_words != 1:
split = minor_words.split()
minor = [x.lower() for x in split]
out = ""
for i in range(0, len(string)):
word = ""
for j in range(0,len(string[i])):
elem = ""
elem += string[i][j]
if j == 0:
word += elem.upper()
else:
word += elem.lower()
if i != len(string)-1:
outList.append(word+" ")
else:
outList.append(word)
list = [x.lower() for x in outList]
print ((list[0]))#Just for debug
if minor_words != 1:
for i in range(0, len(outList)):
if (list[i] in minor):
print("OI")#Just for debug
out += list[i]
else:
out += outList[i]
return out
Well, this happened when trying to execute the code, of course!
One way to initialize this function would be:
title_case('a clash of KINGS', 'a an the of')
Well the 0 elemeny exists, but it says it doesn't, I don't know why, because when I write "print(list)" it shows me the elements of list, in this case, "['a', 'clash', 'of', 'kings']".
What can I do?
Okay, so based on reading this code I think the result you desire from:
title_case('a clash of KINGS', 'a an the of') is:
A Clash of Kings
So it looks like you are stepping through a lot of hoops trying to get there. While I was going through the code it took me a while to see what was actually happening. I also took the liberty to make your variables more consistently named. Rather than mixing caseLetter and case_letter randomly I made it consistent. I also made your loops easier to read. Also for the minorWords argument. Might as well have it passed as a list rather than converting it to a list inside the function. Anyway, I hope this is of help.
def titleCase(title, minorWords=[]):
titleList = [x.lower() for x in title.split()]
outList = []
for Word in titleList:
if Word not in minorWords:
Word = Word.capitalize()
outList.append(Word)
return " ".join(outList)
TitleCased = titleCase("a clash of KINGS", ["an", "the", "of"])
print (TitleCased)
Which outputs A Clash of Kings, which I believe, based on your question and how I understood your code is what you wanted to achieve? Or if you include a in your minorWords, it would be:
a Clash of Kings
Regardless, hope this answers your question!

Resources