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
I have this code , and it is not mine , I saw it online and i am wondering how is the recursion working , can someone please explain !
(this function accepts a list of integers(distances) and a value 'r' lets say 10) and it returns all the possibilities of how we can reach 100 using the distances) lets say the list is [3,5,2,5] and the value r is 10 ! so to make 10 we need [5,5] or [3,2,5] ,this is the code:
def greedy(r, distances):
if r < 0:
return []
if r == 0:
return [[]]
solutions = []
for last_distance in d:
combos = greedy(r - last_distance, d)
for combo in combos:
combo.append(last_distance)
if(not solutions.__contains__(combo)):
solutions.append(combo)
return solutions
i hope i made my self clear
I'd suggest using python print function
print("")
At multiple locations to actually see the recursion happening. You would get a better idea than someone trying to explain it to you.
Although the function itself is quite simple. For every element in distances, the function subtracts the element from the required r value and checks the value with the if conditions.
If r value is zero ie, the for some elements in distance, their sum is r, a multi list is returned, which furthermore has the said elements.
At the end, the complete list of elements whose sum adds to r are appended to solution list and returned.
Say that given a list distances0 of length n, you are able to return all tuples i1,..,infrom the list that sums to a number r for any number r.
You would like to do the same for a list distances of length n+1.
Since you know how to solve the problem for a list of size n, you will do the following: for every element last_distance of distances, return all tuples i1,...,in that sums to r-last_distance from a list distances0 which is similar to distances but without the element last_distance (and hence of length n).
I think there might be some mistakes in the code, here should be a working version:
def greedy(r, distances):
if r < 0:
return []
if r == 0:
return [[]]
solutions = []
for i in range(len(distances)):
d = distances[:i]+distances[i+1:]
last_distance = distances[i]
combos = greedy(r - last_distance, d)
for combo in combos:
combo.append(last_distance)
if(not solutions.__contains__(combo)):
solutions.append(combo)
return solutions
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 2 months ago.
Improve this question
I am fairly new to programming and I try to create the above mentioned sequence.
this problem is about having a strict length of elements which always progresses, this progression is inside the list by moving on the indexes. this strict length shifts from a set of indexes to the next one once all the indexes inside the strict length (not passing it's limits) are finished being scanned, and they are scanned in a format of "one after the other".
after all of that we come to the root of the problem:
once the strict length moves to another set, it starts from the last index that was previously, inside of the strict length but in the previous strict length.
the output of the root problem is the title of this post. I don't know how to solve the root problem.
this problem, involves "k" as an exponent of the strict length.
this is the script:
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while True:
for i in range(k):
print(strarr[n])
n = n+1
print(strarr[n])
the output I got is:
1,2,3,3,4,5,5,6,7,7,8,9,9,10
and I don't know why I got such output, it doesn't seem logical.
As I can understand what you are looking for is to print the even numbers twice.
You can do the following without using a for loop by this way.
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while (n<10):
if(int(strarr[n])%2 == 0):
print(strarr[n])
print(strarr[n])
elif(int(strarr[n])%2 != 0):
print(strarr[n])
n = n+1
The reason why your code gives that output is because,
for the 1st iteration it would print 1, 2, 3
2nd iteration it would print out 3 again as there is another print(stararr[n]) outside the for loop. That's the reason why you are getting the output you are getting.
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while True:
for i in range(k):
print(strarr[n])
n = n+1
print(strarr[n])
The error that I think you're seeing has to do with the order that you print your output and update the index n. In the current, buggy code, you're printing first, then updating the value. This means that the second print outside of the inner loop prints using the next value of n, not the one you just used in the inner loop. The same index gets used a second time in the first pass of the inner loop the next time, but that's not the value you wanted to see repeated.
The solution to this issue is pretty simple. Rather than updating after you print, update before. You'll need to adjust the starting value of n, but that's no problem:
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = -1 # change starting index
while True:
for i in range(k):
n = n+1 # and reorder the lines in the inner loop
print(strarr[n])
print(strarr[n])
That said, the two loop thing is a lot more awkward than anything I'd really recommend. If you just want to repeat the odd-indexed values in the loop, you can do that much more simply:
for index in range(len(strarr)):
print(strarr[index])
if index % 2 == 1:
print(strarr[index])
Or you can avoid directly needing to index at all, using enumerate to get the index and value of each element in the for statement itself. This is probably a more "Pythonic" way to solve the problem.
for index, value in enumerate(strarr):
print(value)
if index % 2 == 1:
print(value)
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 5 months ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Can anyone help me out with this question. I did it in the right way but it is showing me an error. I dont know whats the issue.
Find duplicates in an array
Given an array a[] of size N which contains elements from 0 to N-1, you need to find all the elements occurring more than once in the given array.
Error while compiling
Here is my code
def duplicates(self, arr, n):
result = []
a = []
arr.sort()
for i in arr:
if i not in a:
a.append(i)
else:
if i not in result:
result.append(i)
if len(a) == n:
result.append(-1)
return result
I think the error the error is due to the worst time and space complexity. You have used the brute force method to program the code which is not the right way. Make your code more efficient for a good time and space complexity. Here is my code.
def duplicates(self, arr, n):
# Make an array of n size with a default value of 0
result = [0] * n
ans = []
#Update the index with value in an array
for i in range(n):
result[arr[i]] +=1
# Iterate through each element in an array to find the element which has a value of more than 1. return the I value and break.
for i in range(len(result)):
if result[i] >1:
ans.append(i)
if not ans:
ans.append(-1)
return ans
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 5 months ago.
Improve this question
My teacher gave me an exercise during the computing lesson in week 2:
Write a Python program to create and print a list where the values are first N square of numbers. You are REQUIRED to implement a function named printSquare() to take n where n is an positive integer.
I'mm trying to writing a function called printSquare().
for example, the expected output of printSquare(5) is [1, 4, 9, 16, 25].
def getList(num):
list=[]
for i in range(int(num)):
list.append(i)
return list
def printSquare(num):
wholeList = list(getList(num))
wholeList.pop(0)
wholeList.append(num)
tmp=[]
for i in wholeList:
x = wholeList[i]**2
tmp.append(x)
return tmp
printSquare(5)
I'm struggling in the following part, I don't know why the tmp.append(x) doesn't work.
for i in wholeList:
x = wholeList[i]**2
tmp.append(x)
return tmp
The second question is that is there any faster way to write this code.
There are couple of mistakes and lack of understanding in the code. Let me try and explain mistakes and lack of understanding i found.
you are using range(num) which will give you a list from 0 to num-1. Hence you do wholeList.pop(0) to remove 0 from the list and wholeList.append(num) to then add the last num in.
Instead of that, you can do
range(1,int(num)+1)
This will return you a list from 1 to number, solving both the issue, and not needing to pop and add extra number to list
secondly
for i in wholeList:
x = wholeList[i]**2
That is not how looping over list works
for i in wholeList:
Will return you the element of the list, not its index. Here you are assuming i is the index of elements in list. So wholeList[i]**2 is where your code fails, since you try to access elements at index position that does not exist.
If you want to get index position you have to do
for index, value in enumerate(wholeList):
This will return you the index, and the value associated with the index in the list.
I hope, all of that helped you understand things better. Here is a code that works
def getList(num):
list=[]
for i in range(1,int(num)+1):
list.append(i)
return list
def printSquare(num):
wholeList = getList(num)
tmp=[]
for i in wholeList:
tmp.append(i**2)
return tmp
printSquare(5)
If you look at the error message it states that IndexError: list index out of range meaning that the index isn't in the range of your list. What you could do is try to use the range function over the length of the list: for i in range(1, len(wholeList)), this ensures that the index is always within the range.
when you use for..in you are directly getting elements, not indexes. So to solve the problem write
for i in wholeList:
x = i**2
tmp.append(x)
return tmp
Also, you can write this way more clearly with list comprehensions (and it is a nice tool to have)
def get_list(n):
return [i**2 for i in range(1, n+1)]
You have made this far more complicated than it really is. You can (should) use a list comprehension thus:
def printSquare(n):
print([x*x for x in range(1, n+1)])
printSquare(5)
Output:
[1, 4, 9, 16, 25]
The i in the for loop is the value, not the index. You should either write x=i**2, or in the for loop you should specify it differently:
for i, value in enumerate(wholeList):
x = value**2
tmp.append(x)
The tmp list now includes the square values of the wholeList.
Also, you are not printing anything somewhere.
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 4 years ago.
Improve this question
I got stuck by finding out how to build a recursive function
that sums the elements in a list form a specific starting point
to the end of the list.
for example when list a[1,2,3,4,5,6,7,8,9,10] and starting point is Index 5
I want to get the sum of 6+7+8+9+10.
For me it is quite difficult to understand the whole concept of recursive functions. Maybe you can help me to get a step further understanding the concept.
Many thanks in advance
Define a function that normally computes the sum recursively.
To compute sum of a subsequence of a list, use list slicing.
def recsum(num_list):
if len(num_list) == 0:
return 0
return num_list[0] + recsum(num_list[1:])
a = [1,2,3,4,5]
recsum(a)
>>> 15
# It means 1+2+3+4+5
recsum(a[1:])
>>> 14
# It means 2+3+4+5
recsum(a[2:4])
>>> 7
# It means 3+4
It's difficult to describe a recursive function in short. Please read the comments carefully.
my_recursive_function will take the list and the index from which I want to calculate the sum
If the index==list_length then I already traversed the list so in this case I shall return 0.
If I have not completed traversing the list then I shall take the value of that index call my_recursive_function again from the next index. This is where recursion starts.
Then return the sum of current index and value of next indices.
For recursion we should place the recursion braking condition at the first portion of the function.Otherwise it may run infinitely.
def my_recursive_sum(my_list, index):
list_length = len(my_list)
if index == list_length: # If i am next to the last element then return 0 and I won't go next and I shall go back
return 0
return my_list[index] + my_recursive_sum(my_list, index + 1) # value of current index+value of next indices.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = my_recursive_sum(a, 3)
print(result)
this is how I interpreted the code delivered by Taohidul Islam:
might be right?
recursion
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 6 years ago.
Improve this question
I tried to implement quick select to find the m'th smallest number in the list. When I run the program it returns the correct values sometime and incorrect values other times on the same array. What am I doing wrong her is the code
def select_mth_smallest(A, m):
pivot = np.random.choice(A)
# split into 3 partitions
A1 = []
A2 = []
A3 = []
for item in A:
if item < pivot:
A1.append(item)
if item > pivot:
A3.append(item)
else:
A2.append(item)
#find where m'th largest element is and recurse accordingly
if len(A1) >= m:
return select_mth_smallest(A1, m)
elif (len(A1) + len(A2)) >= m:
return pivot
else:
return select_mth_smallest(A3,m - (len(A1)+len(A2)))
Here is an input where the algorithm fails.
A = [1,2,3,4,5]
select_mth_smallest(A,5)
When I repeatedly execute this above statement I get, 5(correct) and 4(incorrect) alternatingly.
One thing that particularly baffles me (I am new to python) is that why I get different return values for the function when repeated with the same input. Looks rather sporadic.. BTW I am using Jupyter
You are adding some items to multiple partitions.
if item < pivot:
A1.append(item)
if item > pivot:
A3.append(item)
else:
A2.append(item)
A1 is the set of items less than the pivot. A3 is the set of items greater than the pivot. A2, however, is the set of items less than or equal to the pivot, because the 2nd if statement executes for all items, and one or the other branch will execute.
You want one, single if statement with an elif and else clause here.
if item < pivot:
A1.append(item)
elif item > pivot:
A3.append(item)
else:
A2.append(item)