Runtime error Codeforces (71A) - Python - python

firstly, I would like to state that the question I am about to ask is not related to any homework or competiton.
Now, I recently started out with codeforces. I am using Python 2.7.10 to code. The link to the question is this - http://codeforces.com/problemset/problem/71/A
n = input('Enter the test cases :')
b=[]
while n>0:
a = raw_input('Enter the string :')
b.append(a)
n=n-1
t = 0
while t<len(b):
if len(b[t]) > 10:
length = len(b[t])-2
length = str(length)
c = b[t]
print c[0] + length + c[len(c)-1]
else:
print b[t]
t=t+1
The problem I am experiencing is that it says runtime error on test case 1.
My answer comes out fine as mentioned is their test cases. I suppose my syntax is wrong!
I hope you guys can help me out.
Thanks in advance! :)

When taking input you are printing some extra lines like 'Enter the test cases :'. In codeforces your output has to exactly match with the desired output. Printing anything extra will give a verdict of wrong answer or run time error.

Related

Why I am receiving a runtime error in Codechef?

I am getting runtime error(NZEC) on Codechef. Can anyone tell me why?
withdrwal = int(input())
balance = float(input())
amt = balance - withdrwal- 0.5
if (withdrwal%5!=0 or withdrwal+0.5>balance):
print('%.2f'%balance)
else:
print('%.2f'%amt)
It's because for the specific sum that you are solving, the inputs are probably given in the same line. ie.
20 50
Your code expects inputs one after the other:
20
50
Try changing the input format in your code something like this:
withdrawal, balance = map(float, input().split())
Most probably you're trying to read input when there is no more input left to read and python raises an exception, the online judge in return gives the (NZEC) error. Try using raw_input() instead of input(). Comment back to let me know if it worked.

Please help me better understand this one "except"conditional line

I'm about a couple weeks into learning Python.
With the guidance of user:' Lost' here on Stackoverflow I was able to figure out how to build a simple decoder program. He suggested a code and I changed a few things but what was important for me was that I understood what was happening. I understand 97% of this code except for the except: i += 1 line in the decode(). As of now the code works, but I want to understand that line.
So basically this code unscrambles an encrypted word based on a specific criteria. You can enter this sample encrypted word to try it out. "0C1gA2uiT3hj3S" the answer should be "CATS"
I tried replacing the except: i += 1 with a Value Error because I have never seen a Try/Except conditional that just had an operational and no Error clause. But replacing it with Value Error created a never ending loop.
My question is what is the purpose of writing the except: i += 1 as it is.
'Lost' if you're there could you answer this question. Sorry, about the old thread
def unscramble(elist):
answer = []
i = 0
while i <= len(elist):
try:
if int(elist[i]) > -1:
i = i + int(elist[i]) + 1
answer.append(elist[i])
except:
i += 1
return "".join(answer)
def boom():
eword = input("paste in your encrypted message here >> ")
elist = list(eword)
answer = unscramble(elist)
print (answer)
clear()
boom()
The purpose is to advance i by one, skipping the current character in case the cast to int fails, i.e. if elist[i] is not a digit.
There are a couple of errors, than can occur inside the try-Block:
i is out of index, because the while loop runs one index to far.
elist[i] is not a number, which leads to an ValueError
i = i + int(elist[i]) + 1 gets to big, and the next index access leads also to an IndexError
In either way, the except-clause will ignore the next character. And the loop goes on.
An correct implementation wouldn't need any exceptions:
def unscramble(elist):
answer = []
i = 0
while i < len(elist):
i += int(elist[i]) + 1
answer.append(elist[i])
i += 1
return "".join(answer)

Trouble with functions in python 2.7.3

I am new to learning python, and I only have limited programing experience, so I am sorry for asking such a basic question. I am doing an online python tutorial and wanted to take the program a bit further than the lesson requested to test out how far I could take it. The problem is that I have been hitting a roadblock. After reading a bunch of posts on here I have moved things around, changed variable names, used more functions, less functions, if else statements, and toyed around/ troubleshot, but have received all sorts of errors. I am going to paste where I currently am at below and would really appreciate if someone out there could help me finish up the program.
Here is what I would like for the program to do:
I would like the user to be prompted to enter a number.
I would like to make sure that the user entered a number, and if they don't I would like the program to give them an error and restart.
I would like that once the number is received the program squares that number and then prints the answer.
(again thanks much for all the help)
HERE IS WHERE I AM AT:
n1 = raw_input('Please enter your desired number:')
def n2():
n2 = n1.isnumeric()
return n2
def square(n2):
squared = n2**2
print "%d squared is %d." % (n2, squared)
return squared
square(n2)
n2 = raw_input("number pls\n")
while not n2.isdigit():
print("why did you do this\n")
n2 = raw_input("number pls\n")
print int(n2)**2
Problems from your code:
You need a control structure which repeatedly tries to do something until the right thing happens. This should make you think "while loop."
isnumeric isn't a method. but you had the right idea.
Naming all of your variables and functions n2 is not a good way to easily see what's going on..
If you want to add a construct for floats, you should write a function which takes a string in and returns true or false based on if it looks like a float! This is a good example for using functions to decompose the problem you're working with- you know you need to do something like
while not (n2.isdigit or isFloat(n2)):
There are some good suggestions here and elsewhere about how to do that :)
You could check if you could convert into float if so print the square else print the error .To repeat this process while you get a number you could use while loop
def number_validator( numb ):
try:
float( numb )
return True
except Exception:
print "GIven input is not a valid number"
return False
def square( n2 ):
n2=float( n2 )
squared = n2**2
print "%s squared is %s." % ( n2 , squared )
return squared
n2 = raw_input( 'Please enter your desired number:' )
while not number_validator( n2 ):
n2 = raw_input( 'Please enter your desired number:' )
square( n2 )
Output:
Please enter your desired number:wq
GIven input is not a valid number
Please enter your desired number:we
GIven input is not a valid number
Please enter your desired number:21.0
21.0 squared is 441.0.

Python algorithm output troubleshoot

I have attached a python 2.7 script to answer question number 2 from the following link: http://labs.spotify.com/puzzles/
My attempt to solve is currently being met with a "wrong answer" reply, yet my code successfully works for the sample inputs on the site. I have tried modifying it to return and even print a list of the top m songs, instead of printing them out individually, but that did not work either. Any help or ideas would be great. Thanks in advance
import sys
def main():
line1 = sys.stdin.readline().split()
total_songs = int(line1[0])-1
num_songs_return = int(line1[1])
data = sys.stdin.read().split()
while(total_songs >= 0):
data[2*total_songs]= float(data[2*total_songs]) * (total_songs+1)
total_songs-=1
answers = [(data[a], data[a+1]) for a in range(0,len(data),2)]
answers.sort(reverse=True)
for n in range(num_songs_return):
print answers[n][1]
main()

How do I calculate something inside a 'for' loop?

I'm doing an assignment in which I have to move a simulated robot across the screen in a loop - I've got that part down, however, between loops, I also have to print the percentage of area covered with each movement - that's my issue.
I googled a bit and even found someone with the same problem, however, I'm not sure if I'm doing it properly.
This code was offered:
percent_complete = 0
for i in range(5):
percent_complete += 20
print('{}% complete'.format(percent_complete))
However, after an error, further googling revealed that only worked with certain versions
so I used this code:
percent_complete = 0
for i in range(5):
percent_complete += 20
print '% complete' % (percent_complete)
And, at the very least, it now executes the code, however, the output when printing is the following:
Here we go!
hello
omplete
hello
(omplete
hello
<omplete
hello
Pomplete
hello
domplete
What is the cause of this? I assume because one of the codes had to be edited, the other parts do as well, but I'm not sure what needs to be done.
for i in range(5):
percent_complete += 20
print '%d complete' % (percent_complete)
You were missing the d specifier.
The first version only works in Python 3 because it uses print as a function. You're probably looking for the following:
percent_complete = 0
for i in xrange(5):
percent_complete += 20
print '{0} complete'.format(percent_complete)
Your other code doesn't do what you intend to do because it now display the number as a string. What you want is that the number is properly converted to a string first and then displayed in the string. The function format does that for you.
You can also use Ansari's approach which explicitly specifies that percent_complete is a number (with the d specifier).
To add to/correct above answers:
The reason your first example didn't work isn't because print isn't a function, but because you left out the argument specifier. Try print('{0}% complete'.format(percent_complete)). The 0 inside the brackets is the crucial factor there.

Categories

Resources