appending LinkedLists items to list using Recursion - python

I have this:
def ppend(n):
lis = []
if n.rest == None:
pass
else:
lis.append(n.first)
ppend(n.rest)
return lis
n is a linked-list [1,2,3]
The output I am getting is :
[1]
But the output I am looking for is:
[1,2,3]

You are creating a new lis list on every recursion. (Incidentally, you might try to find more descriptive names.) Only the first list is returned, however, because you don't do anything with the other lists that result from recursion. Instead, you simply call the function, which simply creates a new list without doing anything with the value returned by the function. You can see this in the following line:
ppend(n.rest) # a new list is created but nothing is done with the result of the function
If you only plan to use the function once, you can simply move the lis assignment outside of the function:
lis = []
def ppend(n):
if n.rest is not None: # the first if statement appears unnecessary
lis.append(n.first)
ppend(n.rest)
return lis # or don't return it but simply refer to lis where you need to
The above approach, however, will not work as well if you plan to use the function multiple times and always need a new list. In the latter case, you might add a second function like this:
def make_ppend(n, lis): # add lis as a parameter to be explicit, but you could rely on scope instead of adding this extra parameter
if n.rest is not None:
lis.append(n.first)
make_ppend(n.rest, lis)
def ppend(n):
lis = [] # now in the local scope
make_ppend(n, lis)
return lis
I am guessing you are after something like the second solution.

Related

How to return object when using `append` in Python

i have a function to append a list, something like this:
def append_func(element):
if xxxx:
new_list.append(element)
else:
[]
I have another function that uses append_func():
def second_func(item):
for i in item:
append_func(i)
if i run :
new_list = []
second _func(item)
new_list
This will return the list i want, but i can't do new_list = second _func(item) because in this case new_list will be a None.
I understand that append() will return a None type, but i'd like to return the appended list so I can use in other places result = second _func(xxx), what i have missed? Thanks.
According to the clarification you did in the comments you might want something like this. (I changed some of your placeholders so we have running code and a reproducible example)
The list is created by second_func so we get rid of the global list.
def append_func(data, element):
if 2 < element < 7:
data.append(element ** 2)
def second_func(items):
new_list = []
for i in items:
append_func(new_list, i)
return new_list
items = list(range(10))
result = second_func(items)
print(result)
The result is [9, 16, 25, 36].
simply tell python what to return:
def append_func(element):
if xxxx:
new_list.append(element)
else:
[]
return new_list # here, return whatever you want to return
if there is no "return" statement in the function, then the function returns None
The new_list you define before calling second_func is a global variable. Every time you call second_func() it will append the argument to the global variable. But the new_list is not restricted to the namespace of either function, so setting it as a return value doesn't make sense.

How to pass list of string as function argument in python?

I'm having a list of string and i need to pass it to function as a parameter.
a_list = ['apple-banana','brinjal-carrot','cucumber']
function_call = fruit(a_list)
def fruit(a_list):
print("Inside Function:")
print(a_list)
if(len(a_list)!=0):
for i in a_list:
print(i)
But what I'm getting for a_list is something like this:
['a','p','p','l','e','-','b','a','n','a','n','a',....]
What I need is:
Inside Function:
'apple-banana'
'brinjal-carrot'
'cucumber'
Where I'm going wrong.?
Thanks.
Removing the redundant code with some highlights:
a_list = ['apple-banana','brinjal-carrot','cucumber']
def fruit(a_list): # no need to check for the len or if the a_list exists, the for loop takes care of that
for i in a_list:
print(i)
fruit(a_list) # your function is not returning anything so no point of assigning
OUTPUT:
apple-banana
brinjal-carrot
cucumber

Using simple Recursion to create a list

I want every element in l(which is a list) to be added to a.
When I run the function, it gives me '[]' every time. How can I fix this?
def sim(l):
a = []
if len(l)>0:
a = a.append(l.pop())
l.pop()
return sim(l)
return a
Several things are wrong:
You shouldn't use lowercase L for a variable name - it looks like one
At the top of the function you assign an empty list to a - ultimately sim will be called with an empty list, then a will be assigned an empty list, the conditional statement will fail and sim will return an empty list.
Inside the conditional statement you assign the return value of list.append() to a. The return value is None so whatever a was before, it gets wiped out.
Inside the conditional statement you pop() two items out of your control list
An empty list has a boolean value of false so there is no need to explicitly check its length,
def sim(el, a = None):
if el:
a.append(el.pop())
return sim(el, a)
return a
I was taught to write the base case of a recursive function as the first statement:
def sim(el, a = None):
if not el:
return a
a.append(el.pop())
return sim(el, a)
append() doesn't return anything but does update the existing list. In other words, by trying to assign the result of the append() method, you're setting a to nothing after you have already appended the item.
Your Code :def sim(l):
a = []
when you call Function recursively return sim(l) every time it is call sim(l) and a=[] is empty.
Try This :
def sim(l,a):
if len(l)>0:
a.append(l.pop())
print a
return sim(l,a)
return a
Is this a homework assignment where you're required to do it in a certain (overly complicated) way? Because if not, you can add one list to another in Python like so:
>>> l = [1, 2, 3]
>>> a = []
>>> a.extend(l)
>>> a
[1, 2, 3]

recursive sorting in python

I am trying to run a sorting function recursively in python. I have an empty list that starts everything but everytime I try to print the list I get an empty list. here is my code. Any help would be greatly appreciated
def parse(list):
newParse = []
if len(list) == 0:
return newParse
else:
x = min(list)
list.remove(x)
newParse.append(x)
return sort(list)
The value of newParse is not preserved between invocations of the function; you're setting it equal to [] (well, you're creating a new variable with the value []).
Since the only time you return is
newParse = []
if len(list) == 0:
return newParse`
you will always be returning [] because that is the value of newParse at that time.
Because you are doing this recursively, you are calling the function anew, without keeping the function's own state. Take a moment to consider the implications of this on your code.
Instead of initialising newParse = [], add an optional parameter newParse defaulting to a bogus value, and set newParse = [] if you receive that bogus value for newParse. Otherwise, you'll actually be getting the same list every time (i.e. the contents of the list object are being mutated). And newParse through in your tail call.
You also seem to have the problem that your definition and and the supposedly-recursive call refer to different functions.
def sort(list, newParse = None):
if newParse is None:
newParse = []
if len(list) == 0:
return newParse
else:
x = min(list)
list.remove(x)
newParse.append(x)
return sort(list, newParse)
Here is what I think you are trying to do:
def recursive_sort(a_list):
def helper_function(list_to_be_sorted, list_already_sorted):
new = []
if len(list_to_be_sorted) == 0:
return list_already_sorted
else:
x = min(list_to_be_sorted)
list_to_be_sorted.remove(x)
new.append(x)
return helper_function(list_to_be_sorted, list_already_sorted + new)
return helper_function(a_list, [])
You shouldn't name variables list, as that is a builtin.
Also, if you are trying to implement a recursive sort function, you might want to look at quicksort, which is a very common (and fast) recursive sorting algorithm. What you have tried to implement is a recursive version of selection sort, which is much slower.
Also, if you actually need a sorting function, rather than just wanting to implement a recursive one, you should use the list method sort, or the function on an iterable sorted, both of which will be a lot faster than anything you could make in Python.

(Python 2.7) Use a list as an argument in a function?

So I'm trying to learn Python using codecademy but I'm stuck. It's asking me to define a function that takes a list as an argument. This is the code I have:
# Write your function below!
def fizz_count(*x):
count = 0
for x in fizz_count:
if x == "fizz":
count += 1
return count
It's probably something stupid I've done wrong, but it keeps telling me to make sure the function only takes one parameter, "x". def fizz_count(x): doesn't work either though. What am I supposed to do here?
Edit: Thanks for the help everyone, I see what I was doing wrong now.
There are a handful of problems here:
You're trying to iterate over fizz_count. But fizz_count is your function. x is your passed-in argument. So it should be for x in x: (but see #3).
You're accepting one argument with *x. The * causes x to be a tuple of all arguments. If you only pass one, a list, then the list is x[0] and items of the list are x[0][0], x[0][1] and so on. Easier to just accept x.
You're using your argument, x, as the placeholder for items in your list when you iterate over it, which means after the loop, x no longer refers to the passed-in list, but to the last item of it. This would actually work in this case because you don't use x afterward, but for clarity it's better to use a different variable name.
Some of your variable names could be more descriptive.
Putting these together we get something like this:
def fizz_count(sequence):
count = 0
for item in sequence:
if item == "fizz":
count += 1
return count
I assume you're taking the long way 'round for learning porpoises, which don't swim so fast. A better way to write this might be:
def fizz_count(sequence):
return sum(item == "fizz" for item in sequence)
But in fact list has a count() method, as does tuple, so if you know for sure that your argument is a list or tuple (and not some other kind of sequence), you can just do:
def fizz_count(sequence):
return sequence.count("fizz")
In fact, that's so simple, you hardly need to write a function for it!
when you pass *x to a function, then x is a list. Do either
def function(x):
# x is a variable
...
function('foo') # pass a single variable
funciton(['foo', 'bar']) # pass a list, explicitly
or
def function(*args):
# args is a list of unspecified size
...
function('foo') # x is list of 1 element
function('foo', 'bar') # x is list with two elements
Your function isn't taking a list as an argument. *x expands to consume your passed arguments, so your function is expecting to be called like this:
f(1, 2, 3)
Not like this:
f([1, 2, 3])
Notice the lack of a list object in your first example. Get rid of the *, as you don't need it:
# Write your function below!
def fizz_count(lst):
count = 0
for elem in lst:
if elem == "fizz":
count += 1
return count
You can also just use list.count:
# Write your function below!
def fizz_count(lst):
return lst.count('fizz')
It must be a typo. You're trying to iterate over the function name.
try this:
def fizz_count(x):
counter = 0
for element in x:
if element == "fizz":
counter += 1
return counter
Try this:
# Write your function below!
def fizz_count(x):
count = 0
for i in x:
if i == "fizz":
count += 1
return count
Sample :
>>> fizz_count(['test','fizz','buzz'])
1
for i in x: will iterate through every elements of list x. Suggest you to read more here.

Categories