MENÜ

Honlap címe

Előző - #11 óra, perc, másodperc | Tartalomjegyzék | Következő - #13 Sum & Product

12. GYAKORLAT: LEGKISEBB ÉS LEGNAGYOBB

getSmallest([28, 25, 42, 2, 28])  →  2

A Python beépített min()és max() függvényei a legkisebb és a legnagyobb számokat adják vissza az átadott számok listájában. Ebben a gyakorlatban ezeknek a függvényeknek a viselkedését fogja újra megvalósítani.

Ez az a fajta probléma, amelyet triviális az embernek kézzel megoldani, ha a számlista rövid. Ha azonban a lista több ezer, millió vagy milliárd számot tartalmaz, be kell programoznia egy számítógépet a számítás elvégzéséhez.

Gyakorlat leírása

Írj egy getSmallest()függvényt, amelynek van numbersparamétere. A numbers paraméter egész számok és lebegőpontos számértékek listája lesz. A függvény a lista legkisebb értékét adja vissza. Ha a lista üres, a függvénynek vissza kell térnie None. Mivel ez a függvény a Python min()függvényét replikálja, a megoldásnak nem szabad használnia azt.

Ezek a Python- assertutasítások leállítják a programot, ha feltételük False. Másolja őket a megoldási program aljára. Az Ön megoldása akkor helyes, ha a következő assertállítások feltételei mind igazak :

assert getSmallest([1, 2, 3]) == 1

assert getSmallest([3, 2, 1]) == 1

assert getSmallest([28, 25, 42, 2, 28]) == 2

assert getSmallest([1]) == 1

assert getSmallest([]) == Nincs

Próbáljon megoldást írni a leírásban szereplő információk alapján. Ha továbbra is problémái vannak ennek a gyakorlatnak a megoldásával, további tippekért olvassa el a Megoldástervezés és a Különleges esetek és Gotchák című részt.

Ha végzett ezzel a gyakorlattal, írjon egy getBiggest() függvényt, amely a legnagyobb számot adja vissza a legkisebb szám helyett.

Előfeltétel fogalmak: len(), ciklusokhoz , listákhoz, Noneértékhez

Megoldás tervezése

Gondolja át, hogyan oldaná meg ezt a problémát számítógép nélkül, egy papírra írt számlista alapján. Az első számot használja a legkisebb számként, majd minden számot olvas utána. Ha a következő szám a legkisebb, mint az eddig látott legkisebb szám, az lesz az új legkisebb szám. Nézzünk egy kis példát. A 12-1. ábra azt mutatja, hogy a lista áthurkolása hogyan befolyásolná az eddig látott legkisebb számot követő [28, 25, 42, 2, 28]változó tartalmát .smallest

Creates a variable named smallest to track the smallest value found so far and set it to the first value in the list to start. Then have a for loop that loops over every number in the list from left to right, and if the number is less than the current value in smallest, it becomes the new value in smallest. After the loop finishes, the function returns the smallest value.

Special Cases and Gotchas

The function should first check if the list is empty. In that case, return None. And by starting the smallest variable to the first number in a non-empty numbers list, you can guarantee that smallest is always initialized to a value from the list.

Now try to write a solution based on the information in the previous sections. If you still have trouble solving this exercise, read the Solution Template section for additional hints.

Solution Template

Try to first write a solution from scratch. But if you have difficulty, you can use the following partial program as a starting place. Copy the following code from https://invpy.com/smallest-template.py and paste it into your code editor. Replace the underscores with code to make a working program:

def getSmallest(numbers):

    # If the numbers list is empty, return None:

    if len(____) == ____:

        return None

 

    # Create a variable that tracks the smallest value so far, and start

    # it off a the first value in the list:

    smallest = numbers[____]

    # Loop over each number in the numbers list:

    for number in ____:

        # If the number is smaller than the current smallest value, make

        # it the new smallest value:

        if ____ < smallest:

            ____ = number

    # Return the smallest value found:

    ____ smallest

The complete solution for this exercise is given in Appendix A and https://invpy.com/smallest.py. You can view each step of this program as it runs under a debugger at https://invpy.com/smallest-debug/.

Further Reading

The benefit of writing a computer program to do a simple task like finding the smallest number in a list is that a computer can process a list of millions of numbers in seconds. We can simulate this by having the computer generate one million random numbers in a list, and then pass that list to our getSmallest() function. On my computer, this program takes a few seconds, and most of that time is spent displaying the million numbers on the screen.

Write the following program and save it in a file named testsmallest.py. Run it from the same folder as your smallest.py file so that it can import it as a module:

import random, smallest

 

numbers = []

for i in range(1000000):

    numbers.append(random.randint(1, 1000000000))

print('Numbers:', numbers)

print('Smallest number is', smallest.getSmallest(numbers))

When run, this program displays the million numbers between 1 and 1,000,000,000 it generated, along with the smallest number in that list.

Prev - #11 Hours, Minutes, Seconds | Table of Contents | Next - #13 Sum & Product

 

Asztali nézet