How would I divide one list/array by another? - python

For example, I have gathered a list of the lowest numbers of a list and I need to divide them by each other but repeat themselves down the list similar to a Cartesian product.
Not exact code below, but similar. Exact code would just be confusing if I posted it.
lowestnumbers = [2,3,4,5,6,7,8]
highestnumbers = [2,3,4,5,6,7,8]
for matchhigh in highestnumbers:
print (matchhigh)
for matchlow in lowestnumbers:
print (matchlow)
percentage = (matchlow / matchhigh - 1.0)
print (percentage)
When I've done this, it repeats the last number of from "matchhigh" and repeatedly divides itself by that last number.
I need something to do something along the lines of below and I'm completely lost.
list1 = [1,2,3]
list2 = [3,2,1]
for number in list1
answer = number / list2
print = answer
Desired Output:
0.3333333333333333
0.5
1
0.6666666666666667
1
2
1
1.5
3
Please let me know if there is a solution to the issue I am having, it's driving me insane.

A nested loop will do:
>>> list1 = [1,2,3]
>>> list2 = [3,2,1]
>>> for x1 in list1:
... for x2 in list2:
... print(x1/x2) # Python3
... print(float(x1)/x2) # Python2
Or itertools.product:
>>> from itertools import product
>>> for x1, x2 in product(list1, list2):
... print(x1/x2) # Python3
... print(float(x1)/x2) # Python2
0.3333333333333333
0.5
1.0
0.6666666666666666
1.0
2.0
1.0
1.5
3.0

from itertools import product
div_list = [a / b for a, b in product(list1, list2)]
print('\n'.join(str(x) for x in div_list))

Related

how to remove python list cage

Like this, let's assume I have a script like this:
a = ['a','b','c','d','e']
b = random.choices(a)
print (b)
if you run that that will show like this right
['*random range a until e']
what I want the list change from this ['*random range a until e'] to '*random range a until we' can anyone help me
random.choices(), returns a LIST, as you can read here - https://www.w3schools.com/python/ref_random_choices.asp
So workaround would be to do it like this:
import random
a = ['a','b','c','d','e']
n = random.randint(0, len(a) - 1) # The randint() takes in 2 parameters, the
#lowest and the highest choice, the highest here is the length of a list
b = a[n]
print(b)
You need to join the letters obtained from random.choices.
With the argument k=<size> you can specify the length of the generated string.
>>> import random
>>> a = ['a','b','c','d','e']
>>> size = 10
>>> b = "".join(random.choices(a, k=size))
>>> b
'caccbbaade'

Get average difference between all numbers in a list (python)

I have a list where I'd like to get a sense of the difference between all the numbers in it. Algorithmically, it seems like I should take the absolute value of the subtraction of each item from a list from each other and then to find the average of the sum of subtractions. Don't worry about absolute value part. That's only relevant to my application.
For example:
list_a = [1,2,3,4]
list_a0 = (abs(1-2) + abs(1-3) + abs(1-4))/3 = 1+2+3 = 2
list_a1 = (abs(2-1) + abs(2-3) + abs(2-4))/3 = 1+1+2 = 1.33
list_a2 = (abs(3-1) + abs(3-2) + abs(3-4))/3 = 2+1+1 = 1.33
list_a3 = (abs(4-1) + abs(4-2) + abs(4-3))/3 = 3+2+1 = 2
avg = (lista0 + lista1 + lista2 + lista3)/4 = 1.67
I'm newer to python. Would someone be able to give a tip on how to loop through list_a to do this?
Consider using numpy package which is super efficient and rubust.
here is example:
>>> import numpy as np
>>> list_a = [1,2,3,4]
>>> a = np.array(list_a)
>>> np.diff(a)
[1,1,1]
takes 9.489059448242188e-05 seconds which is 0.00009 second
From your example, it appears that you are trying to loop over all permutations of the list of length 2. Luckily, itertools has a function just for that:
>>> import itertools
>>> list_a = [1,2,3,4]
>>> diffs = [abs(e[1] - e[0]) for e in itertools.permutations(list_a, 2)]
>>> sum(diffs)/len(diffs)
1.6666666666666667
If you don't want to use itertools, I advise using a for loop rather than trying to squish this into a nested list comprehension:
>>> list_a = [1,2,3,4]
>>> diffs = []
>>> for i, e in enumerate(list_a):
for j, f in enumerate(list_a):
if i != j: diffs.append(abs(e-f))
>>> sum(diffs)/len(diffs)
1.6666666666666667

Python: how to find intersection of two lists (i need a lenght of intersection, actually) if there are duplicates?

Let me have thse two lists:
a = ['a','b','c','a','a']
b = ['a','b','d']
I need to calculate Jaccard distance = (union-intersect)/union, but I know there gonna be duplicates in each list, and I want to count them, so intersect lenght for the example would be 2 and Jaccard distance = (8-2)/8
How can I do that? first thought is to joint lists and then remove elements one by one...
UPDATE:
probably I had to stress more that I need to count dublicates;
here is my working solution, but it is quite ugly:
a = [1,2,3,1,1]
b = [2,1,1, 6,5]
import collections
aX = collections.Counter(a)
bX = collections.Counter(b)
r1 = [x for x in aX if x in bX]
print r1
print sum((min(aX[x], bX[x]) for x in r1))
>>> 3
a = ['a','b','c','a','a']
b = ['a','b','d']
c = list(set(b).intersection(a))
['a','b']
Note sets will discard duplicates!
To the get the jaccard index between two lists a and b:
def jaccard_distance(a,b):
a = set(a)
b = set(b)
c = a.intersection(b)
return float(len(a) + len(b) - len(c)) /(len(a) + len(b))
here is my working solution, but it is quite ugly:
a = [1,2,3,1,1]
b = [2,1,1, 6,5]
import collections
aX = collections.Counter(a)
bX = collections.Counter(b)
r1 = [x for x in aX if x in bX]
print r1
print sum((min(aX[x], bX[x]) for x in r1))
>>> 3

Python for() loop with math operators

Say I have a list of numbers such as:
my_list = [1, 17, 2]
And I wanted to add those together. I know I can use print(sum(my_list)). However I wanted to see if there was another way of doing so, so I tried the following:
b = len(my_list)
for m in range(my_list[0], my_list[b-1]):
m += m
print(m)
I am sure something like this should work, but I am obviously doing it wrong. The output of this is 2. After I tried:
result = 0
b = len(my_list)
for m in range(my_list[0], my_list[b-1]):
result = result + m
print(result)
This outputs 1.
Please explain what I am doing wrong and how I can correct it.
Since you are using range function defining range between 1 and 2. The only data generated in m is 1 hence result is 1.
In Python, you can iterate over the elements of a sequence directly:
m = [1, 17, 2]
res = 0
for i in m:
res += i
print res
First, you should put a correct range: 0..2 in your case (since your list items' indexes starts from 0 and has 2 items)
for i in range(0, b):
result = result + my_list[i];
Or if you prefer "for each" style you should itterate by list you are summing:
for m in my_list:
result = result + m;
Finally if you want to print a final sum only you should correct print indent:
for m in my_list:
result = result + m;
print(result) # <- mind indent
Wrapping up:
my_list = [1, 17, 2]
result = 0
for m in my_list:
result = result + m;
print(result)
from operator import add
my_list = [1, 17, 2]
result=reduce(add, my_list)
import functools
print(functools.reduce(lambda x,y: x+y, my_list))
try this
my_list = [1, 17, 2]
reduce(lambda x, y: x+y, my_list)
to get the values from my_list you can use this syntax:
for m in my_list:
print m
If you use range it will give you a range from 1 ( first value of your list ) to 2 (length of your list -1)
To add the values of your list you can try this code:
out = 0
for m in my_list:
out = out + m
print(out)

How can I infinitely loop an iterator in Python, via a generator or other?

It's my understanding that using a Generator is the best way to achieve something like this, but I'm open to suggestions.
Specifically, one use case is this: I'd like to print some items alongside another list, of an arbitrary length, truncating the initial iterator as necessary.
Here is working python code that demonstrates the exact example behavior I desire:
def loop_list(iterable):
"""
Return a Generator that will infinitely repeat the given iterable.
>>> l = loop_list(['sam', 'max'])
>>> for i in range(1, 11):
... print i, l.next()
...
1 sam
2 max
3 sam
4 max
5 sam
6 max
7 sam
8 max
9 sam
10 max
>>> l = loop_list(['sam', 'max'])
>>> for i in range(1, 2):
... print i, l.next()
...
1 sam
"""
iterable = tuple(iterable)
l = len(iterable)
num = 0
while num < l:
yield iterable[num]
num += 1
if num >= l:
num = 0
The Problem / My Question
As you may have noticed, this only works on lists/tuples/iterables that implement __getitem__ (if I'm not mistaken). Ideally, I'd like to be able to pass any iterable, and receive a generator that can properly loop over it's content.
If there's a better way to do something like this without a generator, I'm fine with that as well.
You can use itertools.cycle (source included on linked page).
import itertools
a = [1, 2, 3]
for element in itertools.cycle(a):
print element
# -> 1 2 3 1 2 3 1 2 3 1 2 3 ...
Try this-
L = [10,20,30,40]
def gentr_fn(alist):
while 1:
for j in alist:
yield j
a = gentr_fn(L)
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()
>>gentr_fn(x,y)
10 20 30 40 10 20 30 ...
You can use module to keep it simple.
Just make sure not to start iterating from 0.
my_list = ['sam', 'max']
for i in range(1, 100):
print(my_list[(i % len(my_list))-1])
You can iterate over a list, appending an item to it:
somelist = [item1, item2, item3]
for item in somelist:
somelist.append(item)
do_something()

Categories

Resources