Python Multiprocessing module did not work properly - python-3.x

I'm writing right now on a code which counts all Primenumbers up to the highest integer. The problem is that it would take way too long (about 35 days). So the solution was in our opinion the multiprocessing module, to count all Primenumbers in 4 seperated threads (process 1: starts with 1 steps +8, process 2: starts with 3 steps +8, process 3: starts with 5 steps +8, process 4: starts with 7 steps +8). That would test every odd number if it is a Primenumber.
But the following code don't work and we cant find the Problem.
Maybe one of you can help me?
from multiprocessing import Process
import time
import math
timeStart = 0
timeEnd = 0
def istTeilbar (x, y):
if x%y == 0:
return True
return False
def istPrimzahl (x):
for i in range(2, int(math.sqrt(x))+1):
if istTeilbar(x, i):
return False
return True
def schreibePrimzahlBis1 (x):
counter1 = 0
print ("x")
for i in range(1, x, 8):
if istPrimzahl(i):
counter1 = counter1 +1
print (f'Das waren {counter1} Primzahlen\n')
def schreibePrimzahlBis2 (x):
counter2 = 0
for i in range(3, x, 8):
if istPrimzahl(i):
counter2 = counter2 +1
print (f'Das waren {counter2} Primzahlen\n')
def schreibePrimzahlBis3 (x):
counter3 = 0
for i in range(5, x, 8):
if istPrimzahl(i):
counter3 = counter3 +1
print (f'Das waren {counter3} Primzahlen\n')
def schreibePrimzahlBis4 (x):
counter4 = 0
print ('counter4')
for i in range(7, x, 8):
if istPrimzahl(i):
counter4 = counter4 +1
print (f'Das waren {counter4} Primzahlen\n')
grenze = input("Die letzte zu testende Zahl:\n")
timeStart = time.time()
p1 = Process(target=schreibePrimzahlBis1, args=[int(grenze)])
p2 = Process(target=schreibePrimzahlBis2, args=[int(grenze)])
p3 = Process(target=schreibePrimzahlBis3, args=[int(grenze)])
p4 = Process(target=schreibePrimzahlBis4, args=[int(grenze)])
p1.start()
p2.start()
p3.start()
p4.start()
p1.join()
p2.join()
p3.join()
p4.join()
timeEnd = time.time()
print (f'Das hat ca. {timeEnd-timeStart} sekunden gedauert.')
The original code which would take way to long if you are intersted in:
import time
import math
timeStart = 0
timeEnd = 0
def istTeilbar (x, y):
if x%y == 0:
return True
return False
def istPrimzahl (x):
for i in range(2, int(math.sqrt(x))+1):
if istTeilbar(x, i):
return False
return True
def schreibePrimzahlBis (x):
counter = 0
for i in range(2, x):
if istPrimzahl(i):
if counter == 10000:
print (10000)
elif counter == 100000:
print (100000)
elif counter == 1000000:
print (1000000)
elif counter == 10000000:
print (10000000)
elif counter == 100000000:
print (100000000)
counter = counter +1
print ('Das waren')
print (counter)
print ('Primzahlen.\n')
grenze = input("Die letzte zu testende Zahl:\n")
timeStart = time.time()
schreibePrimzahlBis(int(grenze))
timeEnd = time.time()
print ('Das hat ca.')
print (timeEnd-timeStart)
print ('sekunden gedauert')
´´´

One way to parallelize tasks is to use concurrent.futures. I personally like this solution. Maybe you want to try this :
import concurrent.futures
function_A(arg1, arg2):
...
return val_A
function_B(arg1, arg2, arg3):
...
return val_B
if __name__ == '__main__':
arg1, arg2, arg3 = ...
with concurrent.futures.ThreadPoolExecutor() as executor:
future_A = executor.submit(function_A, arg1, arg2)
future_B = executor.submit(function_B, arg1, arg2, arg3)
print(future_A.result())
print(future_B.result())

Related

How to find the shortest path

In the function of find_shortest_func, i think if now position isn't "T" which is also known as the terminal or exit, then i will try to find for direction and see if it is "T", if not, check if it is space and i can go there. Besides, tell the next state function now output and dic to tell the place where i visited. But some errors occur and I don't know why.
I think the problem may occur where I tried to deepcopy the output list
import copy
def set_symbol(symbol_name):
def set_symbol_decorator(func):
def wrapper(self, symbol):
setattr(self, symbol_name, symbol)
return wrapper
return set_symbol_decorator
class Maze:
space_symbol = " "
obstacle_symbol = "X"
path_symbol = "•"
output = []
dis = 0
def __init__(self, input_string):
self.maze = []
if input_string.endswith("txt"):
with open(input_string) as f:
count = 0
for line in f.readlines():
self.maze.append([])
for j in line:
if j != '\n':
self.maze[count].append(j)
count += 1
else:
count = 0
for i in input_string.split("\n"):
self.maze.append([])
for j in i:
self.maze[count].append(j)
count += 1
def __str__(self):
output_string = ""
for i in range(20):
for j in range(20):
output_string += self.maze[i][j]
output_string += "\n"
return output_string
#set_symbol("space_symbol")
def set_space_symbol(self, change):
pass
#set_symbol("obstacle_symbol")
def set_obstacle_symbol(self, change):
pass
#set_symbol("path_symbol")
def set_path_symbol(self, change):
pass
def find_shortest_func(self, position: tuple, d: dict, out: list, dis: int):
dic = copy.deepcopy(d)
output = copy.deepcopy(out)
dic[(position[0], position[1])] = 1
output.append((position[0], (position[1])))
dis += 1
if self.maze[position[0]][position[1]] != "T":
if position[0]+1 < 20 and self.maze[position[0]+1][position[1]] == self.space_symbol and (position[0]+1, position[1]) not in dic:
self.find_shortest_func(
(position[0]+1, position[1]), dic, output, dis)
if position[1]+1 < 20 and self.maze[position[0]][position[1]+1] == self.space_symbol and (position[0], position[1]+1) not in dic:
self.find_shortest_func(
(position[0], position[1]+1), dic, output, dis)
if position[0]-1 >= 0 and self.maze[position[0]-1][position[1]] == self.space_symbol and (position[0]-1, position[1]) not in dic:
self.find_shortest_func(
(position[0]-1, position[1]), dic, output, dis)
if position[1]-1 >= 0 and self.maze[position[0]][position[1]-1] == self.space_symbol and (position[0], position[1]-1) not in dic:
self.find_shortest_func(
(position[0], position[1]-1), dic, output, dis)
if self.maze[position[0]][position[1]] == "T":
if dis < self.dis:
self.output = copy.deepcopy(output)
self.dis = dis
return
def find_shortest_path(self):
d = dict()
output = []
dis = -1
self.find_shortest_func((1, 0), d, output, dis)
return self.output, self.dis

how to create an impossible sudoku detector?

I'm making a sudoku solver on pygame, using backtracking. It's working, both the backtracking and the gui, however, when the user tries to solve an impossible puzzle, the game freezes.
I want to make a modification to my algorithm that, when the puzzle is impossible, the algorithm detects it, warning the user and reseting the board.
For now, this is the main code for the board class.
class Board:
solvedBoard = [[0 for i in range(9)] for j in range(9)]
gameRunning = True
def __init__(self):
self.tabuleiro = [[0 for i in range(9)] for j in range(9)]
def reset(self):
self.tabuleiro = [[0 for i in range(9)] for j in range(9)]
self.gameRunning = True
def show(self):
for i in self.tabuleiro:
for j in i:
print(j, end = ' ')
print('')
def setCell(self, linha, coluna, valor):
self.tabuleiro[linha][coluna] = valor
def isFull(self):
for i in range(9):
for j in range(9):
if self.tabuleiro[i][j] == 0:
return False
return True
def numberPossibilities(self, linha, coluna):
possible = [1 for i in range(10)]
#horizontal check
for col in range(9):
if self.tabuleiro[linha][col]:
possible[self.tabuleiro[linha][col]] = 0
#vertical check
for line in range(9):
if self.tabuleiro[line][coluna]:
possible[self.tabuleiro[line][coluna]] = 0
#mini square check
linhaSquare = (linha // 3) * 3
colunaSquare = (coluna // 3) * 3
for l in range(linhaSquare, linhaSquare + 3):
for c in range(colunaSquare, colunaSquare + 3):
if self.tabuleiro[l][c]:
possible[self.tabuleiro[l][c]] = 0
toTry = []
for k in range(1, 10):
if possible[k]:
toTry.append(k)
return toTry
def solve(self):
self.show()
print('')
if self.isFull():
for i in range(9):
for j in range(9):
self.solvedBoard[i][j] = self.tabuleiro[i][j]
self.gameRunning = False
self.tabuleiro = self.solvedBoard
elif self.gameRunning:
found = False
linha = 0
coluna = 0
for i in range(9):
for j in range(9):
if (not self.tabuleiro[i][j]):
linha = i
coluna = j
found = True
break
if found:
break
numbers = self.numberPossibilities(linha, coluna)
print(*numbers)
print('')
tamanho = len(numbers)
for k in range(tamanho):
if (not self.gameRunning):
self.tabuleiro = self.solvedBoard
break
self.tabuleiro[linha][coluna] = numbers[k]
self.solve()
if (self.gameRunning):
self.tabuleiro[linha][coluna] = 0
Note that the "show" function is only for debugging. I have an actual drawGrid function for handling the GUI.
My idea is to detect the first cell that needs to be changed, and, when the backtracking eventually comes back to It, with no other options to continue, It resets the board and then turns on a flag called "Impossible". Next iteration, the board detects that "Impossible" is on and resets the board, besides breaking the recursion.
However, that's seems too complicated, and I'm not sure how to do It without damaging code readability
What do you think? And also, Thanks in advance! This community is helping me a lot of this project :)

How can I get tuple values (from a class) in my main function?

I am using multiprocesssing in Python 3.5.
#Multiprocessing
def main():
p1 = multiprocessing.Process(name="p1", target=datac)
p2 = multiprocessing.Process(name="p2", target=test)
p2.start()
p1.start()
if __name__ == "__main__":
main()
There are two processes=>
1.test
2.datac
Test:
def test():
#a=0
while 1:
#if 'gaze_point' in gaze_data_callback(gaze_data):
# data = gaze_data_callback['gaze_point']
# if s == 0:
# x = data[0] * 1920
# y = data[1] * 1080
# return [x, y]
#a+=1
for x in range(0, 10):
print("We're on time %d" % (x))
print('Waiting..')
#time.sleep(5)
Datac:
def datac():
while 1:
tmp = eye.__new__(eye)
tmp.__init__()
print(tmp)
This is the class:
class eye(object):
def gaze_data_callback(gaze_data):
left_3d = gaze_data['left_gaze_point_in_user_coordinate_system']
right_3d = gaze_data['right_gaze_point_in_user_coordinate_system']
#Get the gaze point of both eyes
gaze_point = ((left_3d), (right_3d))
gaze_point = tuple(mean(gaze_point, axis=0))
print("3d gaze:",gaze_point)
my_eyetracker.subscribe_to(tr.EYETRACKER_GAZE_DATA, gaze_data_callback, as_dictionary=True)
time.sleep(5)
my_eyetracker.unsubscribe_from(tr.EYETRACKER_GAZE_DATA, gaze_data_callback)
return (gaze_point)
I want to print the gaze point but it is not being printed. I am getting the object location

Kruskal algorithm in python

import heapq
from collections import defaultdict
a = list(map(int, input().split()))
nodes = a[0]
disjoint_set = [-1]*(nodes+1)
rank_set = [0]*(nodes+1)
edges = a[1]
heap = []
def get_parent(u):
if disjoint_set[u] == -1:
return u
return get_parent(disjoint_set[u])
def make_union(x, y):
x_parent = get_parent(x)
y_parent = get_parent(y)
if rank_set[x_parent] == rank_set[y_parent]:
disjoint_set[x_parent] = y_parent
rank_set[x_parent] +=1
elif rank_set[x_parent] > rank_set[y_parent]:
disjoint_set[x_parent] = y_parent
else:
disjoint_set[y_parent] = x_parent
def not_cycle(*item):
x_parent = get_parent(item[1])
y_parent = get_parent(item[2])
if x_parent == y_parent:
return False;
make_union(x_parent, y_parent)
return True
while(edges!=0):
edge = list(map(int, input().split()))
heapq.heappush(heap, [edge[2], edge[0], edge[1]])
edges-=1
cnt = 0
total = 0
while(cnt!=nodes-1):
item = heapq.heappop(heap)
if(not_cycle(*item) is True):
total+= item[0]
cnt+=1
print(total)
I implemented the kruskal algorthm in python. I am getting RecursionError:maximum recursion depth exceeded in comparison error. make_union and get_parent are method of disjoint set algorithm. I am getting the error in get_parent method. How to solve this?
In not_cycle you are passing the parents to make_union but then in make_union you are trying to get the parents again. After the first change the parents will no longer be -1 and you will recurse "forever"[1]
[1] "forever" in this case is until the maximum depth of your stack.
-
aa,bb=list(map(int,input().split()))
c=[] for i in range(bb):
z=list(map(int,input().split()))
c.append(z) c.sort(key=lambda x: x[2])
a=[]
b=[]
for i in c:
a.append((i[0]-1,i[1]-1))
b.append(i[2])
arr=[]
size=[]
for i in range(len(b)):
arr.append(i)
size.append(1)
def root(i):
while arr[i]!=i:
i=arr[i]
return i
def unions(arr,size,p,q):
root_a=root(p)
root_b=root(q)
if size[root_a]>size[root_b]:
arr[root_b]=arr[root_a]
size[root_a]+=size[root_b]
else:
arr[root_a]=arr[root_b]
size[root_b]+=size[root_a]
def kruskals(b,a,aa):
te=[]
i=0
while (len(te))<aa-1:
(p,q)=a[i]
if root(p)!=root(q):
te.append(b[i])
unions(arr,size,p,q)
i+=1
return sum(te)
print(kruskals(b,a,aa))

Missing 1 required positional argument board game

I am trying to create the GUI code for my connect four boardgame but error's keep on coming up that I don't know how to correct. Can anyone help? The error:
TypeError: init() missing 1 required positional argument: 'buttns_list'
Code:
def __init__(self):
self.mw = tkinter.Tk()
self.mw.title = ("Connect Four")
self.rows = 6
self.cols = 7
self.buttons_2d_list = []
for i in range (self.rows):
self.rows = ['']*self.cols
self.buttons_2d_list.append(self.rows)
self.gboard = ConnectFourBoard()
p1 = HumanPlayer("X")
p2 = ComputerPlayer("O", self.buttns_list)
self.players_1st = (p1, p2)
self.currnt_player_index = 0
self.winner = False
def clicked_btn(self, x, y):
p = self.players_1st[self.currnt_player_index]
button = self.buttons_2d_list[x][y]
if button["text"] == "":
button["text"] = p.get_player_symbol()
self.gboard.MakeMove(x, y, p.get_player_symbol())
winner = self.gboard.CheckForWin()
is_full = self.gboard.FullBoard()
if winner == True:
win_message = ("Player %s is the winner!" %p.get_player_symbol())
messagebox.showinfo("Winner Info", win_messge)
self.mw.destroy()
exit()
elif is_full == True:
messagebox.showinfo("Winner Info", "The game is a draw")
self.mw.destroy()
exit()
else:
pass
if self.currnt_player_index == 1:
self.currnt_player_index = 0
else:
self.currnt_player_index += 1
p = self.players_1st[self.currnt_player_index]
p.play()
import random
class ComputerPlayer(Player):
def __init__(self, letter, buttns_list):
Player.__init__(self, letter)
self.buttons_2d_list = buttns_list
def play(self):
pass
It's not clear to me from the rest of the code exactly what you should be passing here, but your init calls for a letter, which you do have, and a buttns_list, which you don't:
def __init__(self, letter, buttns_list):
So the error comes from this line:
p2 = ComputerPlayer("O")
Either:
1) Pass in a buttns_list if your ComputerPlayer class needs it
p2 = ComputerPlayer("O", self.buttons_2d_list)` # in GameGUI init
2) Get rid of it if this was added by mistake:
class ComputerPlayer(Player):
def __init__(self, letter):
Player.__init__(self, letter)

Resources