473,779 Members | 1,912 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

calling functions

This is the first time I have tried out functions (is that the main way
of making subroutines in Python?)

Anyway, my function, mutate, below

#make a child string by randomly changing one character of the parent

Def mutate():
newnum=random.r andrange(27)
if newnum==0:
gene=' '
else:
gene=chr(newnum +96)
position=random .randrange(len( target))
child=parent[:position-1]+gene+parent[position+1:]

mutate()
The trouble is when I later (as in further down the code) attempt to
retrieve the value of gene I get an error saying that gene is undefined.
It works fine when I don't have the routine defined as a function. - the
IF- Else structure means gene must have a value of ' ' or 'a' to 'z'.

It seems that the line:

mutate()

is not invoking the function, but why not?

Thanks again - this group is great. I despair of ever being able to
contribute though :-(
Aug 1 '05 #1
2 1713
Without a 'global' statement, all variables which are assigned in the body of a
function are local to that function.

Here is an example showing that f() does not create a module-level variable,
but g() does.
def f(): ... z = 3
... def g(): ... global z
... z = 3
... z Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'z' is not defined f()
z Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'z' is not defined g()
z 3

You also have a fencepost error in your slicing. You want to write
child = parent[:position] + gene + parent[position+1]
otherwise you end up including too few characters in child, and if
position is 0 you get an even more unexpected result.

However, instead of using 'global' you should just have mutate() return
the new child. Here's a version of mutate() that I wrote:
import string, random
valid = string.lowercas e + " "

def mutate(parent):
position = random.randrang e(len(parent))
newgene = random.choice(v alid)
return parent[:position] + newgene + parent[position+1:]
My mutate() returns the new string after it is mutated, so there's no
need to use 'global'

Here, I repeatedly mutate child to give a new child: child 'forest of grass' for i in range(5): ... child = mutate(child)
... print child
...
forest of grays
forqst of grays
fooqst of grays
zooqst of grays
zooqst of brays

Here, I find many mutations of parent: for i in range(5): ... child = mutate(parent)
... print child
...
foresf of grass
forestsof grass
forest ofpgrass
forest oj grass
forest cf grass

If you have a fitness function f() which returns a higher number the
more fit a string is, and you're using Python 2.4, here is some code to
order several mutations of parent according to fitness: children = sorted((mutate( parent) for i in range(5)), key=f, reverse=True)
fittest_child = children[0]
Here's a stupid fitness function:
def f(s): return f.count(" ")

And it's fairly successful at breeding a string with lots of spaces: child = "forest of grass"
for i in range(10):

... children = (mutate(child) for j in range(100))
... child = sorted(children , key=f, reverse=True)[0]
... print child
...
f rest of grass
f rest of g ass
f rest yf g ass
f rest y g ass
f rest y g a s
t rest y g a s
t rest y g a
t re t y g a
t e t y g a
t e y g a

Over 10 generations, the most fit of 100 mutations is used as the basis forthe
next generation.

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.6 (GNU/Linux)

iD8DBQFC7rk0Jd0 1MZaTXX0RAjrAAJ 9+oThJyQqcqAUWm Det08s8dY2dzQCf dyqm
X/ln9AWpvfTHc9hgv NP8JWI=
=EyqV
-----END PGP SIGNATURE-----

Aug 2 '05 #2
anthonyberet wrote:
This is the first time I have tried out functions (is that the main way
of making subroutines in Python?)
A function is allowed to change it's arguments and to return None, so
yes, you can consider it as a 'subroutine'.

Anyway, my function, mutate, below

#make a child string by randomly changing one character of the parent

Def mutate(): s/Def/def/

<meta>
please copy-paste code - retyping it increases the risk of typos.
</meta>
newnum=random.r andrange(27)
if newnum==0:
gene=' '
else:
gene=chr(newnum +96) position=random .randrange(len( target))
child=parent[:position-1]+gene+parent[position+1:]
Where does this 'gene' come from ?-)
mutate()
The trouble is when I later (as in further down the code) attempt to
retrieve the value of gene I get an error saying that gene is undefined.
Of course it is.
It works fine when I don't have the routine defined as a function. - the
IF- Else structure means gene must have a value of ' ' or 'a' to 'z'.
This 'gene' only lives in the function body - as with almost any other
programming language.
It seems that the line:

mutate()

is not invoking the function,
It is. But this function does not return anything (well, it returns
None, which is the Python representation of exactly nothing) - and you'd
loose it if it did anyway.

<non-pythonic-explanation>
A variable created in a function is local to the function. It disappears
as soon as the function returns - unless you keep a reference to it one
way or another. The usual way to do so is to return the variable to the
caller :
</non-pythonic-explanation>
def mutate():
newnum = random.randrang e(27)
if newnum == 0:
gene=' '
else:
gene = chr(newnum + 96)
return gene

gene = mutate()
# target and parent where undefined...
# please post working code
parent = "0123456789 "
#position = random.randrang e(len(target))
position = random.randrang e(len(parent))
child=parent[:position-1]+gene+parent[position+1:]

Now you may want to check your algorithm, since it doesn't perform as
described - but this is another problem !-)

hints:
import string
string.ascii_lo wercase
help(random.cho ice)

astring = "abcd"
alist = list(astring)
alist[0] = 'z'
astring2 = ''.join(alist)

Also note that a function can take arguments:
def fun_with_args(a rg1, arg2):
print "in func_with_name : arg1 = %s - arg2 = %s" % (arg1, arg2)

fun_with_args(' toto', 'titi')

so you can have the whole algorithm in the function body:

def createChild(par ent):
# code here to create child
return child

parent = "0123456789 "
child = createChild(par ent)
print "parent : %s\nchild : %s" % (parent, child)
Thanks again - this group is great. I despair of ever being able to
contribute though :-(


You did. There would be no answer if there were no questions !-)
BTW, may I suggest you to spend some time on a good Python tutorial ?
(there are many good ones freely available on the net).

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Aug 2 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3232
by: pieter.breed | last post by:
Hi All, Is it possible to export a c# method into a dll in such a way that your "normal" C application can then call this method? To be clear: I am not asking how to use "DllImport" or PInvoke. My question is the other way around. Regards Pieter Breed
19
4261
by: Ross A. Finlayson | last post by:
Hi, I hope you can help me understand the varargs facility. Say I am programming in ISO C including stdarg.h and I declare a function as so: void log_printf(const char* logfilename, const char* formatter, ...); Then, I want to call it as so:
5
2236
by: Dave | last post by:
does calling a regular function cost any cpu time? In other words, is it faster to write the code of two functions into main(), or is it the exact same thing as calling two functions. I know its nitty gritty but its necessary for my program. thanks dave
1
1789
by: Mark Jerde | last post by:
Yesterday I posted the message below to microsoft.public.dotnet.languages.vb and microsoft.public.vc.language. The two replies are also posted. I need to write some ISO C++ functions, more information below. Is C# a better language to use than VB.NET for calling these C++ functions? If so I would appreciate some links on calling C++ from C#. Thanks! -- Mark
1
2914
by: Jesse McGrew | last post by:
Hi all, I'm trying to make a plugin DLL for a third-party application, using VC++ .NET 2003. This DLL acts as a bridge between the C++ plugin API of the application, and my actual plugin code written in C#. When the app calls my unmanaged functions, they work fine. But as soon as my unmanaged functions call managed functions (in the same source file!), the app reports an "unknown exception" error.
1
2605
by: H.B. | last post by:
Hi, I need to make a function that can display data on my Managed C++ app and be called by an unmanaged C++ DLL. Something like : void Form1::Form1_Load(System::Object * sender, System::EventArgs * e) { MyDLLInit(MyAppDisplayFunction); }
2
2818
by: Daniel Lidström | last post by:
I'm using a library called fyba. This library reads and writes files in a format called sosi. fyba uses the following code to determine if the calling process has own methods to handle errors, messages, etc: // If this parameter is NULL, // GetModuleHandle returns a handle of the file used // to create the calling process. hInstExe = GetModuleHandle( NULL ); if( hInstExe!=NULL )
18
4359
by: John Friedland | last post by:
My problem: I need to call (from C code) an arbitrary C library function, but I don't know until runtime what the function name is, how many parameters are required, and what the parameters are. I can use dlopen/whatever to convert the function name into a pointer to that function, but actually calling it, with the right number of parameters, isn't easy. As far as I can see, there are only two solutions: 1) This one is portable. If...
4
4801
by: Edwin Gomez | last post by:
I'm a C# developer and I'm new to Python. I would like to know if the concept of Asynchronous call-backs exists in Python. Basically what I mean is that I dispatch a thread and when the thread completes it invokes a method from the calling thread. Sort event driven concept with threads. Thanks. Ed Gomez
10
3265
by: sulekhasweety | last post by:
Hi, the following is the definition for calling convention ,which I have seen in a text book, can anyone give a more detailed explanation in terms of ANSI - C "the requirements that a programming system places on how a procedure is called and how data is passed between a calling program and procedures are called calling conventions"
0
9632
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9471
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10071
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6723
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5372
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5501
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4036
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3631
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2867
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.