Ex 1: Cable Length

In this session, you will learn:

  • how to write and call a function

  • python list built-in functions

Ex 1.1: Find the longest cable

Question:

You are still working on your cable-net. Now you want to find the longest cable in your cable-net. How can you do it?

Answer:

You can pick one cable, and suppose it is the longest cable. Then, pick the second one. If it is longer than the first one, then the longest one is the second one. Keep repeating this process until you have compared all the cables. Then you will find the longest cable.

1. Flowchart

2. Code

# ==============================================================================
# Input
# ==============================================================================
# cable length of the cable-net
cablenet = [1.6, 3.6, 2.4, 3.4, 2.7, 2.8, 3.3, 3.1, 3.7, 1.8, 1.8, 1.8, 2.6]

# initiate longest cable, suppose the first cable is the longest
longest = cablenet[0]  
index = 0  

# ==============================================================================
# Compare Cable Length
# ==============================================================================
# if the cable is longer than the longest cable
# assign the longest cable the new cable length
for i, cable in enumerate(cablenet):
    if cable >= longest:
        longest = cable
        index = i

# ==============================================================================
# Output
# ==============================================================================
print("The longest cable is cable", index + 1, "and its length is", longest, "m.")

You should achieve the following output: The longest cable is cable 9 and its length is 3.7 m.

Ex 1.2: Sort the cables

Question:

Now you want to sort the cables from the longest to the shortest. How can you do it?

Answer:

One way to solve this problem is to go through all the cables, and find the longest one. Add the longest one to a new list.

sorted cables

length

1

3.7 m

Then do it again and find the next-longest cable.

sorted cables

length

1

3.7 m

2

3.6 m

Keep doing and you would get the sorted cables from longest to shortest.

1. Flowchart

2. Write the function

To find one element in the sorted cable list, we need to find the longest cable in the remaining cable list. We could turn this part of the statements into a function, which we could reuse when needed. When we write a function, it's suggested to write a short doc describing the function.

def find_longest_cable(cablenet):
    """
    to find the longest cable in the cable list
    Parameters
    ----------
    cables : list
        A list containing the cable length of the cable-net

    Returns
    -------
    index: int
        Index of the longest cable in the cable list
    longest: float
        Length of the longest cable in the cable list
    """

    # check the list is not empty
    if cablenet == []:
        return

    # initiate longest cable, suppose the first cable is the longest
    longest = cablenet[0]  
    index = 0  

    # compare every cable with the longest cable
    for i, cable in enumerate(cablenet):
        if cable >= longest:
            longest = cable
            index = i

    return index, longest

3. Call the function

Now we could use find_longest_cable function to sort our cables from longest to shortest. Every time we find the longest cable, we will delete it from the cablenet list and add it to the sorted_cables list.

# ==============================================================================
# Input
# ==============================================================================
# cable length of the cable-net
cablenet = [1.6, 3.6, 2.4, 3.4, 2.7, 2.8, 3.3, 3.1, 3.7, 1.8, 1.8, 1.8, 2.6]
# create empty cable list
sorted_cables = []

# ==============================================================================
# Program
# ==============================================================================
while cablenet != []:
    # find the longest cable in the remaining of the cable list
    i, longest = find_longest_cable(cablenet)
    # remove the longest item from the cable list
    cablenet.pop(i)
    # add the longest item to the sorted cable list
    sorted_cables.append(longest)

# ==============================================================================
# Output
# ==============================================================================
print("The sorted cable list is", sorted_cables)

We would get the following output: The sorted cable list is [3.7, 3.6, 3.4, 3.3, 3.1, 2.8, 2.7, 2.6, 2.4, 1.8, 1.8, 1.8, 1.6]

We could also turn the sorting into a function. We can call a function in another function. This sorting method is also called selecting sorting algorithm.

def sort_cable_length(cables):
    """
    sort the cables in descending order

    Parameters
    ----------
    cables: list
        A list containing the cable length of the cable-net

    Returns
    -------
    sorted_cables: list
        A list containing the cable length of the cable-net in descending order
    
    """
    # create empty cable list
    sorted_cables = []

    while cables != []:
        # find the longest cable in the remaining of the cable list
        i, longest = find_longest_cable(cables)
        # remove the longest item from the cable list
        cables.pop(i)
        # add the longest item to the sorted cable list
        sorted_cables.append(longest)

    return sorted_cables

4. Python list functions

Python has built-in method sorted() that could sort a list easily. max() and min() would find the largest and smallest item in the list.

cablenet = [1.6, 3.6, 2.4, 3.4, 2.7, 2.8, 3.3, 3.1, 3.7, 1.8, 1.8, 1.8, 2.6]

print("Longest cable is", max(cablenet), "m.")
print("Shortest cable is", min(cablenet), "m.")
print("Cables in ascending order:", sorted(cablenet))
print("Cables in descending order:", sorted(cablenet, reverse=True))
print("Total cable length is", sum(cablenet), "m.")

Longest cable is 3.7 m. Shortest cable is 1.6 m. Cables in ascending order: [1.6, 1.8, 1.8, 1.8, 2.4, 2.6, 2.7, 2.8, 3.1, 3.3, 3.4, 3.6, 3.7] Cables in descending order: [3.7, 3.6, 3.4, 3.3, 3.1, 2.8, 2.7, 2.6, 2.4, 1.8, 1.8, 1.8, 1.6] Total cable length is 34.6 m.

Last updated