How it works in python? ruby code - python

I don't understand what it code doing, please help.
How it will be working in python or in another simple language?
a = []
a << [1]
for i in 2..10001
f = 0
a.each{ |group|
m = 1
group.each { |c|
m *= i % c
}
f += m
if m > 0
group << i
break
end
}
a << [i] if f == 0
end
p a
p a.size

Literally translated to python this is:
a = []
a.append([1])
for i in range(2,10001 + 1):
f = 0
for group in a:
m = 1
for c in group:
m *= i % c
f += m
if m > 0:
group.append(i)
break
if f == 0:
a.append([i])
print a
print len(a)

In python:
a = []
a.append(1)
for i in range(2, 10000):
f = 0
for group in a:
m = 1
for c in group:
m *= i%c
f += m
if m>0:
group.append(i)
break
if not f:
a.append(i)
print(a)
print(len(a))

Related

IndexError: list index out of range exeption in python

I try to write an algorithm in python, and i dont understand why its out of range.I am realy dont understand where is the problem
This is my code
B = [1, 2, 3, 4]
n = 4
def b(m, i):
if m % 2 == 0 and m > 2:
if i < m - 1:
return 1
else:
return m - 2
else:
return m - 1
def PERM(m):
if m == 1:
print(P)
else:
for i in range(0, m):
PERM(m - 1)
if i < m:
k = P[m]
P[m] = P[b(m, i)]
P[b(m, i)] = k
PERM(n)
in for i in range(0, m):, the loop is iterting from 0 to 4 which is total of 5 index so better you change the n = 4 to n = 3, hope this help :)

3Sum function debugging

I have been asked to fix this chunk of code. It is to do with sets and the 3Sum problem. I have used print statements and i am very close to the answer, but i get an IndexingError (list index out of range). Any help would be great
def count_c(A, B, C):
"""Counts the number of pairs a in A and b in B so that a + b == c
nb. Assumes that A and B are sorted
"""
rv = 0
n = len(A)
m = len(B)
#t = len(C)
AL, BL, CL = list(A), list(B), list(C)
# i and j are "fingers" on A and B
i, j = 0, m-1
while i < n and j >= 0:
for c in CL:
a, b = AL[i], BL[j] #correct
print ('a,b = ', (a,b))
s = a + b #correct
print('s = ', s)
print ('i , j =', (i,j))
if s == c:
# found a pair that works
rv = rv + 1 #correct
# start again with a smaller b
j = j - 1 #correct
elif s > c:
# too big. decrease the b contribution
j = j - 1
else:
# means s < c, increase the a contribution
i = i + 1
return rv
def three_sum(A, B, C):
"""Solves 3SUM+"""
return count_c(A,B,C)
IndexingError (list index out of range)

Finding squares of big numbers in python using math.pow

I am trying hackers rank to improve my python skills. I have picked a problem.I am able to solve this but I am not getting right output in all the scenarios. Below is the scenario
Link to problem is this
https://www.hackerrank.com/challenges/maximize-it/problem
Below is my code
import math
import sys
lis= sys.stdin.readlines()
def newFunc(lis):
numLines = lis[0].split(" ")[0]
divisor = lis[0].split(" ")[1]
iter = 1
newLis = []
while(int(numLines) >= int(iter)) :
paramNum = lis[iter].split(" ")[0]
iter1 = 1
bigNum = 0
while(int(paramNum) >= int(iter1)):
if int(lis[iter].split(" ")[iter1]) > bigNum:
bigNum = int(lis[iter].split(" ")[iter1])
iter1 = iter1 + 1
newLis.append(bigNum)
iter = iter + 1
sum = 0
for num in newLis:
sum = sum + math.pow(num,2)
finalNum = sum % int(divisor)
return finalNum
value = newFunc(lis)
print int(value)
When I am testing my code against below output
5 84
1 765952241
3 289380515 265118103 309882974
2 747649220 587740446
2 682866882 596381508
1 342723101
Expected output is 83
Actual I am getting is 48
I don't know why. Can somebody help me with this
try this
import itertools
(K, N) = map(int, raw_input().split())
L = list()
for i in range(K):
l = map(int, raw_input().split())
n = l[0]
L.append(l[1:])
assert len(L[i]) == n
S_max = 0
L_max = None
for l in itertools.product(*L):
s = sum([x**2 for x in l]) % N
if s > S_max:
S_max = s
L_max = l
print S_max

Function which measures time M times

I am to measure how much time does it take for the function below to represent: C in range [0, 10] with the numbers in list N. (M measurements for each C).
import itertools
def amount(C):
N = [1, 2, 5]
#N = list(N)
N = sorted(N)
while C < max(N):
N.remove(max(N))
res = []
for i in range(1, C):
for j in list(itertools.combinations_with_replacement(N, i)):
res.append(sum(list(j)))
m = 0
for z in range (0, len(res)):
if res[z] == C:
m += 1
if N[0] == 1:
return m + 1
else:
return m
EDITED:
import itertools
def amount(C):
N = [1, 2, 5]
res = []
for i in range(1, C):
for j in list(itertools.combinations_with_replacement(N, i)):
res.append(sum(list(j)))
m = 0
for z in range (0, len(res)):
if res[z] == C:
m += 1
if N[0] == 1:
return m + 1
else:
return m
I would like to make 10 measurements and then take for example median of all those measurements.
There is my code but something unfortunately doesn't work properly and I have no idea what is wrong:
import time
def time_counter(amount, n=11, M=11):
res = list(range(n))
def count_once():
start = time.perf_counter()
amount(res)
return time.perf_counter() - start
return [count_once() for m in range(M)]
You are again passing a list and trying to do range(1,C) where C is a list
Here is how your program should be
import itertools
import time
def amount(C):
N = [1, 2, 5]
res = []
for i in range(1, C):
for j in list(itertools.combinations_with_replacement(N, i)):
res.append(sum(list(j)))
m = 0
for z in range (0, len(res)):
if res[z] == C:
m += 1
if N[0] == 1:
return m + 1
else:
return m
def time_counter(amount, n=11, M=11):
res = list(range(n))
def count_once(c):
start = time.perf_counter()
amount(c)
return time.perf_counter() - start
return [count_once(m) for m in range(M)]
#testing
print(time_counter(amount))

Finding root/zeros of a function

I am trying to find a root of a function by using the bisection method stating that :
if f(a)*f(b) < 0 then a root exists,
then you repeat with f(a)*f(c)<0 where c = (a+b)/2
but im not sure how to fix the code so it works properly.
This is my code but its not working properly
from scipy import *
from numpy import *
def rootmethod(f, a, b, tol):
x = a
fa = sign(eval(f))
x = b
fb = sign(eval(f))
c = a + b
iterations = 0
if fa == 0:
return a
if fb == 0:
return b
calls = 0
fx = 1
while fx != 0:
iterations = iterations + 1
c *= 0.5
x = a + c
fc = sign(eval(f))
calls = calls + 1
if fc*fa >= 0:
x = a
fx = sign(eval(f))
if fc == 0 or abs(sign(fc)) < eps:
fx = sign(eval(f))
return x, iterations, calls
print rootmethod("(x-1)**3 - 1", 1, 3, 10*e-15)
New edit.. but still doesnt work
if fa*fb < 0:
while fx != 0:
iterations = iterations + 1
c = (a + b)/2.0
x = c
fc = sign(eval(f))
calls = calls + 1
if fc*fa >= 0:
x = c
fx = sign(eval(f))
if fc == 0 or abs(sign(fc)) < tol:
fx = sign(eval(f))
return x, iterations, calls
Edit: Changed c=(a+b)*2 to c=(a+b)/2 in the description of the method.
Frankly your code was a bit of a mess. Here's some that works. Read the comments in the loop.
(BTW the solution to your given function is 2, not 3.75)
from scipy import *
from numpy import *
def rootmethod(f, a, b, tol):
x = a
fa = sign(eval(f))
x = b
fb = sign(eval(f))
c = a + b
iterations = 0
if fa == 0:
return a
if fb == 0:
return b
calls = 0
fx = 1
while 1:
x = (a + b)/2
fx = eval(f)
if abs(fx) < tol:
return x
# Switch to new points.
# We have to replace either a or b, whichever one will
# provide us with a negative
old = b # backup variable
b = (a + b)/2.0
x = a
fa = eval(f)
x = b
fb = eval(f)
# If we replace a when we should have replaced b, replace a instead
if fa*fb > 0:
b = old
a = (a + b)/2.0
print rootmethod("(x-1)**3 - 1", 1, 3, 0.01)
I believe your loop should be something like this (in pseudocode, and leaving out some checking):
before loop:
a is lower bound
b is upper bound
Establish that f(a) * f(b) is < 0
while True:
c = (a+b)/2
if f(c) is close enough to 0:
return c
if f(a) * f(c) > 0:
a = c
else
b = c
In other words, if the midpoint isn't the answer, then make it one of the new endpoints depending on its sign.
I think your one problem is with:
x = a + c
Since c = (a + b)*.5, you don't need to add in a here...
Update
You don't seem to check if fa * fb < 0 to start, and I also don't see where you're narrowing your bounds: you should either reassign a or b to c in your loop and then recalculate c.
Code It's been a while since I played with python last, so take it with a grain of salt ^_^
x = a
fa = sign(eval(f))
x = b
fb = sign(eval(f))
iterations = 0
if fa == 0:
return a
if fb == 0:
return b
calls = 0
fx = 1
while fa != fb:
iterations += 1
c = (a + b)/2.0
x = c
fc = eval(f)
calls += 1
if fc == 0 or abs(fc) < tol:
#fx = fc not needed since we return and don't use fx
return x, iterations, calls
fc = sign(fc)
if fc != fa:
b = c
fb = fc
else
a = c
fa = fc
#error because no zero is expected to be found
Please note that the code has a simple deficiency caused by round-off errors
a=0.015707963267948963
b=0.015707963267948967
c=(a+b)*.5
c is becoming b again (check it out!).
You can end up in infinite loop
in case of very small tolerance like 1e-16.
def FindRoot( fun, a, b, tol = 1e-16 ):
a = float(a)
b = float(b)
assert(sign(fun(a)) != sign(fun(b)))
c = (a+b)/2
while math.fabs(fun( c )) > tol:
if a == c or b == c:
break
if sign(fun(c)) == sign(fun(b)):
b = c
else:
a = c
c = (a+b)/2
return c
Now, to call the eval over and over again is not very efficient.
Here is what you can do instead
expr = "(x-1.0)**3.0 - 1.0"
fn = eval( "lambda x: " + expr )
print FindRoot( fn, 1, 3 )
Or you can put the eval and lambda definition inside the FindRoot.
Was it helpful?
Reson

Categories

Resources