Why is this code not valid for all the cases? [closed] - python

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.

Related

how can I plan this sequence-1,2,2,3,4,4,5 [closed]

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 2 months ago.
Improve this question
I am fairly new to programming and I try to create the above mentioned sequence.
this problem is about having a strict length of elements which always progresses, this progression is inside the list by moving on the indexes. this strict length shifts from a set of indexes to the next one once all the indexes inside the strict length (not passing it's limits) are finished being scanned, and they are scanned in a format of "one after the other".
after all of that we come to the root of the problem:
once the strict length moves to another set, it starts from the last index that was previously, inside of the strict length but in the previous strict length.
the output of the root problem is the title of this post. I don't know how to solve the root problem.
this problem, involves "k" as an exponent of the strict length.
this is the script:
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while True:
for i in range(k):
print(strarr[n])
n = n+1
print(strarr[n])
the output I got is:
1,2,3,3,4,5,5,6,7,7,8,9,9,10
and I don't know why I got such output, it doesn't seem logical.
As I can understand what you are looking for is to print the even numbers twice.
You can do the following without using a for loop by this way.
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while (n<10):
if(int(strarr[n])%2 == 0):
print(strarr[n])
print(strarr[n])
elif(int(strarr[n])%2 != 0):
print(strarr[n])
n = n+1
The reason why your code gives that output is because,
for the 1st iteration it would print 1, 2, 3
2nd iteration it would print out 3 again as there is another print(stararr[n]) outside the for loop. That's the reason why you are getting the output you are getting.
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while True:
for i in range(k):
print(strarr[n])
n = n+1
print(strarr[n])
The error that I think you're seeing has to do with the order that you print your output and update the index n. In the current, buggy code, you're printing first, then updating the value. This means that the second print outside of the inner loop prints using the next value of n, not the one you just used in the inner loop. The same index gets used a second time in the first pass of the inner loop the next time, but that's not the value you wanted to see repeated.
The solution to this issue is pretty simple. Rather than updating after you print, update before. You'll need to adjust the starting value of n, but that's no problem:
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = -1 # change starting index
while True:
for i in range(k):
n = n+1 # and reorder the lines in the inner loop
print(strarr[n])
print(strarr[n])
That said, the two loop thing is a lot more awkward than anything I'd really recommend. If you just want to repeat the odd-indexed values in the loop, you can do that much more simply:
for index in range(len(strarr)):
print(strarr[index])
if index % 2 == 1:
print(strarr[index])
Or you can avoid directly needing to index at all, using enumerate to get the index and value of each element in the for statement itself. This is probably a more "Pythonic" way to solve the problem.
for index, value in enumerate(strarr):
print(value)
if index % 2 == 1:
print(value)

Bracket Question in Python . Solve in Minimum Time and Space? [closed]

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))

Extracting the subsequence of maximum length from a sequence [PYTHON] [duplicate]

This question already has an answer here:
Longest increasing unique subsequence
(1 answer)
Closed 6 years ago.
I have a sequence of values [1,2,3,4,1,5,1,6,7], and I have to find the longest subsequence of increasing length. However, the function needs to stop counting once it reaches a number lower than the previous one. The answer in this sequence in that case is [1,2,3,4]. As it has 4 values before being reset. How would I write the Python code for this?
Note: Finding the "longest increasing subsequence" seems to be a common challenge and so searching online I find a lot of solutions that would count for the entire length of the sequence, and return a subsequence of increasing values, ignoring any decrease, so in this case it would return [1,2,3,4,5,6,7]. That is not what I'm looking for.
It needs to count each subsequence, and reset the count upon reaching a number lower than the previous one. It then needs to compare all the subsequences counted, and return the longest one.
Thanks in advance.
Consider a function that generates all possible ascending subsequences, you would start with an empty list, add items until one element was less (or equal to?) the the previous at which point you save (yield) the subsequence and restart with a new subsequence.
One implementation using a generator could be this:
def all_ascending_subsequences(sequence):
#use an iterator so we can pull out the first element without slicing
seq = iter(sequence)
try: #NOTE 1
last = next(seq) # grab the first element from the sequence
except StopIteration: # or if there are none just return
#yield [] #NOTE 2
return
sub = [last]
for value in seq:
if value > last: #or check if their difference is exactly 1 etc.
sub.append(value)
else: #end of the subsequence, yield it and reset sub
yield sub
sub = [value]
last = value
#after the loop we send the final subsequence
yield sub
two notes about the handling of empty sequences:
To finish a generator a StopIteration needs to be
raised so we could just let the one from next(seq) propegate out - however when from __future__ import generator_stop is in
effect it would cause a RuntimeError so to be future compatible we
need to catch it and explicitly return.
As I've written it passing an empty list to
all_ascending_subsequences would generate no values, which may not
be the desired behaviour. Feel free to uncomment the yield [] to
generate an empty list when passed an empty list.
Then you can just get the longest by calling max on the result with key=len
b = [1,2,3,4,1,5,1,6,7]
result = max(all_ascending_subsequences(b),key=len)
print("longest is", result)
#print(*all_ascending_subsequences(b))
b = [4,1,6,3,4,5,6,7,3,9,1,0]
def findsub(a):
start = -1
count = 0
cur = a[0]
for i, n in enumerate(a):
if n is cur+1:
if start is -1:
start = i - 2
count=1
count+=1
cur = n
if n < cur and count > 1:
return [a[j] for j in range(start,start+count+1)]
print findsub(b)
A somewhat sloppy algorithm, but I believe it does what you want. Usually i would not have simply shown you code, but I suspect that is what you wanted, and I hope you can learn from it, and create your own from what you learn.
a slightly better looking way because I didn't like that:
b = [1,2,0,1,2,3,4,5]
def findsub(a):
answer = [a[0]]
for i in a[1:]:
if answer[-1] + 1 is i:
answer.append(i)
if not len(answer) > 1:
answer = [i]
elif i < answer[-1] and len(answer) > 1:
return answer
return answer
print findsub(b)
You need to do the following:
Create a function W that given a list, returns the index of the last item which is not strictly increasing from the start of the list.
For example, given the following lists: [1,2,3,4,1,2,3], [4,2,1], [5,6,7,8], it should return 4, 1, 4, respectively for each list
Create a variable maxim and set the value to 0
Repeatedly do the following until your list is empty
Call your function W on your list, and let's call the return value x
if x is greater than maxim
set maxim to x
At this point if you wish to store this sequence, you can use the list-slice notation to get that portion of your list which contains the sequence.
delete that portion of your list from the list
Finally, print maxim and if you were storing the parts of your list containing the longest sequence, then print the last one you got

Check whether an element occurs in a list using recursion [closed]

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 6 years ago.
Improve this question
def check(x,num,i):
for n in range(len(x)):
if x[i] == num:
return True
else:
return(check(x,num,i+1))
return False
def User(x,num):
return(check(x,num,0))
User([2,6,1,9,7,3],5,0)
this should out put false since 5 is not in the list
checks whether an element occurs in a list recursively
so for example:
Input: a list L read from the keyboard, for example L = [2,6,1,9,7,3]
an element e, for example e = 9
but for some reason, i get an error when the number is not in the list
The beauty (and purpose) of recursion is that you do not need the loop:
def check(x, num, i):
if not x[i:]: # index past length
return False
if x[i] == num:
return True
return(check(x, num, i+1))
You can also do without the index parameter:
def check(x, num):
if not x:
return False
return x[0] == num or check(x[1:], num)
I don't exactly understand what you're doing, but this is a bizarre combination of recursion and iteration. If you're going to use recursion, it's worthwhile, at least for a basic recursive problem like this, to avoid iteration. Try something like this
def check(x, num, i = 0):
if i >= len(x):
return False
elif x[i] == num:
return True
else:
return check(x, num, i + 1)
This solution will work perfectly fine and is tail recursive so it will work quickly and optimally.
The way this works is it checks if the index, i, is out of bounds. If so, then it returns False. If it is in bounds, it checks if x[i] is equal to the number. If so, it returns True. If it is not, it returns check with the index increased and thus the recursion works.
First of all, your for loop doesn't make any sense. You never use that n and never go into the loop a second time, as you always return something in the first iteration. The return statement after the for loop is also unreachable, so your code could as well be
def check(x,num,i):
if x[i] == num:
return True
else:
return(check(x,num,i+1))
Then the actual issue is, that if you have a list with 5 elements for example, which does not contain the element searched for, you ask what the 6th is, although there is no 6th element, thus the error. You'd have to check whether the list contains 6 elements. So you check whether it has more than 5, return false if it does and continue if it doesn't. (Alternatively you could also check this at the start of the whole function)
def check(x,num,i):
if x[i] == num:
return True
else:
if len(num)>i:
return False
else:
return(check(x,num,i+1))
What you've done then is nothing but a overcomlicated, recursive for-Loop. You just increase i and compare, until you find the element or i is bigger than the list length. So this is equivalent to
def check(x,num):
for i in range(len(num)):
if x[i]==num:
return True
return False
It is very important that the return False is AFTER the for-Loop, as you only return, if you didn't find the element, even after iterating over the WHOLE list.
Also you can avoid indices. With a for-Loop you can directly iterate over the elements in a list:
def check(x,num):
for elem in num:
if elem==num:
return True
return False
This makes the variable elem become every element in you list, one after another.

Counting numbers in a range [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have to write a Python script that will allow the user to enter a set of positive numbers and then count how many are
equal to 50
greater than 50
less than 50
Use appropriate output to prove that your program is working.
Just for example's sake, let's write a function that counts how many numbers are above 50, then one for equal to 50, then one for less than 50. Disclaimer: this is not the only, or even the BEST way to accomplish what you want to do, this is just the best teaching aid :). Also, some of the nomenclature may change if you're not using Python 3.x.
#this function returns how many values in the list that's passed to it
#are greater than 50
def greaterThanFifty(list_to_compare):
how_many_above_fifty = 0
for value in list_to_compare:
if value > 50:
how_many_above_fifty += 1
return how_many_above_fifty
#this function returns how many values in the list that's passed to it
#are less than 50
def lessThanFifty(list_to_compare):
how_many_under_fifty = 0
for value in list_to_compare:
if value < 50:
how_many_under_fifty += 1
return how_many_under_fifty
#this function returns how many values in the list that's passed to it
#are equal to 50
def equalToFifty(list_to_compare):
how_many_are_fifty = 0
for value in list_to_compare:
if value == 50:
how_many_are_fifty += 1
return how_many_are_fifty
Now we have our functions that will return the values we need. Again, this is not the only or even the best way to do this, but it's the way I'm using because it teaches a lot of basic strategies like writing modular programs (each function is performed by its own bit of code) and using functions rather than straight code to perform your task. Unfortunately, on their own, this code doesn't do anything. It just defines functions that we'll leverage to solve the problem at hand. In essence -- we've made our hammer, nails, and saw, but now we have to cut the lumber to size and nail it up. Let's do that.
def main(): #this is always the name of our function that does the heavy lifting
list_of_numbers = []
user_input = input("List some numbers, comma separated please: ")
for num in user_input.split(","):
#loop through user_input, split by commas
list_of_numbers.append(num.strip())
#add to list_of_numbers each item that we find in user_input,
#stripped of leading and trailing whitespace
#at this point we've looped through all of user_input and added each number
#to list_of_numbers, so we can use our functions, defined earlier, to return
#the requested values. Luckily we set up our functions to accept
#lists!
greater_than_fifty = greaterThanFifty(list_of_numbers)
less_than_fifty = lessThanFifty(list_of_numbers)
equal_to_fifty = equalToFifty(list_of_numbers)
#now just to display the results to the user, and we're done.
print("There are "+str(greater_than_fifty)+" numbers over fifty")
print("There are "+str(less_than_fifty)"+ numbers under fifty")
print("There are "+str(equal_to_fifty)"+ numbers that are fifty")
We still haven't actually DONE anything, though, since all we've done is define functions that do what we want from start to finish. our greaterThanFifty function is our hammer, our lessThanFifty function is our saw, and our equalToFifty function is our nails. Now we've added a main function, which is our handyman. Now we need to tell him to work. Luckily that's easy :)
main()
That's it! We're done!
For comparison purposes, this is how I'd write all that:
input_list = [int(each.strip()) for each in input("Enter a list of numbers, comma-separated: ").split(",")]
print("{} are less than 50, {} are more than 50, {} are 50".format(len([each for each in input_list if each<50]),len([each for each in input_list if each>50]),len([each for each in input_list if each==50])))
You'll get there, young padawan :)
def main():
inp = input('enter number of positive numbers to enter ')
print 'enter the list of positive numbers'
num = []
count_eq = 0
count_gr = 0
count_ls = 0
for elem in range(inp):
num.append(input(''))
for item in num:
if item == 50:
count_eq += 1
if item > 50:
count_gr += 1
if item < 50:
count_ls += 1
print '%d are equal %d are less than and %d are greater than 50' % (count_eq, count_ls, count_gr)
main()
This is a very basic program ! You should start python's beginner tutorial here

Categories

Resources