Why am I getting an infinite loop? [PYTHON 2.7] - python-2.7

I am trying to run a very basic while loop and am still new to python I have learned obviously:
numbers = []
def print_numbers(x):
i = 0
counter = x
while i < counter:
print "top of the list"
numbers.append(i)
print i
i += 1
#print "Numbers nows:", numbers
#print"At the bottom i is %d" % i
#print "The numbers:"
y = raw_input("Pleast enter the number:")
print_numbers(y)
#for num in numbers:
# print num
So, this loop does what it says it does, takes a number and add's it to the list one at a time, the length of the list is defined by user input. Seem straight forward enough correct. Well when I run it I get an infinite loop. Why is that?

Your y variable is of type str, so it's never less than i. You need to parse it as an int after reading it from stdin.
numbers = []
def print_numbers(x):
i = 0
counter = x
print i,counter
while i < counter:
print "top of the list"
numbers.append(i)
print i
i += 1
# print "Numbers nows:", numbers
# print"At the bottom i is %d" % i
# print "The numbers:"
y = int(raw_input("Pleast enter the number:"))
print_numbers(y)

Related

How To Make raw_input Not A String In python

I want to make this program do the summation of something with their input. My code thus far
def summation():
start = int(raw_input("Start value of n?: "))
end = int(raw_input("End value of n?: "))
eqn = lambda n: raw_input("Equation?: ")
sum = 0
for i in range(start , end + 1):
sum += eqn(i)
return sum
print summation() # start will be 1, end will be 5 , equation will be n + 1. Should print 20
I get the error that I can't add an integer and a string together so is there any way to make the raw_input for equation not a string. Like instead of it being 'n + 1', I want it to be n + 1.
You could use input instead of raw_input, but this isn't really a good idea, since every time eqn is called it will call a input and prompt you for the equation.
A better method is to store the equation beforehand (using raw_input), and then use eval in the lambda function. Something like:
def summation():
start = int(raw_input("Start value of n?: "))
end = int(raw_input("End value of n?: "))
fx = raw_input("Equation: ")
eqn = lambda n: eval(fx)
sum = 0
for i in range(start , end + 1):
sum += eqn(i)
return sum
print summation()
Don't you need to surround your raw_input in your eqn variable with an int()?
I use python 3, but that should fix your problems.

Using Bubble sort and encountering out of range list index

doc = "unsorted.txt"
out_fil = "H:\Grade 11\Intro to Computer Science\sorted.txt" # Used in the Windows variation of the program
out_file = "/Applications/Banter" # Used in the Mac variation of the program
import time
def main():
order = False
blank = []
passcount = 0
starttime = time.time()
numlist = CreateList(doc)
while not order:
passcount = passcount + 1
switch = False
switchcount = 0
print "1" # These are test prints to I used to find problems
for x in range (len(numlist)):
print "2" # These are test prints to I used to find problems
if numlist[x] > numlist[x+1]:
temp = numlist[x+1]
numlist[x+1] = numlist[x]
numlist[x] = temp
switchcount = switchcount + 1
switch = True
print "9" # These are test prints to I used to find problems
elif switch == 0:
order = True
CreateFile(numlist)
endtime = time.time()
print "This list required",endtime-starttime,"seconds to sort."
print "This list required",switchcount,"switches to sort."
print "This list required",passcount,"passes to sort."
def CreateList(doc):
sort = open(doc,"r")
numlist = sort.readlines()
sort.close()
for x in range (len(numlist)):
numlist[x] = int(numlist[x].strip())
return numlist
def CreateFile(numlist):
sort = open(doc,"w")
sort.write(str(numlist)+"\n")
sort.close()
return numlist
def List(numlist):
print numlist
main()
The main purpose of my program is to sort a list of integers from a file in order using the bubble sort method, and then put that list into a new file. I'm also detailing the amount of time it takes to perform this as well as the number of passes and switches within the program that it took to sort it completely.
Now, the problem I'm having is that the list index falls out of range because it's comparing x and x+1 of my numlist. But, I need to compare x+1 in order to sort the two integers beside each others within the list. Is there any way I can fix the program so that it'll compare all the integers in the list and not try to compare the space that isn't in the list because of the x+1?
You could make your loop in this way:
for x in range ( len(numlist) -1 ):
Though stackoverflow is a great resource for answers, giving them up for homework assignments feels like cheating. I'll meet you half way: Make your loop run for one less iteration.

How to find the min and max in a number list [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 6 years ago.
I'm having trouble with a project for class and I was looking for some help. I need to make a code where it will ask for numbers repeatedly and then print out the min and max in the list. My teacher said we can do this anyway we wish.
num_list = []
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
if num >= 0:
num_list.append(num)
print min(num_list)
print max(num_list)
This is what I have so far, it asks for the number inputs and will break when I enter done, but it will only print out "Done" for the min and max in the list.
you need to convert the numbers to an integer or float type before calling min/max.
# under n >= 0:
num = int(num) # or num = float(num)
num_list.append(num)
so an example of working code would be:
num_list = []
while True:
num = raw_input("Enter a number: ")
if num == "done" :
break
try: # use a try except to verify user input is in fact a number
num = int(num) + 0 # alternatively use float(num) if non integer numerical inputs will be used
if num >= 0:
num_list.append(num)
print "min: ",min(num_list)
print "max: ",max(num_list)
except:
print "invalid input"
Not calling max/min every iteration:
num_list = []
_min, _max = None, None
while True:
num = raw_input("Enter a number: ")
if num == "done" :
break
try: # use a try except to verify user input is in fact a number
num = int(num) # alternatively use float(num) if non integer numerical inputs will be used
if num >= 0:
if not _min or not _max:
_min,_max = num, num
elif num < _min:
_min = num
elif num > _max:
_max = num
num_list.append(num)
except:
print "invalid input"
print "min:", _min
print "max:", _max

How to calculate average / mean on python 2.7

Im trying to calculate the average when an user will enter the numbers and will stop when he decide. I manage to get the sum however I cant divided it because I need somehow get the quantity of the inputs before he stops entering. Here is my code so far:
print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")
s = 0
x = raw_input ('please enter the number')
while (num != 'f'):
x = eval (x)
s = s + x
x = raw_input ('please enter the number')
print (' the average is'), s
Like you see I manage to get the sum however I dont know how I can get the quantity of the input to then divide the sum with this to get the average. Any help will be appreciated
You just needed to add a counter inside your while loop:
print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")
s = i = 0 #declare counter: i = 0
x = raw_input ('please enter the number')
while (x != 'f'):
x = eval (x)
s = s + x
i+=1 #increment counter: i=i+1 or i+=1 (these 2 options are equivalent)
x = raw_input ('please enter the number')
print (' the average is'), s/i #divide the sum by counter

Random walk code in python [2 dimensions]

Please could you help me by figuring out what is the wrong with my code.
I am trying to write a program that generates random walks in two dimensions and that determines statistics about the position of the walker after 500 steps when the number of walks is 1000, the max step size is 0.9, and the separation between the two positions is 0.001.
import math
import random
import time
print "RANDOM WALKS ANALYSIS IN ONE DIMENSION"
NOFW_ = 1000 #The number of walks
NOFS_= 500 #The number of steps in each walk
MSS_ = 0.9 # The maximum step size[m]
SOFP_ = 0.001 # The separation of positions considered equal[m]
print " Number of walks: %3g"% NOFW_
print " Number of steps in each Walk: %3g"% NOFS_
print " Maximum step size: %3g"% MSS_,"m"
print "Separation of positions considered equal: %3g"% SOFP_,"m"
print
print "Please wait while random walks are generated and analyzed..."
print "Date:" + time.ctime()
print
def initialPosition():
return (0.0, 0.0)
def distance(posA, posB):
"""Calculates the distance between two positions posA and posB"""
distance = math.sqrt((posB[0] - posA[0])**2 + (posB[1] - posA[1])**2)
return distance
def printstats(description, numbers):
minimum_value_ = min(numbers)
numbers.sort()
Tenth_percentile = abs(0.10*len(numbers) + 0.5)
Mean_value_ = (1./float(len(numbers))*sum(numbers))
A = 0
for values in numbers:
B = distance(values, Mean_value_)
B = B**2
A = B + A
Standard_deviation = math.sqrt((1./(len(numbers)-1))*A)
Newposition_ = int(0.90*(len(numbers) + 0.5))
Ninetieth_percentile =numbers[Newposition_]
maximum_value_ = max(numbers)
print "Analysis for"""+ description
print "Minimum value: %9.1f" % minimum_value_
print "10th percentile: %7.1f" % Tenth_percentile
print "Mean value: %12.1f" % Mean_value_
print "Standard deviation: %4.1f" % Standard_deviation
print "90th percentile: %7.1f" % Ninetieth_percentile
print "Maximum value: %9.1f" % maximum_value_
list_1 = [minimum_value_, Tenth_percentile, Mean_value_, Standard_deviation, Ninetieth_percentile,maximum_value_]
return list_1
def takeStep(prevPosition, maxStep):
x = random.random()
y = random.random()
minStep = -maxStep
Z = random.random()*2*math.pi
stepsize_ = random.random()*0.9
Stepx= stepsize_*math.cos(Z)
Stepy= stepsize_*math.sin(Z)
New_positionx = prevPosition[0] + Stepx
New_positiony = prevPosition[1] + Stepy
return (New_positionx, New_positiony)
Step_100 = []
Step_500 = []
count_list = []
for walk in range(NOFW_):
Step1 = []
Position = (0.0,0.0)
count = 0
for step in range(NOFS_):
Next_Step_ = takeStep(Position, MSS_)
for word in Step1:
if distance(Next_Step_, word) <= SOFP_:
count +=1
position = Next_Step_
Step1.append(Next_Step_)
Step_100.append(Step1[-1])
Step_500.append(Step1[-1])
count_list.append(count)
Step_100 = printstats("distance from start at step 100 [m]", Step_100)
Step_500 = printstats("distance from start at step 500 [m]", Step_500)
count_list = printstats("times position revisited", count_list)
Your problem is here
Mean_value_ = (1./float(len(numbers))*sum(numbers))
sum() is supposed to get some numbers but your variable numbers is actually containing some tuples of 2 values
You may want to define your own sum function for tuples of 2 numbers, or to sum the first values and second values separately