Why I am receiving a runtime error in Codechef? - python

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.

Related

How to update a global variable based on number of user inputs?

I am trying to make a list of weights that are being brought to a trip to outer space. The way I have tried to show how many people are coming is this:
def flcr():
try:
Value1 = int(input())
except ValueError:
print("That was an incorrect format! Try again.")
flcr()
global x
x = Value1
Then the user has to input the weights one by one. This is what I tried:
def enter():
print("How much is each flight crew member bringing on the trip? Enter one entry at a time, this will be Earth weight.")
amount1()
def amount1():
try:
if x > 0:
equation1 = [float(input())]
x - 1
amount1()
else:
print(listFlcr)
except ValueError:
print("That was an incorrect format! Try again.")
enter()
When I input the weights though, I assume x just resets itself instead of subtracting itself by 1, so my input is infinite. I want to have a code that will allow me to enter the right amount of weights, so if I say there are 2 people coming, I can only input two weights.
If someone could help me out I would greatly appreciate it!
There are a number of issues with your current implementation.
You are using recursion to repeat getting inputs, which means you have a function (flcr, amount1) that calls itself until valid inputs are provided. While this could work for user inputs, it is usually unnecessary. There are better ways to ask for user input until they give a valid response, and as mentioned in the comments, use a loop instead.
The code x-1 does not update x. It actually does nothing because the result is not stored anywhere. If you are using an IDE or a linter, it could warn you that this is a "pointless statement". What you probably wanted was x = x - 1.
You are using globals to track how many weights need to be input and how many were input so far. While this could also work, it is again unnecessary. It would be simpler to just pass the number of flight crew members as a function argument.
Here's a solution that replaces the recursive calls with while loops and gets the number of people from one function, then passes the result of that to another function for getting the weights:
def get_num_people():
while True:
try:
return int(input("How many people are coming? "))
except ValueError:
print("That was an incorrect format! Try again.")
def get_weights(num_weights):
print("How much is each flight crew member bringing on the trip?")
all_weights = []
while len(all_weights) < num_weights:
try:
all_weights.append(int(input()))
except ValueError:
print("That was an incorrect format! Try again.")
print(all_weights)
return all_weights
num_people = get_num_people()
get_weights(num_people)
Here's the sample output:
$ python test.py
How many people are coming? 2
How much is each flight crew member bringing on the trip?
12
33
[12, 33]
$ python test.py
How many people are coming? 3
How much is each flight crew member bringing on the trip?
abc
That was an incorrect format! Try again.
89
def
That was an incorrect format! Try again.
100
4
[89, 100, 4]
I know that your question was about how to update the global variable based on user inputs, ... but I think you have a global x because you were using recursive calls. A cleaner solution would be to get rid of both recursion and the global variable.
You don't need global before the comparison of x in that function.
Generally for me, I find it easier to refer to things I want global as globals()[‘x’]. That way I know nothing weird will happen. If globals() refers to global namespace, represented similar to a dictionary, globals()[‘x’] will always point to the global variable x.
If it is intended to be global, declare it globally before everything else. Outside all the functions, x = None, or x = 0, or x = ‘’.
try to replace :
Value1 = int(input())
with :
Value1 = int(str(input("")))

Error "invalid syntax" appears when trying to redirect using input/output in Python shell

I tried to practice input/output redirection in the Python shell. I have a file named SentinelValue.py which is where I have this code to add up the numbers in another file:
data = eval(input("Enter an integer (the input ends " + "if it is 0): "))
sum = 0
while data != 0:
sum += data
data = eval(input("Enter an integer (the input ends " + "if it is 0): "))
print("The sum is", sum)
The other file "Numbers.txt" contains numbers:
1
2
3
4
5
6
7
8
9
0
and my output.txt file is where I want the sum to show.
I tried using:
python SentinelValue.py < Numbers.txt > output.txt
but on shell, it highlights "SentinelValue" & says "invalid syntax".
I don't know why it's not working.
There are several things wrong with your code:
As already suggested in the comments, do not use eval() for a direct user input (or pretty much any time, in 99% cases when you think you need it - you don't!). A simple int() conversion should be more than enough without all the dangers of eval().
Connected with the previous, eval() evaluates the input. Further more, on Python 2.x input() itself does the evaluation (it's an equivalent of eval(raw_input())) so whenever it encounters an invalid input it will pop a SyntaxError.
Even if it doesn't pop a SyntaxError, it will most certainly pop a TypeError as eval() expects a string and it will receive an integer from the inner input().
You're printing the "Enter an integer..." prompt to STDOUT which will result it ending up in your output.txt (where you redirect the STDOUT).
You're shadowing the built-in sum() by using it as one of your variables. That's a bad practice that can lead to many problems and unexpected results down the line.
So, with all that in mind, here's how to rewrite it to address these issues:
# Let's first make sure it works on Python 2.x and 3.x by shadowing the input
try:
input = raw_input # on Python 2.x use raw_input instead of input
except NameError:
pass
result = 0 # tip: use a name that's not already built-in, like result
while True: # loop 'forever'...
data = input() # don't print anything when asking for input
try:
data = int(data) # don't print anything to STDOUT
if not data: # only if the integer is 0
break
result += data # add to the final result
except ValueError: # risen if the input is not an integer...
pass # so just ignore it
print("The sum is: " + str(result)) # finally, print the result

Transforming an input variable into an interger

I'm completely new to python, and I wanted to create a program that "loads" a number that the user would have entered.
To do this, I made a function with an input variable,
percentage
that I then tried to transform to an interfer,
percentage_int
To then put in a while loop.
However, I get an error message, why?
def loader():
percentage = input("what percentage do you want?")
percentage_int =int(percentage)
x = 0
print("Goal:{} %".format(percentage_int))
while x < percentage_int:
x+=1
print(x)
loader()
You need to do the type conversion, that is in this case from string to integer.
If you dont do so python will consider percentage_int as the input string itself.
percentage = input("what percentage do you want?")
percentage_int = int(percentage)
Go through this tutorial which will help you learn more about type conversions with python.

Runtime error Codeforces (71A) - 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.

Simple python program

Bear with me, i'm extremely new to the world of programming. I'm trying to design a simple data entry/answer program for ICD-9 codes related to medical billing.
Example:
Enter ICD-9: "487.1"
Answer: "Influenza with respiratory manifestations"
Enter ICD-9 Code: "844.2"
Answer: "Cruciate Ligament Tear of Knee"
I sketched this out in a few minutes, but I have no idea how to get the program to read a range of numbers instead of just the one number. I'm also getting ValueErrors: invalid literal for int() with base 10: 844.2, so I used 844 just to test.
Filename: icd9wizard.py
number = 844
running = True
while running:
guess = int(input('Enter ICD-9 Code: '))
if guess == number:
print('Cruciate Ligament Tear of Knee')
elif guess < number:
print('Invalid entry')
else:
print('Invalid entry')
I know it's basic.. I just need an arrow pointing me in the right direction.
Thanks!
If you've got a predefined set of numbers that you'd like to use, you can test for inclusion in a dictionary:
good_numbers = {"487.1": "Influenza with respiratory manifestations",
"844.2": "Cruciate Ligament Tear of Knee",
"133.7": "Being awesome at code"}
running = True
while running:
guess = raw_input('Enter ICD-9 Code: ')
if guess in good_numbers:
print good_numbers[guess]
else:
print('Invalid entry')
In Python, the int data type can hold only whole integers, with no fractional part. For your application, since you won't be doing any actual arithmetic with the entered numbers, it's probably best to keep them as a string. So don't call int at all:
number = "844"
guess = input('Enter ICD-9 Code')
Notice how I changed number so that "844" appears in quotes. This means it could contain any character values, such as "844.2" or "fred".
There is another data type called float that holds floating point values (numbers with fractional parts). However, this type is not suitable for your application because you're not going to do calculations with these numbers.
You can fix the ValueError by using float() instead of int(). An int is incapable of storing non-integers, i.e. numbers with values after the decimal point.
As for the rest of your question, you should think about using a dictionary (see the python documentation) with the ICD-9 codes as the keys and the answer/description as the values. This way you can put in a ton of codes and descriptions without having to use a giant block of if and elif. Consider filling this dictionary by reading in a file or something.
For example (once you have filled the dictonary):
number = 844.2
running = True
while running:
guess = float(input('Enter ICD-9 Code: '))
if guess in icd_9_dict.keys():
print(icd_9_dict[guess])
else:
print('Invalid entry')
don't use input() which tries to interpret the value given by the user (and can pose some security problems). Prefer raw_input() which always return a string. Then you can compare strings instead of numbers.
A Python dictionary is also a nice structure for what you are trying to build.
You should cast it to float() instead of int(). After you convert to float, you can get the integer part with int().
s = "100.3"
f = float(s) # 100.3
i = int(f) # 100
To read a range of values, you can do something like this:
s = input("Enter some values separated by space: ")
a = [float(value) for value in s.split(" ")] # array of floats
If you want N values, you can use a loop:
for i in range(N):
s = input("Enter a value: ")
# do something with this value
Your question is not clear, please improve it if you want a better answer.
First of all, 844.2 is float, not int :)
For range of numbers - you mean like this?:
487.1 456.4 654.7
Than use split(' ') on your input. Use raw_input to always get whole line as a string, than you can do with it whatever you can do with strings.
edit as noted in other answers - if this codes has nothing to do with numbers (beside digits in them;] ) - leave them as strings.
I'm just going to put it out there that it's always better to ask for forgiveness than to ask permission. This is a python best practice, which may not be relevant to you as a beginning programmer, but it's good to get started on the right foot.
try just says "try to do the following stuff" and except says "if there was one of the following errors when you tried to do the above stuff, do this stuff instead". You can tell that KeyError is the right error to put here if you try to access your dictionary with an invalid key (try it yourself in the interactive interpreter, it will always list the exception) just like you were getting ValueError exceptions before:
good_numbers = {"487.1": "Influenza with respiratory manifestations",
"844.2": "Cruciate Ligament Tear of Knee",
"133.7": "Being awesome at code"}
while True:
try:
guess = input('Enter ICD-9 Code: ')
print(good_numbers[guess])
break
except KeyError:
print('Invalid entry')
continue
Oh and just to mention also that break says to quit looping out of the inner-most loop and continue says to go back to the beginning of aforementioned loop.
Enter ICD-9 Code: asd
Invalid entry
Enter ICD-9 Code: 487.1
Influenza with respiratory manifestations
>>>
Now just to point you in the right direction, you might be wanting to read input from a file; in this case, you're going to want to investigate the open command. To parse the input you can probably use split or something:
med_codes = open('IDC-9-2011.txt', 'r')
code_list = med_codes.read().split()
Then you can feed your codes into your dicitonary one at a time like:
for code in code_list:
try:
print (good_numbers[guess])
except KeyError:
print ( code, 'is an invalid IDC-9 code')
I think the main advantage here is that you know that you have some finite input, so you don't have to mess around with while loops and running counters or anything.
Oh yeah and remember to close your file when done!
med_codes.close()
Create a dictionary of results indexed by the values you're looking for like:
ICDCODES = { "487.1": "Influenza with respiratory manifestations",
"844.2": "Cruciate Ligament Tear of Knee" }
Then just compare and match:
print ICDCODES[input('Enter ICD-9 Code: ')]

Categories

Resources