Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I wanted to do something like the following. It is an Euclid's algorithm.
1. Why is it not working when I wanted to call the function which is already in the call stack?
2. How can I make it work?
import sys
def __block_1__():
__block_2__()
def __block_2__():
global b,a
b,a=None,None
__block_3__()
def __block_3__():
global b,a
a=int(raw_input())
__block_4__()
def __block_4__():
global b,a
b=int(raw_input())
__block_5__()
def __block_5__():
global b,a
if a==b:
__block_6__()
else:
__block_7__()
def __block_6__():
global b,a
__block_8__()
def __block_8__():
global b,a
sys.exit(0)
def __block_7__():
global b,a
if a<b:
__block_9__()
else:
__block_10__()
def __block_9__():
global b,a
b=b-a
__block_5__
def __block_10__():
global b,a
a=a-b
__block_5__
__block_1__()
That has to be the craziest implementation of Euclid's GCD algorithm I've ever seen! :) And since it uses recursion and subtraction, it's not very efficient. OTOH, I guess it's intriguing, especially since it was auto-generated. (How was it auto-generated, BTW?)
I normally use:
def gcd(a, b):
if a < b:
a, b = b, a
while b > 0:
a, b = b, a%b
return a
In Python, we try to avoid using globals, but I guess we can forgive your auto-generator for that sin. Note that you only need the global statement when you want to modify a global variable, it's not required merely to read a global.
Apart from the missing parentheses in the call to block_5 that BrenBarn mentioned, your program doesn't have any kind of output statement, so once it calculates the gcd it doesn't actually do anything with it. :)
Also note that if either of the args are <= 0 then the recursion stack blows up.
Anyway, I decided to clean your code up & get rid of the redundant blocks, on the off-chance that others might like to trace through the algorithm to see why it works.
#! /usr/bin/env python
''' Calculate the gcd of two positive integers
Uses a recursive state machine implemetation of the naive form
of Euclid's algorithm.
From http://stackoverflow.com/questions/25928184/calling-the-functions-which-are-already-in-the-callstack
Modified by PM 2Ring 2014.09.19
'''
def block3():
global a
a = int(raw_input('a: '))
block4()
def block4():
global b
b = int(raw_input('b: '))
block5()
def block5():
if a == b:
block8()
else:
block7()
def block7():
if a < b:
block9()
else:
block10()
def block8():
print a
exit()
def block9():
global b
b -= a
block5()
def block10():
global a
a -= b
block5()
if __name__ == '__main__':
block3()
I think you'll agree that my version's a bit more readable. :)
Related
I'm very new to coding and am working on a project where I write a code to perform newtons method for lots of different functions. The code I wrote to do newtons method is as follows:
def fnewton(function, dx, x):
#defined the functions that need to be evaluated so that this code can be applied to any function I call
def f(x):
f=eval(function)
return f
#eval is used to evaluate whatever I put in the function place when I recall fnewton
#this won't work without eval to run the functions
def df(x):
df=eval(dx)
return df
n=0
min=.000001
guess=2
xi_1=guess
#defining these variables before Fnewton so I can use them in print
while np.absolute((xi_1))>min:
#basically this means that you continue the process until funct/der is greater than the tolerance
n=n+1 #helps keep track over how many times I iterated
x=xi_1-f(xi_1)/df(xi_1) #this is the newton eqn
xi_1=x
print('the root is at:')
print(x)
print('after this many iterations:')
print(n)
I am trying to call on this function to operate on functions I defined before it by using the command:
fnewton("a(x)", "dadx(x)",2)
Once I added the two it would run(and tell me variables weren't defined) but now it just runs forever and never computes anything. please help, did I code wrong?
ps. a(x) and dadx(x) are:
def a(x):
f=np.exp(np.exp(-x))-x**2+x
return(f)
def dadx(x):
f=(a(x+.01)-a(x))/.01
return(f)
I executed the code you loop stuck at value 1.7039784148789716, your logic which says while np.absolute(xi_1)>min1: seems not working
try printing values inside the loop as below
while np.absolute(xi_1)>min1:
#basically this means that you continue the process until funct/der is greater than the tolerance
n=n+1 #helps keep track over how many times I iterated
x=xi_1-f(xi_1)/df(xi_1) #this is the newton eqn
xi_1=x
print(np.absolute(xi_1))
and find the proper while expression to suite your result
I think you meant while np.absolute(f(xi_1))>min:
PS: just refrain yourself from using functions like eval() in python, it makes your code a lot harder to debug
Best to write your f and df as discrete functions then pass references to them to fnewton(). In this way the implementation of fnewton() remains constant and you just have to pass your estimate and f and df references. You can reasonably hard-code Euler's Number for this trivial case which avoids the need to import numpy
e = 2.718281828459045
def f(x):
return e**(e**(-x))-x**2+x
def df(x):
return (f(x+.01)-f(x))/.01
def fnewton(x0, f, df, tolerance=0.0001):
if abs(fx0 := f(x0)) < tolerance:
return x0
return newton(x0 - fx0/df(x0), f, df, tolerance)
print(fnewton(1.5, f, df))
Output:
1.7039788103083038
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I honestly do not know what to do. The questions I got on StackOverflow were about strings and csv inputs, but these variables I am expecting are different. Help would be very much appreciated. I always get ValueError: too many values to unpack (expected 3). I want the code to pass the three returned variables from speedCalc() to something I could use in the calculations in spellCheck() (line 35). What should I do?
Here's the code:
#!/usr/bin/env python
import time
import random
import string
import sys
import string
import sys
#from getkey import getkey
def generateTest():
mylines = []
with open ('phrases.txt', 'rt') as myfile: # Open phrases.txt for reading the typing tests
for line in myfile: # For each line of text,
mylines.append(line) # add that line to the list.
# Converting lines of list to select a random phrase
listLen = len(mylines) - 1
return (mylines[random.randint(0,listLen)])
def speedCalc():
# words / time passed (assuming it is 5)
start = time.time()
test = input(print(generateTest()))
end = time.time()
timePassed = (end - start)
generateTestLen = len(generateTest())
return test
return timePassed
return ((generateTestLen/5)/timePassed)*60
def spellCheck():
test, timePassed, wpm = speedCalc()
diff = 0
correctChars = 0
file_A = generateTest()
file_B = test
read_A=open(file_A,'r').read()
read_B=open(file_B,'r').read()
for char_a, char_b in zip(read_A, read_B):
if char_a == char_b:
correctChars = correctChars+1
read_A_len = len(read_A)
correctPercent = (correctChars/read_A_len)*100
errors = read_A_len - correctChars
errorRate = errors/timePassed
netWPM = wpm - errorRate
return correctPercent
return netWPM
correctPercent, netWPM = spellCheck()
print(netWPM)
Instead of using:
return test
return timePassed
return ((generateTestLen/5)/timePassed)*60
use
return test, timePassed, ((generateTestLen/5)/timePassed)*60
Your function as you defined in your example just returnes test and exits then. The second and third return is not executed any more.
When a return statement is reached, a function stops. Any code after the return statement is never executed.
The code
return test
return timePassed
return ((generateTestLen/5)/timePassed)*60
is equivalent to
return test
You should return a tuple of three values. Use
return test, timePassed, ((generateTestLen/5)/timePassed)*60
Adjust spellCheck accordingly, it has the same problem.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I try to write a program and get a variable from a constructor to a method but I don't know how to do it :( I get an error with p.liczba in the method sprawdz. I would like to have here a number from the user. The same situation is with p.wielokrotnosc. I know that I can write this program easier but I really would like to learn OOP with simple examples like this
class Przyklad:
def __init__(self, liczba):
self.liczba = liczba
def podajSzukana(self):
self.wielokrotnosc = 3
class Dane:
def wczytaj(self):
a = int(input('Podaj mi liczbę '))
p = Przyklad(a)
def sprawdz(self):
if (p.liczba % p.wielokrotnosc == 0):
return true
print ('Witaj w programie szukającym wielokrotność liczby 3 \n')
d = Dane()
d.wczytaj()
d.sprawdz()
The problem is not getting the variable from the constructor of Przyklad. The problem is saving it in Dane. The common procedure is to attach it to instance of Dane:
def wczytaj(self):
a = int(input('Podaj mi liczbę '))
self.p = Przyklad(a)
Then, you'll have self.p available in Dane
This is happening because the variable liczba is contained within the class Przyklad, so when you try to access it in Dane, it is not possible.
You should try having liczba be a global variable (which is dangerous), or having Dane be a descendant of Przyklad (these names though....).
a and p are local variables not members of Dane. You have to use self. (as pointed by jonrsharpe) to be able to access this variable from the class context:
class Dane:
def wczytaj(self):
a = int(input('Podaj mi liczbę '))
self.p = Przyklad(a)
def sprawdz(self):
if (self.p.liczba % self.p.wielokrotnosc == 0):
return true
Another issue is that self.wielokrotnosc do not exists until you call podajSzukana(self) method. One way to fix this is calling that function inside your constructor:
class Przyklad:
def __init__(self, liczba):
self.liczba = liczba
self.podajSzukana() // Call the method here.
def podajSzukana(self):
self.wielokrotnosc = 3
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
The code below reads lines from a file, then it executes the custom function (My_Function) and return values to the variables(e.g. condition_A)
for line in input_file:
if condition_A:
condition_A = My_Function(A_tuple[0], B_tuple[0])
if condition_B:
condition_B = My_Function(A_tuple[1], B_tuple[1])
if condition_C:
condition_C = My_Function(A_tuple[2], B_tuple[2])
if condition_D:
condition_D = My_Function(A_tuple[3], B_tuple[3])
if condition_E:
condition_E = My_Function(A_tuple[4], B_tuple[4])
...
My question is: can the code be modified to more elegant version? After all, many code is similar(I don't want to define another function to simplify it because the code is still similar after the new function is defined). thanks.
Instead of having 5 variables condition_*, use a list, conditions:
conditions=[1]*5 # initialize conditions as you wish
for line in input_file:
for i,condition in enumerate(conditions):
if condition:
conditions[i]=My_Function(A_tuple[i],B_tuple[i])
What about something like
conditions = [condition_A, condition_B, condition_C, condition_D, condition_E]
condition_test = lambda c, i: My_Function(A_tuple[i], B_tuple[i]) if c else c
for line in input_file:
conditions = [condition_test(c, i) for i, c in enumerate(conditions)]
'line' is not referenced in teh loop, is that an error in simplifying it for posting?
How about
condition=1 #or 2 or...
for line in input_file:
My_Function(A_tuple[condition],B_tuple[condition])
Before refactoring your code on a purely syntactic level (which is covered in examples above), it might be useful to evaluate what you're doing with the code on a functional level
Check out your condition_x variables. I think you might be using the same variable for two different things (both type-wise and logically) - usually a bad idea in a weakly typed language. It looks to me as if the user sets a condition to true or false, and then that condition is assigned the output - is the output boolean? is it related to the original value of that variable? Rethinking this might lead to more understandable code.
It is also difficult to evaluate how this can be refactored without seeing what goes in to condition_x - since these might have commonalities.
One more sample(not solution) based on unutbu's:
data = [1,2,3,'',4,5,6, '', 0]
for i in (i for i in xrange(len(data)) if data[i] not in ['',0]):
data[i] += 1
Sorry if duplicate
Here is a generic solution where you can have custom index and you can also access conditions by name if need be and it can be easily extended to add any new complexities
class Condition(object):
def __init__(self, active, index1, index2):
self.active = active
self.index1 = index1
self.index2 = index2
conditions = {
'A': Condition(True,0,0),
'B': Condition(True,1,1),
'C': Condition(True,2,2),
'D': Condition(True,3,3),
'E': Condition(True,4,4),
}
for line in input_file:
for condition in conditions.itervalues():
if condition.active:
condition.active = My_Function(A_tuple[condition.active.index1], B_tuple[condition.active.index2])
This question already has answers here:
What is memoization and how can I use it in Python?
(14 answers)
Closed 6 months ago.
Is it "good practice" to create a class like the one below that can handle the memoization process for you? The benefits of memoization are so great (in some cases, like this one, where it drops from 501003 to 1507 function calls and from 1.409 to 0.006 seconds of CPU time on my computer) that it seems a class like this would be useful.
However, I've read only negative comments on the usage of eval(). Is this usage of it excusable, given the flexibility this approach offers?
This can save any returned value automatically at the cost of losing side effects. Thanks.
import cProfile
class Memoizer(object):
"""A handler for saving function results."""
def __init__(self):
self.memos = dict()
def memo(self, string):
if string in self.memos:
return self.memos[string]
else:
self.memos[string] = eval(string)
self.memo(string)
def factorial(n):
assert type(n) == int
if n == 1:
return 1
else:
return n * factorial(n-1)
# find the factorial of num
num = 500
# this many times
times = 1000
def factorialTwice():
factorial(num)
for x in xrange(0, times):
factorial(num)
return factorial(num)
def memoizedFactorial():
handler = Memoizer()
for x in xrange(0, times):
handler.memo("factorial(%d)" % num)
return handler.memo("factorial(%d)" % num)
cProfile.run('factorialTwice()')
cProfile.run('memoizedFactorial()')
You can memoize without having to resort to eval.
A (very basic) memoizer:
def memoized(f):
cache={}
def ret(*args):
if args in cache:
return cache[args]
else:
answer=f(*args)
cache[args]=answer
return answer
return ret
#memoized
def fibonacci(n):
if n==0 or n==1:
return 1
else:
return fibonacci(n-1)+fibonacci(n-2)
print fibonacci(100)
eval is often misspelt as evil primarily because the idea of executing "strings" at runtime is fraught with security considerations. Have you escaped the code sufficiently? Quotation marks? And a host of other annoying headaches. Your memoise handler works but it's really not the Python way of doing things. MAK's approach is much more Pythonic. Let's try a few experiments.
I edited up both the versions and made them run just once with 100 as the input. I also moved out the instantiation of Memoizer.
Here are the results.
>>> timeit.timeit(memoizedFactorial,number=1000)
0.08526921272277832h
>>> timeit.timeit(foo0.mfactorial,number=1000)
0.000804901123046875
In addition to this, your version necessitates a wrapper around the the function to be memoised which should be written in a string. That's ugly. MAK's solution is clean since the "process of memoisation" is encapsulated in a separate function which can be conveniently applied to any expensive function in an unobtrusive fashion. This is not very Pythonic. I have some details on writing such decorators in my Python tutorial at http://nibrahim.net.in/self-defence/ in case you're interested.