I have to implement a recursive function which recieves only two arguments: 'n' and 'k', where n is the length of a set of from '0' to 'n-1' and k is the length of the subsets of different elements from the original set. We have to return finally a list of lists which contains these all sub-lists in k-length. The twist here that I don't know to overcome is we mustn't use other arguments such as lists, tuples, sets, etc...
So I don't know how to "save" in recursion the list of all subsets without "lost" details.
def ret_k_subset(n, k):
if n >= 0 and k >= 0:
lst = []
if len(lst) == k:
return lst
else:
for n in range(n):
return lst + ret_k_subset(n, k)
return lst
I thought of something like that but it always returns an empty list...
So I think I need to understand how do I save data structures consistently in recursion.
Thanks.
It can be done in few ways, IMO the simplest is to take that recursion step that uses property that last element (n-1) is or isn't in result list and with appropriate recursion result construct it's result. Here is implementation:
def ret_k_subset(n, k):
if k == 0:
return [[]]
if k == n:
return [list(range(n))]
return ret_k_subset(n - 1, k) + [x + [n - 1] for x in ret_k_subset(n - 1, k - 1)]
Related
The function takes in a list of integers and returns a list of the same elements sorted into the order of even integers then odd ones. Im struggling with implementing a recursive function to complete it even though I am able to solve this using a for loop.
def sort(lst: list[int]) -> list[int]:
l1 = []
l2 = []
for i in lst:
if i % 2 == 0:
l1.append(i)
else:
l2.append(i)
x = l1 + l2
return x
def eto(lst: list[int]) -> list[int]:
if len(lst) == 1
return lst
else:
y = lst[0]
x = lst[1:]
return(eto(x))
I'm not sure how to proceed from here.
I suppose we are allowed to reorder the odd numbers, as long as they are in the second part of the list. I completed your proposition:
def eto(lst: list[int]) -> list[int]:
if len(lst) <= 1:
return lst
head = lst[0]
tail = lst[1:]
if head % 2 == 0:
return [head] + eto(tail)
return eto(tail) + [head]
My first post on here, I'm a beginner programmer who enjoys coding in spare time. Apologies in advance for any possible, obvious (to you) errors in logic / comprehension.
I'm just trying to grasp recursion. Understand the structure, the rationale for base case etc, some difficulty with grasping the whole 'unwinding' process.
I'm doing some exercises to improve.
I'm now working on Hailstone Sequence. My function is fine generating the numbers (unless the initial input n = 1, but that's a minor problem at this stage) but it is supposed to return a flat list, and the best I can get is a multidimensional array.
I would like to (if possible) avoid writing a separate function or any code outside of the Hailstone function which proceeds to 'flatten' the list.
My code so far. Please help!
def hailstone(n):
if n ==1:
return n
else:
if n%2 == 0:
return [n] + [hailstone(n//2)]
else:
return [n] + [hailstone(3*n+1)]
n = int(input())
print(hailstone(n))
Output from your program
print(hailstone(5))
# [5, [16, [8, [4, [2, 1]]]]]
Expected output
print(hailstone(5))
# [5, 16, 8, 4, 2, 1]
Your program is good and close to the expected result. The problem is, in your recursive calls to hailstone, you are wrapping the result in [].
Instead, always return [n] and optionally concatenate the additional terms in the sequence
def hailstone(n):
if n ==1:
return [n] # always wrap n in []
else:
if n%2 == 0:
return [n] + [hailstone(n//2)] # do not wrap here
else:
return [n] + [hailstone(3*n+1)] # do not wrap here
The if/else->if/else would normally be written using elif instead
def hailstone(n):
if n == 1:
return [n]
elif n % 2 == 0:
return [n] + hailstone (n // 2)
else:
return [n] + hailstone (3 * n + 1)
print (hailstone (5))
# [5, 16, 8, 4, 2, 1]
To get an understanding for how this works, we look at hailstone and notice each of the return branches...
Each branch always returns a list
In the two recursive branches, we return a list plus the result of the recursive call
Since we know that hailstone always returns a list, we know that [n] + hailstone(...) will always be a valid result
Even though it looks not difficult, it makes me crazy.
I couldn't even get close to an answer.
Can you guys give me any help?
Write a recursive function sums_to(nums, k) that takes a list of integers and returns True if the
sum of all the elements in the list is equal to k and returns Falseotherwise.
Example:
>>> nums = [1, 2, 3]
>>> sums_to(nums, 6)
True
>>> sums_to(nums, 5)
False
>>> sums_to([], 1)
False
Note: You are not allowed to use any python sum function in any form, nor sum the list and then at
the end check whether it equals k. In addition, you must write sums_to as a single recursive function:
That is, you may not use a main function and a recursive helper function.
# my pool code
def sums_to(nums, k):
if nums == []:
return False
if nums[0] + sums_to(nums[1:], k) == k:
return True
This is what I tried so far.
Sadly, I could not think of a hint to give. The whole problem is about that return statement:
def sums_to(nums, k):
if not nums:
return k == 0
return sums_to(nums[:-1], k - nums[-1])
print(sums_to([1, 2, 3], 6))
print(sums_to([1, 2, 3], 5))
print(sums_to([], 1))
You can do this using recursion, you have two case, if the list is empty, or not:
def sums_to(nums , n):
if len(nums) == 0:
return n == 0
else:
m = nums[0]
nums.pop(0)
return sums_to(nums, (n-m))
print(sums_to([2,3], 5))
When I run this through the visualizer it only modifies the first element in the 2d list. How do I make it so that the it runs throught the entire list.
def make_even(xss):
for i in range(len(xss)):
for j in range(len(xss)):
if xss[i][j] % 2!= 0:
xss[i][j] += 3
return xss
xss = [[1,2,3],[],[4,5]]
make_even(xss)
print(xss)
So first off you need to correct your indentation in your code:
def make_even(xss):
for i in range(len(xss)):
for j in range(len(xss)):
if xss[i][j] % 2!= 0:
xss[i][j] += 3
return xss
However, because both your loops use len(xss), they expect an array of 3 lists each with 3 elements. If you'd want each list to have variable numbers of elements you should do this instead:
def make_even(xss):
for i in range(len(xss)):
for j in range(len(xss[i])):
if xss[i][j] % 2!= 0:
xss[i][j] += 3
return xss
Which returns: [[4, 2, 6], [], [4, 8]]
However, there are two obvious changes I would make:
Your if statement should be if xss[i][j] % 2 == 1, since it's more readable.
You can make a number even by adding 1. (If 3 is required for your specs that's fine).
Also, this is totally doable in a single line (any line would work):
# List comprehensions only
xss = [[(x + 3 if x % 2 == 1 else x) for x in row] for row in xss]
# map and lamdbas (returns lists)
xss = list(map(lambda row: list(map((lambda x: x + 3 if x % 2 == 1 else x),row)), xss))
# map and lamdbas (returns iterables)
xss = map(lambda row: map((lambda x: x + 3 if x % 2 == 1 else x),row), xss)
Although personally, I think the list comprehensions is the easiest to read.
So basically I'm trying to take a list of numbers and write a recursive function that outputs all possible outputs in a list of lists.
My code:
def permutations(lst):
if len(lst) <= 1:
return lst
l = []
for i in range(len(lst)):
m = lst[i]
remlst = lst[:i] + lst[i+1:]
for p in permutations(remlst):
l.append([m] + p)
return l
I'm getting a few errors about not being able to append int.
Simple output:
>>>permutations([1,2])
[[1,2],[2,1]]
There is an implementation for that in itertools:
import itertools
for p in itertools.permutations(list):
# do stuff
Also, to fix your own function, notice that in your "base case" len(lst) <= 1 your returning a list, instead of a list-of-lists. Also, the second return statement should be moved out of the loop;
def permutations(lst):
if len(lst) <= 1:
return [lst]
l = []
for i in range(len(lst)):
m = lst[i]
remlst = lst[:i] + lst[i+1:]
for p in permutations(remlst):
l.append([m] + p)
return l
Because you iterate through result of permutations
for p in permutations(remlst):
your base case needs to return a list of lists like your recursive case does, otherwise you get the error TypeError: can only concatenate list (not "int") to list
You also need to return after the outer for loop.
def permutations(lst):
if len(lst) <= 1:
return [lst] # [[X]]
l = []
for i in range(len(lst)):
m = lst[i]
remlst = lst[:i] + lst[i+1:]
for p in permutations(remlst):
l.append([m] + p)
return l # return at end of outer for loop