my question is basically this: Create a recursion function that takes a nested list as a
parameter and returns the sub-list that has minimum difference between its maximum and minimum elements.
For example: Function should return [1,2] for input [[1,199,59],[1,2],[3,8]]
I searched Google and stackoverflow, but i could not find this specific example.
What i would like to get help is with iteration. I want to, using recursion, iterate over each sub-list(can be as many as possible). I have achieved this with a for loop, but i cannot grasp the idea of iteration by using recursion method.
So far, i have this:
def sublist(mylist):
if len(mylist) == 0:
return []
elif len(mylist) == 1:
return mylist
else:
a = (mylist[0][0]) - (mylist[0][-1])
if a < sublist(mylist[1:]):
return mylist[0]
sublist([[1,199,58],[1,2],[3,8]])
This part, ( sublist(mylist[1:]) ) i know is clearly wrong. I'm trying to compare the value a, with the values from the mylist[1:]. I would appreciate much advice here.
Updated:
def differences(mylist):
diff = max(mylist) - min(mylist)
return diff
def sublist(nestedlist):
if len(nestedlist) == 1:
return nestedlist[0]
else:
if differences(nestedlist[0]) < differences(sublist(nestedlist[1:])):
return nestedlist[0]
else:
return sublist(nestedlist[1:])
print(sublist([[1,199,59],[1,2],[3,8]]))
i am assuming that you want to use recursion for the first level of the list. So, without giving you the code 100%, you have to do something like that:
1) create a method e.g diferences(list) that calculates the differences of a list and returns a list with the parameter list and the min difference i.e differences([1,2]) should return [1, [1,2]]. call it once on the first sublist i.e min = differences(mylist[0])
2) create your sublist method like this:
def sublist(initial_list):
# 1) call differences() method for the first sublist of the 'initial_list'
# 2) update 'min' with differences(initial_list[0])if differences(inilitial_list[0])[0] < min[0];
# 3) call sublist() again now removing the sublist you checked before from the arguement
# 4) (the following should be at the start of your sublist() method)
if len(initial_list) = 1:
if differences(initial_list) < min:
return initial_list
else: return min[1]
Hope that helps
Related
def myNames():
b = []
while True:
a = input("whats the name: ")
if a != "done":
b.append(a)
elif a == "done":
break
return b
x = myNames()
print (x)
def getAverageLength(myNames):
total = 0
for i in myNames: #This line of code gives me an error and I cant figure it out
total = total + len(i)
average = float(total) / float(len(myNames))
return average
getAverageLength(myNames)
It takes my first function (myNames) as an argument. Ive been trying to figure this error out but have no idea what to do here
Your last line: getAverageLength(myNames), like you said in your description, is using myNames as a parameter which is only present as a function in the current scope.
This means when you reach your for loop, you end up trying to iterate over a function, since that is what was passed into getAverageLength
Maybe you meant getAverageLength(x)?
Or perhaps getAverageLength(myNames()) since myNames() passes the result of the function as opposed to the function itself.
To correctly calculate the average length of the strings, you could use the following:
averageLength = sum(map(len, x)) / len(x)
My function prints the the index of every element in list that is divided by 2 in a given list. I want to know if there is a way to return all the indexes rather than printing?
def printEvenIndex(referenceTuple):
for i in referenceTuple:
if i % 2 ==0:
indexOfEvenIntegers = referenceTuple.index(i)
print(indexOfEvenIntegers)
return indexOfEvenIntegers
referenceTuple = (6,5,3,4,1)
print(printEvenIndex(referenceTuple))
Right now print statement prints 0 ,3 which is valid.
But return function is returning 3 only. Is there a way to tell return function to return every element that is divisible by 2? I want to return all the index rather than print it.
Just create a list and append your indexes there:
def readEvenIndexes(referenceTuple):
""" Named it readEventIndexes, as we are not printing anymore """
indexes = []
for index, i in enumerate(referenceTuple):
if i % 2 ==0:
indexes.append(index)
return indexes
referenceTuple = (6,5,3,4,1)
print(readEvenIndexes(referenceTuple))
Very new to any kind of coding. I would like to write a function that will return the elements of a numeric list, up to the first even number. For example, if the list is [1,5,7,8,9] it will return [1,5,7]
I know the below is not correct, but I am having trouble passing the list into the while loop.
def iter_up_to_even(num_lst):
i=0
new_lst=[]
while i < len(num_lst):
if i%2!=0:
new_lst.append(num_lst)
i=i+1
if i %2==0:
break
return new_lst
Looks like you might have some indentation issues. Try this solution:
def iter_up_to_even(num_list):
to_return = []
current_index = 0 if len(num_list) > 0 else len(num_list)
while current_index < len(num_list):
if num_list[current_index] % 2 == 1:
to_return.append(num_list[current_index])
else:
break
current_index += 1
return to_return
Explanation
We start with an empty list to_return, which we will return at the end of our function. Next, we iterate through each item in the input list num_list. If the input list num_list is empty to begin with, we don't even enter the while loop (see Line 3). If the item is odd, we append it to our to_return list. If it's even, we break from our loop and return to_return.
In addition, you should compare values in the list (e.g. num_list[i]), rather than the current index in the list (e.g. i).
I am supposed to ask the user to input a number then print all the numbers preceding that but, I have to insert a 0 after every even number.
I am a beginner in Python so, I don't know much.
n=0
length_even=[]
length_odd=[]
def length_list(n):
length=int(input('Enter the length of the list: '))
for i in range(1,length+1):
if(i%2 != 0):
length_odd.append(i)
elif(i%2 == 0) :
length_even.append(i)
length_even.insert(i,0)
total=length_odd+length_even
return total
length_list(n)
If a user enters 5, I expect the output to be [1,2,0,3,4,0,5] but, the actual output is (1,3,5,2,0,4,0].
The problem is that you create two independent lists (length_even and length_odd) and concatenate (+ operator) them after you have added the values to each list (length_odd contains: 1,3,5 and length_even contains: 2,0,4,0). The result you get is therefore: 1,3,5,2,0,4,0. Why don't you just use one list? Have a look at the code below (I made only slight changes to avoid confusion):
n=0
lengthList = []
def length_list(n):
length=int(input('Enter the length of the list: '))
for i in range(1,length+1):
if(i%2 != 0):
lengthList.append(i)
elif(i%2 == 0) :
lengthList.append(i)
lengthList.append(0)
return lengthList
length_list(n)
I've written code to find the median of a list but I'm unsure how to display it when I run the code.
I've tried the print function but I'm not sure what to print.
My code is:
wages = [1,2,3]
def median(wages):
sorted_list = sorted(wages)
length = len(sorted_list)
center = length // 2
if length == 1:
return sorted_list[0]
elif length % 2 == 0:
return sum(sorted_list[center - 1: center + 1]) / 2.0
else:
return sorted_list[center]
Any help would be appreciated.
You can just call your function in the print statement:
print(median(wages))
or
print(median([1,2,3])
You might be confused because you labelled wages as the array and put it in the definition of your function, but there is no connection between the two wages in your code. The line
wages = [1,2,3]
creates a variables called wages but it doesn't impact the wages in the line:
def median(wages):
or inside your function definition. To read more have a look into variable scopes in python.
For example, you could call your function on any array such as,
test_array = [1,2,3,4]
print(median(test_array))
You can just print the return value of your median method.
def median():
your code here
print(median())
PS : There are some indentation errors in your code.