Find multiples of a number in list - python-3.x

I have a list and I want to find all the multiples of that number within a certain tolerance as well as get their indices:
def GetPPMError(t, m):
"""
calculate theoretical (t) and measured (m) ppm
"""
return (((t - m) / t) * 1e6)
multiple = n*1.0033
a = 100
b = [100, 101, 101.0033,102, 102.0066,102.123,103.0099]
results = [p for p in b if abs(GetPPMError(a,b)) < 10]
So I want to find all the multiples like 102.0066 and 103.0099 etc.
where a = 100 + 1*1.0033, a = 100 + 2*1.0033, a = 100 + 3*1.0033 etc
So the result would be the indexes.
Results for the indexes:
[2, 4, 6]
and:
[101.0033, 102.0066, 103.0099]
for the values.

This works for your data:
multiple = 1.0033
a = 100
digits = 6
res = []
res_index = []
for n, x in enumerate(b):
diff = round((x - a) / multiple, digits)
if diff != 0 and diff == int(diff):
res.append(x)
res_index.append(n)
print(res)
print(res_index)
Output:
[101.0033, 102.0066, 103.0099]
[2, 4, 6]

Related

Multiplication of polynomials

I have polynomial coefficients. How to get a list of coefficients e.g. by multiplying 10 polynomials?
For example for two polynomials.
(x + 2)*(x + 2) = x^2 + 4x + 4
[1,2] * [1,2] = [1, 4, 4]
I am trying to solve a codewars task which gives me a list of roots and I have to return a polynomial.
My first idea was function from numpy, poly but there is too much difference with large numbers. Thank u!
Source: https://www.codewars.com/kata/5b2d5be2dddf0be5b00000c4
My code:
import re
from numpy import poly
from math import fabs
def polynomialize(roots):
result = ''
data = list(filter(lambda x : x[0] != 0, zip(poly(roots).tolist(), range(len(roots), -1, -1))))
for coe, power in data:
if coe > 0:
result += f'+ {int(coe)}x^{power} '
else:
result += f'- {int(fabs(coe))}x^{power} '
result = re.sub(r'(x\^1)(?![0-9]+)', 'x', result).replace('x^0', '')
result = re.sub(r'(?<![0-9])(1x)','x', result)
return result[2:] + '= 0'
This is likely related to the integer type that numpy uses in its arrays, while the inputs and the resulting coefficients may involve greater numbers than these integers can hold (wrapping around).
You could do this to get data:
coeff = [1]
for r in roots:
coeff = [t[1] - r * t[0] for t in zip(coeff + [0], [0] + coeff)]
data = list(filter(lambda x : x[1] != 0,
reversed(list(enumerate(coeff)))))
for power, coe in data: # notice the pairs are in reverse compared to your loop
Also fabs is limited to integer. I would change int(fabs(coe)) to -int(coe).
I submitted this solution and it was accepted:
import re
def polynomialize(roots):
coeff = [1]
for r in roots:
coeff = [t[1] - r * t[0] for t in zip(coeff + [0], [0] + coeff)]
data = list(filter(lambda x : x[1] != 0,
reversed(list(enumerate(coeff)))))
result = ''
for power, coe in data:
if coe > 0:
result += f'+ {int(coe)}x^{power} '
else:
result += f'- {-int(coe)}x^{power} '
result = re.sub(r'(x\^1)(?![0-9]+)', 'x', result).replace('x^0', '')
result = re.sub(r'(?<![0-9])(1x)','x', result)
return result[2:] + '= 0'
Is it what you want?
from sympy import symbols, Poly
x = symbols("x")
pol1 = Poly(x + 2)
pol = pol1 ** 2
pol.all_coeffs()
# [1, 4, 4]

How to Sort a table of strings according to the order defined by another table of strings (Lua)

I have 2 lua tables:
OrderTbl = {'Hello', 'Question', 'Answer', 'Bye'}
UnsortedTbl = {'Question', 'Bye, 'Bye', 'Question', 'Hello', 'Something'}
How to sort UnsortedTbl in order given by OrderTbl? (Fields not found in OrderTbl are placed in the end of result table, unsorted)
I have translated a sample of code from Java, and it works with numbers. Here it is:
function first(arr, low, high, x, n)
if high >= low then
-- (low + high)/2
local mid = low + math.floor((high - low) / 2)
if (mid == 1 or x > arr[mid - 1]) and arr[mid] == x then
return mid
end
if x > arr[mid] then return first(arr, (mid + 1), high, x, n) end
return first(arr, low, (mid - 1), x, n)
end
return nil
end
-- Sort A1 according to the order
-- defined by A2
function sortAccording(A1, A2)
local m=#A1
local n=#A2
-- The temp array is used to store a copy
-- of A1{} and visited{} is used to mark the
-- visited elements in temp{}.
local temp = {}
local visited = {}
for i = 1, m do
temp[i] = A1[i]
visited[i] = 0
end
-- Sort elements in temp
table.sort(temp)
-- for index of output which is sorted A1{}
local ind = 0
-- Consider all elements of A2{}, find them
-- in temp{} and copy to A1{} in order.
for i = 1, n do
-- Find index of the first occurrence
-- of A2[i] in temp
local f = first(temp, 1, m, A2[i], m+1)
-- If not present, no need to proceed
if not f then
-- continue
else
-- Copy all occurrences of A2[i] to A1{}
j = f
while j < m and temp[j] == A2[i] do
A1[ind] = temp[j]
ind = ind + 1
visited[j] = 1
j = j + 1
end
end
end
-- Now copy all items of temp{} which are
-- not present in A2{}
for i = 1, m do
if visited[i] == 0 then
ind = ind + 1
A1[ind] = temp[i]
end
end
end
function printArray(arr)
for i = 1, #arr do
print(arr[i] .. " ")
end
end
-- Driver program to test above function.
local A1 = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
local A2 = {2, 1, 4, 3, 6, 5, 8, 7}
sortAccording(A1, A2)
printArray(A1)
I don't quite understand how to make it work with strings. Could you help me?
You can use the form of table.sort that accepts a custom comparator:
local OrderTbl = {'Hello', 'Question', 'Answer', 'Bye'}
local UnsortedTbl = {'Question', 'Bye', 'Bye', 'Question', 'Hello', 'Something', 'Else'}
-- convert the order to hash that can be easily queried
for idx, val in ipairs(OrderTbl) do OrderTbl[val] = idx end
local maxIdx = #OrderTbl + 1 -- this will mark "missing" elements
-- pass a custom comparator that will check OrderTbl
table.sort(UnsortedTbl, function(a, b)
local pa = OrderTbl[a] or maxIdx -- desired index of a
local pb = OrderTbl[b] or maxIdx -- desired index of b
if pa == pb then return a < b end -- sort by name
return pa < pb -- sort by index
end)

Sum of Two Arrays - Python

Two random integer arrays/lists have been given as ARR1 and ARR2 of size N and M respectively. Both the arrays/lists contain numbers from 0 to 9(i.e. single digit integer is present at every index). The idea here is to represent each array/list as an integer in itself of digits N and M.
You need to find the sum of both the input arrays/list treating them as two integers and put the result in another array/list i.e. output array/list will also contain only single digit at every index.
NOTE:
The sizes N and M can be different.
Output array/list(of all 0s) has been provided as a function argument. Its size will always be one more than the size of the bigger array/list. Place 0 at the 0th index if there is no carry.
No need to print the elements of the output array/list.
def sumOfTwoArrays(arr1, n, arr2, m, output) :
#Your code goes here
#Taking Input Using Fast I/O
def takeInput() :
n = int(stdin.readline().rstrip())
if n == 0 :
return list(), 0
arr = list(map(int, stdin.readline().rstrip().split(" ")))
return arr, n
#to print the array/list
def printList(arr, n) :
for i in range(n) :
print(arr[i], end = " ")
print()
#main
t = int(stdin.readline().rstrip())
while t > 0 :
arr1, n = takeInput()
arr2, m = takeInput()
outputSize = (1 + max(n, m))
output = outputSize * [0]
sumOfTwoArrays(arr1, n, arr2, m, output)
printList(output, outputSize)
t -= 1
Sample Input:
1
3
6 2 4
3
7 5 6
Sample Output:
1 3 8 0
This problem can be solved by a simple function like this:
(Note - you can made adjustment on the last line of return result if needed to meet the "strange requirement" of - 'place 0 at the 0th index if there is no carry'. It's left as a trivial exercise. )
def sum_two_array(L1, L2):
carry, total = 0, 0
m, n = len(L1), len(L2)
k = max(m, n)
result = [0] + [0] * k # add +1
for i in range(1, k+1):
a = L1[m-i] if m - i >= 0 else 0
b = L2[n-i] if n - i >= 0 else 0
total = a + b + carry
result[k-i + 1] = total % 10
carry = total // 10
if carry > 0: result[0] = carry
return result if result[0] != 0 else result[1:]
if __name__ == '__main__':
L1 = [6, 4, 4]
L2 = [7, 5, 6]
print(sum_two_array(L1, L2)) # [1, 4, 0, 0]
print(sum_two_array([6, 2, 4], [7, 5, 6])) # [1, 3, 8, 0]
print(sum_two_array([1, 2, 4], [8, 0])) # [2, 0, 4]
JAVA CODE:
import java.lang.Math;
public class Solution {
public static void sumOfTwoArrays(int arr1[], int arr2[], int output[]) {
int n = arr1.length; //size of arr1
int m = arr2.length; //size of arr2
int o = n+1; //size of output array
int sum1 = 0, sum2=0, totalSum=0;
//storing sum of arr1 in sum1
for(int i=0; i<n; i++)
{
sum1+= arr1[i] * Math.pow(10,(n-1-i));
}
//storing sum of arr2 in sum2
for(int i=0; i<m; i++)
{
sum2+= arr2[i] * Math.pow(10, (m-1-i));
}
totalSum = sum1+sum2;
//storing totalSum in reverse order in output array
for(int i=o-1; i>=0; i--)
{
output[i] = totalSum % 10;
totalSum = totalSum/10;
}
}
}
Explanation:
condition: arr1[n], arr2[m], output[n+1]
Instead of calculating sum of unit, tens, and so on digits of both the arrays.
we first calculate the sum1 of arr1, and sum2 of arr2, by using:
number at index * (10 ^ ((n-1) - index)) concept.
sum1 and sum2 are equal to the n and m sized numbers of respective arrays
we store totalSum = sum1+sum2
we store totalSum's every digit in output[n+1] array
we store it in reverse order by using % and / operations

Start counting indexes from 1 instead of 0 of a list

I created a program to get the the max value of a list and the position of its occurrences (list starting at indexing with 1 not 0) but I can't manage to find any useful solutions.
The input is always a string of numbers divided by zero.
This is my code:
inp = list(map(int,input().split()))
m = max(inp)
count = inp.count(m)
print(m)
def maxelements(seq): # #SilentGhost
return [i for i, j in enumerate(seq) if j == m]
print(maxelements(inp))
I expect to output the maximum value and then all the positions of its occurrences. (also is it possible to do without brackets as in the example below?)
Input: 4 56 43 45 2 56 8
Output: 56
2 6
If you want to shift index values, you could just do
return [i + 1 for i, j in enumerate(seq) if j == m]
more generally any transformation of i or j!
def f(i, j):
# do whatever you want, and return something
return i + 1
return [f(i, j) for i, j in enumerate(seq) if j == m]
Without brackets, as a string:
return " ".join(str(i + 1) for i, j in enumerate(seq) if j==m)
Specifiy start=1 with enumerate():
>>> l = [4, 56, 43, 45, 2, 56, 8]
>>> max_num = max(l)
>>> [i for i, e in enumerate(l, start=1) if e == max_num]
[2, 6]
By default enumerate() uses start=0, because indices start at 0.

How to find median of a list using indexing

I am trying to define a function, median, that consumes a list of numbers and returns the median number from the list. If the list is empty, then I want to return None. To calculate the median, I need to find the middle index of the list after it has been sorted. Do not use a built-in function.
SURVEY_RESULTS = [1.5, 1, 2, 1.5, 2, 3, 1, 1, 1, 2]
def median(SURVEY_RESULTS):
length = 0
order = sorted(SURVEY_RESULTS)
I'm not sure how to use indexing to now determine the median.
Here is my implementation:
def QuickSort(myList,start,end):
if start < end:
i,j = start,end
base = myList[i]
while i < j:
while (i < j) and (myList[j] >= base):
j = j - 1
myList[i] = myList[j]
while (i < j) and (myList[i] <= base):
i = i + 1
myList[j] = myList[i]
myList[i] = base
QuickSort(myList, start, i - 1)
QuickSort(myList, j + 1, end)
return myList
def median(l):
half = len(l) // 2
return (l[half] + l[~half])/2 # Use reverse index
SURVEY_RESULTS = [1.5, 1, 2, 1.5, 2, 3, 1, 1, 1, 2]
# Sort first
QuickSort(SURVEY_RESULTS, 0, len(SURVEY_RESULTS)-1)
result = median(SURVEY_RESULTS)
print (result)

Resources