Generating random numbers using LCG method - python

I'm trying to generate random numbers between 0 and 1 using the LCG method but it keeps giving me the error "local variable 's' referenced before assignment" How do I fix it without using a global variable?
def set_seed(S):
return S
def pseudo():
S = (S*a + c) % m/m
return S
m = 233280 # modulus
a = 9301 # multiplier
c = 49297 # increment
set_seed(1234)
VALUE_1 = pseudo()
set_seed(4321)
VALUE_2 = pseudo()
print(VALUE_1)
print(VALUE_2)

Related

Function does not modify variable in python

I create two lists, a, b with 10 random numbers from 0 to 61 and then I compare the lists if they have common numbers or not.
I store the common numbers in a separate list.
If the list does have numbers in it the commonCount is going up and if the list is empty the noCommonCount is going up.
But when I want to print the counts after I rand the function 10 times it prints out 0.
I don't know why because I declared the variables commonCount and noCommonCount outside the function.
import random
noCommonCount = 0
commonCount = 0
def list_overlap():
a = []
b = []
count = 0
while count < 10:
count = count + 1
a.append(random.randint(0, 61))
b.append(random.randint(0, 61))
commonNumbers = []
for i in a:
if i in b:
if i not in commonNumbers:
commonNumbers.append(i)
if not commonNumbers:
noCommonCount + 1
else:
commonCount + 1
functionCount = 0
while functionCount < 10:
functionCount = functionCount + 1
list_overlap()
print(noCommonCount)
print(commonCount)
For a function modifying a variable declared on outer scope additionally a declaration of the form
global variable_name
is required in the function (typically directly after function declaration.

Count number of function calls for distinct input argument values

With the code
def myfunction():
myfunction.counter += 1
myfunction.counter = 0
from https://stackoverflow.com/a/21717084/2729627 you can keep track of the number of times the function is called.
But how do I keep track of the number of times a function is called when (one of) its input arguments takes on a certain value?
So for instance
def myfunction(a):
# Do some calculations...
b = a**2
# Increase counter for specific value of 'a'.
myfunction.counter[a] += 1
# Return output argument.
return b
myfunction.counter[5] = 0
myfunction.counter[79648763] = 0
print(myfunction.counter[5])
print(myfunction.counter[79648763])
myfunction(5)
myfunction(79648763)
myfunction(79648763)
print(myfunction.counter[5]) # Should return 1.
print(myfunction.counter[79648763]) # Should return 2.
How should I modify this code to get it to work?
You can use a dictionary to keep this information:
counter_dict={} #new line
def myfunction(a):
b = a**2
if a in counter_dict.keys():
counter_dict[a] = counter_dict[a]+1 #increment the previous value
else:
counter_dict[a] = 1 #if the value is not present then initialize it with 1
return b
myfunction(5)
myfunction(79648763)
myfunction(79648763)
print(counter_dict[5]) # Should return 1.
print(counter_dict[79648763]) # Should return 2.
If you don't want to use global dict then you can write this:
def myfunction(a):
b = a**2
if a in myfunction.my_dict.keys():
myfunction.my_dict[a] = myfunction.my_dict[a]+1
else:
myfunction.my_dict[a] = 1
return b
myfunction.my_dict={}
myfunction(5)
myfunction(79648763)
myfunction(79648763)
print(myfunction.my_dict[5])
print(myfunction.my_dict[79648763])

Error with user input for standard deviation program

My program is meant to calculate the standard deviation for 5 values given by the users. There is an issue with my code when getting the input in a for loop. Why is that?
givenValues = []
def average(values):
for x in range(0, 6):
total = total + values[x]
if(x==5):
average = total/x
return average
def sqDiff(values):
totalSqDiff = 0
sqDiff = []
av = average(values)
for x in range(0,6):
sqDiff[x] = (values[x] - av)**2
totalSqDiff = totalSqDiff + sqDiff[x]
avSqDiff = totalSqDiff / 5
SqDiffSquared = avSqDiff**2
return SqDiffSquared
for counter in range(0,6):
givenValues[counter] = float(input("Please enter a value: "))
counter = counter + 1
sqDiffSq = sqDiff(givenValues)
print("The standard deviation for the given values is: " + sqDiffSq)
There are several errors in your code.
Which you can easily find out by reading the errormessages your code produces:
in the Function average
insert the line total = 0
you are using it before asigning it.
List appending
Do not use for example
sqDiff[x] = (values[x] - av)**2
You can do this when using dict's but not lists! Since python cannot be sure that the list indices will be continuously assigned use sqDiff.append(...) instead.
Do not concatenate strings with floats. I recommend to read the PEP 0498
(https://www.python.org/dev/peps/pep-0498/) which gives you an idea on how string could/should be formated in python

power series expansion for sine function

import math
def sine_func(x):
power = 0
sine = x
add = (-1)**(power)*(x**(2*power+1))/(math.factorial((2*power+1)))
while math.fabs(add) > 1.0e-8:
sine += add
power += 1
add == (-1)**(power)*(x**2*power+1)/(math.factorial((2*power+1)))
return sine
print(sine_func(1))
Program is just running forever, any thoughts on where I made my error?
This line:
add_ == (-1)**(power_int)*(x**2*power_int+1))/(math.factorial((2*power_int+1)))
Neither refers to the previous variable ("add" != "add_") nor assigns any value - == is comparison in Python, not assignment. Try:
add = (-1)**(power_int)*(x**2*power_int+1))/(math.factorial((2*power_int+1)))
Your code is running fine for me (Python 3.3.3), after fixing the brackets and the initialization as sine=0.
import math
def sine_func(x):
power = 0
sine = 0
add = (-1)**(power)*(x**(2*power+1))/(math.factorial((2*power+1)))
while math.fabs(add) > 1.0e-8:
sine += add
power += 1
add = (-1)**(power)*(x**(2*power+1))/(math.factorial((2*power+1)))
return sine

Returning multiple integers as separate variables

I am trying to make a program that grabs 5 integers from the user, and then finds the average of them. I have it set up to take in the 5 numbers, but how do I return them all as separate variables so I can use them later on? Thanks!
def main():
x = 0
testScoreNumber = 1
while x < 5:
getNumber_0_100(testScoreNumber)
x += 1
testScoreNumber += 1
calcAverage(score1, score2, score3, score4, score5)
print(calculatedAverage)
def getNumber_0_100(testnumber):
test = int(input("Enter test score " + str(testnumber) + ":"))
testcount = 0
while testcount < 1:
test = int(input("Enter test score " + str(testnumber) + ":"))
if test > 0 or test < 100:
testcount += 1
return test
^Here is the problem, the everytime this function runs, I want it to return a different value to a different variable. Ex. test1, test2, test3.
def calcAverage(_score1,_score2,_score3,_score4,_score5):
total = _score1 + _score2 + _score3 + _score4 + _score5
calculatedAverage = total/5
return calculatedAverage
You need to store the result somewhere. It is usually (always?) a bad idea to dynamically create variable names (although it is possible using globals). The typical place to store the results is in a list or a dictionary -- in this case, I'd use a list.
change this portion of the code:
x = 0
testScoreNumber = 1
while x < 5:
getNumber_0_100(testScoreNumber)
x += 1
testScoreNumber += 1
to:
results = []
for x in range(5):
results.append( getNumber_0_100(x+1) )
which can be condensed even further:
results = [ getNumber_0_100(x+1) for x in range(5) ]
You can then pass that results list to your next function:
avg = get_ave(results[0],results[1],...)
print(avg)
Or, you can use the unpacking operator for shorthand:
avg = get_ave(*results)
print(avg)
It isn't the responsibility of the returning function to say what the caller does with its return value. In your case, it would be simple to let main have a list where it adds the return values. You could do this:
scores = []
for i in range(5):
scores.append(getNumber_0_100(i))
calcAverage(*scores)
Note that *scores is to pass a list as arguments to your calcAverage function. It's probably better to have calculateAverage be a general function which takes a list of values and calculates their average (i.e. doesn't just work on five numbers):
def calcAverage(numbers):
return sum(numbers) / len(numbers)
Then you'd call it with just calcAverage(scores)
A more Pythonic way to write the first part might be scores = [getNumber_0_100(i) for i in range(5)]
Python allows you to return a tuple, and you can unroll this tuple when you receive the return values. For example:
def return_multiple():
# do something to calculate test1, test2, and test3
return (test1, test2, test3)
val1, val2, val3 = return_multiple()
The limitation here though is that you need to know how many variables you're returning. If the number of inputs is variable, you're better off using lists.

Categories