0

beginner in python here, probably asking simple question. Basically I got an assigment that sounds like this. Each line in a.txt represents a question to which responders could respond with a,b,c (1,2,3 to simplify). For example line 1 is: 1 2 1 1 3 3 . There are 3 questions(obv lines too). My assigment is to find out which answer is the most common for every question. I wanted to make my code universal - a.txt can be modified with additional questions and answers. So far I got this:

for l in range(sum(1 for line in open('a.txt'))):
  a, b, c = 0, 0 ,0
  with open("a.txt") as subor:
    o=[int(i) for i in subor.readline().split()]
    for k in range(len(o)):
      if o[k] == 3:
       c = c+1
      elif o[k] == 1:
        a = a + 1
      else:
        b = b + 1
    if a > b and a > c:
      print("In question", l + 1 ,'is answer A the most common one')
    elif c > b and c > c:
      print("In question", l + 1 ,'is answer C the most common one')
    elif a == b or a == c:
      print("Cannot be decided")
    else:
      print("In question", l + 1 ,'is answer B the most common one')
    a, b, c = 0, 0 ,0
    o.clear()

The code works, but it only finds the most common answer for the 1st question, it never moves to the next one. How can i modify this code to move to the next question?

2
  • 1
    Hum! the condition c > c is always False (see the line: elif c > b and c > c:). Nov 20, 2020 at 19:19
  • An additional tip for readability: make your variables long. There's no need to use one character variables anymore, instead, try naming them things like answers_a, answers_b, answer_line, etc. Nov 20, 2020 at 19:23

1 Answer 1

0

In the for loop every time you execute line with open("a.txt") as subor: you open again the file. So you read the first line of the file with subor.readline(), then you re-open the file in the next iteration of the for loop. There are some errors also in the following part, I fixed them for you:

with open("a.txt") as subor:
    lines = subor.read().splitlines()

    l = 0
    for line in lines:

        o = [int(i) for i in line.split()]
        a = len([x for x in o if x == 1])
        b = len([x for x in o if x == 2])
        c = len([x for x in o if x == 3])

        if a > b and a > c:
            print("In question {} is answer A the most common one".format(l + 1))
        elif b > a and b > c:
            print("In question {} is answer B the most common one".format(l + 1))
        elif c > a and c > b:
            print("In question {} is answer C the most common one".format(l + 1))
        else:
            print("Question {} cannot be decided".format(l + 1))

        l += 1
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.