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.
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):
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
I am trying to apply a stress test on python maximum pairwise product, fast and slow algorithm. However, The fast code appears to return a wrong result in some tests. I think the problem comes from the if condition in the fast algorithm. The condition doesn't occur in some cases, though it should be applies. I wasn't able to figure out the problem. any help?
Here is the problem, I/P, O/P details:
Given a sequence of non-negative integers a0,…,an−1, find the maximum pairwise product, that is, the largest integer that can be obtained by multiplying two different elements from the sequence (or, more formally, max0≤i≠j≤n−1aiaj). Different elements here mean ai and aj with i≠j (it can be the case that ai=aj).
Input format
The first line of the input contains an integer n. The next line contains n non-negative integers a0,…,an−1 (separated by spaces).
Constraints:
2≤n≤2⋅105; 0≤a0,…,an−1≤105.
Output format:
Output a single number — the maximum pairwise product.
from random import randint
from random import randrange
def max_pairwise(n,a):
# n = int(input())
res = 0
# a = [int(x) for x in input().split()]
assert(len(a) == n)
for i in range(0,n):
for j in range(i+1,n):
if a[i]*a[j] > res:
res = a[i]*a[j]
return(res)
def max_pairwise_fast(n,a):
# n = int(input())
# a = [int(x) for x in input().split()]
max_index1 = -1
max_index2 = -1
for i in range(0,n):
if a[i] > a[max_index1]:
max_index1 = i
else:
continue
for j in range(0,n):
if ((a[j] != a[max_index1]) and (a[j] > a[max_index2])):
max_index2 = j
else:
continue
res = a[max_index1]* a[max_index2]
return(res)
#stress_test
while(1):
n = randint(0,9) +2
print(n,"n")
a = []
for i in range (n):
a.append(randrange(9000))
for i in range(n):
print(a[i],'a[i]',"/n")
if (max_pairwise(n,a) == max_pairwise_fast(n,a)):
print(max_pairwise(n,a), max_pairwise_fast(n,a),"true")
else:
print(max_pairwise(n,a), max_pairwise_fast(n,a), "false")
break
This is an example of the result:
6 n
318 a[i] /n
7554 a[i] /n
7531 a[i] /n
7362 a[i] /n
4783 a[i] /n
4897 a[i] /n
56889174 56889174 true
5 n
6879 a[i] /n
6985 a[i] /n
8561 a[i] /n
5605 a[i] /n
3077 a[i] /n
59798585 59798585 true
9 n
8285 a[i] /n
3471 a[i] /n
2280 a[i] /n
2443 a[i] /n
5437 a[i] /n
2605 a[i] /n
1254 a[i] /n
6990 a[i] /n
2943 a[i] /n
57912150 68641225 false
In your fast implementation, when you are finding a largest number, you must also update the second largest to the value of the previous largest, otherwise, there are cases where you end up multiplying numbers that are not the two largest.
def product_of_two_largest(seq):
largest = float("-inf")
second_largest = float("-inf")
for elt in seq:
if elt > largest:
second_largest = largest
largest = elt
elif elt > second_largest:
second_largest = elt
return second_largest * largest
Note 1:
Your while loop must also be updated, you are calculating the values twice instead of once.
while(1):
n = randint(0,9) +2
print(n,"n")
a = []
for i in range (n):
a.append(randrange(9000))
for i in range(n):
print(a[i],'a[i]',"/n")
slow, fast = max_pairwise(n, a), two_largest_product(a)
if (slow == fast):
print(slow, fast, slow == fast)
else: # attention, this never happens now.
break
Note 2:
As we are dealing with only non-negative integers, you will likely have a faster implementation if you simply sort the sequence and multiply the last two numbers (in spite of the fact that sort is O(nlogn), vs O(n) for the fast implementation above.
b = sorted(a)
print("max1 x max2 = ", b[-1] * b[-2])
Note 3:
Using a heap data structure (from collections import heap) is the theoretical best way to find the n largest items, but you'd likely need to have 100,000's of items to make it worth your while.
def max_pairwise_fast(n, a):
max_index1 = 0
max_index2 = 0
for i in range(n):
if a[i] > max_index1:
max_index2 = max_index1
max_index1 = a[I]
elif a[i] > max_index2:
max_index2 = a[I]
return max_index1 * max_index2
if __name__ == '__main__':
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_fast(input_n, input_numbers))
This might not help you.
I was attempting this question at Coursera ( Assignment ) and found that we don't need to make the solution more complex. We can simply store the first two largest integers while scanning from the user and print their product. A complex solution is the main reason for the TLE error.
code in c
#include<stdio.h>
int main() {
long long n, a = 0, b = 0, i = 0, numb = 1;
scanf("%lld", &n);
for (i = 0; i < n; i++){
scanf("%lld", &numb);
if(numb >= a){
b = a;
a = numb;
}
else if(numb > b)
b = numb;
}
printf("%lld", a * b);
return 0;
}
With input array data:
Example: [1, 2, 3]
def max(arr):
a = 0
b = 0
for i in range(len(arr)):
if a == 0 & arr[i]>a:
a = arr[i]
else:
if arr[i]>a:
b = a
a = arr[i]
else:
if arr[i]>b:
b = arr[i]
return a*b;
def max_pairwise_fast(n, a):
max_index1 = 0
max_index2 = 0
for i in range(n):
if a[i] > max_index1:
max_index2 = max_index1
max_index1 = a[i]
elif a[i] > max_index2:
max_index2 = a[i]
return max_index1 * max_index2
if __name__ == '__main__':
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_fast(input_n, input_numbers))
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).