Briana Billups
Briana Billups

Reputation: 1

Defining sequences with recursive for loop

I'm trying to write a for loop that will remove any combinations that are a number sequence, but it's not running through the whole tuple just the first value before breaking and running through the next. I'm not quite sure where the last value definition should be placed as it seems to just be running the if statement against the same number, not the actual last value

Here's the code:

from itertools import combinations as comb
import itertools

# combinations

list_1 = [1,2,3]

list_2 = [3]


pick_5 = list(comb(list_1,2))

pick_1 = list(comb(list_2,1))

combos = list(itertools.product(pick_5,pick_1))

sequence = []
for t in list(combos):
    for value in t:
        for subvalue in value:
            lastvalue = subvalue
            if lastvalue != subvalue - 1:
                sequence.append(t)
                should_break = True
                break
            lastvalue = subvalue
            should_break = False
        if should_break:
            break

the output is:

((1, 2), (3,))
((1, 3), (3,))
((2, 3), (3,))

And it should be:

((1, 3), (3,))
((2, 3), (3,))

Upvotes: 0

Views: 42

Answers (2)

Anurag
Anurag

Reputation: 3114

The assignment of lastvalue seems to be wrong, modified the for loop and addded comments wherever modified the code

for t in list(combos):
    lastvalue = None                #initialize lastvalue here
    for value in t:
        for subvalue in value:
            # lastvalue = subvalue  #No need of this
            if lastvalue and lastvalue != subvalue - 1:      #add a check for lastvalue
                sequence.append(t)
                should_break = True
                break
            lastvalue = subvalue
            should_break = False
        if should_break:
            break

Upvotes: 0

pepoluan
pepoluan

Reputation: 6808

These two lines

            lastvalue = subvalue
            if lastvalue != subvalue - 1:

In the first line, you've set lastvalue to be the same with subvalue.

In the second line, you're checking if lastvalue is not equal to subvalue-1... guess what? lastvalue will always be unequal to subvalue-1, because you've set it to be equal to subvalue in the preceding line!

That said, if you want to get the last value of a tuple, just use [-1] on that tuple.


EDIT: If I don't misunderstand what you want, you should be able to greatly simplify the loop by using indexing and Python's "tuple unpacking" feature:

sequence = []
for a, b in combos:  # Because combos is already a list
    if a[-1] == b[-1]:
        sequence.append((a, b))

And since it's only a single list.append command within an if within a for, you can utilize Python's awesome "list comprehension":

sequence = [
    (a, b) for a, b in combos if a[-1] == b[-1]
]

(Can be written as a one-liner, but for ease of reading, I've split it into three lines)

Upvotes: 1

Related Questions