0

I'm trying to make a function where it checks to see if a number gets repeated 2 times and 3 times and when it does it will return either 0 (no repeats detected) or 1 (both arguments entered have repeats). But for someone reason, 1 always prints even when there are no repeats. Is there an easier way to do this or a way to fix my code? Also ignore the print('t'), print("w"), and print("x"). Those were just a way to check what was going on.

def triple_double(num1, num2):
    num1 = str(num1)
    num2 = str(num2)
    if ('111') or ('222') or ('333') or ('444') or ('555') or ('666') or ('777') or ('888') or ('999') in num1:

        if ('11') or ('22') or ('33') or ('44') or ('55') or ('66') or ('77') or ('88') or ('99') in num2:

            print('t')
            print(1)

        else:
            print("w")
            print(0)

    else:
        print("x")
        print(0)
triple_double(0, 0)
marianydev
  • 87
  • 2
  • 6
  • The answer to the question in your title (which is just part of the problem) is: `if ('111') or ('222') or ('333') in 0:` is effectively the same as `if True or True or True in 0:` and since the first condition (`'111'` - left of the first `or`) is `True` (any non-zero string is always True), then everything after the first `or` is never evaluated, and the whole thing is `True`. – Son of a Beach Dec 14 '16 at 03:32

2 Answers2

0

I would just flip it around and test if either of the string representations of the numbers are in a list containing your triple and doubles.

from itertools import repeat

def triple_double(num1, num2):
    # create triple and double lists
    triples = [''.join(repeat(str(i), 3)) for i in list(range(1, 10))]
    doubles = [''.join(repeat(str(i), 2)) for i in list(range(1, 10))]
    num1 = str(num1)
    num2 = str(num2)

    # test if num1 in triples
    if num1 in triples:
        # test in num2 in doubles
        if num2 in doubles:

            print('t')
            print(1)

        else:
            print("w")
            print(0)

    else:
        print("x")
        print(0)

triple_double(0, 0) # x, 0
datawrestler
  • 1,527
  • 15
  • 17
0

It should be:

def triple_double(num1, num2):
    num1 = str(num1)
    num2 = str(num2)
    if ('111') in num1 or ('222') in num1 or ('333') in num1 or ('444') in num1 or ('555') in num1 or ('666') in num1 or ('777') in num1 or ('888') in num1 or ('999') in num1:

        if ('11') in num2 or ('22') in num2 or ('33') in num2 or ('44') in num2 or ('55') in num2 or ('66') in num2 or ('77') in num2 or ('88') in num2 or ('99') in num2:

            print('t')
            print(1)

        else:
            print("w")
            print(0)

    else:
        print("x")
        print(0)
triple_double(0, 0)

Otherwise the if conditions will always evaluate to True.

Nurjan
  • 5,889
  • 5
  • 34
  • 54