SphereOJ Prime Generator submission error - python-3.x

I know there are some answers on website on this issue, but trust me none of them are helping. Some have not working code claiming to be working.
I keep getting this error at runtime, NZEC, maybe because of spaces and all or type of input it takes but I have tried everything. Please help me, it been 5 hrs + already on this problem. I am sharing my basic code, please visit the problem if necessary and suggest me something.
import sys
def isprime(n):
if n==1:
return False
if n==2:
return True
l=n//2
for i in range(2,l+1):
if(n%i==0):
return False
return True
t=int(input())
if t<=10:
for q in range(t):
m=int(input("Lower Number"))
n=int(input("Higher number"))
if (m>=1 and m<=1000000000 and n>m and n<=1000000000 and n-m<=100000):
for i in range(m,n+1):
if isprime(i):
print(i)
else:
quit()
I went and checked submitted answer on codechef, and they were accepting answers which don't even give correct output on my local machine. I don't understand this submission thing, help is much appreciated.

Related

Union-find algorithm not working for finding number of connected components(HackerEarth)

I tried implementing Union-find algorithm for finding number of connected components in a graph.
Problem link - https://www.hackerearth.com/problem/algorithm/connected-components-in-a-graph/
Problem code in python -
def cc(n,edges):
length=len(edges)
l=[-1]*(n+1)
rank=[0]*(n+1)
for i in range(length):
a=edges[i][0]
b=edges[i][1]
union(a,b,rank,l)
count=0
for i in range(1,n+1):
if l[i]==-1:
count+=1
print(count)
def union(a,b,rank,l):
fromp=find(a,l)
top=find(b,l)
if rank[fromp]>rank[top]:
l[top]=fromp
elif rank[top]>rank[fromp]:
l[fromp]=top
else:
l[fromp]=top
rank[top]+=1
def find(a,l):
if l[a]==-1:
return a
par=find(l[a],l)
l[a]=par
return par
n,e=map(int,input().split())
edges=[]
for _ in range(e):
edges.append(list(map(int,input().split())))
cc(n,edges)
The code is not working and giving wrong answers and even runtime error for one test case.Could anyone please help?

Name is not defined but earlier it worked, now it doesn't; Exact same code

Newbie at Python here and am practicing some questions online.
Somehow after working on another question, this code does not work anymore when it was the exact same code
def diff(a):
a = int(input("Give me a number: "))
if a > 17:
return (a-17)*2
else:
return
diff(a)

Defining function difficulties ["NameError: name 'number' is not defined"]

Okay, trying to make a simple game of Guessing Numbers but I can't find the mistake in this code. Still pretty new to python so probably the reason why but I can't figure out what is wrong with it.
import random
from time import sleep
def start():
print("Welcome To The Guessing Game \n Try to guess the number I'm thinking of \n Good luck!")
selectRandomNumber()
guessCheck(number, numberInput=1)
def restart():
print("Creating new number ...")
sleep(1)
print("OK")
selectRandomNumber()
guessCheck(number,numberInput=1)
def selectRandomNumber():
number = random.randint(0,1000)
tries = 0
return
def tryAgain():
while True:
try:
again = int(input("Do you want to play again? y/n:"))
except ValueError:
print("Couldn't understand what you tried to say")
continue
if again == "y" or "yes":
print("Awesome! Lets go")
restart()
elif again == 'n' or "no":
print("Goodbye!")
break
else:
print("Not a valid option")
continue
def guessCheck(number,numberInput=1):
while True:
try:
numberInput = int(input("What number do you think it is?: "))
except ValueError:
print("Couldn't understand that. Try again")
continue
if numberInput > number:
print("Too high")
tries += 1
continue
elif numberInput < number:
print("Too low")
tries += 1
continue
elif numberInput == number:
print("Congrats! You got my number")
tryAgain()
number = selectRandomNumber()
print(number)
start()
Every time I try to run the program I keep getting the same mistake.
It tells me:
Traceback (most recent call last):
File "python", line 60, in <module>
start()
File "python", line 8, in start
guessCheck(number, numberInput)
NameError: name 'number' is not defined
Don't quite understand what that means.
Some help would be appreciated. Thanks!
* UPDATE *
Was able to fix the part about defining the variable but now new problem happened where when I try to run
Same code as before but added
guessCheck(number,numberInput=1)
and also added the variable number at the end
number = selectRandomNumber()
print(number)
start()
when I run it I get this
None # this is from `print(number)` so instead of getting a number here I'm getting `None`
Welcome To The Guessing Game
Try to guess the number I'm thinking of
Good luck!
What number do you think it is?:
The Traceback is telling you this:
We got to start().
start() called guessCheck().
We tried to pass two pieces of information to guessCheck(): the variable names number and numberInput.
We don't have those variables defined yet! numberInput doesn't get defined until once we've already started guessCheck(), and number isn't actually defined anywhere.
As Manoj pointed out in the comments, you probably want number to hold the output of selectRandomNumber(). So, instead of just calling selectRandomNumber() in start(), try number = selectRandomNumber() instead.
You can add a print(number) on the line right after that to make sure number has a value assigned to it.
Now number has a value, going into your call to guessCheck(). That still leaves numberInput undefined though. You can set a default value for function arguments like this:
guessCheck(number, numberInput=1)
That way, when guessCheck is called but numberInput hasn't been defined yet, it will automatically give it the value 1 until you set it explicitly.
You may encounter other issues with your code the way it is. My advice would be to start really simply - build up your game from each individual piece, and only put the pieces together when you're sure you have each one working. That may seem slower, but trying to go too fast will cause misunderstandings like this one.

Yahtzee, need two arguments to an if, remove method

So I'm trying to make yahtzee-board, but I've come to an obstacle which shouldn't be that hard to solve, but I simply cant fix it. This is how my remove function is looking currently:
class Player:
def __init__(self,name):
self.name=name
self.lista={"aces":0,"twos":0,"threes":0,"fours":0,"fives":0,"sixs":0,"upperscore":0,"bonus":0,"pair":0,"twopair":0,"3ofakind":0,"4ofakind":0,"smallstraight":0,"largestraight":0,"fullhouse":0,"chance":0,"yahtzee":0,"lowerscore":0,"totalscore":0}
self.upperbracket={"aces":0,"twos":0,"threes":0,"fours":0,"fives":0,"sixs":0}
self.lowerbracket={"pair":0,"twopair":0,"3ofakind":0,"4ofakind":0,"smallstraight":0,"largestraight":0,"fullhouse":0,"chance":0,"yahtzee":0}
def remove(self,i):
b=input("Do you want to remove a moment?:")
if b=="yes":
c=input("Which moment do you want to remove?")
spelarlista[i].lista[c]=str("&")
self.printtable()
return True
if b=="no":
return False
def add(self):
rundor=0
while rundor!=15:
for i in range(len(spelarlista)):
count=0
print("Rolling dice for: ", str(spelarlista[i]))
self.rolldice()
if self.remove(i)==True:
i=i+1
count+=1
while count<=0:
moment=input("Where do you want to put your points,"+" "+ str(spelarlista[i])+"?:""\n" )
while moment not in self.lista:
print("oops! Try again!")
if spelarlista[i].lista[moment]!=0 or spelarlista[i].lista[moment]==str("&"):
print("Moment has either been removed or you already got points there")
else:
points=input("How many points did you get?: ")
What I want to do is that if I decide to remove an already removed "moment" it's supposed to print "no can do" or something like that, the same thing is if there is already points there.
currently the line of code is looking like this:
if spelarlista[i].lista[moment]!=0 or spelarlista[i].lista[moment]==str("&"):
Notice that this line is working prefectly if I've already added points, but if I try to remove an already removed "moment" it does not work as intended, I simply cant see where everything has gone wrong...
thanks in advance

Python Threading Issue, Is this Right?

I am attempting to make a few thousand dns queries. I have written my script to use python-adns. I have attempted to add threading and queue's to ensure the script runs optimally and efficiently.
However, I can only achieve mediocre results. The responses are choppy/intermittent. They start and stop, and most times pause for 10 to 20 seconds.
tlock = threading.Lock()#printing to screen
def async_dns(i):
s = adns.init()
for i in names:
tlock.acquire()
q.put(s.synchronous(i, adns.rr.NS)[0])
response = q.get()
q.task_done()
if response == 0:
dot_net.append("Y")
print(i + ", is Y")
elif response == 300:
dot_net.append("N")
print(i + ", is N")
tlock.release()
q = queue.Queue()
threads = []
for i in range(100):
t = threading.Thread(target=async_dns, args=(i,))
threads.append(t)
t.start()
print(threads)
I have spent countless hours on this. I would appreciate some input from expedienced pythonista's . Is this a networking issue ? Can this bottleneck/intermittent responses be solved by switching servers ?
Thanks.
Without answers to the questions, I asked in comments above, I'm not sure how well I can diagnose the issue you're seeing, but here are some thoughts:
It looks like each thread is processing all names instead of just a portion of them.
Your Queue seems to be doing nothing at all.
Your lock seems to guarantee that you actually only do one query at a time (defeating the purpose of having multiple threads).
Rather than trying to fix up this code, might I suggest using multiprocessing.pool.ThreadPool instead? Below is a full working example. (You could use adns instead of socket if you want... I just couldn't easily get it installed and so stuck with the built-in socket.)
In my testing, I also sometimes see pauses; my assumption is that I'm getting throttled somewhere.
import itertools
from multiprocessing.pool import ThreadPool
import socket
import string
def is_available(host):
print('Testing {}'.format(host))
try:
socket.gethostbyname(host)
return False
except socket.gaierror:
return True
# Test the first 1000 three-letter .com hosts
hosts = [''.join(tla) + '.com' for tla in itertools.permutations(string.ascii_lowercase, 3)][:1000]
with ThreadPool(100) as p:
results = p.map(is_available, hosts)
for host, available in zip(hosts, results):
print('{} is {}'.format(host, 'available' if available else 'not available'))

Resources