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']]]]]
Related
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 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 2 years ago.
Improve this question
I have a code listed below that accepts a list and then returns a new list with every second value removed.
Can someone explain to me how this code works? I understand that the enumerate function will put the list into a list of tuples. Example: [1,2,3,4,5] will go to (0,1) (1,2) (2,3) (3,4) (4,5)
Question 1: In the code why is "val" listed before the for loop in the return statement and then listed a second time after the for?
Question 2: After the word "for" is i for index 0 of the resulting tuple from the enumerate?
Question 3: After the word "for" is val for index 1 of the resulting tuple from the enumerate?
CODE:
def remove_every_other(lst):
return [val for i,val in enumerate(lst) if i % 2 == 0]
print(remove_every_other([1,2,3,4,5])) # [1,3,5]
Regarding Q1, this is just a list comprehension syntax.
In your function it creates a list and returns it.
It could be rewritten as a regular for loop, e.g.
def remove_every_other(lst):
result = []
for i, val in enumerate(lst):
if i % 2 == 0:
result.append(val)
return result
In Python list comprehension is a more natural way to do this same thing.
Answers to Q2 & Q3 are yes and yes.
I think the function would be easier to understand if it looked something like this
def remove_every_other(lst):
return [i for i in lst if i % 2 != 0]
print(remove_every_other([1,2,3,4,5])) # [1,3,5]
This is not a "for" loop, this is a list comprehension syntax. [val for i,val in enumerate(lst)] would go over what enumerate(lst) yields, tuple by tuple, and put just the val-s into a new list. All of them. Hence, this would simply recreate the same list. Adding the condition [val for i,val in enumerate(lst) if i % 2 == 0] will make it take just the values the condition is true for, so only the ones where index is dividable by 2. As others have already mentioned, reading about list comprehension would be very helpful.
This said, you can do the same thing in a much simpler form. Specifically, just lst[::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 3 years ago.
Improve this question
It's a simple question of recursive function, which extracting every digits from a positive number. As the comment mentioned, I have known the mistake is because of global variable, but I still have no idea to fix it to get expected result. Thanks.
def getdigits(n):
if n == 0:
return list_1[::-1]
list_1.append(n % 10)
return getdigits(int(n / 10))
list_1 = []
print(getdigits(120)) # output = [1,2,0]
print(getdigits(5)) # output = [5,1,2,0]
But the expected output should be
print(getdigits(120)) # expected output = [1,2,0]
print(getdigits(5)) # expected output = [5]
You are using the existing LIST that already have values from the previous function call.
First clear the list and then try to call for another value.\
Try it
def getdigits(n):
if n == 0:
return list_1[::-1]
list_1.append(n % 10)
return getdigits(int(n / 10))
list_1 = []
print(getdigits(120))
list_1.clear() #clear list values
print(getdigits(5))
def getdigits(n):
global list_1
if n == 0:
listTemp = list_1
list_1 = []
return listTemp
list_1.append(n % 10)
return getdigits(int(n / 10))
list_1 = []
print(getdigits(120)) # output = [1,2,0]
print(getdigits(5)) # output = [5]
you need to declare list 1 as a global varible inside your function so you can clear list one within th function
i have tested it and got that output
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 4 years ago.
Improve this question
so my function needs to filter a list so that it returns a list of only the values that return a positive value when a function is applied to it without the use of any loops. My code is currently:
def positive_places(f, xs):
"""takes a function f and list xs and returns
a list of the values of xs which satisfy
f>0"""
y = list(map(f, xs))
x = filter(lambda i: i > 0, y)
return x
This currently returns a list of all the positive output values of the function, however I need their corresponding values from the original list xs.
Thanks for any help in advance!
Using a list comprehension:
return [x for x in xs if f(x) > 0]
Without using a list comprehension:
return filter(lambda x: f(x) > 0, xs)
Since you said it should return a list:
return list(filter(lambda x: f(x) > 0, xs))
Two solutions are possible using recursion, which do not use looping or comprehensions - which implement the iteration protocol internally.
Method 1:
lst = list()
def foo(index):
if index < 0 or index >= len(xs):
return
if f(xs[index]) > 0:
lst.append(xs[index])
# print xs[index] or do something else with the value
foo(index + 1)
# call foo with index = 0
Method 2:
lst = list()
def foo(xs):
if len(xs) <= 0:
return
if f(xs[0]) > 0:
lst.append(xs[0])
foo(xs[1:])
# call foo with xs
Both these methods create a new list consisting of the desired values. The second method uses list slicing, which I am not sure whether internally implements iteration protocol or not.
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)