The task is to write function that foldes number into prime factors. By given number 'n' this function should return a list of tuples p_i,c^i, for example if input is 100, the output is (2,2),(5,2).
So, here is how i try to write it:
def factor(n):
c = 1
pre_ans = list()
temp_n=n
for i in range(2,temp_n+1):
if (is_prime(i) == True) and (temp_n % i == 0):
for j in range (2,temp_n+1):
if (temp_n % (i ** j) == 0):
pre_ans.append((i,j))
temp_n /= (i **j)
pre_ans.append((i,c))
temp_n /= i
print(pre_ans)
It works wrong but I can't find a mistake :(
Your general idea is ok. However there are some minor issues with the following part of your code:
for j in range (2,temp_n+1):
if (temp_n % (i ** j) == 0):
pre_ans.append((i,j))
temp_n /= (i **j)
pre_ans.append((i,c))
temp_n /= i
In fact the main problem is that you need to iterate in the other direction in this statement for j in range (2,temp_n+1). If you rewrite it like
def factor(n):
c = 1
pre_ans = list()
temp_n=n
for i in range(2,temp_n+1):
if (is_prime(i) == True) and (temp_n % i == 0):
for j in range (temp_n+1, 0,-1):
if (temp_n % (i ** j) == 0):
pre_ans.append((i,j))
temp_n /= (i **j)
print(pre_ans)
it will work. The whole code can also get written a bit shorter:
from collections import Counter
def factor(n):
lst = []
for i in range(2, n+1):
while n % i == 0:
lst.append(i)
n = n / i
return Counter(lst).items()
print(factor(100))
Fixed the code. This is working version
def factor(n):
c = 1
pre_ans = list()
temp_n=n
for i in range(2, n // 2 + 1):
if (is_prime(i) == True):
k = 1
while temp_n % (i ** k) == 0:
if temp_n % (i ** (k + 1)) == 0:
k += 1
else:
k += 1
break
if k > 1:
pre_ans.append((i, k - 1))
return pre_ans
Related
I have a python code which solves the 3-Partition problem using Dynamic Programming method. But I don't really understand how he utilizes the DP method. Could anyone tell me what is the recursion formula in this code and why it works? (Especially the middle loop part)
import sys
def partition3(A):
n = len(A)
if sum(A)%3 != 0:
return 0
W = sum(A)//3
value = [[[0 for x in range(W+1)] for y in range(W+1)] for z in range(len(A)+1)]
#print("dimension,n:",len(value[0][0]), len(A))
value[0][0][0] = 1
for idx in range(len(A)+1):
value[idx][0][0] = 1
for i in range(1, n+1):
for j in range(W+1):
for k in range(W+1):
value[i][j][k] = value[i-1][j][k]
if (j >= A[i-1] and value[i-1][j-A[i-1]][k]):
value[i][j][k] = 1
if (k >= A[i-1] and value[i-1][j][k-A[i-1]]):
value[i][j][k] = 1
for idx in range(n+1):
print(value[idx][0][:])
if(value[len(A)][W][W] == 1):
return 1
else:
return 0
if __name__ == '__main__':
input = sys.stdin.read()
n, *A = list(map(int, input.split()))
print(partition3(A))
This is the code I have thus far:
def frac_knapsack(n,size, profit,K):
if K <= 0:
return 0
for i in range(0,i):
if profit[i]/size[i]>profit[i-1]/size[i-1]:
profit.append[i] and size.append[i]
s = 0
p = 0
for i in range(n):
if s + size[i] <= K:
p += profit[i]
s += size[i]
else:
p += (K-s) * (profit[i]/size[i])
s = K
break
return p
def Knapsack(i, size):
if i > n or size <= 0:
print(x)
return
if x[j] == 1:
for j in range(0,i-1):
p+=P[j]
if x[j] == 1:
for j in range(0,i-1):
s+=S[j]
if x[i] == 1:
if s+size[i] <= K and (p + profit[i] + B) > MaxProfit:
B = fractional_Knapsack(n-(i+1), size[i+1:], profit[i+1:], T-size[i])
if p+profit[i] > MaxProfit:
MaxProfit=p+profit[i]
x=solution
Knapsack(i+1, T-size[i])
if x[i] == 0:
B = frac_Knapsack(n-(i+1), size[i+1:], profit[i+1:], T)
if (p + B) > MaxProfit:
Knapsack(i+1, T)
I have a problem with sorting in line 4. I have to sort it as weight-efficiency. do i need to use quick sort algorithm?
I want to make input for four things:
n,size,profit and K
do i need to use map? as size and profit is list?
You used
B = fractional_Knapsack(n-(i+1), size[i+1:], profit[i+1:], T)
your method is called
def frac_knapsack(n,size, profit,K):
I'm working on a code challenge in which I have to reduce the execution time as much as possible, the only thing I able to find where I can make an improvement is a nested if-else statement inside a nested for-loop but I'm not sure how it can be improvided.
Here's my code:
mat = [[0] * n] * n
count = 0
for i in range(n,0,-1):
count += 1
for j in range(i,n+1,1):
if i == j:
pass
else:
if getEnemyStatus(mat, i, j):
break
else:
if isEnemy(enemyDict, i, j):
setStatus(mat, i, j)
break
else:
count += 1
value of n can be from 1 to 10^5
You can skip the first if condition by starting with i+1 in range
for j in range(i+1, n+1, 1):
# code here
Second, nested if else condition should be avoided with elif for reading purpose.
Update code should be like:
mat = [[0] * n] * n
count = 0
for i in range(n,0,-1):
count += 1
for j in range(i + 1, n + 1, 1):
if getEnemyStatus(mat, i, j):
break
elif isEnemy(enemyDict, i, j):
setStatus(mat, i, j)
break
else:
count += 1
NOTE: Also if you can set the status setStatus in your isEnemy function then you can get more cleaner code:
mat = [[0] * n] * n
count = 0
for i in range(n,0,-1):
count += 1
for j in range(i + 1, n + 1, 1):
if getEnemyStatus(mat, i, j) or isEnemy(enemyDict, i, j):
break
count += 1
Hi I am learning the basics of algorithms using python, this is my first stress testing script (I am still new to python).
When i run the test both the variables fast and result are printed as 0, the random number generator i included doesn't seem to be creating numbers for the functions mpp and mppf to use, either that or they are not assigning their results to the relevant variable, hence the variable remains = 0 and the loop keeps printing '0 0 OK'
I am receiving no errors except for the fact that my script isn't doing what i want it too!
import random
result = 0
fast = 0
while result == fast:
if __name__ == '__main__':
n = (random.randint(2, 11))
a = list(random.randint(0, 99999) for r in range(n))
assert (len(a) == n)
def max_pairwise_product(n, a):
global result
for i in range(0, n):
for j in range(i + 1, n):
if a[i] * a[j] > result:
result = a[i] * a[j]
return result
def max_pairwise_product_fast(n, a):
global fast
max_index1 = -1
for i in range(n):
if max_index1 == -1 or a[i] > a[max_index1]:
max_index1 = i
max_index2 = -1
for i in range(n):
if i != max_index1 and (max_index2 == -1 or a[i] > a[max_index2]):
max_index2 = i
fast = a[max_index1] * a[max_index2]
return fast
print(fast, result, "OK")
else:
print("Wrong Answer")
I think this seems to work:
import random
def max_pairwise_product_fast(n, a):
global fast
max_index1 = -1
for i in range(n):
if max_index1 == -1 or a[i] > a[max_index1]:
max_index1 = i
max_index2 = -1
for i in range(n):
if i != max_index1 and (max_index2 == -1 or a[i] > a[max_index2]):
max_index2 = i
fast = a[max_index1] * a[max_index2]
return fast
def max_pairwise_product(n, a):
global result
for i in range(0, n):
for j in range(i + 1, n):
if a[i] * a[j] > result:
result = a[i] * a[j]
return result
result = 0
fast = 0
while result == fast:
if __name__ == '__main__':
n = (random.randint(2, 11))
result=0;fast=0
a = list(random.randint(0, 99999) for r in range(n))
assert (len(a) == n)
result = max_pairwise_product(n, a)
fast=max_pairwise_product_fast(n, a)
print(fast, result, "OK")
else:
print("Wrong Answer")
I don't know what your code is suppose to do but it now seems to run.
You should not keep you defined function inside your loop.
Hope this helps.
I am trying to permute a list but I cannot do it, it goes infinite cycle. I tried different things but somehow the only thing that it shows me is 1 2 3 ... 1 2 3 etc
This is the code:
def prints(v,k):
s = ''
for i in range(k + 1):
s += str(v[i]) + ' '
print(s)
def continuare(v,k):
ok = True
for i in range(k):
if v[i] == v[k]:
ok = False
break
return ok
def back(v,a):
k = 0
caut = False
while k>-1:
caut = False
pos = 0
while pos < len(a) and caut == False:
v[k] = a[pos]
pos += 1
if continuare(v,k):
caut = True
if caut == False:
k -= 1
elif k == len(a) - 1:
prints(v,k)
else:
k += 1
a = [1,2,3]
v = []
for x in range(len(a)):
v.append(a[0])
back(v,a)
Here's a trivial Python transcription from http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/ :
def swap(a, i, j):
a[i], a[j] = a[j], a[i]
def permute(a, i, n):
if i == n:
print(a)
return
for j in range(i, n+1):
swap(a, i, j)
permute(a, i+1, n)
swap(a, i, j) # backtrack
def main():
a = list('ABC')
permute(a, 0, 2)
if __name__ == '__main__':
main()
I'd rather have permute be a generator yielding the permutations, with main looping on them and printing them, but this may be closer to the C original and thus easier to follow. Note that one difference is a must: what's being permuted here is a list, not a string as in the C original, because strings are immutable in Python (so swap would require substantially different logic, returning the "string with swapped characters" rather than being able to work in-place as the "backtracking" logic requires).