I am working on a code to identify subsets of an array with sum of the elements in subsets equal to a given number, k. Here is the recursive code I attempted.
First approach:
def subset_sum(arr,curr,k,idx):
if idx==len(arr):
print(curr) //print the current subset for debugging
if sum(curr)==k:
print(curr)
return
subset_sum(arr,curr,k,idx+1) //exclude the element
curr.append(arr[idx]) //include the element
subset_sum(arr,curr,k,idx+1) // make recursive call
Then this function has been called using;subset_sum([1,2,3],[],4,0), and we get following output;
[]
[3]
[3]
[3, 2]
[3, 2, 3]
[3, 2, 3, 1]
[3, 2, 3, 1, 3]
[3, 2, 3, 1, 3, 2]
[3, 2, 3, 1, 3, 2, 3]
It is being difficult to comprehend, why are the elements being duplicated above. After some brainstorming, I tried second approach below.
Second approach.
def subset_sum(arr,curr,k,idx):
cnt=0
if idx==len(arr):
if sum(curr)==k:
cnt+=1
print(curr,cnt)
return cnt
subset_sum(arr,curr,k,idx+1)
subset_sum(arr,curr+[arr[idx]],k,idx+1)
We call the function subset_sum([1,2,3],[],3,0,0). This gives the output as;
[1,2],1
[3],1
since 1+2 gives us the required sum 3. May I know what is wrong in updating the element curr as I did in the first approach; curr.append(arr[idx]). And why is that the second approach is working fine.
Related
I was using the torch.tensor.repeat()
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
period = x.size(1)
repeats = [1,2]
result = x.repeat(*repeats)
the result is
tensor([[1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6]])
if I get result as follows
result = x.repeat(repeats)
the result is the same
tensor([[1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6]])
It seems that x.repeat(repeats) and x.repeat(*repeats) work the same.
Does it mean that, for an input parameter, e.g, Y, I can use either Y or *Y
Kinda. If repeats is a (list or tuple) of ints, then it is equivalent. But in general the rule appears to be:
If the first argument is a list or tuple, take that as repeats. Ignore all other arguments.
Otherwise, take the full *args as repeats
So if your repeats is something weird like repeats=((1,2),(3,4)), then a.repeat(*repeats) succeeds and is the same as a.repeat(1, 2)==a.repeat((1, 2)) and a.repeat(repeats) fails.
Note: This is observational based on my own tests. The only official documentation is the defined type of the function, e.g. repeat(torch.Size or int...) which isn't perfectly clear with regards to semantics.
You can also get error messages like this:
TypeError: repeat(): argument 'repeats' (position 1) must be tuple of ints, not tuple
when you pass floats. In general error reporting could be better.
I want to make a function that takes a list of integers and replaces the elements in the list with their respective squares.
I tried reassigning every element by virtue of its position (index) in the list, but for some reason the second element in the list gets squared twice.
def square_list(list1):
for i in list1:
list1[list1.index(i)] = i**2
print(list1)
square_list([1, 2, 3, 4, 5])
I expect the printed list to be [1, 4, 9, 16, 25] since the list I'm testing the function with is [1, 2, 3, 4, 5].
If a function is required to square list elements in-place, use it:
def square_list(list_1):
for i in range(len(list_1)):
list_1[i] = list_1[i]**2
my_list = [1, 2, 3, 4, 5]
square_list(my_list)
print(my_list)
Since the function doesn't return anything, square_list([1, 2, 3, 4, 5]) is useless.
Python's map built-in function is good for this, so you don't really have to write your own function.
l = [1, 2, 3, 4, 5]
l = list(map(lambda x: x**2, l))
I had followed the book and can sum lists in lists by column but one of the test cases is missing variables in the list and I'm unable to move forward because I keep getting an index error.
The first initial_list works as it should giving [3,6,9]
The second one though should apparently give me [3,4,9,4]
list_initial = [[1, 2, 3], [1, 2, 3],[1, 2, 3 ]]
list_initial = [[1, 2, 3], [1], [1, 2, 3, 4]]
def column_sums(list_initial):
column = 0
list_new = []
while column < len(list_initial):
total = sum(row[column] for row in list_initial )
list_new.append(total)
column = column + 1
print(list_new)
column_sums(list_initial)
You can effectively "transpose" your data so that rows become columns, and then use itertools.zip_longest with a fillvalue of 0, to sum across them, eg:
from itertools import zip_longest
list_initial = [[1, 2, 3], [1], [1, 2, 3, 4]]
summed = [sum(col) for col in zip_longest(*list_initial, fillvalue=0)]
# [3, 4, 6, 4]
I have this task building a code using recursion. The task is taking a list who can have an infinite amount of lists inside it and making it one list.
This is so far what I have:
def flat_list(array):
new_array =[]
for i in range(0,len(array)):
if len(str(array[i])) > 1:
flat_list(array[i:i+1])
else:
new_array += array[i:len(str(array))-1]
return new_array
These are the tests it needs to pass:
assert flat_list([1, 2, 3]) == [1, 2, 3]
assert flat_list([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4]
assert flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) == [2, 4, 5, 6, 6, 6, 6, 6, 7]
assert flat_list([-1, [1, [-2], 1], -1]) == [-1, 1, -2, 1, -1]
Mine returns this:
flat_list([1, [2, 2, 2], 4])
my result: [1,[2,2,2],4]
right answer: [1,2,2,2,4]
I think my problem is with creating a new local variable of the new_array at each entry, How can I return one list with no other lists inside it?
This task is without using numpy, but if you can also show me how it can be done with numpy it will really educate me. :)
Thank you for answering
Try this:
def flatten(S):
if S == []:
return S
if isinstance(S[0], list):
return flatten(S[0]) + flatten(S[1:])
return S[:1] + flatten(S[1:])
How it works:
1. The list is passed as an argument to a recursive function to flatten the list.
2. In the function, if the list is empty, the list is returned.
3. Otherwise the function is recursively called with the sublists as the parameters until the entire list is flattened.
I suggest you the following suggestion: it iterates over the list and if the encountered item is a list, then it recursively flattens it before appending it to the resulting flattened list:
def flat_list(aList):
result = []
for i in aList:
if isinstance(i, list):
result += flat_list(i)
else:
result.append(i)
return result
Let us say we have a list of integers:
list = [6, 4, 1, 4, 4, 4, 4, 4, 2, 1]
I now wrote a function which returns another list with all the integers from the list above without repeats.
def no_repeats(s):
new_list = []
for number in s:
if new_list.count(number) < 1:
new_list.append(number)
return(new_list)
The new_list returns [6, 4, 1, 2] which is good! My question is how I would now write two similar functions:
A function clean(s) which does not return a new list like the function above, but changes the original list by deleting all the numbers that repeat. Thus, the result has to be the same and the function must not include "return" or create a new list. It must only clean the original list.
A function double(s) which, again, changes the original list (does not return a new list!) but this time, by doubling every number in the original list. Thus, double(list) should change the original list above to:
[6, 6, 4, 4, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 1, 1]
Thank you for all the help!
Removing duplicates inplace without preserving the order:
def no_repeats(L):
L[:] = set(L)
There are several variations possible (preserve order, support non-hashable items, support item that do not define total ordering) e.g., to preserve order:
from collections import OrderedDict
def no_repeats(L):
L[:] = OrderedDict.fromkeys(L)
To double each element's value inplace:
def double(L):
for i in range(len(L)):
L[i] *= 2
To duplicate each element:
def duplicate_elements(L):
L[:] = [x for x in L for _ in range(2)]
>>> def clean(s):
... s[:] = [s[i] for i in range(len(s)) if s[i] not in s[:i]]
...
>>> st = [1, 2, 3, 2, 1]
>>> clean(st)
>>> st
[1, 2, 3]
>>> def double(s):
... s[:] = [s[i//3] for i in range(3*len(s)) if i % 3]
...
>>> st = [1, 2, 3, 2, 1]
>>> double(st)
>>> st
[1, 1, 2, 2, 3, 3, 2, 2, 1, 1]
neither is particularly efficient nor pythonic, yet do address the OP question
def double(s):
... s[:] = [s[i//2] for i in range(2*len(s))]
will also do the trick, with a little less obsfucation