boardrider
boardrider

Reputation: 6185

Flipping one digit to get all digits the same: is the code wrong?

Trying to solve the following problem:

Given a binary D containing only digits 0's and 1's, I have to determine if all the digits could be made the same, by flipping only one digit.

The input is the number of Ds to test, and then the Ds, one per line. for instance:

3
11111001111010
110
100000000000000

The output is "Yes" or "No", namely in this instance, the run will look like:

$ python3 first.py
3
11111001111010
NO
110
YES
100000000000000
YES

However, the automatic evaluator of this problem judges the following code wrong:

T = int(input())

for i in range(T):
    line = input()
    ones = zeros = 0
    for c in line:
        if int(c) == 1:
            ones += 1
        elif int(c) == 0:
            zeros += 1
        else:
            raise ValueError
        if ones > 1 and zeros > 1:
            print("NO")
            break

    if ones == 1:
        print("YES")
    elif zeros == 1:
        print("YES")

Can you suggest why?

Upvotes: 0

Views: 1852

Answers (2)

boardrider
boardrider

Reputation: 6185

The solution is rather embarrassing: I outputted the answer as all uppercase, where the expected output is Title case. The following code is accepted:

T = int(input())

for i in range(T):
    line = input()
    ones = zeros = 0
    for c in line:
        if int(c) == 1:
            ones += 1
        elif int(c) == 0:
            zeros += 1
        else:
            raise ValueError
        if ones > 1 and zeros > 1:
            print("No")
            break

    if ones == 1:
        print("Yes")
    elif zeros == 1:
        print("Yes")
    elif ones == 0 or zeros == 0:
        print("No")

Upvotes: 0

niemmi
niemmi

Reputation: 17263

Your program doesn't output anything in case that all the digits are the same. You can fix the problem by changing the last part in following way:

if ones == 1:
    print("YES")
elif zeros == 1:
    print("YES")
elif ones == 0 or zeros == 0:
    print("NO") # assuming that one bit must be changed

Note that you could just use str.count to count zeros (or ones) and then check if count is 1 or len(line) - 1:

T = int(input())

for i in range(T):
    line = input()
    zeros = line.count('0')
    print('YES' if zeros == 1 or zeros == len(line) - 1 else 'NO')

Upvotes: 2

Related Questions