Random Choice is out of list range in Python? - python

I am trying to create a program that will guess the number you entered. I was trying to get the computer to get the number in as few guesses as possible so I am doing something like a binary search. I keep getting a Index out of range when I run the code and it gets to total = total[the_low_one:computer2_guess]. I am confused why it is out of range. Should I be adding or subtracting one to the_low_one each time it hits a new low so it stays in range? I would appreciate any help as I am lost. Thanks a bunch in advance!
Code:
def second_computer():
global computer2_score
computer2_score=0
computer2_guess= -1
the_low_one=1
the_high_one=1000000
total= range(1,1000000)
while computer2_guess != pick_number:
computer2_guess=random.choice(total)
if computer2_guess>pick_number:
total=total[the_low_one:computer2_guess]
the_high_one=computer2_guess-1
else:
total=total[computer2_guess:the_high_one]
the_low_one=computer2_guess+1
computer2_score+=1

As total shrinks, the numerical values in the list no longer line up with their indices. You could make it work by doing
total=total[total.index(the_low_one):total.index(the_high_one)]
A simpler approach would be to do away with total altogether and set
computer2_guess=random.randint(the_low_one,the_high_one)

Related

np.random.randint: ValueError: low >= high

getting a high low error on this. Works with another 1D dataframe and dtype but not on this. I'm trying to create a list of means taken randomly from a 1D list. Thanks!
new = []
for x in df:
sb_ = np.random.randint(x, size=100).mean()
new.append(sb_)
numpy.random documentation here. If only one input parameter is given as in your case, that input is the lower end of the range, and high is taken as 0. So, if any x in df is less than 0 (we'll say x', this code tries to draw a random integer from the range [0,x'], which is an empty range (no possible values). Thus your high-low error.
Based on your code and description it's a bit unclear exactly what you're trying to accomplish but with a bit more detail I can probably help you work out the correct code.

sum of cubes using formula

Given
\sum_{k=0}^{n}k^3 = \frac{n^2(n+1)^2}{4}
I need to compute the left hand side. I should make a list of the first 1000 integer cubes and sum them.
Then I should compute the right hand side and to the same.
Also, I am supposed to compare the computational time for the above methods.
What I've done so far is:
import time
start = time.clock()
list = []
for n in range(0,1001):
list.append(n**3)
print(list)
print("List of the first 1000 integer cubes is:",list, "and their sum is:", sum(list))
stop = time.clock()
print("Computation time: ",stop-start, "seconds.")
a=0
for n in range (0,1001):
a=(int)(n*(n+1)/2)
print ("Sum of the first 1000 integer cubes is:",a*a)
First part for the left hand side works fine, but the problem is the right hand side.
When I type n=4, I will get the same result for the both sides, but problem occurs when n is big, because I get that one side is bigger than the other, i.e. they are not same.
Also, can you help me create a list for the right hand side, I've tried doing something like this:
a=[]
for n in range (0,10):
a.append(int)(n**2(n+1)**2/4)
But it doesn't work.
For the computational time, I think I am supposed to set one more timer for the right hand side, but then again I am not sure how to compare them.
Any advice is welcome,
Ok, I think what you tried in a for loop is completely wrong. If you want to prove the formula "the hard way" (non-inductive way it is) - you need to simply sum cubes of n first integers and compare it against your formula - calculated one time (not summed n times).
So evaluate:
n=100
s=0
for i in range(1,n+1):
s+=i**3
###range evaluates from 1 till n if you specify it till n+1
s_ind=(n**2)*((n+1)**2)/4
print(s==s_ind)
Otherwise if you are supposed to use induction - it's all on paper i.e. base condition a_1=1^3=((1)*(2)^2)/4=1 and step condition i.e. a_n-a_(n-1)=sum(i^3)[i=1,...,n]-sum(j^3)[i=1,...,n-1]=n^3 (and that it also holds assuming a_n=your formula here (which spoiler alert - it does ;) )
Hope this helps.

Loops and float numbers

I’m taking an online basic programming class and I’m completely lost on this assignment. Our book went over basic loops, but not how to find max, min, or average in a loop with values input by a user. Here is my assignment:
Write a loop control program that will provide important statistics for the grades in a class. The program will utilize a loop to read five floating-point grades from user input. Ask the user to enter the values, then print the following data: Average Maximum Minimum
My textbook and instructor have really given me no guidance on how to use floating numbers in a loop. Here is what I have come up with so far:
for grade in range(5):
int(input("Enter Grade (percentage): "))
if max:
print('Max:')
if min:
print('Min:')
else:
print('Average:')
This allows me to get the loop to run 5 times but how do I actually calculate the min, max, and average for unknown variables?
I don't do python, but I'd know how to approach this problem.
For the average, declare a variable called sum or something and set it to 0. Then, every time you get an input, add that value to the sum. After 5 inputs, print that sum divided by 5. That'll be the average.
To get the max, initiate a variable to 0. On input, check if that input is greater than the currently stored maximum. If so, set the variable to that input. After 5 inputs that variable will contain the max.
Similarly for the min. But make sure to set that variable to something big at the start (like 100000), and then check if the new input is smaller than that variable.
Also, if you're supposed to use floats, don't cast your user input to an int. Use float instead.
You use floating numbers in a loop the same way you use them outside the loop.
The loop does not change anything.
But, it seems you are misunderstanding the task wording:
You are not suppose to print the min, max, and average calculation inside the loop.
That would be impossible, since you can not know them, until the user inputs all 5 grades.
What you are suppose to do inside the loop, are 4 steps:
Read a float from the user. Currently, you are trying to read an int for some reason. Do you know how to read a float in Python?
Add it to the sum you will use after the loop to calculate average.
See if it is the max of all numbers the user inputted so far.
See if it is the min of all the numbers the user inputted so far.
Once you exit the loop, all you have to do is print 3 numbers:
The max and min you found and the average calculation.
You'll want to make a list first,
Then create a for loop that will run 5 times, range(5) should work.
Then exit the loop and run an average, min and max
You can create a simple function for this task. You can do the following:
def take_what(statistic = None):
f = []
for grade in range(5):
f.append(int(input("Enter Grade (percentage): ")))
if statistic == "max":
print('Max: {}'.format(max(f)))
elif statistic == "min":
print('Min: {}'.format(min(f)))
else:
print('Average: {}'.format(sum(f)/len(f)))
print(take_what('max'))
print(take_what('min'))
print(take_what())

average value of inputs in python

I am in intro programming class and I just started learning the loops. My question asks about the average value of the inputs and it supposed to be done with while-loops. When the user inputs end instead of a number, that signifies the end of the loop and calculates the average value. The program should print the average value and return it. Also, if the user does not input any number and directly inputs end, the program should print "No numbers were entered". I tried creating the loop, but I do not know what I am missing for my loop to be running.
Also, I am not allowed to use any inbuilt functions like sum, ave, etc.
Here is the code I've written so far
def avgOfTheSum():
total = 0
avg = 0
count = 0
while True:
number = input("Enter next number:")
if number != 'end':
num = float(number)
total = total + num
count = count + 1
average = total/count
else:
print("The Average is:",average)
break
return average
a few tips from my not-so-experienced point of view :
when you increment a variable, eg. 'total = total + num', you can do so with a more compact way : use 'total += num' which does exactly the same thing and lightens your code. Some people find it ugly though, so use it if you will.
You first declared a variable named 'avg' but you then later use 'average', which leads to an error when trying to print 'average' which was not defined because the first 'if' statement was bypassed.
You should use one naming for the average. Either 'avg' or 'average' is okay but remember your code must be easy to understand so try not to squeeze things too much, especially if someone is reviewing it when you are finished.
Use one name and stick to it. That way you don't have an error when the user inputs something that isnt handled by your code.
You could add safe nets to ensure the user passes a number but the most simple ways need to use python built-ins.
You could add something like (not python do not write it like so)
if count = 0
then print 'no numbers entered'
then either :
break if you want to quit the application
or pass if you want to force the user to enter a number (enforcing a new loop)
Hope it helped you a little bit !

I have to write a program that calculates and displays the total score using a for loop?

I'm quite new to the for loops in Python. So, I want to write a program that asks the user to enter to enter 20 different scores and then I want the program to calculate the total and display it on the screen. How could I use a for loop to do this?
edit: I can ask the user to for the different numbers but I don't know how to then add them.
Without giving you the full code here is the pseudocode for what your code should look like
x = ask user for input
loop up till x //Or you could hard code 20 instead of x
add user input to a list
end
total = sum values in list
print total
Here are all the things you need to implement the logic
User input/output:
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.html
Loops:
https://wiki.python.org/moin/ForLoop
Summing a list:
https://docs.python.org/2/library/functions.html
Try something like this:
total = 0; # create the variable
for i in range(1,20): # iterate over values 1 to 20 as a list
total += int(input('Please enter number {0}: '.format(i)));
print("Sum of the numbers is '{0}'".format(total))
I'd suggest you go through the tutorials on the python site:
Python 3 is here https://docs.python.org/3/tutorial/index.html
Python 2 is here https://docs.python.org/2/tutorial/index.html
I could go into a lot of detail here and explain everything, however I'd only be duplicating the resources already available. Written far better than I could write them. It would be far more beneficial for you (and anyone else reading this who has a similar issue) to go through these tutorials and get familiar with the python documentation. These will give you a good foundation in the basics, and show you what the language is capable of.
Input
To read a value from the commandline you can use the input function, e.g. valueString = input("prompt text"). Notice the value stored is of type string, which is effectively an array of ASCI/Unicode characters.
So in order to perform math on the input, you first need to convert it to its numerical value - number = int(valueString) does this. So you can now add numbers together.
Adding numbers
Say you had two numbers, num1 and num2, you can just use the addition operator. For example num3 = num1 + num2. Now suppose you have a for loop and want to add a new number each time the loop executes, you can use the total += newNum operator.
total = 0
for _ in range(1,20):
num = input('> ')
total += int(num)
print(total)
I hope this helps.

Categories