简体   繁体   中英

Python Min-Max Function - List as argument to return min and max element

Question: write a program which first defines functions minFromList(list) and maxFromList(list). Program should initialize an empty list and then prompt user for an integer and keep prompting for integers, adding each integer to the list, until the user enters a single period character. Program should than call minFromList and maxFromList with the list of integers as an argument and print the results returned by the function calls.

I can't figure out how to get the min and max returned from each function separately. And now I've added extra code so I'm totally lost. Anything helps! Thanks!

What I have so far:

def minFromList(list)

texts = []
    while (text != -1):
    texts.append(text)

high = max(texts)

return texts 

def maxFromList(list)

texts []
    while (text != -1):
    texts.append(text)

low = min(texts)

return texts



text = raw_input("Enter an integer (period to end): ")
list = []
while text != '.':
    textInt = int(text)
    list.append(textInt)
    text = raw_input("Enter an integer (period to end): ")

print "The lowest number entered was: " , minFromList(list)
print "The highest number entered was: " , maxFromList(list) 

I think the part of the assignment that might have confused you was about initializing an empty list and where to do it. Your main body that collects data is good and does what it should. But you ended up doing too much with your max and min functions. Again a misleading part was that assignment is that it suggested you write a custom routine for these functions even though max() and min() exist in python and return exactly what you need.

Its another story if you are required to write your own max and min, and are not permitted to use the built in functions. At that point you would need to loop over each value in the list and track the biggest or smallest. Then return the final value.

Without directly giving you too much of the specific answer, here are some individual examples of the parts you may need...

# looping over the items in a list
value = 1
for item in aList:
    if item == value:
        print "value is 1!"

# basic function with arguments and a return value
def aFunc(start):
    end = start + 1
    return end
print aFunc(1)
# result: 2

# some useful comparison operators
print 1 > 2  # False
print 2 > 1  # True

That should hopefully be enough general information for you to piece together your custom min and max functions. While there are some more advanced and efficient ways to do min and max, I think to start out, a simple for loop over the list would be easiest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM