import math
import time
import sys
import random
import os
def isPrime(number):
if number % 2 != 0:
for i in range (3,math.floor(number**0.5)+1,2):
if number % i == 0:
return False
else:
if number != 2:
return False
return True
def makeListInts(lst):
for item in range(len(lst)):
try:
lst[item] = int(lst[item])
except:
try:
lst[item] = float(lst[item])
except:
pass
return lst
def getData():
with open('CurrentProgress.txt') as data:
return makeListInts([line[:-1].split(': ')[1] for line in data.readlines()])
def setData(data, ID):
titles = [
'Start: ' + str(data[1] + 1),
'End: ' + str(data[1] + data[2]),
'Step: ' + str(data[2]),
'Time: ' + str(time.time()),
'IDsRegistered: ' + ID]
with open('CurrentProgress.txt','w') as data:
for item in titles:
data.write(str(item)+'\n')
def checkFileProgress(data):
files = os.listdir('Calculated Primes/') #List all primes files
filesStripped = [int(i.split('-')[1][:-4]) for i in files] #Get the end numbers of each file
filesStripped.sort() # and sort
diffs = [filesStripped[i+1] - filesStripped[i] for i in range(len(filesStripped)-1)]
lastFileEnd = filesStripped[-1]
#print (diffs, sum(diffs) / len(diffs))
if max(diffs) != sum(diffs) / len(diffs): #If there is one that should not be there (max != avg)
indx = diffs.index(max(diffs))
print (indx)
data = [filesStripped[indx-1] + 1, filesStripped[indx-1] + data[2], data[2], data[3],data[4]] #Go back to there
setData(data,data[-1])
elif lastFileEnd + 1 != data[0]: # Otherwise, if the last file is before the recoreded end , go back there
data = [lastFileEnd - data[2] + 1, lastFileEnd, data[2], data[3], data[4]]
setData(data, data[-1])
def setMyID(currentIDs):
possibleIDs = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']
if currentIDs == ' ':
return possibleIDs[0]
else:
try:
return possibleIDs[possibleIDs.index(currentIDs[-1]) + 1]
except IndexError:
return False
def removeMyID(data,ID):
ID = data[-1].replace(ID,'')
setData(data, ID)
print ()
def writePrimes(listOfPrimes, data):
direc = 'Calculated Primes/'
with open(direc + 'Primes' + str(data[0]) + '-' + str(data[1]) + '.txt','w') as primes:
for prime in listOfPrimes:
primes.write(str(prime) + '\n')
def checkTime(dataTime):
if dataTime + 1 > time.time():
sleepTime = round(random.random()+1,3) #01179107383 James
print ('Sleeping for ' + str(sleepTime) + ' to avoid collisions')
time.sleep(sleepTime);
return False
else:
return True
def makeBar(barWidth,data):
print ('Calculating primes between ' + str(data[0]) + ' and ' + str(data[1]) + ':')
sys.stdout.write("[%s]" % (" " * barWidth))
sys.stdout.flush()
sys.stdout.write("\b" * (barWidth+1)) # return to start of line, after '['
def updateBar():
sys.stdout.write("==")
sys.stdout.flush()
def closeBar():
sys.stdout.write("\n")
def main(ID):
data = getData()
if checkTime(data[3]):
barWidth = 40
if ID in data[-1]:
ID = data[-1]
else:
ID = data[-1] + ID
setData(data,ID)
makeBar(barWidth, data)
listOfPrimes = []
for number in range(data[0],data[1]):
result = isPrime(number)
if (number - 1) % round(data[2] / (barWidth / 2)) == 0:
updateBar()
if result:
listOfPrimes += [number]
writePrimes(listOfPrimes, data)
closeBar()
else:
main(ID)
def setup():
data = getData()
if data[-1] == ' ':
checkFileProgress(data)
if checkTime(data[3]):
ID = setMyID(data[-1])
print (ID)
if ID:
try:
while True:
main(ID)
except KeyboardInterrupt:
data = getData()
removeMyID(data,ID)
quit('Saving and Exiting')
else:
quit('Already 12 programs running')
else:
setup()
setup()
Here is the file it accesses (CurrentProgress.txt
):
Start: 381000001
End: 382000000
Step: 1000000
Time: 1468445801.017807
IDsRegistered:
The last line of the file has 2 trailing spaces.
It has an ID function, allowing any ID from A-L. A script is prevented from running if there are already 12. Each script waits for a random time to prevent collisions with others (which is unlikley anyway). When the script is terminated, the ID is removed. Because the file is updated before calculations are finished, when the first script is run it sets the file back to the next block (by checking the file). This only happens for the first script (i.e. that which takes ID A
). Equally, it checks if a block has been skipped (in case the scripts are terminated in the wrong order) and jumps back to there.
I realise this code is quite long (150 lines) so if you feel like picking a function to review it would still help me learn!