taking averages of certain indices using another list in python - python-3.x

I was hoping to take the average of a list using another list with the start and stop indices.
for example:
a = [3, 9]
b = [0, 1, 12, 9, 0, 8, 9, 3, 3, 5, 7, 1, 4, 6, 6]
I want to take the average of the numbers from b[3] to b[9] and this is what I have so far
counter = a[0]
sum = b[counter]
while counter < a[1] + 1:
counter += 1
sum = sum + b[counter]
denominator = a[1] - a[0] + 1
avg = sum/denominator
But after checking, it seems to be giving the wrong thing

you could use statistics.mean
from statistics import mean
a = [3, 9]
b = [0, 1, 12, 9, 0, 8, 9, 3, 3, 5, 7, 1, 4, 6, 6]
mean(b[a[0]: a[1] + 1])
or you could use:
sum(b[a[0]: a[1] + 1]) / len(b[a[0]: a[1] + 1])

I would suggest the following:
from statistics import mean
a = [3, 9]
b = [0, 1, 12, 9, 0, 8, 9, 3, 3, 5, 7, 1, 4, 6, 6]
avg = mean(b[a[0]:a[1]+1])
print (avg)

Related

How to append item to match the length of two list in Python

I am working on a Python script which is connected to a server. Every x min, server returns two list but the length of these list is not same. For ex:
a = [8, 10, 1, 34]
b = [4, 6, 8]
As you can see above that a is of length 4 and b is of length 3. Similarly, sometimes it returns
a = [3, 6, 4, 5]
b = [8, 3, 5, 2, 9, 3]
I have to write a logic where I have to check if length of these two list is not same, then add the 0 at the end of the list which is smaller than other list. So for ex, if input is:
a = [3, 6, 4, 5]
b = [8, 3, 5, 2, 9, 3]
then output will be:
a = [3, 6, 4, 5, 0, 0]
b = [8, 3, 5, 2, 9, 3]
What can I try to achieve this?
def pad(list1, list2):
# make copies of the existing lists so that original lists remain intact
list1_copy = list1.copy()
list2_copy = list2.copy()
len_list1 = len(list1_copy)
len_list2 = len(list2_copy)
# find the difference in the element count between the two lists
diff = abs(len_list1 - len_list2)
# add `diff` number of elements to the end of the list
if len_list1 < len_list2:
list1_copy += [0] * diff
elif len_list1 > len_list2:
list2_copy += [0] * diff
return list1_copy, list2_copy
a = [3, 6, 4, 5]
b = [8, 3, 5, 2, 9, 3]
# prints: ([3, 6, 4, 5, 0, 0], [8, 3, 5, 2, 9, 3])
print(pad(a, b))
a = [8, 10, 1, 34]
b = [4, 6, 8]
# prints: ([8, 10, 1, 34], [4, 6, 8, 0])
print(pad(a, b))
For now, I can suggest this solution:
a = [3, 6, 4, 5]
b = [8, 3, 5, 2, 9, 3]
# Gets the size of a and b.
sizeA, sizeB = len(a), len(b)
# Constructs the zeros...
zeros = [0 for _ in range(abs(sizeA-sizeB))]
# Determines whether a or b needs to be appended with 0,0,0,0...
if sizeA < sizeB:
a += zeros
else:
b += zeros
print(a,b)
You should use extend instead of append. This is the way to add a list to another list in Python. The list here is the list of zeros.
a = [3, 6, 4, 5, 9, 3]
b = [8, 3, 5, 2]
lenA, lenB = len(a), len(b)
diff=abs(len(a)-len(b))
if lenA < lenB:
a.extend([0]*diff)
else:
b.extend([0]*diff)
print(a)
print(b)
You could also try to use more_itertools padded() method:
It's prob. more elegant and adaptable for future Use cases.
Notes: just need to do pip install more_itertools first.
# simple example to demo it:
from more_itertools import padded
print(list(padded([1, 2, 3], 0, 5))) # last num: 5 is the numbers of 0 to be padded to make the total length to be 5. (needs 2 zeros)
# [1, 2, 3, 0, 0]
# more examples:
>>> L = [1, 2, 3]
>>> K = [3, 4, 5, 6, 8, 9]
>>> gap = len(K) - len(L)
# 3
# shorter list is L
>>>list(padded(L, 0, len(L) + gap))
[1, 2, 3, 0, 0, 0]

Apply if statement on multiple lists with multiple conditions

I would like to append ids to a list which meet a specific condition.
output = []
areac = [4, 4, 4, 4, 1, 6, 7,8,9,6, 10, 11]
arean = [1, 1, 1, 4, 5, 6, 7,8,9,10, 10, 10]
id = [1, 2, 3, 4, 5, 6, 7,8,9,10, 11, 12]
dist = [2, 2, 2, 4, 5, 6, 7.2,5,5,5, 8.5, 9.1]
for a,b,c,d in zip(areac,arean,id,dist):
if a >= 5 and b==b and d >= 3:
output.append(c)
print(comp)
else:
pass
The condition is the following:
- areacount has to be >= 5
- At least 3 ids with a distance of >= 3 with the same area_number
So the id output should be [10,11,12].I already tried a different attempt with Counter that didn't work out. Thanks for your help!
Here you go:
I changed the list names to something more descriptive.
output = []
area_counts = [4, 4, 4, 4, 1, 6, 7, 8, 9, 6, 10, 11]
area_numbers = [1, 1, 1, 4, 5, 6, 7, 8, 9, 10, 10, 10]
ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
distances = [2, 2, 2, 4, 5, 6, 7.2, 5, 5, 5, 8.5, 9.1]
temp_numbers, temp_ids = [], []
for count, number, id, distance in zip(counts, numbers, ids, distances):
if count >= 5 and distance >= 3:
temp_numbers.append(number)
temp_ids.append(id)
for (number, id) in zip(temp_numbers, temp_ids):
if temp_numbers.count(number) == 3:
output.append(id)
output will be:
[10, 11, 12]

Finding elements in specific index between two lists using a function or other

How do I define a function where for a and b it would return 7 and 5
or a[0] and b[0] and a[4] and b[4]. The problem is the length of both lists could change at any time...
I've tried:
if a[0]== b[0]:
print(a[0])
but if the length of lists changes then it would eventually return a list Index out of range error.
Any help is much appreciated.
a = [7, 5, 9, 3, 5, 3, 6, 7, 8, 4, 3, 3, 4, 5]
b = [7, 3, 3, 5, 5, 2, 1, 5, 2, 5, 2, 9, 8, 6]
Zip two lizts with zip and iterate over it:
a = [7, 5, 9, 3, 5, 3, 6, 7, 8, 4, 3, 3, 4, 5]
b = [7, 3, 3, 5, 5, 2, 1, 5, 2, 5, 2, 9, 8, 6]
for a_i, b_i in zip(a, b):
if a_i == b_i:
print(a_i, b_i)
Out:
7, 7
5, 5
or define it as a fiunction:
def extract_matches(a, b):
result = []
for a_i, b_i in zip(a, b):
if a_i == b_i:
result.append((a_i, b_i))
return result
matches = extract_matches(a, b)
matches
Out:
[(7, 7), (5, 5)]
How the zip works. zip function always zips lists by shorter. It returns a generator, so you should iterate it:
list(zip([1,2,3], [1,2]))
Out:
[(1, 2), (1, 2)] # list of pairs
list(zip([], [1,2,3]))
Out:
[] # length of shorter is 0, so you get zero length list

How to sum an output in Python

The program below will create a list of 100 numbers chosen randomly between 1-10. I need help to then sum the list, then average the list created.
I have no idea how to begin and since I'm watching videos online I have no person to turn to. I'm very fresh in this world so I may just be missing entire ideas. I would doubt that I don't actually know enough though because the videos I paid for are step by step know nothing to know something.
Edit: I was informed that what the program does is overwrite a variable, not make a list. So how do I sum my output like this example?
This is all I have to go on:
Code:
import random
x=0
while x < 100:
mylist = (random.randrange(1,10))
print(mylist)
x = x+1
I think the shortest and pythonic way to do this is:
import random
x = [random.randrange(1,10) for i in range(100)] #list comprehension
summed = sum(x) #Sum of all integers from x
avg = summed / len(x) #Average of the numbers from x
In this case this shouldn't have a big impact, but you should never use while and code manual counter when you know how many times you want to go; in other words, always use for when it's possible. It's more efficient and clearer to see what the code does.
def sum(list):
sm = 0
for i in list:
sm+=i
return sm
Just run sum(list) to get sum of all elements
Or you can use
import random
x=0
mylist = []
sm = 0
while x < 100:
mylist.append(random.randrange(1,10))
sm += mylist[x]
x += 1
Then sm will be sum of list
The code is not correct. It will not create a list but generate a number everytime. Use the below code to get your desired result.
import random
mylist = []
for x in range(100):
mylist.append(random.randrange(1,10))
print(mylist)
print(sum(mylist))
OR
import random
mylist = [random.randrange(1,10) for value in range(100)]
print(mylist)
print(sum(mylist))
Output:
[3, 9, 3, 1, 3, 5, 8, 8, 3, 3, 1, 2, 5, 1, 2, 1, 4, 8, 9, 1, 2, 2, 4,
6, 9, 7, 9, 5, 4, 5, 7, 7, 9, 2, 5, 8, 2, 4, 3, 8, 2, 1, 3, 4, 2, 2,
2, 1, 6, 8, 3, 2, 1, 9, 6, 5, 8, 7, 7, 9, 9, 9, 8, 5, 7, 9, 4, 9, 8,
7, 5, 9, 2, 6, 8, 8, 3, 4, 8, 4, 7, 9, 9, 4, 2, 9, 9, 6, 3, 4, 9, 5,
3, 8, 4, 1, 1, 3, 2, 6]
512

Creating all the possible combinations inside an element of list

I need to explore every permutations of a list. Let's say I have this initiated variable:
samplelist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
An example output would be:
output = [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 3, 2, 4, 5, 6, 7, 8, 9], [1, 3, 4, 2, 5, 6, 7, 8, 9], [1, 3, 5, 3, 2, 6, 7, 8, 9]] .... and so on.
Here's what I did:
import itertools
samplelist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def combinations(iterable, r):
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = range(r)
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)
list(combinations_with_replacement(samplelist, 9))
Since the length of the list is 9, the factorial of 9 is 362,880. I'm trying to get all these combinations of the elements in the list
But my output is not what I'm trying to achieve.
itertools.permutations(samplelist) returns the 9! lists

Resources