How to tackle this random number Python homework? [closed] - python

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)

Related

Is it possible to work out the average of a list whilst excluding index 0? [closed]

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.

Python index error when trying to make a mean [closed]

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

Can this kind of code (if ... for if ... for ...) be both short and fast [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have some problems with the following kind of code:
if a == b:
forloop:
CODE_1
k = t # t will be changed in CODE_1 and CODE_2
CODE_2
elif a == c:
forloop:
CODE_1
k = t + 1
CODE_2
As you can see, both the code in two for loop is very similar (they might just have some difference in several characters. The above is just an example.) Now I want to make it shorter because they are nearly the same.
I know there is a way to make it shorter:
forloop:
CODE_1
if a == b:
k = t
elif a == c:
k = t + 1
CODE_2
But the point is for every loop, it will need to do the comparison. I think it should be slower than the former one. And in fact, because a, b and c will not be affected by the for loop, it does not need to compare them every loop. Could anybody tell me how to make it shorter without making it slower?
I am now using python.
Sorry for not providing a specific code because I am just curious about this general situation. If this can be optimized only in some specific code, it will be great if you can point it out.
And copying is not the way to solve it since they still have some difference (not just 1 maybe 25 positions).
If a == c, you could simply call t = t + 1 before the loop, and use the same code whatever a is.
If t itself changes during the loop, you could write k = t + dt, where dt has been set to 0 or 1 depending on the value of a.
This should work, because, as you mentioned in your question:
And in fact, because a, b and c will not be affected by the for loop
Finally, it might be possible to use a dict instead of elif statements.
Generalizing another answer, you can lift comparisons and other code out of the loop.
Say that a == c is really expensive--perhaps they are big matrixes. You could do something like
compare = a == c #store comparison
for ... :
if compare:
...
else: ...
You can also pull any operations and computations that are constant out of the loop.

Python random.randint() keeps returning 0 after certain time [closed]

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

I created a class in Python, but am unable to call the method [closed]

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

Categories