Home > Software engineering >  Iterating through tuples of varying sizes in a list
Iterating through tuples of varying sizes in a list

Time:01-05

This is an exercise to find the smallest number out of three options in a tuple. If the tuple doesn’t have exactly three option, then it should be skipped.

Why doesn’t the code below work. I thought that len() return an integer and would be comparable to an integer of 3, starting the second for loop to solve the problem. Thanks for any help you can give in advance,

xoxo

data = [
    (3),
    (7, 3, 5),
    (15, 20, 40),
    (300, 550, 137),
    ]


for i in range(len(data)):
    variable = len(data[i])
    if variable == 3:
        for num1, num2, num3 in data[i]:
            if num1 < num2:
                if num1 < num3:
                    answer.insert(0, num1)
            if num2 < num1:
                if num2 < num3:
                   answer.insert(0, num1)
            else:
                answer.insert(0, num3)

print(answer)

I've tested to make sure that the integer from the for loop using len() gives the correct value. I've experimented with the data[i] variable in hopes that was the problem. The loop to find out the smallest number worked when I removed the single 3 tuple, but in larger scale data that won't be an option.

Thanks again!

CodePudding user response:

You're doing an extra iteration here:

        for num1, num2, num3 in data[i]:
            if num1 < num2:

This will iterate over each element of data[i] and then try to destructure it as num1, num2, num3 (which fails because data[i] is itself the 3-tuple you want, at least if I'm interpreting your description correctly -- it'd be helpful to see a sample value of data).

What I think you want to do instead is:

        num1, num2, num3 = data[i]
        if num1 < num2:

A simpler way to do the whole thing would be to use the min function in a list comprehension:

answer = [min(t) for t in data if len(t) == 3]

CodePudding user response:

It's simper to just try unpacking each tuple, catching the resulting ValueError if an exception is raised.

for t in data:
    try:
        num1, num2, num3  = t
    except ValueError:
        continue

    # Process num1, num2, and num3 to determine
    # which gets added to answer here.
    ...
  • Related