Get average difference between all numbers in a list (python) - 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

Related

How would I divide one list/array by another?

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))

Count mismatches in list of lists

i have two lists arr_list1 and arr_list2 which are both lists of lists. they are both exactly the same size. I need to count how many elements differ between the two, per list. for example,
arr_list1 = [[0,1,1],[0,1,0],[1,0,1]]
arr_list2 = [[0,1,0],[1,1,1],[1,0,1]]
I would like to get result = (1,2,0)
Is there a 'simple' way of doing this that doesnt require loops?
import numpy as np
arr_list1 = [[0,1,1],[0,1,0],[1,0,1]]
arr_list2 = [[0,1,0],[1,1,1],[1,0,1]]
print np.sum(np.asarray(arr_list1) != np.asarray(arr_list2),axis=1)
Just iterate two lists and use sum() method to count the mismatches
a1 = [[0,1,1],[0,1,0],[1,0,1]]
a2 = [[0,1,0],[1,1,1],[1,0,1]]
print [sum([a1[i][j]!=a2[i][j] for j in range(len(a1[i]))]) for i in range(len(a1))]
Output:
[1, 2, 0]
You can use zip to compare the differences:
arr_list1 = [[0,1,-1],[0,1,0],[1,0,1]]
arr_list2 = [[0,1,0],[1,1,1],[1,0,1]]
def get_differences(arr_list1, arr_list2):
all_differences = []
for a, b in zip(arr_list1, arr_list2):
sum_differences = 0
for a_item, b_item in zip(a, b):
if a_item != b_item:
sum_differences += 1
all_differences.append(sum_differences)
return all_differences
print get_differences(arr_list1, arr_list2)

for each gives different result?

I tried to add the comma seprated value between the : seprated then multiply the whole value
For example, consider my value is 1,2,3:4,5,6
I want to add the 1+2+3 ,and 4+5+6 then multiply the result of this value so answer is 6 * 15 = 90
For my bellow data i want the result is 7.224 but this script gives 61.658886435
I don't know what is the problem in my script'
ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
x_data = ar.split(":")
x_final = 1
x_add = 0
for i in x_data:
x_each = i.split(",")
for j in x_each:
x_add = x_add + float(j)
x_final = x_add * x_final
print x_final
Is any possible way to get the result without iterating loop? For above problem
This problem could be also solved in a functional way:
You have to multiply all values in the list - this is what functools.reduce + operator.mul for
You have to sum up all values in all inner lists - this is what sum for
Example:
In [5]: ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
In [6]: import operator
In [7]: import functools
In [8]: functools.reduce(operator.mul, (sum(float(x) for x in s.split(',')) for s in ar.split(':')))
Out[8]: 7.223521582500001
I don't necessarily recommend this complicated expression, but you can do it with list comprehensions and avoid the for loops:
import operator
ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
reduce(operator.mul, [sum([float(n) for n in e]) for e in [x.split(',') for x in ar.split(":")]], 1)
Use missed the initialize value as zero (x_add = 0) in each iterating. So your script add with the previous values
ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
x_data = ar.split(":")
x_final = 1
for i in x_data:
x_each = i.split(",")
x_add = 0 # Here you not initialize it
for j in x_each:
x_add = x_add + float(j)
x_final = x_add * x_final
print x_final
!!! As from #jpmc26 and #soon comment. Avoid using eval, and conform your input string format.
Without looping use regex for to do it
Use regex for solve your problem without looping.
ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
import re
ar = "("+ar #Add the ( with your data
ar = re.sub(r",","+",ar) #Substitute with + instead of ,
ar = re.sub(r"(?=\:|$)",")",ar) #look ahead for add `)` after colon
ar = re.sub(r"(?<=)\:","*(",ar) #Replace the color with *
#NOw you data look likes(0.212+1.231+0.112)*(1.001+3.212+0.002)*(0.002+0.0001+1.1)
#Finally evaluvate the string as a expression
print eval(ar)

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)

Create a Python list filled with the same string over and over and a number that increases based on a variable.

I'm trying to create a list that is populated by a reoccurring string and a number that marks which one in a row it is. The number that marks how many strings there will be is gotten from an int variable.
So something like this:
b = 5
a = range(2, b + 1)
c = []
c.append('Adi_' + str(a))
I was hoping this would create a list like this:
c = ['Adi_2', 'Adi_3', 'Adi_4', 'Adi_5']
Instead I get a list like this
c = ['Adi_[2, 3, 4, 5]']
So when I try to print it in new rows
for x in c:
print"Welcome {0}".format(x)
The result of this is:
Welcome Adi_[2, 3, 4, 5]
The result I want is:
Welcome Adi_2
Welcome Adi_3
Welcome Adi_4
Welcome Adi_5
If anybody has Ideas I would appreciate it.
You almost got it:
for i in a:
c.append('Adi_' + str(i))
Your initial line was transforming the whole list a as a string.
Note that you could get rid of the loop with a list comprehension and some string formatting:
c = ['Adi_%s' % s for s in a]
or
c = ['Adi_{0}'.format(s) for s in a] #Python >= 2.6
Or as a list comprehension:
b = 5
a = range(2, b + 1)
c = ["Adi_" + str(i) for i in a]
Using list comprehensions:
b = 5
a = range(2, b + 1)
c = ['Adi_'+str(i) for i in a]
for x in c:
print"Welcome {0}".format(x)
Or all on one line:
>>> for s in ['Welcome Adi_%d' % i for i in range(2,6)]:
... print s
...
Welcome Adi_2
Welcome Adi_3
Welcome Adi_4
Welcome Adi_5

Categories

Resources