import threading
# The number to add.
# Change this for your experiment
n = 1000000
# Result variable
result = 0
def thread1(count):
global result
x = 0
for i in range(1, count + 1):
x = x + i
result = x
def thread2():
global result
result = result * 3
th1 = threading.Thread(target = thread1, args=[n, ])
th2 = threading.Thread(target = thread2)
th1.start()
th2.start()
correct = n * (n + 1) / 2 * 3
print("Correct result is %d." % correct)
print("Final result is %d." % result)
if result == correct:
print("CORRECT!")
else:
print("WRONG!")
When running the code with n = 10, we will get correct result. But when running the code with n= 1000000, we would get incorrect results. May I know what's wrong with n= 1000000 that leads to incorrect execution?
Related
I have a function that factor a number. It depends on some random condition.
So what I am trying to do it's to run multiple processors in this function and the processor that finds the factor first returns the value and all processors terminate.
What I have so far is very wrong. The processors are not terminating and I also don't know how to get the value that was returned by the function
flag = False
def rho(n, processor):
while True:
x = random.randrange(1, n-1)
x2 = x
gcd = 1
c = random.randrange(1, n-1)
while gcd == 1:
x = (x**2 + c) % n
x2 = (x2**2 + c) % n
x2 = (x2**2 + c) % n
gcd = math.gcd(abs(x - x2), n)
if gcd != n:
flag = True
print("Factor was found from "+process+" and is ", gcd)
return gcd
if __name__ == "__main__":
p1 = multiprocessing.Process(target=rho, args=(91, "process 1" ))
p2 = multiprocessing.Process(target=rho, args=(91, "process 2"))
p1.start()
p2.start()
if flag:
p1.terminate()
p2.terminate()
The output is:
Factor was found from process 2 and is 13
Factor was found from process 1 and is 7
You can use multiprocessing.Pool and it's methods map(), imap_unordered() etc. These will return also values from worker functions.
Example (I used time.sleep() to simulate some time-intesive computation):
from time import sleep
from multiprocessing import Pool
def rho(params):
n, processor = params
# your computation here
# ...
sleep(n)
print("Factor was found from " + processor + " and is 42")
return 42
if __name__ == "__main__":
with Pool() as pool:
for result in pool.imap_unordered(
rho, ((10, "process 1"), (1, "process 2"))
):
print("Result I got:", result)
break # <-- I don't want other results, so break
Prints:
Factor was found from process 2 and is 42
Result I got: 42
EDIT: Two different functions:
from time import sleep
from multiprocessing import Pool
def fn1(n, p):
sleep(n)
print("Factor was found from " + p + " and is 42")
return 42
def fn2(n, p):
sleep(n)
print("Factor was found from " + p + " and is 99")
return 99
def rho(params):
what_to_call, n, processor = params
return what_to_call(n, processor)
if __name__ == "__main__":
with Pool() as pool:
for result in pool.imap_unordered(
rho, ((fn1, 10, "process 1"), (fn2, 1, "process 2"))
):
print("Result I got:", result)
break # <-- I don't want other results, so break
I got my code to work but now I need to divide it into functions input(), processing() and output().
lista=[]
lista = [int(clan) for clan in input("Unesi članove niza : ").split(',')]
lista.reverse()
rezultat=[]
c=0
for i in lista:
if i < 0:
i = i * -1
t = i
rev = 0
rev = rev * 10 + t % 10
t = t // 10
i = i * -1
rezultat.append(str(i))
else:
t = i
rev = 0
while t > 0:
rev = rev * 10 + t % 10
t = t // 10
if rev == i:
c=c+1
rezultat.append(str(i))
if c == 0:
print("")
print(','.join(rezultat))
I do not really know how to do it so it would be nice if someone can help me
Something like this...
def input(clan):
lista = [int(clan) for clan in input("Unesi članove niza : ").split(',')]
lista.reverse()
return lista
def processing(lista):
rezultat = []
c = 0
for i in lista:
if i < 0:
i = i * -1
t = i
rev = 0
rev = rev * 10 + t % 10
t = t // 10
i = i * -1
rezultat.append(str(i))
else:
t = i
rev = 0
while t > 0:
rev = rev * 10 + t % 10
t = t // 10
if rev == i:
c=c+1
rezultat.append(str(i))
if c == 0:
print("")
return(','.join(rezultat))
def output(result):
print(result)
if __name__ == '__main__':
result_list = input(clan)
result = processing(result_list)
output(result)
Try using the def command,
like this
def inp(): #declare a function
#your commands
inp() #run the commands
Don't forget to declare global variables a.k.a. those variable that you might alter in many functions by using the global command.
try this
def get_input():
lista = [int(clan) for clan in input("Unesi članove niza : ").split(',')]
lista.reverse()
return lista
def process_input(input):
rezultat=[]
c=0
for i in input:
if i < 0:
i = i * -1
t = i
rev = 0
rev = rev * 10 + t % 10
t = t // 10
i = i * -1
rezultat.append(str(i))
else:
t = i
rev = 0
while t > 0:
rev = rev * 10 + t % 10
t = t // 10
if rev == i:
c=c+1
rezultat.append(str(i))
if c == 0:
print("")
return rezultat
def main():
lista = get_input()
result = process_input(lista)
def output(xlist):
return ','.join(xlist)
output(result)
if __name__ == "__main__":
main()
that should work, but I don't see the need to divide it into functions, since the code might even work well as one function.
Here's my code:
def ispalindrome(p):
temp = p
rev = 0
while temp != 0:
rev = (rev * 10) + (temp % 10)
temp = temp // 10
if num == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (palindrome(i) == True):
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)
I believe my ispalindrome() function works. I'm trying to figure out what's wrong inside my while loop.
here's my output so far:
n = 1 answer = 1,
n = 2 answer = 22,
n = 3 answer = 333 ...
I also think the runtime on this really sucks
Please help
i belive the problem is with your ispalindrom functon it returns 200 as palindrome number
def ispalindrome(p):
rev = int(str(p)[::-1])
if p == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (ispalindrome(i) == True):
print(i)
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)
def is_palindrome(number):
return str(number) == str(number)[::-1]
num = int(input("Enter a number: "))
palindromes = [i for i in range(1, num) if is_palindrome(i)]
print(f"Sum of the {len(palindromes)} palindromes in range {num} is {sum(palindromes)}")
def sumdigits(number, start):
if number > 0:
if start == True:
new_number = ((number % 10) * 2)
digits = (new_number % 10) + (new_number // 10)
print(digits)
sumdigits((number // 10), False)
elif start == False:
the_number = (number % 10)
print(the_number)
sumdigits((number // 10), True)
sumdigits(7992739871005, False)
Add the result of calculation to a variable each time, and return that variable at the function's end.
def recursion_is_fun(num) :
sum = 0
sum += calculate_whatever(num) + recursion_is_fun(num % 10)
return sum
And good luck with the rest of your homework ;)
def makeArray(a):
a = []
for i in range(n):
a.append(i)
return a
print makeArray(a)
import random
def shuffleArray(a):
size = len(a)
for i in range(size):
r = random.randrange(0,size)
if r != i:
temp = a[r]
a[r] = a[i]
a[i] = temp
return a
print shuffleArray(makeArray(a))
if __name__ == '__main__':
a = raw_input("please enter size of array: ")
print ("you entered " + a)
makeArray(a)
shuffleArray(a)
how do I make this piece of code ask for input via terminal and take that input through both of the functions then returning a result? I'm asking the user for input storing that input in a variable printing the result and then shuffling by randominzing.
def makeArray(n):
a = [] #you were using 'a' for the size and the array itself at the same time
for i in range(n):
a.append(i)
return a
import random
def shuffleArray(a):
size = len (a)
for i in range(size):
r = random.randrange(0,size)
if r != i:
temp = a[r]
a[r] = a[i]
a[i] = temp
return a
if __name__ == '__main__':
n = int(raw_input("please enter size of array: ")) #'n' needs to be an integer because it's the size of the array
print ("you entered " + str(n))
anArray = makeArray(n)
print shuffleArray(anArray)
you can also replace:
def makeArray(n):
a = []
for i in range(n):
a.append(i)
return a
with:
def makeArray(n):
a = list(range(n))
return a