lundi 9 novembre 2015

if/elif and sequencial if statements [duplicate]

This question already has an answer here:

Sorry if this question is a duplicated, but as my English is not so good, I didn't figure how to formulate the question and I want to understand something about if and elif statements.

I am doing an exercise where I have to get from list x, the items that are not found in list y. This is with a method of comparing each element from both lists.

I solved it, but I didn't udnerstand the logic behind sequential if-elif statements for example:

My working code:

def merge_2(xs, ys):
    """
      Return only those items that are present in the first list,
      but not in the second.
    """
    result = []
    x_index = 0
    y_index = 0

    while True:

        if x_index >= len(xs):
            return result

        if y_index >= len(ys):
            result.extend(xs[x_index:])
            return result


        if xs[x_index] < ys[y_index]:
            result.append(xs[x_index])
            x_index += 1
        elif xs[x_index] > ys[y_index]:
            y_index += 1
        else:
            x_index += 1


print(merge_2([1, 2, 3, 4, 12, 35, 46, 54, 58, 62, 78, 82, 94], [1, 2, 4, 5, 6, 9, 54, 68, 78, 82]))

The result is: [3, 12, 35, 46, 58, 62, 94]

The code that differs is:

def merge_2(xs, ys):
    """
      Return only those items that are present in the first list,
      but not in the second.
    """
    result = []
    x_index = 0
    y_index = 0

    while True:

        if x_index >= len(xs):
            return result

        if y_index >= len(ys):
            result.extend(xs[x_index:])
            return result


        if xs[x_index] < ys[y_index]:
            result.append(xs[x_index])
            x_index += 1
        if xs[x_index] > ys[y_index]:
            y_index += 1
        else:
            x_index += 1


print(merge_2([1, 2, 3, 4, 12, 35, 46, 54, 58, 62, 78, 82, 94], [1, 2, 4, 5, 6, 9, 54, 68, 78, 82]))

Giving the result [3, 12, 46, 58, 94]

So, my question is: Why do my results differ so much if they appear to do the same thing?

Aucun commentaire:

Enregistrer un commentaire