MENÜ

Honlap címe

Előző - #25 Szorzótábla | Tartalomjegyzék | Következő - #27 Téglalap rajz

26. GYAKORLAT: KÉZFOGÁS

Két ember között csak egy kézfogás történhet. Három ember között három lehetséges kézfogáspár van. Négy ember között hat kézfogás történik; öt ember, tíz kézfogás és így tovább. Ez a gyakorlat feltárja a lehetséges kézfogási kombinációk teljes skáláját beágyazott forhurkokkal.

Gyakorlat leírása

Írjon egy nevű függvényt printHandshakes() egy listaparaméterrel people, amely emberek neveiből álló lista lesz. A függvény kiírja, hogy „X kezet fog Y-val” , ahol X és Y a listában szereplő személyek közötti összes lehetséges kézfogás pár. Nem megengedett a duplikáció: ha „Alice kezet fog Bobbal” megjelenik a kimenetben, akkor a „Bob kezet fog Alice-szel” nem jelenhet meg.

Például a printHandshakes(['Alice', 'Bob', 'Carol', 'David']) a következőket írja ki:

Alice kezet fog Bobbal

Alice kezet fog Carollal

Alice kezet fog Daviddel

Bob kezet fog Carollal

Bob kezet fog Daviddel

Carol kezet fog Daviddel

A printHandshakes()függvénynek a kézfogások számának egész számát is vissza kell adnia.

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 helyes, ha a kimenet az összes lehetséges kézfogást megjeleníti, és a következő assert állítások feltételei mind teljesülnek True:

assert printHandshakes(['Alice', 'Bob']) == 1

assert printHandshakes(['Alice', 'Bob', 'Carol']) == 3

assert printHandshakes(['Alice', 'Bob', 'Carol', 'David']) == 6

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.

Előfeltétel fogalmak: forciklusok, range() két argumentummal, len(), kiterjesztett hozzárendelési operátorok

Megoldás tervezése

Szükségünk van egy pár egymásba ágyazott forhurokra, hogy megkapjuk az emberpárokat minden kézfogásban. A külső for ciklus az első kézfogás személylistájának minden indexén, a belső forciklus pedig a külső ciklus indexe utáni személylista minden indexén iterál.

i A és a mozgások mögötti minta jvizuálisan könnyebben látható, mint a 26-1. ábra, amely egy 5 elemből álló peoplelistát használ példaként. Az indexek iés j a kézfogásban részt vevő két emberre utalnak:

As the algorithm runs, j starts after i and moves to the right, and when it reaches the end, i moves right once and j starts after i again. In the above example with 5 people (indexes 0 to 4) i starts at 0 and j starts at i + 1, or 1. The j variable increments until it reaches 4, at which point i increments to 1 and j resets back to i + 1, which is now 2.

If you look at the overall range of i and j, you’ll see that i starts at index 0 and ends at the second to last index. Meanwhile, j starts at the index after i and ends at the last index. This means our nested for loops over the people list parameter would look like this:

for i in range(0, len(people) - 1):

    for j in range(i, len(people)):

This solution is identical to the nested for loops in Exercise #42, “Bubble Sort.”

Special Cases and Gotchas

The most common mistake you want to avoid is having repeated handshakes. This can happen if your nested for loops cover the full range of indexes in the people list like so:

for i in range(0, len(people)):

    for j in range(0, len(people)):

In this case, i and j would run with each pair twice: for example, the first time with people[i] as the first handshaker and people[j] as the second handshaker, and then with people[i] as the second handshaker and people[j] as the first handshaker.

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/handshake-template.py and paste it into your code editor. Replace the underscores with code to make a working program:

def printHandshakes(people):

    # The total number of handshakes starts at 0:

    numberOfHandshakes = ____

    # Loop over every index in the people list except the last:

    for i in range(0, len(____) - 1):

        # Loop over every index in the people list after index i:

        for j in range(i + ____, len(____)):

            # Print a handshake between the people at index i and j:

            print(people[____], 'shakes hands with', people[____])

            # Increment the total number of handshakes:

            numberOfHandshakes += ____

    # Return the total number of handshakes:

    return numberOfHandshakes

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

Prev - #25 Multiplication Table | Table of Contents | Next - #27 Rectangle Drawing

 

Asztali nézet