Let us consider polynomials in a single variable x with integer coefficients: for instance, 3x^4 - 17x^2 - 3x + 5. Each term of the polynomial can be represented as a pair of integers (coefficient,exponent). The polynomial itself is then a list of such pairs.
We have the following constraints to guarantee that each polynomial has a unique representation:
Terms are sorted in descending order of exponent
No term has a zero coefficient
No two terms have the same exponent
Exponents are always nonnegative
For example, the polynomial introduced earlier is represented as
[(3,4),(-17,2),(-3,1),(5,0)]
The zero polynomial, 0, is represented as the empty list [], since it has no terms with nonzero coefficients.
Write Python functions for the following operations:
addpoly(p1,p2) ?
def addpoly(p1,p2):
p1=[]
p2=[]
for i in range(0,len(p1)):
for j in range(0,len(p2)):
L=[]
if p1[i][1]==p2[j][1]:
L=L[p1[i][0]+p2[j][0]][p1[i][1]]
elif p1[i][1]!=p2[j][1]:
L=L+p1[i][j]
L=L+p2[i][j]
print("L")
You are reassigning the p1 and p2 arguments to empty lists at the top of your function. This means you will always be checking for i in range(0, 0), which is an empty range. In other words, nothing in your loop will be executed. This is why you are not seeing any output. You are not seeing any error messages, because there is nothing wrong with your syntax, the problem is with the logic.
My math skills are nonexistent, so I cannot comment on the accuracy of most of the logic in your code, but for sure you need to get rid of the first two lines of your function (p1 = [] and p2 = []) or your function will do nothing.
Also, make sure to print the variable L rather than the string "L" to print your list:
print(L)
try this code
def addpoly(p1,p2):
L=[]
for i in range(0,len(p1)):
for j in range(0,len(p2)):
if p1[i][1] == p2[j][1] and p1[i][0]+p2[j][0] != 0 :
L.append((p1[i][0]+p2[j][0],p1[i][1]))
elif p1[i][1] == p2[j][1] and p1[i][0]+p2[j][0] == 0 :
pass
elif i == j:
L.append(p2[i])
L.append(p1[i])
return (L)
Related
I am creating a program that
accepts an inputted list
finds all the prime numbers and only displays them.
I tried many different methods, many derived from existing prime filters, but they have hardcoded lists rather user-inputted ones.
I just can't seem to get a filter working with inputting a list, then filtering the prime numbers.
my_list = input("Please type a list")
list(my_list)
prime=[]
for i in my_list:
c=0
for j in range(1,i):
if i%j==0:
c+=1
if c==1:
prime.append(i)
return (prime)
When you get input, you're getting a string. You can't cast a string to a list immediately. Maybe you can request the user to use a separator between the numbers then use split method and cast strings to integers like this:
my_list = input("Please enter the list of numbers and use space seperator")
s_list = my_list.split()
cast_list = [int(num) for num in s_list]
Then, you can work on your prime number task based on your preferred algorithm.
Not sure what your c variable is for, current_number? Your loop returns 'str' object cannot be interpreted as an integer for me. I have used len(my_list) to get the length for the loop.
range() defines as range(start, stop, step) - learn more - it accepts integers and parameters are partially optional.
I copied the code from https://www.codegrepper.com/code-examples/python/how+to+find+prime+numbers+in+list+python
my_list = input("Please type a list")
primes = []
for i in range(0, len(my_list)):
for j in range(2, int(i ** 0.5) + 1):
if i%j == 0:
break
else:
primes.append(i)
print(primes)
More helpful resources from SO: Python function for prime number
I hope this helps.
I wish to find Number of sub sequences of length K having total sum S, given an array.
Sample Input:
a=[1,1,1,2,2] & K=2 & S=2
Sample Output:
3 {because a[0],a[1]; a[1]a[2]; a[0]a[2] are only three possible for the case}
I have tried to write a recursive loop in Python for starter but it isn't giving output as expected.Please can you help me find a loophole I might be missing on.
def rec(k, sum1, arr, i=0):
#print('k: '+str(k)+' '+'sum1: '+str(sum1)) #(1) BaseCase:
if(sum1==0 and k!=0): # Both sum(sum1) required and
return 0 # numbers from which sum is required(k)
if(k==0 and sum1 !=0): # should be simultaneously zero
return 0 # Then required subsequences are 1
if(k==0 and sum1==0 ): #
return 1 #
base_check = sum1!=0 or k!=0 #(2) if iterator i reaches final element
if(i==len(arr) and base_check): # in array we should return 0 if both k
return 0 # and sum1 aren't zero
# func rec for getting sum1 from k elements
if(sum1<arr[0]): # takes either first element or rejects it
ans=rec(k-1,sum1,arr[i+1:len(arr)],i+1) # so 2 cases in else loop
print(ans) # i is taken in as iterator to provide array
else: # input to rec func from 2nd element of array
ans=rec(k-1, sum1-arr[0], arr[i+1:len(arr)],i+1)+rec(k, sum1, arr[i+1:len(arr)],i+1)
#print('i: '+str(i)+' ans: '+str(ans))
return(ans)
a=[1,1,1,2,2]
print(rec(2,2,a))
I am still unable to process how to make changes. Once this normal recursive code is written I might go to DP approach accordinlgy.
Using itertools.combinations
Function itertools.combinations returns all the subsequences of a given lengths. Then we filter to keep only subsequences who sum up to the desired value.
import itertools
def countsubsum(a, k, s):
return sum(1 for c in itertools.combinations(a,k) if sum(c)==s)
Fixing your code
Your code looks pretty good, but there are two things that appear wrong about it.
What is this if for?
At first I was a bit confused about if(sum1<arr[0]):. I think you can (and should) always go to the else branch. After thinking about it some more, I understand you are trying to get rid of one of the two recursive calls if arr[0] is too large to be taken, which is smart, but this makes the assumption that all elements in the array are nonnegative. If the array is allowed to contain negative numbers, then you can include a large a[0] in the subsequence, and hope for a negative element to compensate. So if the array can contain negative numbers, you should get rid of this if/else and always execute the two recursive calls from the else branch.
You are slicing wrong
You maintain a variable i to remember where to start in the array; but you also slice the array. Pretty soon your indices become wrong. You should use slices, or use an index i, but not both.
# WRONG
ans=rec(k-1, sum1-arr[0], arr[i+1:len(arr)],i+1)+rec(k, sum1, arr[i+1:len(arr)],i+1)
# CORRECT
ans = rec(k-1, sum1-arr[i], arr, i+1) + rec(k, sum1, arr, i+1)
# CORRECT
ans = rec(k-1, sum1-arr[0], arr[1:]) + rec(k, sum1, arr[1:])
To understand why using both slicing and an index gives wrong results, run the following code:
def iter_array_wrong(a, i=0):
if (a):
print(i, a)
iter_array_wrong(a[i:], i+1)
def iter_array_index(a, i=0):
if i < len(a):
print(i, a)
iter_array_index(a, i+1)
def iter_array_slice(a):
if a:
print(a)
iter_array_slice(a[1:])
print('WRONG')
iter_array_wrong(list(range(10)))
print()
print('INDEX')
iter_array_index(list(range(10)))
print()
print('SLICE')
iter_array_slice(list(range(10)))
Also note that a[i:len(a)] is exactly equivalent to a[i:] and a[0:j] is equivalent to a[:j].
Clean version of the recursion
Recursively count the subsequences who use the first element of the array, and the subsequences who don't use the first element of the array, and add the two counts. To avoid explicitly slicing the array repeatedly, which is an expensive operation, we keep a variable start to remember we are only working on subarray a[start:].
def countsubsum(a, k, s, start=0):
if k == 0:
return (1 if s == 0 else 0)
elif start == len(a):
return 0
else:
using_first_element = countsubsum(a, k-1, s-a[start], start+1)
notusing_first_elem = countsubsum(a, k, s, start+1)
return using_first_element + notusing_first_elem
I apologize if this is a duplicate, I tried my best to find an existing question but was unsuccessful.
Recently, I've run into a couple of problems where I've needed to find the element in a list that produces the max/min value when a calculation is performed. For example, a list of real numbers where you want to find out which element produces the highest value when squared. The actual value of the squared number is unimportant, I just need the element(s) from the list that produces it.
I know I can solve the problem by finding the max, then making a pass through the list to find out which values' square matches the max I found:
l = [-0.25, 21.4, -7, 0.99, -21.4]
max_squared = max(i**2 for i in l)
result = [i for i in l if i**2 == max_squared]
but I feel like there should be a better way to do it. Is there a more concise/one-step solution to this?
This will return you just the element which gives the max when squared.
result = max(l, key = lambda k: k**2)
It does not get much better if you need the value in a list f.e. to see how often it occures. You can remeber the source element as well if you do not need that:
l = [-0.25, 21.4, -7, 0.99, -21.4]
max_squared = max( (i**2, i) for i in l) # remeber a tuple, with the result coming first
print(max_squared[1]) # print the source number (2nd element of the tuple)
Output:
21.4
Your calculation does only return the first occurence of abs(24.1) because max only returns one value, not two - if you need both, you still need to do:
print( [k for k in l if abs(k) == max_squared[1]])
to get
[21.4,-21.4]
I have the code below where in the function neural_net_trainer(p, a), the while-loop is meant to end/exit when the value of p is equal to the value of a. However, the loop keeps running infinitely.
Instead of while-loop I tried for-loop, to loop it 30 times (running the 'update' function each time), and 'p' eventually becomes equal to 'a'. But I need to use while-loop instead because I don't know how many times the loop will run. It's whenever 'p' will become equal to 'a'.
# 'p' represent prediction. 'a' represent actual output of Neural network.
#-- improving Neural Network prediction (using derivative of cost function) --
def slope(p, a):
return 2 * (p - a)
# --- Create the Update rule function (to correct prediction) ---
def update(p, a):
p = p - 0.1 * slope(p, a)
return p
# -- Train network - minimising the cost function until prediction is equal to actual output
# - In while loop, if 'p' is not equal to 'a', then 'update' function will increment/decrement 'p' accordingly, until 'p' == 'a'. While-loop should then exit.
def neural_net_trainer(p, a):
print('prediction = ' + str('{:.2f}'.format(p)) + '. Actual Output = ' + str('{:.2f}'.format(a)))
while p != a:
p = update(p, a)
print('prediction = ' + str('{:.2f}'.format(p)))
else:
print('Prediction = ' + str('{:.2f}'.format(p)) + ', and actual output = ' + str('{:.2f}'.format(a)) + '. Our Neural Network is trained on this dataset.')
# - Testing 'neural_net_trainer' function
a = 4
p = 3
neural_net_trainer(p, a)
Basically the code simulates functions of a very simple neural network, where the functions receive two values - p (the predicted output) and a (the actual output). In the code - the slope function is a formula needed to correct the prediction (to become equal to the actual output). update function does the updating/correction. And neural_net_trainer function uses a while-loop to run update function enough times, until p (prediction) is equal to a (actual output). At which point the while-loop should exit.
Any help would be really appreciated.
The problem here is that you're checking for exact equality and p - a never reaches the exact 0.
Try a weaker condition as a guard of the while loop, for example:
THRESHOLD = 1e-5
while abs(p - a) > THRESHOLD:
p is not reaching 4.0, it is merely reaching 3.999999999999999..., which gets rounded to 4.00 when you use {:.2f} to format it. p != a remains True because 4.0 != 3.999999999999999.
This is more of an algorithmic problem than a python problem, but perhaps round() will come in handy to solve this based on p approaching a instead of a fixed number of iterations.
I have a quadratic Matrix of size n, say A, with non-negative real entries a_ij.
Furthermore I have a permutation tree. For n = 3 it looks like this: .
Now I would like to do a Depth-search (I don't know really, whether "Depth-search" is the correct description for this, but let's use it for now) along the branches of the tree in the following way:
On the first partial tree on the very left do the following starting with an "empty" Permutation (x,x,x):
If a_12 > a_21 set (1,2,x) and then check whether a_23 > a_32. If this is true as well, save (1,2,3) in a list, say P. Then go back to the first Level and check whether a_13 > a_31 and so on.
If a_21 > a_12 or a_32 > a_23 do not save the Permutation in P and go back to the first Level and check whether a_13 > a_31. If this is true set (1,3,x) and then check whether a_23 > a_32. If this is true save (1,3,2) in P and continue with the next partial tree. If a_31 > a_13 or a_32 > a_23 do not save the Permutation in P and continue with the same procedure for the next partial tree.
This procedure/algorithm I would like to implement for an arbitrary natural n > 0 with Input just the Matrix A and n and as an Output all permutations of size n that fullfill these conditions. By now I am not able to implement this in a general way.
Preferably in Python, but Pseudo Code would be nice as well. I also want to avoid functions like "itertools Permutation", because in the use case I Need to apply this for large n, for example n = 100, and then itertools Permutation is very slow.
If I understand correctly, this should get you what you want:
import numpy as np
from itertools import permutations
def fluboxing_permutations(a, n):
return [p for p in permutations(range(n))
if all(a[i, j] > a[j, i] for i, j in zip(p, p[1:]))]
n = 3
a = np.random.random([n, n])
fluboxing_permutations(a, n)
itertools.permutations will yield permutations in lexicographical order, which corresponds to your tree; then we check that for each consecutive pair of indices in the permutation, the element in the matrix is greater than the element at swapped indices. If so, we retain the permutation.
(No idea how to describe what the function does, so I made a new name. Hope you like it. If anyone knows a better way to describe it, please edit! :P )
EDIT: Here's a recursive function that should do the same, but with pruning:
def fluboxing_permutations_r(a, n):
nset = set(range(n))
def inner(p):
l = len(p)
if l > 1 and a[p[-2]][p[-1]] <= a[p[-1]][p[-2]]:
return []
if l == n:
return [p]
return [r for i in nset - set(p)
for r in inner(p + (i,))]
return inner(())
p starts as empty tuple, but it grows in recursion. Once there's at least two elements in the partial permutation, we can test the last two elements and see if it fails the test, and reject it if it does (pruning its subtree out of the search space). If it is a full permutation that wasn't rejected, we return it. If it's not full yet, we append to it all possible indices that are not already in there, and recurse.
tinyEDIT: BTW, parameter n is kind of redundant, because n = len(a) at the top of the function should take care of it.