I use a randomizer to make random number from 5 to 10. Can't be so hard? I have used it previously on code (+2000 lines of code, too much for here) and no coding errors occurred.
My code is simply easter egg to my game but it broke all my code:
...
def slowp(t):
for l in t:
sys.stdout.write(l)
sys.stdout.flush()
x=random.randint(0.1,0.9)
time.sleep(x)
print("")
if act=="++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>":
slowp("Hey, that is hello world made in brainfuck!")
...
act is a string whose value is provided by the user simply with act=str(input("type here.")). It is directly done before this part.
Error message:
Traceback (most recent call last):
File "startgame.py", line 2084, in <module>
slowp("Hey, that is hello world made in brainfuck!")
File "startgame.py", line 140, in slowp
x=random.randint(0.1,0.9)
File "/usr/lib/python3.4/random.py", line 216, in randint
return self.randrange(a, b+1)
File "/usr/lib/python3.4/random.py", line 180, in randrange
raise ValueError("non-integer arg 1 for randrange()")
ValueError: non-integer arg 1 for randrange()
What is the actual problem?
You are trying to pass floating point values to random.randint(). That function only takes integers.
You need to use the random.uniform() function instead; it'll produce a uniformly random value between the lower and upper bound (inclusive):
Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.
Demo:
>>> import random
>>> random.uniform(0.1, 0.9)
0.6793304134926453
ValueError: non-integer arg 1 for randrange()
random.randint(0.1,0.9)
You have to pass integers to that function. 0.1 and 0.9 are not integers
you can
random.randint(1,9)/10
in random.randint(start, stop, step) we can use step
random.uniform(start, stop) - no step
Related
I'm trying to convert the following Pinescript function into Python.
xrf(values, length) =>
r_val = float(na)
if length >= 1
for i = 0 to length by 1
if na(r_val) or not na(values[i])
r_val := values[i]
r_val
r_val
The attempt that I've made so far to convert to Python is as follows...
import math
#Function 1
def xrf(values, length):
r_val = float("NaN")
if length >= 1:
for i in range(0, length):
if math.isnan(r_val) or not math.isnan(values[I]):
r_val = values[i]
The code works fine up until the bit that reads math.isnan(values[i]). In particular, the problematic bit seems to be the square brackets and the i.
Therefore, I was wondering if anyone knew what the 'series subscript' is for Python - this is the operator that I'm struggling to convert.
Here's an example of the function in a small snippet of code, with the error message that it returns.
import examplemodule
from examplemodule import xrf
variable = xrf(6,50)
print(variable)
The error message that this returns is...
Traceback (most recent call last):
File "mypath/script.py", line 4, in <module>
variable = xrf(6,50)
File "mypath/examplemodule.py", line 9, in xrf
r_val = values[i]
TypeError: 'int' object is not subscriptable
import math
import random
m = 1.5 #mu
l = 2 #lambda
c = 3 #control/number of servers
def single(m, l, c):
p = (l/m)
Po = (1-(l/m))
Ls = (l/(m-l))
Ws = (1/(m-l))
Wq = (l/(m*(m-l)))
Lq = (l**2/(m*(m-l)))
return(p, Po, Ls, Ws, Wq, Lq)
def multi(m, lm, mu):
rho=lm/mu
n=0
sm=0
while(n<=m-1):
sm=(1/math.factorial(n))*pow(rho,n)
n+=1
sm = sm + 1/(1/math.factorial(m))*(pow(rho,m)*m*mu/(m*mu-lm))
lS=lm*mu*pow(rho,m)/((math.factorial(m-1)*(m*mu-lm)**2))*(1/sm)+rho
lQ=lS-rho
#Po = 1/sm
return(lq, ls)
singReturn=single(m, l, c)
multiReturn=multi(3, 2, 1.5)
print("SINGLE SERVER QUEUEING")
print("-----------------------")
print("p: %4.4f \nPo: %4.4f \nLs: %4.4f \nWs: %4.4f \nWq: %4.4f \nLq: %4.4f"%singReturn)
I am being returned and error with:
Traceback (most recent call last):
File "/home/schnipdip/Desktop/final_part1_chris_herzog.py", line 35, in <module>
multiReturn=multi(3, 2, 1.5)
File "/home/_____/Desktop/final_part1_.py", line 28, in multi
sm = sm + 1/(1/math.factorial(m))*(pow(rho,m)*m*mu/(m*mu-lm))
ZeroDivisionError: integer division or modulo by zero
I am trying to find the value of SM and then convert it into the Po variable. The while loop is controlling how many servers there are by m(or c) - 1.
I changed the variables in the loop to see if the variable was being overwritten in memory by a previous value and not resetting for whatever reason. I'm sure that has nothing to do with it.
If you're using Python 2, it's probably due to this part:
... 1/(1/math.factorial(m)) ...
Logically, it doesn't make much sense: mathematically, 1/(1/x) is just a clumsy way to spell plain x. So I bet your code has a logical error there.
But, in Python 2, it also has a programming error: / applied to integers does truncating integer division in Python 2:
>>> import math
>>> m = 3
>>> math.factorial(m)
6
>>> 1 / math.factorial(m)
0
To prevent that, use, e.g., 1.0 instead of 1 to force float division:
>>> 1.0 / math.factorial(m)
0.16666666666666666
I am quite new to the Python language, and for my first exercise I wanted to make a script that calculates the constant e.
To do this, I defined a function calc_temp which would have a variable temp and temp would start off equal to one. I would then multiply temp by the quotient of 1 and a variable called e_num I would then add temp to a variable approx_e.
Then, I used a while True: loop to perform the function indefinitely.
The code looks like this:
#!/usr/bin/python
import math
from decimal import *
temp = 1
approx_e = Decimal(1)
e_num = 1
def calc_temp(e_num):
global approx_e
global temp
len_ = math.log10(math.factorial(e_num))
getcontext().prec = len_
temp = Decimal(temp * 1 / e_num)
e_num = e_num + 1
approx_e = approx_e + temp
return approx_e
while True:
calc_temp(e_num)
However, when I execute the script, it raises the following TypeError:
Traceback (most recent call last):
File "/home/dorian/Desktop/ever3.py", line 17, in <module>
calc_temp(e_num)
File "/home/dorian/Desktop/ever3.py", line 14, in calc_temp
approx_e = approx_e + temp
File "/usr/lib/python2.7/decimal.py", line 1209, in __add__
ans = ans._fix(context)
File "/usr/lib/python2.7/decimal.py", line 1692, in _fix
changed = rounding_method(self, digits)
File "/usr/lib/python2.7/decimal.py", line 1771, in _round_half_even
if _exact_half(self._int, prec) and \
TypeError: integer argument expected, got float
I tried changing the type of the variables, making them Decimals, integers, and floating point numbers, but it still raises the error. What could be causing it?
You are setting the context precision to a float:
len_ = math.log10(math.factorial(e_num))
getcontext().prec = len_
Set it to an integer:
getcontext().prec = int(len_)
Quoting the decimal.Context() documentation:
The prec field is a positive integer that sets the precision for arithmetic operations in the context.
from math import sqrt
def fermatBook (n):
x=int(sqrt(n))
c=x**2-n
while (sqrt(c)!=int(sqrt(c))):
x=x+1
y=sqrt(c)
a=x+y
b=x-y
if a==1 or b==1:
print "The number is prime"
return a, b
error:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
fermatBook (23867)
File "C:/Python27/fermatLivro.py", line 6, in fermatBook
while (sqrt(c)!=int(sqrt(c))):
ValueError: math domain error
I don't know what is going wrong with the program... Could someone help me ?
most likely your variable c is going negative:
Example
if you call:
n = 2
fermatBook(n)
it will assign the following values to the following variables:
x = int(sqrt(n)) = int(1.47...) = 1
c = x**2 - n = 1**2 - 2 = 1 - 2 = -1
This will likely happen alot on values of n whose square root is not an integer.
sqrt(n) >= int(sqrt(n)), n >= 0
Then when you call sqrt(c) it is out of the domain because it cannot handle negative values.
>>> from math import sqrt
>>> sqrt(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
You should rather use something that can handle imaginary numbers, i.e. cmath
Or perform checks to assure this does not happen:
As an example...
if c < 0:
c = 0
As soon as you fix this however you are going to run into another problem:
This is an infinite loop:
while (sqrt(c)!=int(sqrt(c))):
x=x+1
you need to update c otherwise the condidtion will never change no matter how many times you increment x. You probably meant this?
while (sqrt(c)!=int(sqrt(c))):
x=x+1
c = x**2+n # <--- UPDATE c
I can't find my mistake in here, if someone can help me would be great.
def heapsort (lista) :
n= len(lista)-1
k= n/2
while (k>0) :
downheap(lista,n,k)
k-=1
while (n>=0) :
(lista[1]),(lista[n])=(lista[n]),(lista[1])
n-=1
return downheap(lista, n, 1)
return lista
def downheap (lista, n, k) :
v= lista[k]
while (k<=(n/2)) :
j=k+k
if (j<n and (lista[j]) == (lista[j])) :
break
(lista[k]) = (lista[j])
k = j
lista[k] = v
Error:
>>> heapsort([4,2,3,1])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in heapsort
File "<stdin>", line 2, in downheap
TypeError: list indices must be integers, not float
In Python 3, using the / division operator always returns a float value:
>>> 2/2
1.0
>>> 3/2
1.5
Use floor division instead, the // operator:
k = n // 2
The // operator always returns an integer, flooring the result:
>>> 2//2
1
>>> 3//2
1
Perhaps you coded your functions from an example in Python 2; in Python 2 the / operator is an ambiguous operator; it'll act like the floor division operator when both operands are integers, but if either operand is a float, then suddenly it behaves differently and returns floating point division results instead. Because both operands in your code are integers, in Python 2 your code would not have thrown that exception.
Your next problem is that downheap() does not return anything, so when you use return downheap(lista, n, 1) in heapsort() you'll return None. I suspect that the return there is a mistake.
When dividing just cast to int
def heapsort (lista) :
n= len(lista)-1
k= int(n/2) // instead of k= n/2
while (k>0) :
downheap(lista,n,k)
k-=1
while (n>=0) :
(lista[1]),(lista[n])=(lista[n]),(lista[1])
n-=1
return downheap(lista, n, 1)
return lista