The problem is to find the number of subsets that add up to a target, for example, if the target is 16 and the array is [2, 4, 6, 10], it should return 2, because 2 + 4 + 10 = 16 and 10 + 6 = 16. I tried to make the recursive solution. I need help to figure out where is the mistake in my code. This is my code:
def num_sum(target, arr, ans=0 ):
if target == 0:
return 1
elif target < 0:
return 0
for i in arr:
arr.remove(i)
num = num_sum(target - i, arr, ans)
ans += num
return ans
print(num_sum(16, [2, 4, 6, 10]))
Thanks in advance.
You are trying to use backtracking to calculate the subsets that add up to a target. However, in your code, you keep removing the item from the arr, and it was not added back for backtracking. That's why it prints only 4 times, as the arr size is getting smaller during the recursion.
But in this case, your arr should not be changed, as it can be in different subsets to make up to the target, for example the number 10 in your example. So I would use an index to note the current position ,and then exam the remaining to see if it adds up to a target.
Here is my sample code for your reference. I used an int array as a mutable result holder to hold the result for each recursion.
def num_sum(current_index, target, arr, ans):
if target == 0:
ans[0]+=1;
return
elif target < 0:
return
for i in range(current_index, len(arr)):
num_sum(i+1, target - arr[i], arr, ans)
ans = [0]
num_sum(0, 16, [2, 4, 6, 10, 8], ans)
print(ans[0])
Related
I have a long list of number of which a sample look something like shown below:
L = [0, 1, 2, 0, 0, 2, 3, 1, 0, 10, 0, 2, 4, 5, 0, 0, 7, 8, 9, 0, ...]
singleData = []
sumofTwo = []
sumofThree = []
sumofFour = []
.
.
What I want to be able to do is categorize a data OR sum of two or more consecutive data into the respective lists based on the COUNT of numbers involved in the sum operation. So, if there is an occurrence of zero between two numbers, then their sum would not be considered.
For example, if I take the list above, the sum of 1 and 2 is to be added to the list sumofTwo. Similarly, if it is the sum of three consecutive numbers without the occurrence of 0's then the sum is expected to be in the sumofThree list (sum of 2,3,1; 2,4,5 and 7, 8, 9). If a number occurs between two or more 0's then it is to be appended to the singleData list (eg. 10).
How can i achieve this considering that in the list(L) there can be a sum of random consecutive numbers? Example, sum of 6 or 7 or 8 or any consecutive numbers?
I was able to segregate only a single number between 0's and the sum of two numbers. Following is the code:
for i in range(len(l)):
try:
if i == 0:
if l[i] == 0:
continue
elif l[i] != 0 and l[i+1] == 0:
singleData.append(l[i])
elif l[i] != 0 and l[i+1] != 0:
sumofTwo.append(l[i]+l[i+1])
elif i == len(l)-1:
if l[i] != 0 and l[i-1] == 0:
singleData.append(l[i])
else:
if l[i] != 0:
if l[i+1] == 0 and l[i-1] == 0:
singleData.append(l[i])
elif l[i+1] != 0:
sumofTwo.append(l[i]+l[i+1])
except IndexError:
print("Index out of range")
I realized that my code will only get messier with more cases of the sum of consecutive numbers and ultimately end up with error.
Can anybody help me out? Thanks in advance :))))
I would recommend using a dictionary to store the results:
L = [0, 1, 2, 0, 0, 2, 3, 1, 0, 10, 0, 2, 4, 5, 0, 0, 7, 8, 9, 0]
consecutive_sums = {} # Create an empty dictionary
I would also recommend directly iterating through the list, rather than using range(len(L). e.g.
for number in L:
print(number)
Then, you can just create a counter variable to check how long the current sequence is, and reset the counter when you get to a zero.
L = [0, 1, 2, 0, 0, 2, 3, 1, 0, 10, 0, 2, 4, 5, 0, 0, 7, 8, 9, 0]
consecutive_sums = {} # Create an empty dictionary
counter = 0
sum = 0
for number in L:
if number == 0: # Save the current sum and reset counter
# Check if we've already had a sequence of this length.
# If so, we have already added a list, so can append to it.
if counter in consecutive_sums:
consecutive_sums[counter].append(sum)
else: # If this is the first time we've had this length sequence
# we need to create a new key value pair in the dictionary.
# Note that the value is a list containing `sum`.
# Make sure to use a list so that you can append to it later.
consecutive_sums[counter] = [sum]
# Reset counter and sum
counter = 0
sum = 0
else: # Increment counter
counter += 1
sum += number
print(consecutive_sums)
Note that this code will not sort the dictionary keys, so the sums of sequences of length 1 may not appear at the beginning. But you can access it using consecutive_sums[1].
Also note that this version of the code also counts sequences of length 0. I suspect this is not what you want, but I'll let you figure out how to fix it!
Output:
{0: [0, 0, 0], 2: [3], 3: [6, 11, 24], 1: [10]}
EDIT:
I've intentionally tried to solve this using just builtin functions and datatypes. But if you really want to be fancy, you can use collections.defaultdict.
Below is an alternative version which uses defaultdict:
from collections import defaultdict
L = [0, 1, 2, 0, 0, 2, 3, 1, 0, 10, 0, 2, 4, 5, 0, 0, 7, 8, 9, 0]
consecutive_sums = defaultdict(list) # Create an empty defaultdict of type list
counter = 0
sum = 0
for number in L:
if number == 0: # Save the current sum and reset counter
# The magic of defaultdict:
# We don't need to check if the key exists.
# If it doesn't exist yet, defaultdict will automatically make
# an empty list for us to append to!
consecutive_sums[counter].append(sum)
# Reset counter and sum
counter = 0
sum = 0
else: # Increment counter
counter += 1
sum += number
print(consecutive_sums)
The first thing I would do is to organize a bit better our output lists, so that each can be accessed in the same way using the number of consecutive numbers. As #daviewales suggested, you could do this with a dictionary with lists as values, something like sums = {}, so that sums[1] would be the same as singleData, sums[2] the same as sumofTwo, and so on. That way, you will avoid a lot of if to know in what list you should put your data, you'll just need to use stuff like sums[nbOfValuesInSum].
Second thing, you could write a function that detects your sequences of non-zero values. A possibility would be a function that takes a list and a start index, and returns the start and end indexes of the next "interesting" sequence. It would look like this :
def findNextSequence(l, start):
while l[start] == 0:
if start == len(l)-1:
return None # there is no non-zero value left
start+=1
# when we exit the loop, start is the index of the first non-zero value
end = start + 1
while l[end] != 0:
if end == len(l)-1:
break
end+=1
# and now end is the index of the first zero value after the sequence
return (start, end)
Then you can call it in a loop, like this:
i = 0
while True:
bounds = findNextSequence(l, i)
if bounds is None:
break # there is no non-zero value left
seq = l[bounds[0]:bounds[1]] # get the start and end index of the sequence
if len(seq) not in sums:
sums[len(seq)] = []
sums[len(seq)].append(sum(seq)) # see? No need to explicitly check len(seq) to know what list I want
i = bounds[1] # get ready for the next iteration
if i == len(l):
break
NB : no need to pass l as a parameter of findNextSequence if it's a global variable
I wanted to use a for loop within a while loop to add up the last 3 numbers of the list and generate a new number to append into the existing list. However, the code would not enter the for loop within the while loop and I have no clue why.
What the function is supposed to do:
Take in a list of numbers (as signature)
Total up the LAST 3 numbers in the list and produce the next number to be appended
Continue step 2 until length of list == n
#my code
def tribonacci(signature, n):
total = 0
for i in range(len(signature)):
num = signature[i]
total += num
signature.append(total)
while len(signature) < n:
for j in range(-1,-4):
num = signature[j]
total += num
signature.append(num)
return signature
#Some sample test code:
print(tribonacci([1, 1, 1], 10))
print("Correct output: " + "[1, 1, 1, 3, 5, 9, 17, 31, 57, 105]")
print(tribonacci([0, 0, 1], 10))
print("Correct output: " + "[0, 0, 1, 1, 2, 4, 7, 13, 24, 44]")
print(tribonacci([300, 200, 100], 0))
print("Correct output: " + "[]")
UPDATE!
As suggested, I resetted the total count in the while loop by creating a total_2 = 0. I've also added the -1 to the range and changed .append(num) in the while loop block to .append(total_2).
def tribonacci(signature, n):
total = 0
for i in range(len(signature)):
num = signature[i]
total += num
signature.append(total)
while len(signature) < n:
total_2 = 0
for j in range(-1,-4, -1):
num = signature[j]
total_2 += num
signature.append(total_2)
return signature
However, this code doesnt work the 3rd print test code where n = 0. One of the users shared a much shorter code which works for ALL of the test code.
Try range(-1,-4,-1). You need to tell python to go backwards.
Just for the reference, I've implemented your function with a few improvements:
def tribonacci(signature, n):
signature = signature[:n]
while len(signature) < n:
signature.append(sum(signature[-3:]))
return signature
Input : l1 = [1,2,3,4,5,6]
Output : [7, 8, 9, 10, 11, 11]
To find the maximum sum of each pair of all elements in a list.
In general, i have to add each element in list to another element (not to itself).
Below is the code what i tried. I know this is complexity of (n^2)
Any better way to reduce complexity (can be both time and space) ?
Any better approach (may be with some modules or with just single for loop) ?
list l1 need not to be in sorted.
l2=[]
l3=[]
for i in range(len(l1)):
for j in range(len(l1)):
if i!=j:
l2.append(l1[i]+l1[j])
l3.append(max(l2))
l2.clear()
print(l3)
[7, 8, 9, 10, 11, 11]
Update:
Submitted this solution in hackerrank, but it fails for few cases.
Reason for failure is TimeLimitExceed (TLE). I assume, it's failing because of large numbers.
**Constraints:**
n = size_of_list
1<= n <= 4*10^4
1<= l1[i] <= 1024
1<= i <= n
1<= j <= n
j != i
Is it because of time-complexity, failing to handle these scenarios in above snippet ?
you can do something like this:
l1 = [1,2,3,4,5,6]
l2=[]
for i in range(len(l1)):
for j in range(i+1,len(l1)):
l2.append(l1[i]+l1[j])
l3=set(l2)
l2=list(l3)
print(l2)
output:
[3, 4, 5, 6, 7, 8, 9, 10, 11]
Sorting your list before processing it also helps.
Let me know if i have made any mistake.
You can do this in O(n).
The basic idea is to get the indices of the maximum element and the second maximum element in the list. Then for each element in the list, append the element + max_element, if the element is not the max_element. Otherwise, append the max_element + second_max_element.
I used the get_first_second_max_index to get the indices of the maximum element and the second maximum element because there might be identical elements in the list.
The code should look like this:
def get_first_second_max_index(nums):
if len(nums) < 2:
return None, None
first_max_index = 0 if nums[0] > nums[1] else 1
second_max_index = 0 if nums[0] <= nums[1] else 1
for index in range(2, len(nums)):
if nums[index] > nums[first_max_index]:
first_max_index, second_max_index = index, first_max_index
elif nums[index] > nums[second_max_index]:
second_max_index = index
return (first_max_index, second_max_index)
def max_sum_pair(nums):
res = []
if len(nums) >= 2:
first_max_index, second_max_index = get_first_second_max_index(nums)
for index in range(len(nums)):
if index == first_max_index:
res.append(nums[index] + nums[second_max_index])
else:
res.append(nums[index] + nums[first_max_index])
return res
nums = [1,2,3,4,5,6]
res = max_sum_pair(nums)
print(res)
For starters, we can use sorting to our advantage. The Python sorting method, sorted, operates in O(n log n) time. (See this question: What is the complexity of this python sort method?)
Once our numbers are sorted, the maximum sums are trivial. The maximum for a number is simply that number added to the last element in the sorted list or, if the number is the maximum element, the second to last element. Rewriting your code we could obtain:
l3 = []
l1 = sorted(l1)
for i in range(len(l1)):
if i + 1 == len(l1):
l3.append(l1[i] + l1[i - 1])
else:
l3.append(l1[i] + l1[-1])
print(l3)
I hope this helps. Let me know if I've misunderstood your question.
I'm trying to create a function that will fill in any missing numbers in between two numbers in a list. The original list must be altered and cannot be new.
For example: [13,15,20] would return [13,14,15,16,17,18,19,20].
Note that I am not allowed to use a range function.
Here's my code:
def complete(list1):
i= 0
if len(list1) > 1:
for number in list1:
if number - list1[i+1] != -1:
number += 1
list1.insert(i + 1, number)
i += 1
return list1
else:
return list1
I got a "list index out of range" error.
Here is the source of your error:
...
for number in list1:
if number - list1[i+1] != -1:
...
i += 1
Basically, there comes a point (that point being the last number in list1) when i+1 gets you out of bounds and you are not doing anything to prevent that from happening. Indexing is tricky like that, so I would like to offer an indexing-free (well, almost) approach. By the way, from your comment to Bonfire's answer, I see that the task is to change original lists in-place. While mutating arguments is considered a very poor coding practice these days, here is a relatively efficient way of doing that:
import typing as t
def complete_sequence(partial: t.List[int]) -> t.List[int]:
# edge case
if len(partial) < 2:
return partial
# a lookup table for numbers we already have
observed = set(partial)
# append numbers we don't have
start = partial[0]
stop = partial[-1]
num = start + 1
while num < stop:
if not num in observed:
partial.append(num)
num += 1
# in-place sort
partial.sort()
return partial
As you see, instead of inserting values between existing numbers (paying O(n) time for each insertion), we can simply append everything (O(1) per insertion) and sort. This not only simplifies the logic (we no longer have to track those pesky indices), but also reduces computational time-complexity from O(n^2) to O(n*log(n)).
To achieve what you want to do I have made some changes to the logic:
def complete(list1):
if len(list1) < 2 : return list1
num = list1[0]
i = -1
while num < list1[-1]:
num += 1
i += 1
if num in list1: continue
if i < len(list1) - 1:
list1.insert(i + 1, num)
else:
list1.append(num)
return list1
print(complete([13, 14, 20]))
# [13, 14, 15, 16, 17, 18, 19, 20]
print(complete([13, 14, 15]))
# [13, 14, 15]
I am trying to solve this competitive programming problem using python3. The problem asks, given an array of size n, split the array into three consecutive, contiguous parts such that the first part has maximum sum and equals the sum of the third part. The elements in the array are positive integers.
My approach:
inputN = int(input())
inputString = input()
usableString = stringToList(inputString)
counting = 0
sum1 = usableString[0]
sum3 = usableString[-1]
maxSum1 = 0
countFromLeft = 1
countFromRight = 2
while counting < inputN-1:
if sum1 > sum3:
sum3 += usableString[-countFromRight]
countFromRight += 1
elif sum3 > sum1:
sum1 += usableString[countFromLeft]
countFromLeft += 1
elif sum1 == sum3:
maxSum1 = sum1
sum1 += usableString[countFromLeft]
countFromLeft += 1
counting += 1
print(maxSum1)
We read in the array elements and store them in a list usableString.
We set two variables sum1 and sum3 to the first and last elements of the list respectively.
We set a variable to keep track of the maximum sum of the first part of the list.
Finally, we set a variable counting to 0 which will represent the number of elements we have added from the list into sum1 or sum3.
The rest of the logic is in the while loop, which just checks if sum1 is larger than sum3 or the other way around and otherwise if they equal. After each iteration we add 1 to counting as an extra element has been included in a part. The while loop should stop when the number of elements used (i.e counting) is equal to the number of elements in the array - 1, since we added the first and last elements before entering the loop, which makes (array - 2), however, we still need to loop one additional time to check if sum1 and sum3 are equal.
I checked your submitted algorithm, and the problem is your stringToList function:
def stringToList(s):
list=[]
for elem in s:
if elem != " ":
list.append(int(elem))
return list
As far as I can tell, your main algorithm is completely fine, but stringToList does one crucial thing incorrectly:
>>> stringToList('2 4 6 8 10')
[2, 4, 6, 8, 1, 0]
# should be
[2, 4, 6, 8, 10]
As it treats each character individually, the two digits of 10 are turned into 1, 0. A simpler method which performs correctly would be to do the following:
# explanation
>>> input()
'2 4 6 8 10'
>>> input().split(' ')
['2', '4', '6', '8', '10']
>>> map(int, input().split(' ')) # applies the int function to all elements
<map object at 0x...>
>>> list(map(int, input().split(' '))) # converts map object into list
[2, 4, 6, 8, 10]
Sorry it took so long, I ended up making my own algorithm to compare to yours, ran my own tests, and then ran your code with the input to list method I just explained, and figured the only difference was your stringToList function. Took a while, but I hope it helps!
Just for the fun, here's my algorithm and turns out it was pretty similar to yours!
array = [1, 3, 2, 1, 4]
n = len(array)
slice = [0, n]
sum = [array[0], 0]
bestSum = 0
while slice[0] < slice[1]-1:
i = 0 if (sum[0] < sum[1]) else 1
slice[i] += 1-(2*i)
sum[i] += array[slice[i]]
if sum[0] == sum[1]: bestSum = sum[0]
# print(array[ : slice[0]+1], array[slice[0]+1 : slice[1]], array[slice[1] : ])
print(bestSum)