Remove minimum from list without min() in Python - python

I am trying to remove the minimum value from a list of randomly generated numbers without using the minimum function or the remove function.
I created a function minremo, but I am unsure of what the return value should be to make it actually work. Thus far, I have a method of removing the minimum.
def minremo(lst):
lst.sort()
lst.reverse()
lst.pop()
return n
import random
number_list = []
for count in range(10):
number = random.randint(1, 100)
number_list.append(number)
print(number_list)
print(minremo(number_list))
The algorithms to remove the minimum works at file-level scope though:
import random
number_list = []
for count in range(10):
number = random.randint(1, 100)
number_list.append(number)
print(number_list)
number_list.sort()
number_list.reverse()
number_list.pop()
print(minremo(number_list))
But it does not work within the function itself. I'm not sure what I should return within the function. What should the return be within this function?

Return the list that you just modified (lst).
def minremo(lst):
lst.sort()
lst.reverse()
lst.pop()
return lst

Related

Why is my code not displaying the output?

I have written a program that reads integers until the user enters a 0, which stores the integers and then returns the sum of integers. But its not displaying the output, what went wrong?
def readList():
n=int(input())
while n!=0:
n=int(input())
return n
def calSum(n):
n=myList
myList = readList()
sum = calSum(myList)
print(sum)
calSum was assigning myList to n, but it was INSIDE the calSum and anything OUTSIDE this def was unable to read it, as it is local variable.
Same thing about n from readList. It's local. So "n" in readList and "n" in calSum does not exist outside those functions and can not be used anywhere else.
You were able to use "n" from readList, only because you used return, which returned this value to the rest of the program. And in the very same way you have to make in in calSum to make it work.
Google for global and local variables in python for more information on topic :)
def readList():
n=int(input("Input from readList"))
while n!=0:
n=int(input("Looped input from readList"))
return n
def calSum(n):
n=myList
return n #Added return as student suggested
myList = readList()
sum = calSum(myList)
print(sum)
This should be what you're looking for
The readList function appends to a list and then returns the list, as apposed to return just the first number as it was doing previously.
The calcSum function uses Python's built-in sum function to calculate the sum of all the integers in the list.
def readList():
myList = []
n=int(input())
while n!=0:
n=int(input())
myList.append(n)
return myList
def calSum(n):
return sum(n)
myList = readList()
sum = calSum(myList)
print(sum)

Create List of 100 Random Integers, Return Max Value

Write a Python function that will take a the list of 100 random integers between 0 and 1000 and return the maximum value. (Note: there is a builtin function named max but pretend you cannot use it.)
Here's what I tried:
import random
list = []
for i in range(100):
list.append(random.randint(0,1000))
def max(list):
#sort list from least to greatest
answer = list.sort()
#get last item in list (max value)
list.pop()
return max
print (max(list))
As you can see, what I'm confused about is how to correctly use the sort and pop methods to return the max value within the max function. I'm currently getting:
ParseError: bad input on line 12
Which is this line:
list.pop()
Not sure how to correct this. Thanks.
1) Your indentation was off
2) You managed to overwrite 2 Python builtins in 4 lines of code (max() and list()))
3) my_list.sort() does not return a list. It operates in place sorting the list in-place. On the contrary, sorted(my_list) does return a list so you can either do my_list.sort() or my_list = sorted(my_list).
4) Your return was just wrong.
See the code below:
a_list = []
for i in range(100):
a_list.append(random.randint(0, 1000))
def my_max(my_list):
return sorted(my_list)[-1] # here, the list we passed gets sorted and its last item is retrieved (item with index -1)
print(my_max(a_list))
Other interesting answers (hats off to #Rob) that feature a bit of cockiness:
def my_max(my_list):
return min(l, key:lambda i: 1/i)
or
def my_max(my_list):
return min(l, key:lambda i: -i)
my_list.sort() sorts the list itself. If you want to store your sorted list in answer, you should use:
answer = sorted(my_list)
You can also use a list comprehension to generate your first list as follows:
>>> random
>>>
>>> my_list = [random.randint(0, 1000) for i in range(100)]
>>> answer = sorted(my_list)
>>> answer.pop()
996 # This should be different each time
Now, your function can be:
def max(my_list):
# sort list from least to greatest
answer = sorted(my_list)
# get last item in list (max value)
max = answer.pop()
return max
If you still want to use the same list, you can do:
my_list.sort()
max = my_list.pop()
Note that: I prefer to call the list my_list because list is a python keyword.
I usually try to avoid using names that are have a predefined function / built-in names, this helps to avoid problems quite often. Like this it should work.
import random
my_list = []
for i in range(100):
my_list.append(random.randint(0,1000))
def my_max(my_list):
#sort list from least to greatest
my_list.sort()
#get last item in list (max value)
my_max = my_list.pop()
return my_max
print my_max(my_list)

Python problems w/ code

I would like to ask for some help with python ask since im new and im trying to learn it.
Write the following functions.
empty_list() returns an empty "list" of songs. This doesn't have to be a list in a Python sense of a word: the function can return a list, a tuple, dictionary, string, None ... or even a number if you think this is a good idea. (Hint: it's not. :) Return something that will be useful un the following functions.
play(a_list, song) somehow adds the given song (a string) to the list. How it does it depends on what your list is (a list, dictionary...).
song_plays(a_list, song) returns the number of times the song was played.
Say we do this:
new_list = empty_list()
play(new_list, "Yesterday")
play(new_list, "Tomorrow")
play(new_list, "Yesterday")
play(new_list, "Yesterday")
After this, a call song_plays(new_list, "Yesterday") returns 3, call song_plays(new_list, "Tomorrow") returns 1, and call song_plays(new_list, "Today") returns 0.
First part is done but now i need to write 4 more functions which i dont know where to start.
In the following functions we assume that we have two lists.
number_of_common(list1, list2) returns the number of songs that appear on both lists.
repertoire_size(list1, list2) returns the number of songs that appear on one (or even both) lists.
similarity(list1, list2) returns the similarity computed as the quotient of the above two numbers. If both lists are empty, the similarity is 0.
Write a function rang(a_list, n) that returns a list of the n most played songs. If two songs share equal number of plays, sort them alphabetically. If the list contains less than n song, the returned list will be shorted (but still ordered).
This is what i have for now:
def empty_list():
list = {}
return list
def play(list, song):
if song in list:
list[song] += 1
else:
list[song] = 1
def song_plays(list, song):
if song not in list:
return 0
else:
return list[song]
def total_songs(list):
return len(list)
def total_plays(list):
totalplays = 0
for name in list:
a = list[name]
totalplays += a
return totalplays
def favourite(list):
if list == {}:
return None
else:
max_name = ''
max_a = 0
for name in list:
a = list[name]
if max_a < a:
max_a = a
max_name = name
return max_name
def number_of_common(list1,list2):
def repertoire_size(list1,list2):
def similarity(list1,list2):
def rang(list,n):
For the list datatype, I'd recommend a Counter, then everything gets pretty compact:
from collections import Counter as empty_list
def play(a_list, song):
a_list[song] += 1
def song_plays(a_list, song):
return a_list[song]
def number_of_common(list1, list2):
return len(set(list1) & set(list2))
def repertoire_size(list1, list2):
return len(list1 + list2)
def similarity(list1, list2):
try:
return number_of_common(list1, list2) / repertoire_size(list1, list2)
except ZeroDivisionError:
return 0
def rang(a_list, n):
ranks = sorted(a_list.most_common(n), key = lambda x: (-x[1],x[0]))
return [song for song, times in ranks]
For the first three functions, look to the set data type. Set union, intersection, and length will solve these problems quickly. For instance:
set1 = set(list1)
set2 = set(list2)
either = set1.union(set2)
both = set1.intersection(set2)
full_count = len(either)
both_count = len(both)
similarity = float(both_count) / full_count
Note that within a single function, you can easily reduce the computations to a single line, such as
both_count = len(set(list1).intersection(set(list2)))
Sort by play frequency
You should be able to find supporting code through this sorting tutorial. The list is your main list; the play frequency is the sort key.

How to write a recursive function that returns a list made up of squares of the elements of lst?

Im not sure how to get my recursion to work properly or keep from infinitely repeating.
This is what i have so far:
def listSquareR(lst):
if len(lst)== 1:
return lst[0]**2
else:
return lst[0]**2+[listSquareR(lst[1:])]
last return line is obviously wrong
Another possibility:
def listSquare(L):
if L: return [L[0]**2] + listSquare(L[1:])
else: return []
An even shorter version (as Cristian Ciupitu mentions below) is:
def listSquare(L):
return [L[0]**2] + listSquare(L[1:]) if L else []
You have it almost right, but the key is to mind your types. In your code:
def listSquareR(lst):
if len(lst)== 1:
return lst[0]**2 # Returning a number
else:
return lst[0]**2+[listSquareR(lst[1:])] # Returning a number plus a list of a list
We just need two small fixes:
def listSquareR(lst):
if len(lst)== 1:
return [lst[0]**2] # Returning a list
else:
return [lst[0]**2] + listSquareR(lst[1:]) # Returning a list plus a list
def SquareArea(width):
if width == 0:
return 0
else:
return SquareArea(width-1) + (2*width-1)
This is a recursive function I've recently used to find the area of a square.
And since the area of a square is Side*Side, one can use it to find the square of any function.
Now all that is required of you is to make a loop, eg:
for i in range (list):
and implement this function on i
Or maybe use while loop.
newList=[]
length = len(list)
while i != length:
newList.append(SquareArea(i))
And then return the newList

Python Overwriting List Element

Is there a quick and easy way that is not computationally expensive to overwrite an element in a list corresponding to an element in another list (of the same length)?
iterates = input("How many iterates: ")
trials = input("How many trials: ")
aggregateList = [iterates]
def function():
recordList = []
for i in range(iterates):
# math goes here
recordList.append()
aggregateList[i] += recordList[i]
for i in range(trials):
function()
The problem is coming from aggregateList[i] += recordList[i]Any ideas on something else that will work? Say the value in recordList[i] is 5 for the first "iteration", 5 for the second, 5 for the third, at this time aggregateList[i] should be 15.
I think you are looking for either:
aggregateList += recordList
or
aggregateList.append(recordList)
depending on whether you want your aggregate to be flat or nested.
And change aggregateList = [iterates] to aggregateList = [].
This is how I personally would implement it:
iterates = input("How many iterates: ")
trials = input("How many trials: ")
def function():
recordList = []
for i in range(iterates):
# math goes here
recordList.append()
return recordList
aggregateList = []
for i in range(trials):
aggregateList.append(function())
Or even:
def calculate (i): pass #math goes here
#nested:
aggregateList = [[calculate(i) for i in range(iterates)] for _ in range(trials)]
#flat:
aggregateList = [x for trial in ([calculate(i) for i in range(iterates)] for _ in range(trials)) for x in trial]
Let us assume you've have a list of lists (in a variable name lists). This would be after you have called your 'function()' function (not the greatest function name by the way) and collected your recordLists in a list.
trials = 3
lists = [[1,2,3],[4,5,6],[7,8,9]]
for i in range(trials):
aggregateList = [reduce(lambda x, y: x+y, [listn[i] for listn in lists]) for i in range(trials)]
print aggregateList
would output
[12, 15, 18]
which I think is the type of solution you are looking for.
reduce is a fun function from functional programming. It allows you to apply the anonymous function lambda continuously to items of a list and then return the accumulated value. So in this case, it is preforming (1+4)+7,(2+5)+8,(3+6)+9. The list we are applying reduce to is constructed through a comprehension to extract the i's from the lists inside lists. The call to reduce is wrapped inside another comprehension to return a list of the results.
So iterates is a number like 4, and trials another like 3.
aggregateList = [iterates]
now aggregateList = [4]. What's the purpose of that?
def function():
recordList = []
for i in range(iterates):
# math goes here
recordList.append()
what are you appending to recordList? That last line should produce an error like: append() takes exactly one argument (0 given)
aggregateList[i] += recordList[i]
what is i at this point? The last value of the above iteration, i.e. iterates-1 =3, or is supposed to be the trials iterator. How many items do you expect aggregateList to have at this point? As written I expect it to give an error: IndexError: list assignment index out of range.
for i in range(trials):
function()
What is 'the problem'? What error message or bad result were you getting?
I suspect you are more familiar with another language, and trying to apply its idioms to Python. Also, get the calculation working before worrying about efficiency. At some point, though you might want to use numpy which adds arrays, and the ability to do math on a whole array at once.

Categories

Resources