Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to make an average but for some reason when I try to make one it doesn't work.
I have global variables and array defined at the begining of my document :
vent_moyenne_km = []
compteur_moyenne=0
I have one of my function that is called every X time. In that one, I calculate a velocity with some value that are display on a label of my interface. that part is working, but not the mean
global compteur_moyenne
compteur_moyenne += 1
ventkmh = (vent_1[3][0]*256 + vent_1[4][0]) /100 *3.6
label_vent2_2.config(text= "%.2f" % ventkmh)
vent_moyenne_km.append("%.2f" % ventkmh)
vent_1.clear()
if compteur_moyenne == 5:
compteur_moyenne = 0
print(vent_moyenne_km)
label_vent4_2.config(text=statistics.mean(vent_moyenne_km))
vent_moyenne_km.clear()
of course in my imports I have :
import statistics
When I comment the line label_vent4_2.config(text=statistics.mean(vent_moyenne_km)), everything works and I see in the terminal my array with 5 values. I also tried numpy and even tried to make a for items in array: then add then manually, and everytime I get the error : class 'IndexError'
I'm really not sure how to fix that.
For calculating an average of a list just use numpy:
def function():
value = random.randint(0,1)
return value
list = []
for i in range(100):
list.append(function())
if i%5 == 0:
print(np.average(list))
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to work out the average sum of a list without index 0, is this possible in python? as you can see below, my list includes 1 name and 4 numbers. can I work out the average of the 4 numbers without including the name?
student = [Dan, 60, 70, 80, 90]
I have tried to achieve this in a number of different ways such as copying the list and removing index 0 however, this wasn't sufficient as I need this function to be looped a number of times inputted by the user previously.
I also tried to use the sum(student)/len(student) but that also gave an error as the list is a mix of int and str
Try excluding the first element, you can achive that with:
studentWithoutFirstElement = student[1:]
Then you can calculate the mean doing the following:
sum(studentWithoutFirstRow)/len(studentWithoutFirstRow)
You can also use the function provided by the numpy library by typing:
import numpy as np
np.mean(studentWithoutFirstRow)
You can use this code for general case not only for your case.
sum_ = 0
count = 0
for i in student:
if type(i) == int or type(i) == float:
sum_ += i
count += 1
avg = sum_/count
This code loop though list and check whether the type of element is int/float or not, if so adds it to sum and increase count by one. Finally you just divide sum to count.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to use a list of values to alter a bunch of class values that I added to another (temporary) list.
class game_events():
def __init__(self):
self.stage = 0
self.rules = False
saved_vars = [12, True]
game = game_events()
i = 0
for x in [game.stage, game.rules]:
x = saved_vars[i]
i+=1
It seems like everything is working, but that only the temporary list is being altered, like a decoy.
Desired results:
game.stage == 12
game.rules is True
Actual results:
game.stage == 0
game.rules is False
Any ideas?
When you do x = saved_vars[i], you're rebinding the variable x, not modifying the game object where it's previous value came from. If you want to modify just a few attributes on game, it's a whole lot easier to just do so directly:
game.stage, game.rules = saved_vars[0:2]
If you have a whole lot of attributes to go through, rather than just two in this example, you might return to your loop idea, but you'd need to do it differently. Rather than an assignment, you'd need to use setattr. And that means you'll need to specify the name of the attributes as strings, not with dotted notation:
for attr, value in zip(['stage', 'rules'], saved_vars):
setattr(game, attr, value)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I was trying to get 3 random numbers within range in python without replacement. I did this
rand_lst = []
while(True):
rand = random.randint(0, length-1 )
if(len(rand_lst) == 3):
break
if(rand not in rand_lst):
rand_lst.append(rand)
This code is inside a for loop. This returns only 0 and thus an infinite loop. I also tried numpy.random.randint but some how random is keeping track of previously generated numbers and I endup with value error.
Trying putting print(length) right before your while True. You'll almost certainly find that the value of length is not what you expect it to be. (It's probably 0 or 1, when you want it to be 3 at least.)
if i understand you correctly,
you want something like this:
import random
rand_lst = []
length = 10
while(True):
rand = random.randint(0, length-1 )
if(len(rand_lst) == 3):
break
if(rand not in rand_lst):
rand_lst.append(rand)
print(rand_lst)
this way "length" has a value and will not throw an error
Explanation: https://stackoverflow.com/a/33806926/8386640
Use random.sample. Here is code.
import random
rand_lst = []
length = 3
while(len(rand_lst) < 3):
rand_lst.append(random.sample(range(length), 3))
print rand_lst
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Here is my homework:
Write a function that repeatedly generates random integers in the range [0,n[, until two consecutively generated numbers are identical.then return the number of generated numbers.
Here is what I did:
def function(n):
for i in range(100):
random.randint(0,n)
and this outputs a hundred numbers, however I need it to stop when it detects two identical numbers, how is that done?
For this you could use two names: one for the newly generated random number, and one for the previous one.
You need also to make your loop differently, as you don't know how long it needs to iterate before getting a match:
import random
def function(n):
a = -2
b = -1
i = 0
while a != b:
a, b = random.randint(0,n), a
i += 1
return i
# Sample run
times = function(400)
print (times)
See it run on repl.it
To do it without assigning a and b strange values, use an infinite while loop, then break when the values are the same. This is similar to #trincot's solution:
import random
def function(n):
a = None
i = 0
while True:
a, b = random.randint(0,n), a
i += 1
if a == b:
return i
# Sample run
times = function(400)
print(times)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
What I'm trying to accomplish - I wrote this code so that I can use the bootstrapping method from statistics to create a 95% confidence interval of the mean. I want to pass a list of integers to the "CI" method and then have the method return the string at the end.
Problem - The code doesn't generate any output when I run it. Please help!
Here is the code:
class bootstrapping(object):
def __init__(self,hours=[]):
self.hours = hours
def CI(self,hours):
from random import randint
x=0
for numbers in range(0,1000):
bootstraplist = []
while x >= 0:
bootstraplist.append(hours[randint(0,6)])
if x <= 5:
x += 1
continue
else:
break
listofmeans.append(sum(bootstraplist) / len(bootstraplist))
import numpy
s = numpy.std(listofmeans)
z = 1.96
lower_confidence = (sum(listofmeans) / len(listofmeans)) - z*s
upper_confidence = (sum(listofmeans) / len(listofmeans)) + z*s
return "Lower confidence:",lower_confidence,"Upper confidence:",upper_confidence
Snapshot of the error I'm seeing
the problem is here:
while x >= 0:
bootstraplist.append(hours[randint(0,6)])
this is a infinite loop, as should know the indentation level is what create block of code in python, so as the if bellow have the same level as the while, the if is outside the while block.
I am not sure what your objective is there, but the more easy way to repeat a code a fixed number of time is with a for-loop over a range(n) where n its the number time to repeat the action. In your case that can be something like this
for _ in range(5):
bootstraplist.append(hours[randint(0,6)])
( the use of _ is a convention for a variable for which we don't care its value and/or we don't use)
or you could use list comprehension to create the list directly
bootstraplist = [hours[randint(0,6)] for _ in range(5) ]
also, by the way you use it looks like instead of randint, choice is the better option
bootstraplist = [choice(hours) for _ in range(5) ]
Other things, is good practice to put all your imports as the first thing you do in your code.
Taking that in consideration along with the comment, perhaps this is what you want?
import numpy
from random import choice
class bootstrapping(object):
def __init__(self,hours=[]):
self.hours = hours
def CI(self):
listofmeans = []
for numbers in range(0,1000):
bootstraplist = [ choice(self.hours) for _ in range(5) ]
listofmeans.append(sum(bootstraplist) / len(bootstraplist))
s = numpy.std(listofmeans)
z = 1.96
lower_confidence = (sum(listofmeans) / len(listofmeans)) - z*s
upper_confidence = (sum(listofmeans) / len(listofmeans)) + z*s
return "Lower confidence:",lower_confidence,"Upper confidence:",upper_confidence
test
>>> test=bootstrapping(range(1,6))
>>> test.CI()
('Lower confidence:', 1.7676140938359097, 'Upper confidence:', 4.2427859061640962)
>>>