how to remove the runtime (NZEC) error in my python code? - python

I am trying to solve the prime generator problem PRIME1 in spoj.com but getting runtime error(NZEC). The problem needs to take a number of test cases and for each test case, it needs to input two numbers in a line for each different test case and then finally print the output as the prime numbers in the range of each number
The error is Runtime error time: 0.01 memory: 7736 signal:-1
# your code goes here
def is_prime(x):
if x<2:
return False
if x==2:
return True
for y in range(2,x):
if x%y==0:
return False
return True
t=int(raw_input())
mylist=[]
for i in range(0,t):
a=raw_input()
a=a.split(' ')
mylist.append(int(a[0]))
mylist.append(int(a[1]))
k=0
while k<len(mylist):
c=mylist[k]
k+=1
d=mylist[k]
k+=1
for z in range(c,d+1):
if is_prime(z):
print z
print

On running this on python 2.7.9, I found that there is only one error that you are using t in range(0, t) but t is string here, because our raw_input() method reads input and returns string. That raises in Python parlance. To remove this we should have to type cast the input we got. Like, t = int(raw_input()).
And this will result in t as an integer.
For info about raw_input() follow: https://docs.python.org/2/library/functions.html#raw_input
For reading integer in python you can follow this post on stackoverflow.

Your issue is raw_input() returns string , not integer. But you are trying to use it directly in your range() function - for i in range(0,t) . range() function only accepts integers as arguments, so you need to convert your input into int before using in range.
t=int(raw_input())

Related

Validating given input and printing every prime number =< given input. (Python)

So I have read tons of solutions to this type of questions, but they all seem to be way too complicated, or I can't find any useful solutions in them.
I have written the first part where I have to ask for an input and validate it to be an integer, but I can't figure out how to write the code for the second part. Efficiency isn't a necessity here, but I think it's better if I learn the most efficient way from the get go. From what I read, using the radicle of the input and checking the divisors is the way to go here, but as I said, I can't figure out how to actually write the code and integrate it into what I already have.
while True:
x = str(input("Please enter an integer: "))
try:
x = int(x)
except ValueError:
print("Please enter a valid integer: ")
continue
break
Any help is greatly appreciated!
It is better to edit multi-line code into your question, rather than post a comment, because then you are not limited to a single line.
Your code appears to be:
def is_prime2(n):
if n == 2 or n == 3:
return True
#endif
if n % 2 == 0 or n < 2:
return False
#endif
for i in range(3, int(n**0.5)+1, 2):
if n % i == 0:
return False
#endif
#endfor
return True
#enddef
print(n)
I have added comments to indicate where I think that various statements end. I may have mistaken the indentation converting from a single line.
Apart from that print(n), which is either not part of the function definition or comes after a return, this appears to work correctly. It will be too slow for very large values of n though it will be fine for smaller values and for testing. For very large values have a look at the Sieve of Eratosthenes.
Write an isPrime(n) function that returns true if n is prime, false otherwise. Then test all the numbers from 2 up to the entered integer to see if they are prime.
We will help you to improve your code, but you have to write it first.

Calculating a factorial using loops in Python3

I am currently studying Software Development as a beginner and I have a task in my programming class to calculate and display a factorial using a loop. I've been given the pseudo-code and have to translate it into true code and test it in the REPL to make sure it returns the expected results.
I almost have it but I've run into two issues that I just can't seem to resolve.
1) The function is returning an extra line of "None" after the calculation and
2) The answer is displaying over multiple lines when I want it to display on a single line.
My current code (which does return the correct answer) is as follows:
def calcFactorial(number):
factorial = 1
print(str(number)+"! =", number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*number-count
print("x", str(number-count))
factorial = factorial*number
print("=", factorial)
When I test, using 3 for example, the REPL returns the following:
>>> print(calcFactorial(3))
3! = 3
x 2
x 1
= 12
None
So I have the correct answer but with an extra line of "None" which I would like to remove (I believe it has something to do with the print function?) and I don't know how to format it correctly.
Any help would be much appreciated.
your function calcFactorial(3) prints already, so you shouldn't call it with
print(calcFactorial(3))
just call it with
calcFactorial(3)
without the print function.
you might think about calling the function calc_and_print_factorial() in order to make it clear, that this function does already the printing
Regarding your second question:
Blockquote
2) The answer is displaying over multiple lines when I want it to display on a single line.
You can fix it by using a single print statement:
def calcFactorial(number):
factorial = 1
string = str(number) + "! = " + str(number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*(number-count)
string = string + " x " + str(number-count)
factorial = factorial * number
print(string + " = " + str(factorial))
This will give you:
IN: calcFactorial(3)
OUT: 3! = 3 x 2 x 1 = 6
On a side note: you might want to think of how to implement this recursively. Maybe that comes later in your class but this would be one of the first go-to examples for it.
Adding to the blhsing's answer, you should choose between these built-in ways to print the "returned" value.
First way:
def calcFactorial(number):
... # <- Your function content
return factorial
Then, call your function with a print() to get the explicitly returned value, as you can see in the return factorial line. See this reference for more details:
print(calcFactorial(3))
Second way:
Having the same function definition with its return statement, just call the function with its instance statement:
calcFactorial(8)
By default, python will print the returned value without a print()
Third way:
Just call the function (without the explicit return statement, this will return a "None" (null-like) value by default), using the print() method. Do NOT use print() inside another print().
Your calcFactorial function does not explicitly return a value, so it would return None by default, so print(calcFactorial(3)) would always print None.
You should make the calcFactorial function return factorial as a result at the end:
def calcFactorial(number):
factorial = 1
print(str(number)+"! =", number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*number-count
print("x", str(number-count))
factorial = factorial*number
print("=", factorial)
return factorial
So I have the correct answer but with an extra line of "None" which I would like to remove
You are printing the return value from your function. In this case, you haven't specified a return value with a return statement so the function automatically returns None.
To fix the problem, you should return a value from your function. Note that you don't need to call print() for final answer because the REPL already does this for you.
Note that the REPL will automatically print the return value for you, so you can just type calcFactorial(3) instead of print(calcFactorial(3)).
Additionally, you are not getting the correct answer. You should get 6 instead of 12. It looks like you are trying to count down from number and multiplying each number together. You can get the same result by counting up from 1. This will lead to much simpler code and avoid the error.
If you want to understand why your code isn't doing the correct thing, look closely at factorial = factorial*number-count and think about the order of operations that are used to calculate the result here.

Program to find permutation of a string - Error

Python Program
x=input("Enter any string:")
Taking input from user
z=len(x)*len(x)
y=len(x)-1
l,m=0,0
function to swap the values
def swap(s1,s2):
g=s1
s1=s2
s2=g
print(s1,s2)
return s1,s2
after swapping values to be printed in this for loop
for i in range(0,z,1):
s=x
swap(s[l],s[m+1])
print(s)
m=m+1
if m==y:
l=l+1
m=0
Code is not working properly but ending with the error IndexError: string index out of range
It might be the lack of brackets, for example, it might have to be:
if (m == y):

Python Code Error

What's wrong with this program in Python?
I need to take an integer input(N) - accordingly, I need to create an array of (N)integers, taking integers also as input. Finally, I need to print the sum of all the integers in the array.
The input is in this format:
5
4 6 8 18 96
This is the code I wrote :
N = int(input().split())
i=0
s = 0
V=[]
if N<=100 :
for i in range (0,N):
x = int(input().split())
V.append(x)
i+=1
s+=x
print (s)
Its showing the following error.
Traceback (most recent call last):
File "main.py", line 1, in <module>
N = int(input().split())
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
split() returns a list which you are trying to convert to an integer.
You probably wanted to convert everything in the list to an integer:
N = [int(i) for i in input().split()]
You can also use map:
N = list(map(int, input().split()))
You could use sys module to take the input when calling the program and a lambda function to convert the string items in list to integers. You could also make use of the built-in sum function. Something like that:
#!/usr/bin/env python
import sys
s = sum(i for i in map(lambda x: int(x), sys.argv[1].split(',')))
print s
Example:
python test.py 1,2,3,4
The output should be 10.
Modifying your code:
Now, if you want to modify your code to do what it intends to do, you could modify your code like that:
#!/usr/bin/env python
N = input()
s = 0
V=[]
if N<=100 :
for i in range (0,N):
x = input()
V.append(x)
s+=x
print (s)
Note 1: In python when you use range you don't have to manually increase the counter in the loop, it happens by default.
Note 2: the 'input()' function will maintain the type of the variable you will enter, so if you enter an integer you don't have to convert it to integer. (Have in mind that input() is not recommended to use as it can be dangerous in more complicated projects).
Note 3: You don't need to use '.split()' for your input.
You code fails because str.split() returns a list.
From the Python documentation
Return a list of the words in the string, using sep as the delimiter
string
If your input is a series of numbers as strings:
1 2 3 4
You'll want to iterate over the list returned by input.split() to do something with each integer.
in = input()
for num in in.split():
x.append(int(num))
The result of this will be:
x = [1,2,3,4]

Getting MemoryError in Python

I am running following code on python to print nos. in the range specified for even floating nos.:
def float_range(begin,end,step):
i=begin-step
numbers=[]
while i!=end:
i=i+step
numbers.append(i)
return numbers #returning the list
a=2
b=4
c=.1
for j in float_range(a,b,c): #calling function
print j
and it gives following error
Traceback (most recent call last):
File "C:\Users\b53659\Desktop\My python\float_range.py", line 13, in <module>
for j in float_range(a,b,c):
File "C:\Users\b53659\Desktop\My python\float_range.py", line 7, in float_range
numbers.append(i)
MemoryError.
but in above code if i replace
a=1
b=1000
c=1
it gives correct output i.e. prints no. from 1 to 1000.
why is it happening? thanks in advance
The problem is that you're using c=.1, which makes the counter floating point. When the loop gets to the 'end' (in float_range), i will be something like 4.00000000001 or 3.9999999999998, and so it doesn't compare equal to the integer 4.
There are a few possible solutions:
Only use integers (whole numbers, not 0.1)
Use python's fixed-point numbers (the decimal.Decimal class)
Make the loop end condition i < end instead of i!=end
You should do something like this
def float_range(begin,end,step):
i = begin-step
numbers = []
while i < end:
i += step
numbers.append(i)
return numbers #returning the list
for j in float_range(2,4,0.1): #calling function
print round(j, 2)
This way you'll be sure that the loop stops when it's above end even if the float doesn't hit the exact integer value.
I also made two other changes apart from while i < end:. You can use += instead of i = i+step. I've also rounded the floats down, since it'll print something like 3.9000000000000017 if you don't.
I hope this helps.
main flaw in code is while condition !=.
You are checking if i!=end. Here step is 0.1, which is actually something like 0.100000000000001. So when you reach to last iteration(as per your logic)
i = 3.9 + step = 4.000000001
and you have end= 4.0
and i!=end
So your while loops condition i!=end is True always and loop continues forever and throw memory error
I have debugged you code And found the actual values in the list. You can see from the screen shot then 4.0 value never generated instead 4.0000001 get generated
This code would work as you expected:
def float_range(begin,end,step):
i=begin-step
numbers=[]
while i < end:
i=i+step
numbers.append(i)
return numbers #returning the list

Categories

Resources