Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I am making an attempt to learn recursion better so I have been practicing some problems.
A common problem is flatten an list of lists to a single list. For example
[3,4,[1,2]] so the desired result will be [3,4,1,2].
The way I am approaching the problem is:
is 0 element a list - no
is 1 element a list - no
is 2 element a
list - yes
call the function again and do tests again
My base case will be to return if element is not a list.
Is there a better approach to understand recursion better?
Your approach is in the right direction, but you should not check more than the first element. In general - a "pure" recursive solution will only have to look at the "head" of the list (first element), and the "tail" (list[1:]).
something like (python like pseudo code):
def flatten(l):
if len(l) == 0:
return []
if isinstance(l[0], list):
left = flatten(l[0])
else:
left = [l[0]]
return left + flatten(l[1:])
You example is certainly one that works however it may be slightly too simple for you to get a full understanding. I found that maze problems were the most helpful in me understanding recursive problems. The main preface is there is a 2x2 array consisting of two different values. One value denotes a wall within the maze and the other value denotes empty space. Your job would be to traverse through the maze using recursion. Here is an example problem and solution:
https://www.cs.bu.edu/teaching/alg/maze/
Hope this helps!!
You should.
Create a new list (passed) before calling function. Call function.
Loop through the old one and check if the type of list if so, then call function recursive.
else add element to passed list.
aList = [3,4,[1,2]]
def flatten(inList,outList):
for elem in inList:
if isinstance(elem,list):
flatten(elem,outList)
else:
outList.append(elem)
bList = list()
flatten(aList,bList)
print bList
Related
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
prepping for interviews and this is something i couldnt find. https://blog.finxter.com/python-list-reverse/#:~:text=The%20time%20complexity%20of%20the,the%20number%20of%20list%20elements. says .reverse() is the O(n) which I assume is because it replaces every index. is [::-1] just printing the list backwards or is something similar going on
list.reverse operates in place. That means that it almost certainly does something like this under the hood:
for i in range(len(self) // 2):
j = len(self) - 1 - i
self[i], self[j] = self[j], self[i]
The actual method is implemented in C, so of course it will be much more verbose, especially in the swapping operation.
list[::-1] creates a copy of the original. The idea is similar, but since the reversal of not in place, you have the luxury of just writing to a destination index rather than swapping via a temporary object:
new = [None] * len(self)
for i in range(len(self)):
j = len(self) - 1 - i
new[j] = self[i]
The actual slice processing code is much more complex since it has to be able to accept integers and all sorts of unorthodox slice expressions that set custom start and stop bounds, and step sizes.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Could you please tell me why it is considered as "not pythonic" when I need the index and the value when looping over a list and use:
a = [1,2,3]
for i in range(len(a)):
# i is the idx
# a[i] is the value
but rather it is recommended to use
for idx, val in enumerate(a):
print idx, val
who defines "pythonic" and why is the latter one better? I mean it's not that much better concerning readability, is it!?
Thanks in advance
First of all, the first way is ugly: You either need a separate variable assignment to get the element or use a[i] all the time which could theoretically be an expensive operation. Imagine a being a database cursor: When you iterate it (a.__iter__ being called) the object can safely assume that you are going to iterate over all its items. So all or at least multiple rows could be retrieved at once. When getting the length such an optimization would be stupid though since you surely don't want to retrieve data just because you want the number of items. Also, when retrieving a specific item you cannot assume that other items will be retrieved, too.
Additionally, using enumerate() works with any iterable while range(len()) only works with countable, indexable objects.
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 7 years ago.
Improve this question
I just started to learn Python and I am confused in its syntax.
I am not sure what square brackets around the variable word mean... I understand word should be our value and prev is a key.
mimic_dict[prev] = [word]
I also do not understand this expression
mimic_dict[prev] = mimic_dict.get(prev, []) + [word]
Need your help to clarify this.
I checked out documentation for python dictionary, but it was not much of help.
Sorry for such a basic question, but I really could not figure it out by googling.
mimic_dict[prev] = [word]
[word] is a list containing a single element, the value of the word variable.
mimic_dict.get(prev, []) + [word]
+ can be used to concatenate two lists. This adds word to the list returned by mimic_dict.get(prev, []).
And what does mimic_dict.get(prev, []) do? It is the same as mimic_dict[prev], but if the key prev doesn't exist then it returns a default value of [] (an empty list). It ensures you always get a list back whether or not the key exists.
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 8 years ago.
Improve this question
I just started to learn programming 4 weeks ago. I read the book "Learn Python the hard way" and I am currently working through "Learn Raspberry Pi programming with Python". The code that I wrote above completely confuses me and I can't seem to wrap my head around it. The book states it lists the indices of slashes (I am working on a web bot). I just have never seen a format like this in a for loop. Why is there a variable in front of the for? Please explain (in english please:D).
Thanks,
Michael
That is a list comprehension, a more compact way of running a loop to build up a list in Python.
The long way of writing this would be:
SlashList = []
for i, ind in enumerate(start):
If ind == '/':
SlashList.append(i)
Where ind is the name for the value of the field in list 'start' and i is ind's index (or position in the list)
And 'ind' and 'start' being particularly unhelpful variable names likely adds to the confusion in understanding the line :-)
A "for loop" inside brackets is called "list comprehension".
Here it iterates over enumerate(start) which is an iterator yielding a tuple of (index, item) for each item of the iterable given.
This iterator is iterated over, putting index into i and the character into ind (which is confusing, variable-wise). For each item, if it is a /, the index is taken over into the final list so that, at the end, the list consists of all indexes of the slashes in the string(?) start.
It does the same thing as the following code:
slashList = []
i = 0
for ind in start:
if ind == '/':
slashList.append(i)
i += 1
It uses a few tricks to squeeze that all on to one line. The first is called a list comprehension. It lets you make a list without breaking out a for loop and if statement onto different lines. The second is the enumerate built-in function. It lets you get the index i of every item in an iterable like start at the same time as the item (here, assigned to ind) itself.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Could you please tell me why it is considered as "not pythonic" when I need the index and the value when looping over a list and use:
a = [1,2,3]
for i in range(len(a)):
# i is the idx
# a[i] is the value
but rather it is recommended to use
for idx, val in enumerate(a):
print idx, val
who defines "pythonic" and why is the latter one better? I mean it's not that much better concerning readability, is it!?
Thanks in advance
First of all, the first way is ugly: You either need a separate variable assignment to get the element or use a[i] all the time which could theoretically be an expensive operation. Imagine a being a database cursor: When you iterate it (a.__iter__ being called) the object can safely assume that you are going to iterate over all its items. So all or at least multiple rows could be retrieved at once. When getting the length such an optimization would be stupid though since you surely don't want to retrieve data just because you want the number of items. Also, when retrieving a specific item you cannot assume that other items will be retrieved, too.
Additionally, using enumerate() works with any iterable while range(len()) only works with countable, indexable objects.