I'm trying to keep a count of the amount of times a random number is generated and stop it after a certain number has been hit. I'm new to python there's probably a simple fix that I can't see.
p = 0
def gameplay():
i = random.randint(1,2)
if i <= 1:
print(1)
p = p + 1
gameplay();
else:
print(2)
p = p + 1
gameplay();
if p <= 10:
gameplay();
I keep getting the error: "local variable 'p' referenced before assignment"
p = 0
def gameplay(p):
i = random.randint(1,2)
if i <= 1:
print(1)
else:
print(2)
p = p + 1
return p
while p <= 10:
p = gameplay(p)
I edited your code, so that p is incremented in the gameplay-function and then returned to the variable 'p' again. Thereby eliminating your error and the need for a global variable p.
I changed the if-statement to a while loop, because I thought that the sample code tried to implement a recursive function that ran until p was larger than 10. If that's not what you want, just change it back to an if-statement, but then make sure p gameplay(p) gets called somewhere else in your code.
Related
There was this question in a university assignment related to Hofstadter sequence. It basically say that it is a integer sequence blah blah and there are two values for a given index n. A male value [M(n)] and a female value [F(n)].
They are defined as:
M(0)=0
F(0)=1
M(n)=n-F(M(n-1))
F(n)=n-M(F(n-1))
And we were asked to write a program in python to find the Male and Female values of the sequence of a given integer.
So the code I wrote was:
def female(num):
if num == 0:
return 1
elif num >0:
return num - male(female(num-1))
def male(num):
if num==0:
return 0
elif num >0:
return num - female(male(num-1))
And when executed with a command like
print male(5)
It works without a fuss. But when I try to find the value of n = 300, the program gives no output.
So I added a print method inside one of the functions to find out what happens to the num value
[ elif num>0:
print num ...]
And it shows that the num value is decreasing until 1 and keeps hopping between 1 and 2 at times reaching values like 6.
I can’t figure out why it happens. Any insight would be nice. Also what should I do to find the values relevant to bigger integers. Thanks in advance. Cheers.
The code is theoretically fine. What you underestimate is the complexity of the computation. Formula
M(n)=n-F(M(n-1))
actually means
tmp = M(n-1)
M(n) = n - F(tmp)
So if you represent this calculation as a tree of necessary calls, you might see that its a binary tree and you should go through all its nodes to calculate the results. Given that M(n) and F(n) are about n/2 I'd estimate the total number of the nodes to be of order 2^(n/2) which becomes a huge number once you put n = 300 there. So the code works but it just will take a very very long time to finish.
The one way to work this around is to employ caching in a form of memoization. A code like this:
femCache = dict()
def female(num):
#print("female " + str(num))
global femCache
if num in femCache:
return femCache[num];
else:
res = 1 # value for num = 0
if num > 0:
res = num - male(female(num-1))
femCache[num] = res
return res
maleCache = dict()
def male(num):
#print("male " + str(num))
global maleCache
if num in maleCache:
return maleCache[num];
else:
res = 0 # value for num = 0
if num > 0:
res = num - female(male(num-1))
maleCache[num] = res
return res
print(male(300))
should be able to compute male(300) in no time.
I have a while loop which calls the function mainrt() on each iteration.
if __name__ == "__main__":
inp = sys.stdin.read()
inpList = inp.split('\n')
inpList.pop()
for n in inpList:
i = 0
p = 0
n = int (n)
while True:
i += 1
p = n*i
if n == 0:
print "INSOMNIA"
break
else:
res = True
res = mainrt(p)
if res == False:
print p
break
And the mainrt()
def mainrt(n):
#print n
while True:
rem = n % 10
if rem in diMon:
pass
else:
diMon.insert(rem,rem)
if len(diMon) == 10:
return False
break
n = n/10
if n == 0:
return True
break
else:
continue
The problem is as i take input from stdin.read() the first line of the input processed properly by the function, but the second line of the input get printed as it is. It is not being processed by the function
example
INPUT
3
5
OUTPUT SHOLD BE
30
90
But instead I get
30
5
Why the function not processing the input the second time???
There is no run time error so far.
In your mainrt function I do not see that you declare diMon list, so it looks like it is a global variable and you do not clean that list. That mean your mainrt return False at the first check of if len(diMon) == 10: for the second input. You should declare diMon at the beginning od mainrt function or clear it at the end of while loop body.
EDIT:
Now I checked your code one more time and I suggest you to declare diMon at the beginning of for loop
for n in inpList:
diMon = []
i = 0
p = 0
n = int (n)
I'm currently working on a small script that aims to find taxicab numbers. There is only one small problem, the for loop doesn't increment the variable x and is stuck looping forever. I'll paste the relevant part of the code below:
n = int(10)
counter = int(0)
m = int(m)
x = int(1)
y = int(n**(1/3))
cheatsheet = []
while counter in range(0,m):
for x in range(1,y):
if x**3 + y**3 < n:
print('less than')
print(x,y,n)
continue
elif x**3 + y**3 > n:
print('greater than')
y -= 1
continue
elif x > y:
if n in cheatsheet:
print('counting')
counter = counter+1
#checking if n occurs in the list, if so it will add 1 to the counter so that the program will know when to stop
n = n + 1
y = int(n**(1/3))
x = 1
print('break1')
#resetting values and bumping n so that it will continue the quest to find 'em all
break
else:
if x and y == 1:
#this is an error correction for low n values, i mean really low it might be redundant by now
n = n + 1
y = int(n**(1/3))
x = 1
print('break2')
break
cheatsheet.append((n,x,y))
print(cheatsheet)
This yields the following result in a terminal window:
image
Note that I killed the process by myself, the program did not.
As you can tell, the script just loops around and prints 'less than' and the values for x,y,n.
Help is greatly appreciated!
EDIT: the variable m is given by the user, but not included in this bit of code.
This has a number of issues wrong with it I'm not willing to post functional code but I will point some of the issues out.
For starters:
n = int(10)
isn't required, not an error but redundant. Use n = 10 with the same effect.
Then:
while counter in range(0,m):
will always evaluate to True. m is *never modified so the membership test always succeeds, maybe you need to re-evaluate your looping.
for x in range(1,y):
This will assign x the value 1 all the time. y evaluates to 2 by your arithmetic (int rounds floats to the floor, i.e int(2.9) -> 2) so either use math.ceil or add one to your y.
Appart from that you re-assign variable names all the time inside your loops, that's confusing and might lead to unexpected behavior.
I keep getting
TypeError: 'int' object is not callable
in my program.
The purpose of this program is to list all the Pentagonal Numbers from 1 to 100, doing 10 per line. So far I have this:
def getPentagonalNumber(n):
p = n(3*n-1) // 2
print(p)
def printPentagonalNumber(numberOfPentagonal):
number_of_Pentagonal = 100
NUMBER_OF_PENTAGONAL_PER_LINE = 10
count = 0
n = 1
while count < numberOfPentagonal:
if getPentagonalNumber(n):
count += 1 # increase count
if count % NUMBER_OF_PENTAGONAL_PER_LINE == 0:
print()
n =+1
def main():
print("The first 100 pentagonal numbers are")
printPentagonalNumber(100)
main()
The error is due to this line:
p = n(3*n-1) // 2
Python does not implicitly do multiplication.
Instead, you have to use:
p = n*(3*n-1) // 2
However, there are certain other things that are not correct in your code. Let us know if you need further help.
I am newbee in Python . JUst wandering if it is possible to define a Global variable in Python.
I have this python code to compute total number of times Fib(2) has been accessed. But count is printing 0 when called.
import sys
def fib(n):
"""Takes input a natural number n > 0.
Returns n! """
global count
count = 0
if n == 1 or n == 0:
return 1
else:
if n == 2:
print 'encountered here::: '
count += 1
return fib(n-1) + fib(n-2)
def main():
x = int(raw_input('Enter a natural number > 0 :'))
print 'Fibonacci(%d) = %d' % (x, fib(x))
print 'Count =', count
if 1:
main()
A variable defined in the module outside of any function is considered a global variable. To modify a global variable inside of a function, you must write global variableName inside of the function.
You did this, however, that variable is only defined in your function, it must also be declared outside of the function to be considered a global variable. If not, it will be local to your function, despite the global in front of it.
TL;DR Also declare the variable outside of your function.
EDIT (I was wrong):
By writing global variableName in a function and executing said function, it does make the variable a global variable; if not you would be getting a NameError when you tried to print it.
The reason that you're getting a 0, however, is because everytime you call your function, you initialize count to 0. Nonetheless, the solution about still holds.
Move count = 0 outside your fib(n) function. You only need to declare it as global count once inside the function, while the initialization should be outside. What you're doing is that you are re-initializing it with 0 every time the function is called.
import sys
count = 0
def fib(n):
"""Takes input a natural number n > 0.
Returns n! """
global count
if n == 1 or n == 0:
return 1
else:
if n == 2:
print 'encountered here::: '
count += 1
return fib(n-1) + fib(n-2)
def main():
x = int(raw_input('Enter a natural number > 0 :'))
print 'Fibonacci(%d) = %d' % (x, fib(x))
print 'Count =', count
if 1:
main()
Although, you should avoid global variables.
global foo
foo = [1,2,3]
Now foo can be used anywhere in the program
Put the count = 0 outside the function.