Function to find a continuous sub-array which adds up to a given number in python [closed] - python

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 last month.
Improve this question
I want to know what's wrong in the below code. Will it consume more time to in some certain scenarios?
Expected time complexity: O(n)
def subArraySum(self,arr, n, s):
if sum(arr[0:n]) == s:
return [1, n]
if sum(arr[0:n]) < s:
return [-1]
start = 0
i =1
sum_elements = 0
while i < n:
sum_elements = sum(arr[start:i+1])
if sum_elements == s:
return [start+1, i+1]
if sum_elements < s:
i += 1
continue
if sum_elements > s:
start += 1
continue
if sum_elements < s:
return [-1]

Instead of running sum(arr[start:i+1]) in each iteration of the while loop, you should use a variable and add or subtract the respective value that is included or excluded from the subarray in each iteration. That way you can avoid the O(n^2) complexity and stay within O(n).
Currently there is a lot of overhead for calculating the sum of a (potentially large) subarray that has only changed by one single value at the beginning or the end during each iteration.

Related

How to get list of palindrome in text? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 10 months ago.
Improve this question
I have the following interview question that may require traversing through the entire string.
Problem I searched about find Problem and most people do it like this def palindrome(s): return s==s[::-1] But this task is diffrent?
palindrome is a word the can read from both directions like 'mam', 'dad'. Your task is to get a list of palindrome in a given string.
def palindrome(s):
stack = []
return ['aaa']
exampls
palindrome('aaa') #['aaa']
palindrome('abcbaaaa') #['abcba','aaaa']
palindrome('xrlgabccbaxrlg') #['abccba']
palindrome('abcde') #['']
Let's try to avoid checking all the possible combinations :). My idea is, start from the extremities and converge:
def palindrome(s):
out = [''] #we need the list to not be empty for the following check
for main_start in range(len(s) - 1):
for main_end in range(len(s) - 1, main_start, -1):
start = main_start
end = main_end
while (end - start) > 0:
if s[start] == s[end]: ##may be palindrome
start += 1
end -= 1
else:
break
else:
if s[main_start:main_end + 1] not in out[-1]: #ignore shorter ("inner") findings
out.append(s[main_start:main_end + 1])
return out[1:] #skip the dummy item

Difference in Selection Sort Algorithm [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 last year.
Improve this question
Can someone help explain if these two selection sorts have different Big O notations for worst case scenarios or are they the same? Thanks a lot.
""" Selection Sort 1: This function uses 'find_smallest' function
Question: In the worst case, will selection_sort1 be O(nlogn) since
the size of the arr decreases by 1 every time the for loop runs? """
def selection_sort1(arr):
new_arr = []
for i in range(len(arr)):
smallest = find_smallest(arr)
new_arr.append(arr.pop(smallest))
return new_arr
""" Selection Sort 2: This function uses 'min()' function and 'remove()' method. Since these methods run for
O(n).
Question: is it cleverto conclude that selection_sort2 funtion will
runfor O(n^2)? and therefor selection_sort1 is betterthan
selection_sort2? """
def selection_sort2(arr):
new_arr = []
for i in range(len(arr)):
new_arr.append(min(arr))
arr.remove(min(arr))
return new_arr
This function is used by Selection_sort1
def find_smallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
Test Case
arr = [5,2,8,5,1,9,4]
print(selection_sort1(arr))
I believe it is because selection sort #2 has more processes inside the for-loop.

How do I make a function that adds once and subtract once for every number in the list? [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 1 year ago.
Improve this question
This is my code, but I figured out that it only works if the numbers are 'even and odd in that order' so, How do I create a function that adds and then subtracts for every number in the list, so like if my list is 1,3,4,5 then the output is 1+3-4+5 or if my list is 4,6,7,4,5,3 then the output would be 4+6-7+4-5+3... please help
def alt_sum(lst):
total = 0
for i, value in enumerate(lst):
if i % 2 == 0:
total += value
else:
total -= value
return total
print(alt_sum([3, 4, 5, 8]))
If the index is greater than 0 and an even number, take the negative value, and then add.
def alt_sum(lst):
alt_lst = [-v if (i % 2 == 0 and i > 0) else v for i, v in enumerate(lst)]
# print(alt_lst)
return sum(alt_lst)
print(alt_sum([3, 4, 5, 8]))
your explanation and sample intput/output differs.
your code is right by your explanation if you meant even and odd in that order as index, but is wrong based on sample input/output. Heres what should be based on sample input/output:
def alt_sum(lst):
total = lst[0]
for i in range(1,len(lst)):
if i % 2 == 0:
total -= lst[i]
else:
total += lst[i]
return total
print(alt_sum([3, 4, 5, 8]))
same thing, I'd prefer the above one.
def alt_sum(lst):
return lst[0]+sum([lst[i] for i in range(1,len(lst),2)])-sum([lst[i] for i in range(2,len(lst),2)])

Python Really Basic For Loop question. Why is it loop forever? [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 years ago.
Improve this question
def print_range(start, end):
# Loop through the numbers from start to end
n = start
while n <= end:
print(n)
print_range(1, 5) # Should print 1 2 3 4 5 (each number on its own line)
Basic For Loop question. Why is it loop forever?
You never increase n, therefore your code keeps on printing 1.
Change your code to:
def print_range(start, end):
# Loop through the numbers from start to end
n = start
while n <= end:
print(n)
n+=1
print_range(1, 5) # Should print 1 2 3 4 5 (each number on its own line)
Your loop variable, n, is not changed within the while loop so it always stays equal to start and thus it is (likely) less than end forever.
Add n = n+1 to the loop.
You should really mark up your code.
use ``` at the beginning and end of your code to make it a code block.
def print_range(start, end):
# Loop through the numbers from start to end
n = start
while n <= end:
print(n)
n += 1
print_range(1, 5) # Should print 1 2 3 4 5 (each number on its own line)

How does this for loop on consecutive integers work? [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 5 years ago.
Improve this question
This seems like an embarrassingly easy concept but I can't understand why this for loop is working the way it is. The question is simply asking "Given a binary array, find the maximum number of consecutive 1s in this array."
def main(nums):
count = 0
for num in nums:
if num == 1:
count+=1
else:
count = 0
main([1,1,0,1,1,1,0,0,1,1,1,1,1])
My question is, why does this for loop work? I expected the loop to print out the total count of 1's.
It just doesn't work.
You can't expect to have the sum of all the 1s because when the loop find a zero it reset the counter (the "else" part).
However, your code doesn't do what it was expected to do, add a zero at the end of the list and you will easily see that the code fails.
To do what you asked, without changing your code too much, try this
def main(nums):
count = maxcount = 0
for num in nums:
if num == 1:
count+=1
else:
maxcount=max(maxcount, count)
count = 0
return maxcount
print(main([1,1,0,1,1,1,1,1,1,0,0,1,1,1,1,0,1]))
Dave
The difference is that once it sees a zero, it sets the value of count back down to zero, saying that it's seen 0 consecutive ones. This code actually doesn't work—it only gets lucky on this input because the longest sequence is at the very end of the list.
A better practice would be to store both the lengths of the current_group of ones and the highest_total count.
It's probably hard to believe, but could it be that the reason you are wondering why this loop works at all is that you are not familiar with Python ability to iterate over all elements of a list, not needing any counter variable increasing its value?
[1,1,0,1,1,1,0,0,1,1,1,1,1]
is in Python a kind of array storing multiple number of values.
Here some "pseudo-code" for explanatory purpose only demonstrating that "for num in nums" means in Python (in terms of programming in other
languages which don't support iteration over elements of a list/array):
noOfValuesIn_nums = lengthOf/sizeOf(nums)
for i = 0 to noOfValuesIn_nums do:
# get i=th value from 'nums' and put it to a variable named 'num':
num = nums[i]
...
By the way: the loop provided in the question gives the desired result for the provided example:
main([1,1,0,1,1,1,0,0,1,1,1,1,1])
but won't work on another one as demonstrated here:
def main(nums):
count = 0
for num in nums:
if num == 1:
count+=1
else:
count = 0
return count
print( main([1,1,1,1,1,1,0,0,1,1,1,0,1]) )
# it prints 1 instead of 6
The task of finding the longest consecutive sequence of ones
solves following code:
def main1(nums):
count = 0
maxOnes = 0
for num in nums:
if num == 1:
count+=1
else:
if count > maxOnes:
maxOnes = count
count = 0
return maxOnes
print( main1([1,1,1,1,1,1,0,0,1,1,1,0,1]) )
# gives 6

Categories