Multiplying two sets of numbers in python - python

I have two lists of numbers, say [1, 2, 3, 4, 5] and [7, 8, 9, 10, 11], and I would like to form a new list which consists of the products of each member in the first list with each member in the second list. In this case, there would be 5*5 = 25 elements in the new list.
I have been unable to do this so far with a while() loop.
This is what I have so far:
x = 0
y = 99
results = []
while x < 5:
x = x + 1
results.append(x*y)
while y < 11:
y = y + 1
results.append(x*y)

Use itertools.product to generate all possible 2-tuples, then calculate the product of that:
[x * y for (x, y) in itertools.product([1,2,3,4,5], [7,8,9,10,11])]

The problem is an example of an outer product. The answer already posted with itertools.product is the way I would do this as well.
But here's an alternative with numpy, which is usually more efficient than working in pure python for crunching numeric data.
>>> import numpy as np
>>> x1 = np.array([1,2,3,4,5])
>>> x2 = np.array([7,8,9,10,11])
>>> np.outer(x1,x2)
array([[ 7, 8, 9, 10, 11],
[14, 16, 18, 20, 22],
[21, 24, 27, 30, 33],
[28, 32, 36, 40, 44],
[35, 40, 45, 50, 55]])
>>> np.ravel(np.outer(x1,x2))
array([ 7, 8, 9, 10, 11, 14, 16, 18, 20, 22, 21, 24, 27, 30, 33, 28, 32,
36, 40, 44, 35, 40, 45, 50, 55])

Wht dont you try with known old ways;
list1 = range(1, 100)
list2 = range(10, 50, 5)
new_values = []
for x in list1:
for y in list2:
new_values.append(x*y)

Without any importing, you can do:
[x * y for x in range(1, 6) for y in range(7, 12)]
or alternatively:
[[x * y for x in range(1, 6)] for y in range(7, 12)]
To split out the different multiples, but it depends which order you want the results in.

from functools import partial
mult = lambda x, y: x * y
l1 = [2,3,4,5,5]
l2 = [5,3,23,4,4]
results = []
for n in l1:
results.extend( map( partial(mult, n) , l2) )
print results

Related

Reversed returning same index if value is the same

This works fine for my purposes, except that when the value (in this case 20) is the same, it will only return the index from the front. Code is as follows, I'm not sure what the workaround is, but I need it to return the index of the value from reversed. I have some floats that would differ, but seem more difficult to work with.
lmt_lst = [-1, 5, 9, 20, 44, 37, 22, 20, 17, 12, 6, 1, -6]
lft_lmt = next(x for x in lmt_lst if x >=20)
rgt_lmt = next(x for x in reversed(lmt_lst) if x >= 20)
lft_idx = lmt_lst.index(lft_lmt)
rgt_lmt = lmt_lst.index(rgt_lmt)
print('Left Limit:', lft_lmt, 'Left Index:', lft_idx)
print('Right Limit:', rgt_lmt, 'Right Index:', rgt_idx)
If you change either of the values of '20' to 21, it works just fine
It does not return any errors, just returns the first index of the value, regardless of reversed
Your lft_lmt and rgt_lmt lists only contain values greater than or equal to 20, so your lists are [20, 44, 37, 22, 20] and [20, 22, 37, 44, 20] respectively.
>>> lmt_lst = [-1, 5, 9, 20, 44, 37, 22, 20, 17, 12, 6, 1, -6]
>>> [x for x in lmt_lst if x >=20]
[20, 44, 37, 22, 20]
>>> [x for x in reversed(lmt_lst) if x >= 20]
[20, 22, 37, 44, 20]
The first item of both of these lists is 20, and so when you search for them (using .index which searches from the beginning of the list) in the initial list you'll get 3 both times (because 20 is found at position 3 no matter how many times you search the list from beginning to end).
To find your right index you want to search the reversed list and account for the result being as if searching the list backwards:
>>> lft_idx = lmt_lst.index(lft_lmt)
>>> lft_idx
3
>>> rgt_idx = len(lmt_lst) - 1 - lmt_lst[::-1].index(rgt_lmt)
>>> rgt_idx
7

only print numbers in list between x and y

I'm trying to find out of there is a library I can use to identify if a number is between two numbers, or if I have to iterate through every number with a for loop and an if condition
def get_numbers_in_between(li, x, y):
# x can be bigger than y or vice versa
if x > y:
big = x
small = y
else:
big = y
small = x
nums_in_between = [n for n in li if (n >= small and n <= big)]
return nums_in_between
print(get_numbers_in_between([9, 10, 11, 15, 19, 20, 21], 20, 10))
output:
[10, 11, 15, 19, 20]
Is there a library that will automatically figure out which is bigger/smaller (x,y), and take the list as an input and return a new list with the numbers between?
if you start from a given list and need to extract the ones that satisfy a contition:
lst = [9, 10, 11, 15, 19, 20, 21]
print([n for n in lst if 10 <= n <= 20])
and if you need all the integers its just
list(range(10, 20+1))
if you need to sort the max an min first, this is an option:
def get_numbers_in_between(li, x, y):
mx, mn = sorted((x, y))
return [n for n in li if mx <= n <= mn]
print(get_numbers_in_between(li=[9, 10, 11, 15, 19, 20, 21], x=20, y=10))
Try this :
def get_numbers_in_between(l,x,y):
return [i for i in l if i in range(min(x,y), max(x,y)+1)]
get_numbers_in_between([9, 10, 11, 15, 19, 20, 21], 20, 10) # [10, 11, 15, 19, 20]
Could be as simple as suggested:
small = 8
big = 16
nums_in_between = [n for n in li if n in range(small, big)]
You can use filter,
>>> nums
[9, 10, 11, 15, 19, 20, 21]
>>> sorted_list = sorted(nums) # easier to find min, max ?
>>> min_, max_ = sorted_list[0], sorted_list[-1]
>>> filter(lambda x: min_ < x < max_, nums)
[10, 11, 15, 19, 20]
And there's is similar itertools.ifilter in python2,
>>> import itertools
>>> list(itertools.ifilter(lambda x: 10 <= x <= 20, nums))
[10, 11, 15, 19, 20]
And in itertools.filterfalse in python3,
>>> list(itertools.filterfalse(lambda x: not (10 <= x <= 20), nums))
[10, 11, 15, 19, 20]
with help from roganjosh - good one!
dat=np.random.randint(0,20,50)
x=5
y=10
ans=dat[(dat>=x) & (dat<y)]
print(ans)
old (with np.where):
import numpy as np
dat=np.random.randint(0,20,50)
x=5
y=10
ans=dat[np.where((dat>=x) & (dat<y))]
print(ans)
OP: automatically figure out which is bigger/smaller (x,y), and take the list as an input and return a new list with the numbers between?
Generic method:
def GetNumbersInBetween(lst, l_Bound, u_Bound):
n_List = []
lowerBound = min(l_Bound, u_Bound) # Get the lower val
upperBound = max(l_Bound, u_Bound) # Get the higher val
for x in lst:
if x >= lowerBound and x <= upperBound:
n_List.append(x)
return n_List
lst = [9, 10, 11, 15, 19, 20, 21]
lowerBound = 20 # intentionally given the wrong value
upperBound = 10 # intentionally given the wrong value
print(GetNumbersInBetween(lst, lowerBound, upperBound))
OR
Using list comprehension:
print([x for x in lst if min(lowerBound,upperBound) <= x <= max(lowerBound,upperBound)])
OUTPUT:
[10, 11, 15, 19, 20]

Pyschools Number Sequence

So i'm doing pyschools topic 6 question 23:
Write a function getNumbers(number) that takes in a number as argument and return a list of numbers as shown in the samples given below.
Examples
>>> getNumbers(10)
[100, 64, 36, 16, 4, 0, 4, 16, 36, 64, 100]
>>> getNumbers(9)
[81, 49, 25, 9, 1, 1, 9, 25, 49, 81]
>>> getNumbers(8)
[64, 36, 16, 4, 0, 4, 16, 36, 64]
>>> getNumbers(0)
[0]
This is my code:
def getNumbers(num):
x = []
y = []
if num % 2 == 0:
x = [i**2 for i in range(0, num+2, 2)]
y = [i**2 for i in range(0, num+2, 2)]
z = sorted(x, reverse=True) + y
if z.count(0) > 1:
z.remove(0)
return z
elif num % 3 == 0:
x = [i**2 for i in range(1, num+2, 2)]
y = [i**2 for i in range(1, num+2, 2)]
return sorted(x, reverse=True) + y
elif num == 1:
x.append(num)
y.append(num)
return sorted(x, reverse=True) + y
Which works but, i'm not passing Private Test Case. Any ideea why?
Private Test Case is something made by them to see if you hard code.
Test Cases Expected Result Returned Result
getNumbers(10) [100, 64, 36, 16, 4, 0, 4, 16, 36, 64, 100] [100, 64, 36, 16, 4, 0, 4, 16, 36, 64, 100]
getNumbers(9) [81, 49, 25, 9, 1, 1, 9, 25, 49, 81] [81, 49, 25, 9, 1, 1, 9, 25, 49, 81]
Private Test Cases Passed Failed
getNumbers(0) [0] [0]
getNumbers(1) [1, 1] [1, 1]
This was the easiest thing to do:
def getNumbers(num):
x = -num
y = list(range(x, num+1, 2))
return [i**2 for i in y]
getNumbers(10)
[100, 64, 36, 16, 4, 0, 4, 16, 36, 64, 100]
Also please find below a version
def getNumbers(num):
n=list(range(num+1))
num1=[]
x=num
for i in n:
x=num**2
num1.append(x)
num-=2
return num1
def getNumbers(num):
return [i * i for i in range(-num, num + 1, 2)]
Square of a number is always positive. You need to end the range on num + 1 to include number in the result. The range is iterable, so the list around range is spurious.

Python: How to range() multiple values from list or dictionary?

Im new to programming. Trying to range numbers - For example if i want to range more than one range, 1..10 20...30 50...100. Where i need to store them(list or dictionary) and how to use them one by one?
example = range(1,10)
exaple2 = range(20,30)
for b in example:
print b
or you can use yield from (python 3.5)
def ranger():
yield from range(1, 10)
yield from range(20, 30)
yield from range(50, 100)
for x in ranger():
print(x)
The range function returns a list. If you want a list of multiple ranges, you need to concatenate these lists. For example:
range(1, 5) + range(11, 15)
returns [1, 2, 3, 4, 11, 12, 13, 14]
Range module helps you to get numbers between the given input.
Syntax:
range(x) - returns list starting from 0 to x-1
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
range(x,y) - returns list starting from x to y-1
>>> range(10,20)
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>>
range(x,y,stepsize) - returns list starting from x to y-1 with stepsize
>>> range(10,20,2)
[10, 12, 14, 16, 18]
>>>
In Python3.x you can do:
output = [*range(1, 10), *range(20, 30)]
or using itertools.chain function:
from itertools import chain
data = [range(1, 10), range(20, 30)]
output = [*chain(*data)]
or using chain.from_iterable function
from itertools import chain
data = [range(1, 10), range(20, 30)]
output = [*chain.from_iterable(data)]
output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

Numpy: find index of the elements within range

I have a numpy array of numbers, for example,
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
I would like to find all the indexes of the elements within a specific range. For instance, if the range is (6, 10), the answer should be (3, 4, 5). Is there a built-in function to do this?
You can use np.where to get indices and np.logical_and to set two conditions:
import numpy as np
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.where(np.logical_and(a>=6, a<=10))
# returns (array([3, 4, 5]),)
As in #deinonychusaur's reply, but even more compact:
In [7]: np.where((a >= 6) & (a <=10))
Out[7]: (array([3, 4, 5]),)
Summary of the answers
For understanding what is the best answer we can do some timing using the different solution.
Unfortunately, the question was not well-posed so there are answers to different questions, here I try to point the answer to the same question. Given the array:
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
The answer should be the indexes of the elements between a certain range, we assume inclusive, in this case, 6 and 10.
answer = (3, 4, 5)
Corresponding to the values 6,9,10.
To test the best answer we can use this code.
import timeit
setup = """
import numpy as np
import numexpr as ne
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
# or test it with an array of the similar size
# a = np.random.rand(100)*23 # change the number to the an estimate of your array size.
# we define the left and right limit
ll = 6
rl = 10
def sorted_slice(a,l,r):
start = np.searchsorted(a, l, 'left')
end = np.searchsorted(a, r, 'right')
return np.arange(start,end)
"""
functions = ['sorted_slice(a,ll,rl)', # works only for sorted values
'np.where(np.logical_and(a>=ll, a<=rl))[0]',
'np.where((a >= ll) & (a <=rl))[0]',
'np.where((a>=ll)*(a<=rl))[0]',
'np.where(np.vectorize(lambda x: ll <= x <= rl)(a))[0]',
'np.argwhere((a>=ll) & (a<=rl)).T[0]', # we traspose for getting a single row
'np.where(ne.evaluate("(ll <= a) & (a <= rl)"))[0]',]
functions2 = [
'a[np.logical_and(a>=ll, a<=rl)]',
'a[(a>=ll) & (a<=rl)]',
'a[(a>=ll)*(a<=rl)]',
'a[np.vectorize(lambda x: ll <= x <= rl)(a)]',
'a[ne.evaluate("(ll <= a) & (a <= rl)")]',
]
rdict = {}
for i in functions:
rdict[i] = timeit.timeit(i,setup=setup,number=1000)
print("%s -> %s s" %(i,rdict[i]))
print("Sorted:")
for w in sorted(rdict, key=rdict.get):
print(w, rdict[w])
Results
The results are reported in the following plot for a small array (on the top the fastest solution) as noted by #EZLearner they may vary depending on the size of the array. sorted slice could be faster for larger arrays, but it requires your array to be sorted, for arrays with over 10 M of entries ne.evaluate could be an option. Is hence always better to perform this test with an array of the same size as yours:
If instead of the indexes you want to extract the values you can perform the tests using functions2 but the results are almost the same.
I thought I would add this because the a in the example you gave is sorted:
import numpy as np
a = [1, 3, 5, 6, 9, 10, 14, 15, 56]
start = np.searchsorted(a, 6, 'left')
end = np.searchsorted(a, 10, 'right')
rng = np.arange(start, end)
rng
# array([3, 4, 5])
a = np.array([1,2,3,4,5,6,7,8,9])
b = a[(a>2) & (a<8)]
Other way is with:
np.vectorize(lambda x: 6 <= x <= 10)(a)
which returns:
array([False, False, False, True, True, True, False, False, False])
It is sometimes useful for masking time series, vectors, etc.
This code snippet returns all the numbers in a numpy array between two values:
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56] )
a[(a>6)*(a<10)]
It works as following:
(a>6) returns a numpy array with True (1) and False (0), so does (a<10). By multiplying these two together you get an array with either a True, if both statements are True (because 1x1 = 1) or False (because 0x0 = 0 and 1x0 = 0).
The part a[...] returns all values of array a where the array between brackets returns a True statement.
Of course you can make this more complicated by saying for instance
...*(1-a<10)
which is similar to an "and Not" statement.
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.argwhere((a>=6) & (a<=10))
Wanted to add numexpr into the mix:
import numpy as np
import numexpr as ne
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.where(ne.evaluate("(6 <= a) & (a <= 10)"))[0]
# array([3, 4, 5], dtype=int64)
Would only make sense for larger arrays with millions... or if you hitting a memory limits.
This may not be the prettiest, but works for any dimension
a = np.array([[-1,2], [1,5], [6,7], [5,2], [3,4], [0, 0], [-1,-1]])
ranges = (0,4), (0,4)
def conditionRange(X : np.ndarray, ranges : list) -> np.ndarray:
idx = set()
for column, r in enumerate(ranges):
tmp = np.where(np.logical_and(X[:, column] >= r[0], X[:, column] <= r[1]))[0]
if idx:
idx = idx & set(tmp)
else:
idx = set(tmp)
idx = np.array(list(idx))
return X[idx, :]
b = conditionRange(a, ranges)
print(b)
s=[52, 33, 70, 39, 57, 59, 7, 2, 46, 69, 11, 74, 58, 60, 63, 43, 75, 92, 65, 19, 1, 79, 22, 38, 26, 3, 66, 88, 9, 15, 28, 44, 67, 87, 21, 49, 85, 32, 89, 77, 47, 93, 35, 12, 73, 76, 50, 45, 5, 29, 97, 94, 95, 56, 48, 71, 54, 55, 51, 23, 84, 80, 62, 30, 13, 34]
dic={}
for i in range(0,len(s),10):
dic[i,i+10]=list(filter(lambda x:((x>=i)&(x<i+10)),s))
print(dic)
for keys,values in dic.items():
print(keys)
print(values)
Output:
(0, 10)
[7, 2, 1, 3, 9, 5]
(20, 30)
[22, 26, 28, 21, 29, 23]
(30, 40)
[33, 39, 38, 32, 35, 30, 34]
(10, 20)
[11, 19, 15, 12, 13]
(40, 50)
[46, 43, 44, 49, 47, 45, 48]
(60, 70)
[69, 60, 63, 65, 66, 67, 62]
(50, 60)
[52, 57, 59, 58, 50, 56, 54, 55, 51]
You can use np.clip() to achieve the same:
a = [1, 3, 5, 6, 9, 10, 14, 15, 56]
np.clip(a,6,10)
However, it holds the values less than and greater than 6 and 10 respectively.

Categories