Python for maximum pairwise product - python

n = int(input("Enter the number of elements in the array (2-200,000):"))
a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()]
c = list()3
for i in range(0,n):
for j in range (1,n):
if a[i] != a[j]:
m = a[i]*a[j]
c.append(m)
else:
continue
print(max(c))
This code works. However, I want to define a function to automatically calculating the max product from the 5th line in the code shown below.
def MaxPairwiseProduct(n,a,c):
for i in range(0,n):
for j in range (1,n):
if a[i] != a[j]:
m = a[i]*a[j]
c.append(m)
else:
continue
Product = max(c)
return Product
n = int(input("Enter the number of elements in the array (2-200,000):"))
a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()]
c = list()
MaxPairwiseProduct(n,a,c)
I re-write the function but it does not work. It reveals "IndentationError: expected an indented block"

# python3
result = 0
def max_pairwise_product_fast(n, numbers):
max_index1 = -1
for i in range(n):
if max_index1 == -1 or numbers[i] > numbers[max_index1]:
max_index1 = i
max_index2 = -1
for i in range(n):
if i != max_index1 and (max_index2 == -1 or numbers[i] > numbers[max_index2]):
max_index2 = i
return numbers[max_index1] * numbers[max_index2]
if __name__ == '__main__':
n = int(input())
a = [int(x) for x in input().split()]
assert (len(a) == n)
print(max_pairwise_product_fast(n, a))

# Uses python3
def MaxPairwiseProduct(n,a,c):
for i in range(0,n):
for j in range (1,n):
if a[i] != a[j]:
m = a[i]*a[j]
c.append(m)
else:
continue
Product1 = max(c)
return Product1
def MaxPairwiseProductFast(n,a):
max_index1 = -1
for i in range(0,n):
if a[i] > a[max_index1]:
max_index1 = i
else:
continue
#the value of the other index should be different compared to the #first, else it will assume the same indices for both the max
max_index2 = -2
for j in range(0,n):
if a[j] > a[max_index2] and a[j] != a[max_index1]:
max_index2 = j
else:
continue
Product2 = a[max_index1]*a[max_index2]
return Product2
n = int(input("Enter the number of elements in the array (2-200,000):"))
a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()]
c = list()
print('The max value by regular algorithm:', MaxPairwiseProduct(n,a,c))
print('The max value by faster algorithm:', MaxPairwiseProductFast(n,a))
This code contains the second algorithm to calculate the max value.

def MaxPairwiseProduct(n,a,c):
for i in range(0,n):
for j in range (1,n):
if a[i] != a[j]:
m = a[i]*a[j]
c.append(m)
else:
continue
Product = max(c)
return Product
n = int(input("Enter the number of elements in the array (2-200,000):"))
a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()]
c = list()
print(MaxPairwiseProduct(n,a,c))

My stupid solution to the maximum pairwise product.
n = int(input()) #
nums = input().strip().split()
nums = [ int(i) for i in nums ]
firstmax, secondmax = sorted(set(nums))[-2:]
print(firstmax*secondmax)

To do the stress testing: you can use this code here. It works when I did an assignment.
#Stress test
from random import randint
def max_prod_stress(N,M):
while True:
n = randint(2,N)
A = [None]*n
for i in range(n):
A[i] = randint(0,M)
print(A)
result1 = max_prod_naive(A)
result2 = max_prod_fast(A)
if result1==result2:
print('OK')
else:
print('Wrong answer:',result1,result2)
return
max_prod_stress(5,100)

Related

Finding unique elements from the list of given numbers

I have written a code which finds unique elements from the list of integers.
def Distinct(arr, n):
for i in range(0, n):
d = 0
for j in range(0, i):
if (arr[i] == arr[j]):
d = 1
break
if (d == 0):
print(arr[i], end=',')
n = int(input('Enter length of numbers: '))
arr = []
for i in range(n):
a = input('enter the number: ')
arr.append(a)
print(Distinct(arr, n))
if my given input array is [1,2,2,3,4] where n = 5 i get the output as 1,2,3,4,None but i want the output to be 1,2,3,4
can anyone tell how to fix this ?
Your function Distinct has no return statement so it will always return None. When you call print(Distinct(arr, n)) this is printing the None that is returned. You can simply remove the print() like so:
Distinct(arr, n)
To remove the last comma you can't print a comma on the first iteration, then print the commas before the items. This is because you don't know which item will be the last one.
if d == 0 and i == 0:
print(arr[i], end='')
elif d == 0:
print("," + arr[i], end='')
Try something like this:
def Distinct(arr, n):
lst = []
for i in range(0, n):
for j in range(0, i):
if (arr[i] == arr[j]):
lst.append(arr[i])
break
print(*lst, sep=',')
n = int(input('Enter length of numbers: '))
arr = []
for i in range(n):
a = input('enter the number: ')
arr.append(a)
Distinct(arr, n)
So first you compute all the numbers, and only at the end you print them

I'm trying to write a condition on the python list

I tried writing a Python program to accept a list of integers starting with 0 and ending with 20 from the user. Each integer of the said list either differs from the previous one by two or is four times the previous one. Return true or false
Can someone correct the condition which I have written
lst = []
n = int(input("Enter the no of elements in the list :"))
for i in range (0,n):
elem = int(input("Enter the elements between 0 and 20 : "))
lst.append(elem)
if elem >= 0 and elem <=20:
print(lst)
for i in elem:
if (i+1) >= 2(i) or 4(i+1) == i:
print(True)
else:
print(False)
You can use zip to pair up items with their successors. This will let you compare them and check your condition using any() or all() depending on your requirement:
if any(abs(a-b)==2 or a*4==b for a,b in zip(lst,lst[1:]):
print(True) # at least one number pair meets the criteria
else:
print(False)
or
if all(abs(a-b)==2 or a*4==b for a,b in zip(lst,lst[1:]):
print(True) # all numbers meets the criteria
else:
print(False)
arr_len = int(input("Input a length for list: "))
nums = [0] * arr_len
res = [False] * arr_len
for i in range(len(nums)):
num = -1
while not(num >= 0 and num <= 20):
num = input("Enter the elements between 0 and 20 : ")
num = nums[i] = int(num)
if num >= 0 and num <= 20:
print('appended')
else:
print('that number is not between 0 and 20')
for i in range(1, len(res)):
num = nums[i]
prev_num = nums[i-1]
if abs(num-prev_num) == 2 or prev_num == 4*num:
res[i] = True
for i in range(len(nums)):
print('i is: ', i, 'nums[i], ', nums[i],
', is allowed in array: ', res[i])
res = dict(zip(nums, res))
print(res)

Getting closest number to 0 and can be negative number

I have the below range and I want to pick the number closets to 0. in the below array, -4 would be the closet number and the right answer. Thanks in advance
num_array = [-37,-24,-18,-10,-4,5,12,18,26]
Let us do min and pass the selection via key
min(num_array, key=lambda x:abs(x-0))
-4
Check with -1..
num_array = [-37,-24,-18,-10,-4,5,12,18,26,-1]
min(num_array, key=lambda x:abs(x-0))
-1
Keep track of the smallest positive and the largest negative number. If 0 is not there in the list then select the closest one from the two numbers mentioned above.
import sys
a = [-37,-24,-18,-10,-4,5,12,18,26]
maxn = sys.maxsize
minn = -sys.maxsize - 1
f = 0
for i in range(len(a)):
if a[i] == 0:
ans = 0
f = 1
break
elif a[i] > 0 and a[i] < maxn :
maxn = a[i]
elif a[i] < 0 and a[i] > minn :
minn = a[i]
else:
None
if f == 0:
if abs(maxn) < abs(minn):
ans = maxn
else:
ans = minn
print(ans)

how to print sum of primes in a list in python?

How do I print sum of primes in a list in Python?
I'm a new to Python, therefore I might be making a terrible mistake.
Please help out.
def prime(n):
i = 2
c = 0
for i in range(1,n+1):
if(n%i == 0):
c = c+1
if(c == 2):
return True
else:
return False
def sumprimes(l1):
l1 = []
l = len(l1)
i = 0
sum = 0
for i in range(0,l):
if(prime(l1[i]) is True):
sum = sum +l1[i]
print(sum)
l1 = [3,4,5,6]
print(sumprimes(l1))
Output should be equal to 8.
def prime(n):
i = 2
c = 0
for i in range(1,n+1):
if(n%i == 0):
c = c+1
if(c == 2):
return True
else:
return False
def sumprimes(l1):
sum=0
for x in l1:
if prime(x):
sum += x
return sum
l1 = [3,4,5,6]
print(sumprimes(l1))
Use the above code. You need to use the return statement to print the result of a function. And there is no need for your range() loop, there is a more elegant way to do this in python, use a for loop over all elements of the list.
You can do it using below code too.
lst = [1,2,5,7,9,10,12]
def isPrime(x):
if x == 1:
return False
for i in range(2,x-1):
if x%i == 0:
return False
return True
def getPrimeSum(l):
l = [i for i in l if isPrime(i)]
return sum(l)
print(getPrimeSum(lst))
#Check and add into the list of primeval numbers (all primeval number under a specific number)
H = int(input("What the maxium number?: "))
RangeFinding = list(range(3, H+1))
import math
Prime = [2]
for a in RangeFinding:
x = True
y = 2
while x:
NCanA = math.floor(math.sqrt(a))
if a %y == 0:
print(f'{a} is not prime')
x = False
else:
if y > NCanA:
print(f'{a} is prime')
Prime.append(a)
x = False
else:
y = y + 1
x = True
print(Prime)
#**this function will check weather number is prime or not**
def prime(k):
i = 2
j = 0
for i in range(1,k+1):
if(k % i == 0):
j = j + 1
if(j == 2):
return True
else:
return False
#**this function will add all prime numbers**
def sumOfPrimes(l1):
sum=0
for y in l1:
if prime(y):
sum += y
return sum
list1 = [3,4,5,6]
print(sumOfPrimes(list1))
**You Will get output as 8**
Explain
I have created a function prime() that will check whether numbers are prime or not.
I have created a function sumOfPrime() that will add all the prime numbers.
list1
4)Called the function sumOfPrime(list1)
I have shared a Screenshot of the code and outputProgram and Output

How to calculate sum of prime numbers from list of integers in Python?

I am struck and need help with this..
I want to find the sum of prime numbers from a given list of integers. Here are a few test cases for the same.
n([3,3,1,13])
19
n([2,4,6,9,11])
13
n([-3,0,1,6])
0
The Code that I have written is as follows but it fails with the test cases above..
def sumprimes(n):
sum1 = 0
for i in range(0,len(n)):
num = n[i]
if num > 1:
for j in range(2, int(num**0.5)+1):
if num%j != 0:
sum1 = sum1 + num
else:
sum1 = 0
return(sum1)
This part is wrong:
for j in range(2, int(num**0.5)+1):
if num%j != 0:
sum1 = sum1 + num
you are summing num for each number in the range that didn't divide.
you should sum just if all of them didn't divide.
Simple way to do this is:
prime = True
for j in range(2, int(num**0.5)+1):
if num%j == 0:
prime = False
break
if prime:
sum1 = sum1 + num
Or in a more pythonic way using all():
if all(num%j != 0 for j in range(2, int(num**0.5)+1)):
sum1 = sum1 + num
Don't try to do everything in one function. I separated out the rest of the logic, but I'll leave isprime to you:
def isprime(x):
# Replace this with your code
# separate function so it can have its own tests
return x in [3, 13, 11, 2]
def sum_prime_numbers_in_list(l):
return sum([x for x in l if isprime(x)])
if 19 != sum_prime_numbers_in_list([3, 3, 1, 13]):
raise ValueError
else:
print 'pass'
if 13 != sum_prime_numbers_in_list([2, 4, 6, 9, 11]):
raise ValueError
else:
print 'pass'
if 0 != sum_prime_numbers_in_list([-3, 0, 1, 6]):
raise ValueError
else:
print 'pass'
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
lst=[]
print("Prime numbers between",lower,"and",upper,"are:")
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
lst.append(num)
print(lst)
sum=0
for i in lst:
sum=sum+i
print('sum of all prime numbers=%d'%sum)
def sum_primes(a):
sum = 0
for num in a:
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
sum = sum + num
if sum < 1:
print("sum_primes(" + str(a) + ") --> " + "None")
else:
print("sum_primes(" + str(a) + ") --> " + str(sum))
sum_primes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
sum_primes([2, 3, 4, 11, 20, 50, 71])
sum_primes([])
#code by Rushabh Koradia
The Answer should be this. [You should try this code, in this link.Gist]
def sumprimes(n):
sum1 = 0
for i in range(0,len(n)):
num = n[i]
if num > 1:
prime = True
for j in range(2, int(num**0.5)+1):
if num%j == 0:
prime = False
break
if prime:
sum1 = sum1 + num
#else:
# sum1 = 0
return(sum1)
> def sumprimes(n):
sum=0
fact=[]
for i in range (0,len(n)):
num=n[i]
if num>1:
fact=[]
for j in range (1,num+1):
if num%j==0:
fact=fact+[j]
if fact==[1,num]:
sum=sum+num
return(sum)
def sumprimes(n):
s=0
f=[]
for i in range (0,len(n)):
num=n[i]
if num>1:
f=[]
for j in range (1,num+1):
if num%j==0:
f=f+[j]
if f==[1,num]:
s=s+num
return(s)
def sumprimes(l):
def findprime(n):
if n > 1:
# check for factors
for i in range(2, n):
if (n % i) == 0:
return False
break
else:
return True
# if input number is less than
# or equal to 1, it is not prime
else:
return False
sum = 0
for x in l:
if findprime(x):
sum += x
print(sum)
def isPrime(n):
if (n<2):
return False
for i in range (2,n):
if (n%i==0):
return False
return True
li = []
a = [1,10,11,12,13]
for x in a:
if isPrime(x):
li.append(x)
print(li)
total = 0
for j in range(len(li)):
total += li[j]
print(total)
s=input("Enter :")
arr=s.split(",")
sum=0
for f in range(2,(len(arr)+1)):
k=0
for i in range(2,f//2+1):
if (f%(int(arr[i]))==0):
k=k+1
if(k<=0):
sum=sum+f
print("Sum :",sum)
L = [11,14,13,12,60,50,1]
for a in L:
if(a % 2 == 0):
L.remove(a)
for a in L:
if (a % 3 == 0):
L.remove(a)
print(sum(L))

Categories