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 7 years ago.
Improve this question
def gSubsets(L):
if len(L) == 0:
print '2'
return [[]]
smaller = gSubsets(L[:-1])
extra = L[-1:]
print L
new = []
for small in smaller:
new.append(small+extra)
return smaller+new
print gSubsets([1,2])
I am a beginner in python. I didn't get how actually the return at very last didn't end by getting:
smaller + new =[[][5]]
Break it down into pieces
def gSubsets(L): #recursive function
if len(L) == 0: #when weve reached the last subset we then have to handle an empty list
print '2'
return [[]] #returns a list of lists for the small in smaller
smaller = gSubsets(L[:-1]) #get subsets by recursive call for all elements in the list except the last one
extra = L[-1:] #get the last element in the list not used in this recursive call
print L
new = []
for small in smaller: #loop through list of lists from recursive call
new.append(small+extra) #append all combinations of the last element in the list to every other element in the same list to new
return smaller+new #return subset with new combinations
print gSubsets([1,2])
this outputs
>>> 2
>>> [1]
>>> [1, 2]
>>> [[], [1], [2], [1, 2]]
by the way, in python you should use underscores in your variable and function names (its the preferred syntax) and I would work on your variable names too.. you want them to be very specific so anyone else coming by can understand what it is right away.. this is how I would rename the variables.
def generate_subsets_from_list(input_list):
if len(input_list) == 0:
# print '2' -- not sure why you are printing 2 here?
return [[]]
subsets = generate_subsets_from_list(input_list[:-1])
last_element = L[-1:]
print L
return_list = []
for subset in subsets:
return_list.append(subset+last_element)
return subsets+return_list
initial_list = [1,2]
print generate_subsets_from_list(initial_list)
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 4 months ago.
Improve this question
Hi i am new to python and i have a little problems with my code.
def Sumn(mylist):
i = 0
sum = 0
for i in mylist[1]:
sum += mylist[i]
return sum
i+=1
import myFunctions
mylist = [6, 12, 645, 3, -8]
print(myFunctions.Sumn(mylist))
I was expecting that the numbers from the list will add and then the anwser will get printed
Line by line comments:
def Sumn(mylist):
i = 0 # this variable is unused
sum = 0 # variable name overrides builtin 'sum' function
for i in mylist[1]: # this will error because mylist[1] is a single int
sum += mylist[i] # this only works if i is an index of mylist
return sum # returns in first iteration
i+=1 # this variable still isn't used for anything
A correct implementation might look like:
def Sumn(mylist):
total = 0
for i in mylist: # iterate over each value in mylist
total += i # add it to total
return total # return AFTER the entire loop is done
Of course in real life you would just call the builtin sum function:
mylist = [6, 12, 645, 3, -8]
print(sum(mylist)) # 658
There are some errors in your code. In for loop you should use list myList, but you are using element at index 1 of the list myList[1].
Also for loop iterates over elements not indices, so you should add i to the sum instead of myList[i].
Finally, return statement should be after the loop, not inside it. The last line i += 1 is after return so it does nothing (just remove it). Here is fixed code:
def Sumn(mylist):
list_sum = 0
for i in mylist:
list_sum += i
return list_sum
Btw. don't use variables names that are builtins (sum).
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
Closed 6 months ago.
This post was edited and submitted for review 6 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I have this problem
E1). L is a list whose elements may be hidden. A hidden element is one that is stored inside one or more lists in the list L. Design a recursive function that displays all the "visible elements" of L
for example For L = [1,[2],[[3]],[4,5],6], the expected result is [1,2,3,4,5,6].
In this example the numbers 1 and 6 are visible and the elements 2, 3, 4 and 5 are hidden.
im learning recursion in python, i tried to find a solution for this problem but i was just able to do this:
l = [1,2,4,5,6]
def simple_vista(l):
if l==[]:
return 0
else:
if isinstance(l[0], list):
pass
else:
l[0] + simple_vista(l[1:])
print("los numeros a simple vista son: ", simple_vista(l))
The idea that i have to solve the problem:
My idea is to check if the l[0] is a iterable type item (a list) and if is it, ignore it and the same with the rest of elements of the list (l[1:]), if an element is not a iterable type item, save it and at the end, show that numbers.
Note: recursion means that im not able to use cicles for and while in order to answer the problem
This should work. We can actually achieve the same thing using your code as a starting point.
L = [1,[2],[[3]],[4,5],6]
def simple_vista(l):
if l==[]:
return [] # return empty list from base case
out = []
if isinstance(l[0], list): # check if the first element is a list
out += simple_vista(l[0] + l[1:]) # recursive call
else:
out += [l[0]] + simple_vista(l[1:]) # otherwise add it to
# the output and recurse the rest
return out
OUTPUT
[1, 2, 3, 4, 5, 6]
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 months ago.
Improve this question
Question
You are given a read only array of n integers from 1 to n.
Each integer appears exactly once except A which appears twice and B which is missing.
Return A and B.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Note that in your output A should precede B.
Example:
Input:[3 1 2 5 3]
Output:[3, 4]
A = 3, B = 4
My code:
class Solution:
def repeatedNumber(self, A):
n=len(A)
asum=0
rsum = (n*(n+1))//2
x=0
dict={}
for i in A:
asum+=A[i]
if A[i] in dict:
x=A[i]
else:
dict[i]=1
diff=rsum-asum
return x,x+diff
Your error is simple, you're using for i in A: but you refer to i within the for loop as if you did for i in range(len(A)):. To fix this all you need to do is replace all instances of A[i] in your code with i. It should look something like this:
class Solution:
def repeatedNumber(self, A):
n=len(A)
asum=0
rsum = (n*(n+1))//2
x=0
distinct={}
for i in A:
asum+=i
if i in distinct:
x=i
else:
distinct[i]=1
diff=rsum-asum
return x,x+diff
Note: It doesn't have any functional relevance in this case, but it is generally go practice to name your variables something other than the object name. In this case I just renamed the dict variable to distinct, as it also gives readers a better understanding of what the dictionary is actually used for.
This could be a solution. It runs in O(2n)
my_list = [3, 1, 2, 5, 3]
new_list = []
length = len(my_list)
for x in range(1,length+1):
new_list.append(x)
for x in range(1,length+1):
try:
my_list.remove(x)
except:
missing_number = x
double_number = my_list[0]
print(missing_number)
print(double_number)
Basically, according to your input, you can use the fact that the max value inside the list is the max length. So you create a new list with all the possible values, scan your first list and removing the values from the second list. If you try to remove a value that doesn't exist in the list you got error (that's why the try, except) and at the end you get, in the original list, only the double value (as it has been removed just one time)
EDIT: actually, if you consider the execution time of .remove() function, the overall running time of the function is O(n+n^2)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
list0 = [[]]
list0[0].append([])
list0[0][0].append([])
list0[0][0][0].append(["I'm in deep!"])
print(list0)
How do I achieve the nested effect above in a loop? Like how I can append lists to a list in a loop.
def list_deepener(layers):
list1 = [[]]
count = 0
while count != layers:
count += 1
y = "list1" + ("[0]" * count)
y.append([])
print(x)
list_deepener(5)
I tried this but I couldn't think of any way to convert the string into code which would allow me to alter list1.
You could pass a range and initial string to functools.reduce for a simple one-liner:
from functools import reduce
layers = 4
reduce(lambda a, _: [a], range(layers), "I'm in deep!")
# [[[["I'm in deep!"]]]]
Suppose that we have mylist = [] to begin with, and we want to add lists to a certain depth. The trick is to use a separate variable to keep track of where we are in the nesting process, and update that variable as we add each layer. Thus:
>>> mylist = []
>>> current = mylist
>>> for i in range(5):
... to_add = []
... current.append(to_add)
... current = to_add
...
>>> mylist # 6 pairs of brackets: the initial list, plus 5 added nested lists
[[[[[[]]]]]]
There's many ways to solve this issue, but when you find yourself constructing code in strings and looking for ways to execute that, you're on the wrong path.
A recursive solution:
def nest(x, levels):
assert levels >= 0
if levels == 0:
return [x]
else:
return [nest(x, levels-1)]
print(nest("I'm in deep", 5))
An iterative solution:
def nest(x, levels):
assert levels >= 0
result = [x]
for _ in range(levels):
result = [result]
return result
print(nest("I'm in deep", 5))
Another way to think about this is recursively. Consider what you want in the deepest part of your list (your 'base' case') and then layer on top for each iteration.
def deepen(layers: int) -> list:
if layers <= 1: # Base case, i.e. 'what happens at the bottom'
return ["Deeper than deep"]
else: # Iterative case, i.e. 'what happens at each layer'
return [deepen(layers - 1)]
This gives you the correct result:
>>> def deepen(layers: int) -> list:
... if layers <= 1:
... return ["Deeper than deep"]
... else:
... return [deepen(layers - 1)]
...
>>> deepen(5)
[[[[['Deeper than deep']]]]]
This question already has answers here:
How do I remove duplicates from a list, while preserving order?
(30 answers)
Closed 6 years ago.
I am working my way through the Think Python Textbook, and one of the problems it gives is to make a function that takes a list and returns a list with only unique elements from the original. What I have so far is this:
def remove_duplicates(l):
index = 0
new_l = []
dup_l = []
while index < len(l):
if l[index] in l[index+1:] or l[index] in new_l:
dup_l += [l[index]]
index = index + 1
elif l[index] in dup_l:
index = index + 1
else:
new_l += [l[index]]
return new_l
I feel like there must be a more succinct, pythonic way to write this function. Can somebody help this beginner programmer?
I assume you want to do it manually, to understand python syntax so this is a way of doing it.
Update for the comment made about only getting elements that occur only once and not removing duplicates, you can replace the if condition to if L.count(element) == 1: and it will return [1,2,4] as you were requesting.
def unique(L):
uniqueElements = []
for element in L:
if element not in uniqueElements:
uniqueElements.append(element)
return uniqueElements
print(unique([1,2,3,3,4]))
And if you want to delve further into the python syntax, you could do a list comprehension and simplify it further, while still not using the set method which loses the order of elements:
def unique(L): return [element for element in L if L.count(element) == 1]