Why is there no IndexError thrown when length of list is smaller than the index used in return statement? - python-3.x

Here is the python code:
#!/usr/bin/python3
def top_three_new(input_list):
return sorted(input_list, reverse=True)[:100]
print(top_three_new([2, 1]))

[:100] does not mean that it will return exactly the 100th element.
[:n] returns the n items from last. If there is less than n items it simply returns all.

Related

How to find a minimum value in given list using recursion function

I have tried to write a recursion function to find minimum value in my list but I stuck on what to do next.
def findRecMin(aList):
if(len(aList)==1):
return aList[0]
else:
min_of_the_rest = findRecMin(aList[1:])
myList = [16, 20, 3, 37, 95, 49, 61]
n = findRecMin(myList)
print(n)
I need to find a minimum value of the given list. Can anyone help me with this?
Writing recursive functions like this is straightforward if you take a "leap of faith" and assume that the recursive call gives a correct result. In this case, your code
min_of_the_rest = findRecMin(aList[1:])
makes a recursive call on the tail of the list, which is everything except the first element. So let's assume it truly does give you the minimum element from the tail; the only problem you need to solve now is, how do I use the first element at aList[0], and the minimum value of the tail, to find the minimum of the whole list? The answer is that whichever is smaller, either aList[0] or min_of_the_rest, is the true minimum of the whole list. So we can write something like
if aList[0] < min_of_the_rest:
return aList[0]
else:
return min_of_the_rest
Or more simply, using the min function,
return min(aList[0], min_of_the_rest)
This approach works for writing many kinds of recursive function on lists; assume the recursive call gives you the correct result for the tail, then work out how to combine the first element with that result in order to get the result for the whole list. For example:
Finding the sum: the sum of the whole list is aList[0] + sum_of_the_rest.
Finding the length: the length of the whole list is 1 + len_of_the_rest.
Testing whether the number x is in the list: aList[0] == x or the_rest_contains_x.

max() arg is an empty sequence in max(listname)

I have written a program which accepts a list of numbers and returns the largest number possible by concatenating the list of numbers in Python. But when I execute the code I get following error message ValueError: max() arg is an empty sequence. Here is my code:
def create_largest_number(number_list):
l=list()
m=max(number_list)
while(number_list!=0):
m=max(number_list)
l.append(m)
number_list.remove(m)
return l
number_list=[23,45,67]
largest_number=create_largest_number(number_list)
print(largest_number)
Sample Input: 23,34,55
Sample Output: 554323
number_list!=0 is always going to be true because number_list is a list, not a number, so while number_list != 0 is an infinite loop, and given that you're removing items from the list on each iteration, the list will eventually become empty. Yet it'll never become zero, so on the next iteration your code will attempt to calculate max(number_list) == max([]), which is an error.
You can solve it this way:
while number_list: # a.k.a. `while len(number_list) > 0:`

Function that removes zeroes from list?

I just need a function that removes zeroes from an input list
def no_zero(a):
pos=0
while (pos+1)<=len(a):
if a[pos] == "0":
a.remove[pos]
pos= pos +1
return a
print(no_zero([0,1,0,2,0,3]))
I should be getting an output of 1,2,3 but instead it skips right to return a. Any pointers as to why? Cheers.
You can use a list comprehension:
def no_zero(a):
return [x for x in a if x != 0]
print(no_zero([0,1,0,2,0,3]))
Additionally, the reason your code currently isn't working is because you are comparing the items to a string ("0") instead of an integer (0). You are also attempting to modify a list as you iterate over it, which means that your indices don't correspond to the original indices of the list, and your result will be wrong.

Getting a list item with the max evaluation in a list of tuples in Python

Given this list of tuples:
my_tuples = [(1,2), (3,4)]
and the following evaluation function:
def evaluate(item_tuple):
return item_tuple[0] * 2
Question: how can I get the list item (tuple) that has the highest evaluation value? (I'm guessing I can use a list comprehension for this)
def max_item(tuples_list, evaluation_fn):
'''Should return the tuple that scores max using evaluation_fn'''
# TODO Implement
# This should pass
assertEqual((3,4), max_item(my_tuples, evaluate))
Correct me if I'm wrong, you want the list of tuples sorted by the result of multiplying one of the values inside the tuple with x (in your example above it would be the first value of the tuple multiplied by 2).
If so, you can do it this way:
from operator import itemgetter
sorted(l, key=itemgetter(0 * 2), reverse=True)
I managed to do it this way:
def max_item(tuples_list, evaluation_fn):
zipped = zip(map(evaluation_fn, tuples_list), tuples_list)
return max(zipped, key=lambda i:i[0])[1]
I don't know if there's a simpler (more pythonic?) way to solve it though.
Edit
I figured how I could use a list comprehension to make it more succinct/readable:
def max_item(tuples_list, evaluation_fn):
return max([(evaluation_fn(i), i) for i in tuples_list])[1]

Python - Create a recursion function

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

Resources