Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
Two strings M and W are given, need to check if one is subsequence of another.
I tried the following:
def filterr(bigStr,smallStr,i):
res=''
for char in bigStr:
if(char in smallStr[i:]):
i+=1
res+=char
return res
m,w=input().split()
if(m==w):
print('YES')
else:
if(len(m)<len(w)):
m,w=w,m
s=filterr(m,w,0)
if(s==w): print('YES')
else: print('NO')
I don't understand what is wrong with my above code. It's not working for some unknown testcases (on a coding site). I have tried all types of inputs that I can think of and it is giving the correct answer for all of them.
Examples:
i/p: "john johanna" o/p: YES
i/p: "ira ira" o/p: YES
i/p: "kayla jayla" o/p: NO
Please help in finding why my code is not working for some unknown testcases.
Think about a test case:
m = "baab"
w = "ab"
With your filterr implementation, filterr("baab", "ab", 0) will return "bb" not "ab". Since "bb" != "ab", it will not think "ab" as a subsequence of "baab". But it is clear that "ab" is a subsequence of "baab".
To solve this subsequence problem, I'd recommend using two pointers approach.
# assume len(s) <= len(t)
def is_subsequence(s, t):
p1 = 0
p2 = 0
while p1 < len(s) and p2 < len(t):
if s[p1] == t[p2]:
p1 += 1
p2 += 1
else:
p2 += 1
return p1 == len(s)
you will understand what is wrong with your code after reading this solution
Try this:
https://www.geeksforgeeks.org/given-two-strings-find-first-string-subsequence-second/
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
def trouble(x, t):
for i in range(0,len(x)):
if (x[i]+ x[i+1]) == t:
return x
else:
return None
answer = trouble([4,5,6,7], 9)
print(answer)
Firstly it's not quite clear what you're actually asking, you just shoved a code blob and a title. Assuming you want someone to tell you if your code is correct; it is not.
Now this really just looks like a homework problem, so I won't just post an answer code blob, but here are some comments that might be useful:
def trouble(x, t):
for i in range(0,len(x)): # Range starts at 0 even when not specified
if (x[i]+ x[i+1]) == t:
return x
# You also want to remove the second number no ?
# Hint: you could use slicing, or the list remove(elem) function
else:
# Because this is in the loop it will return immediately
# if the if condition fails (ie: you'll only ever
# look at the first element !
return None
answer = trouble([4,5,6,7], 9)
print(answer)
Is this that you want done. It removes the second value that adds up to t. And returns that new list.
def trouble(x, t):
x = list(x)
for i in range(0, len(x)-1):
if (x[i]+ x[i+1]) == t:
y = list(x)
y.pop(i+1)
return y
else:
return None
answer = trouble([1,3,6], 9)
print(answer)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to solve
https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/bracket-sequence-1-40eab940/submissions/ in python
Its showing Time Exceed Error. Can anyone tell me how time complexity can be decreased?
Here is my code:
def findBalanced(expr):
stack = []
for char in expr:
if char in ['(']:
stack.append(char)
else:
if not stack:
return False
current_char = stack.pop()
if current_char == '(':
if char != ')':
return False
if stack:
return False
return True
if __name__ == '__main__':
expr = input()
count = 0
for x in range(len(expr)):
expr = expr[1:] + expr[0]
if findBalanced(expr):
count +=1
else:
pass
print(count)
How to solve this problem using minimum time and minimum space?
I suggest adding the line print(stack) at the beginning or the for loop. Then execute your algorithm on a few example inputs. You might notice something a bit weird.
Please take a second to actually do it, and try to find out what's so weird about it. This will give you inspiration on how to improve your algorithm.
...
Did you do it? Please don't read further until you've done it.
The remainder of this answer assumes that you have added print(stack) at the beginning of the for loop, and that you have looked at the output on a few examples of input, and that you have tried to notice something a bit surprising about the outputs. Please do that before you read the remainder of this answer.
Your algorithm maintains a stack, but if you output the stack at every iteration, you'll notice something: the stack only contains copies of the character (. Nothing else. This is because the only occurrence of stack.append(char) is right under if char in ['(']:, so you are only ever appending (.
So really the only information contained in this stack is how many ( it contains. Instead of actually maintaining the stack, you could simply maintain a counter, i.e., an integer telling you how many ( would be on the stack if you had a stack.
Replace stack = [] with depth = 0, then stack.append(char) with depth += 1 and stack.pop() with depth -= 1.
Your check if current_char == '(': is not useful at all, because the chars on the stack are all (, so the check is always true and thus redundant.
I will let you figure out on which values of the counter you should return true and on which values you should return false. Good luck!
def solve(s):
p=0
t=0
res = 0
for i in s:
if(i=='('):
p+=1
else:
p -= 1
if (p<t):
print(f"Values of p and t are {p} and {t}")
t=p
res = 0
if(t==p):
res+=1
if p:
return 0
else:
return res
s= input()
print(solve(s))
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to solve this problem on hacker rank:
Here is my code:
L = []
check = True
num_cases = int(input())
for i in range(num_cases):
num_cubes = int(input())
inp = input()
L = inp.split(" ")
for m in range(0, len(L)):
L[m] = int(L[m])
while len(L) != 1:
x = max(L)
if L.count(x) <= 2:
if x == L[0] or x == L[-1]:
while x in L:
L.remove(x)
else:
check = False
break
else:
check = False
break
if check == False:
print("No")
else:
print("Yes")
L = []
check = True
Here I check if the maximum values of the list lie on either end of the list.
This code is working for all the cases that I have given it but works for none of the cases that the website gives it.
Test case 1: Here
Expected solution to test case 1: Here
PS. please inform me if I need to edit my question in any way.
the L.count(x) <= 2 is not correct, as long as it's at either end repeated number are fine e.g. 1 1 1 1 1 1 should be Yes
the while x in L bit is also incorrect, on two fronts
given 2 1 2 1 2 you're going to remove the 2 from the middle of the sequence, which should not be the case
not that this matters because you're also misunderstanding the behaviour of while... else, so this is never going to work either
finally the way you're going at it is extremely inefficient as you're traversing the entire sequence (looking for the max) on every iteration, with a double-ended queue (collections.deque) this can be solved in O(n):
define a "tip of stack" larger than anything possible (e.g. 231 or 232)
check which is the largest of the first or last of the row
if that is larger than your tip of stack, the row is not stackable
otherwise pop it (popleft/pop) and set it as the new tip of stack
then loop around to (2)
alternatively you can first pop the larger end of the row, then check against the current tip, then set as the new tip, same difference:
def solve(cubes):
"""
:param list(int) cubes: cube edge length
:rtype: bool
:returns: whether the input cubes can be stacked
"""
current = 2**32
cubes = collections.deque(cubes)
while cubes:
# pick largest value from either end
if cubes[0] > cubes[-1]:
val = cubes.popleft()
else:
val = cubes.pop()
# found a cube that's larger than the current top of the
# stack, can't solve
if val > current:
return False
current = val
return True
Also note that for this sort of things you might be well-served by:
separating the "parsing" step from the "resolution" step, this lets you more easily feed values and check results
learn about property-testing tools like hypothesis which can automatically generate and reduce test cases as long as you can define a property which should always hold (that's the hardest part)
You should remove if L.count(x) <= 2: , that is one error in your code's logic.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
The problem is given here
I am coding in python and my code is given below:
num =raw_input()
li=list()
count=150*[0]
ans=0
while num>0:
li.append(raw_input())
num=int(num)-1
for i in range (0, len(li)):
for j in range(0, len(li[i])):
count.insert (ord(li[i][j]), count[ord(li[i][j])]+1)
for i in range(0, len(count)):
if count[i]==len(li):
ans=ans+1
print ans
On running the sample test case the output is 3 instead of 2.
Where am I going wrong?
There are several things wrong with your program.
First the insert method doesn't do what you seem to think it does.
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
Second, you're attempting to count every time a letter appears at all, not just the first instance in a line.
This also looks like a low effort question, which is why you're getting downvoted. What have you tried?
Here's a solution that uses your method correctly, but it's still not a very pythonic approach. Have you considered using a dict to keep track of this information instead?
num = raw_input()
li = list()
count = 150*[0]
seen = 150*[False]
ans = 0
while num > 0:
li.append(raw_input())
num = int(num)-1
for i in range(0, len(li)):
for j in range(0, len(li[i])):
if (not seen[ord(li[i][j])]):
count[ord(li[i][j])] += 1
seen[ord(li[i][j])] = True
seen = 150*[False]
print count
for i in range(0, len(count)):
if count[i] == len(li):
ans = ans+1
print chr(i)
print ans
Here's the same approach using more pythonic language, isn't this much easier to understand?
num = raw_input()
lines = []
seen = set()
count = {}
while num > 0:
lines.append(raw_input())
num = int(num)-1
for line in lines:
for char in line:
if (char not in seen):
count[char] = count.get(char, 0) + 1
seen.add(char)
seen = set()
print count
print list(count.values()).count(len(lines))
There are, of course even better ways to do this.
The website states: Required Knowledge: Implementation, Sets: Time Complexity: O(n)
So using set.intersection would be a better way to go:
num = raw_input()
sets = [set(raw_input()) for x in range(int(num))] ]# make set from each line
print len(set.intersection(*sets)) # find letters that are common in all sets and print the length
You are counting c as a gem-element. It occurs 3 times, but not in 3 different lines. Thus count[i]==len(li) is not a sufficient criterion for a gem-element.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
there are two strings:
str1 = "black_red_yellow"
str2 = "blue_red_green"
which python library can I use to check these two strings have a substring"_red_" in common? thank you in advance.
Something like this should work if you don't know the actual string you're searching for
import difflib
str1 = "black_red_yellow"
str2 = "blue_red_green"
difference = difflib.SequenceMatcher()
difference.set_seqs(str1, str2)
for match in difference.get_matching_blocks():
print str1[match[0]:match[0] + match[2]]
test for presence of common substring, including length 1:
if set(str1).intersection(set(str2)): print "yes we can!"
if you can't find anything else, then there's at least this naive implementation:
str1 = "black_red_yellow"
str2 = "blue_red_green"
if len(str1) < len(str2):
min_str = str1
max_str = str2
else:
min_str = str2
max_str = str1
matches = []
min_len = len(min_str)
for b in xrange(min_len):
for e in xrange(min_len, b, -1):
chunk = min_str[b:e]
if chunk in max_str:
matches.append(chunk)
print max(matches, key=len)
prints _red_
You can use difflib to compare strings in that way. However, if you know the string you're looking for you could just do '_red_' in str1 and '_red_' in str2. If you don't know the string, then do you look for a specific length of match? E.g. would 'red' match 'blue' because they both contain 'e'? The shortest, simplest way of checking for any match at all would be
bool([a for a in str1 if a in str2])
Edit: Or, more efficiently,
any(a for a in str1 if a in str2)