Improving the IO of python code for testing machines
<p>I was doing some practice problems in <a href="http://www.codechef.com" rel="nofollow">Codechef</a>. There is this problem called <a href="http://www.codechef.com/problems/PERMUT2/" rel="nofollow">Ambiguous permutations</a>:</p>

<p>My Solution to this was:</p>

<pre><code>while 1:
   cnt = int(raw_input())
   if cnt == 0:
      break
  vals = [int(u) for u in raw_input().split(' ')]
  valr = []
  for i in range(cnt):
    valr.append(vals.index(i+1)+1)
  if vals == valr:
    print 'ambiguous'
  else:
    print 'not ambiguous'  
</code></pre>

<p>When I checked it out in <a href="http://www.trypython.org" rel="nofollow">Trypython.org</a>, it worked as expected. But when I submitted the solution in Codechef, it timed out.</p>

<p>My question is this. Is there anything wrong (/could be improved) with the code, or is there any specific way to handle sysin and outputs for testing machines?</p>

<p>[EDIT]
The accepted solution provided some great suggestions, and I rethought the code logic and modified the code accordingly. The code now runs within time, although it fails with wrong answer (not able to replicate the wrong answer in my test cases though). Thanks for the advice.</p>

<pre><code>import sys
def ambigcheck(lis):
   amb = 'ambiguous'
   for i in range(1,len(lis)+1):
       if lis[lis[i-1]-1] != i:
          amb = 'not ambiguous'
          break
   return amb 
while 1:
   cnt = int(sys.stdin.readline())
   if cnt == 0:
       break
   vals = [int(u) for u in sys.stdin.readline().split(' ')]
   sys.stdout.write(ambigcheck(vals))
</code></pre>
