Don't have an account? Register now to chat, post, use our tools, and much more.
Latest Headlines
Online Users
There are 120 users online: 8 members, 82 guests and 30 bots. Members: Ashbad, HOMER-16, Link, patrickdavidson, Piguy-3.14, Svenne, zeldaking. Bots: VoilaBot (4), Spinn3r (1), Magpie Crawler (4), VoilaBot (3), Googlebot (12), Googlebot (4), MSN/Bing (2).
RSS & Social Media
SAX
You must log in to view the SAX chat widget
|
| Author |
Message |
|
elfprince13

OVER NINE THOUSAND!

Joined: 23 May 2005 Posts: 10224 Location: A galaxy far far away......
|
Posted: 05 Mar 2009 02:33:29 pm Post subject: Python Crack (or: those features you're hooked on) |
|
|
Feel free to contribute as you see fit.
_
In the interactive python shell, the special variable _ is equivalent to Ans in TI-Basic. It holds the last returned value.
classmethod and staticmethod
Most object oriented Python code doesn't make use of these two, but they're very useful for declaring static functions inside a class. Normally if you have a class definition like so:
Code:
class Blah:
def blahblah(self, other, arguments):
dosomething()
blahobj = Blah()
blahobj.blahblah(42, 1337 )
and the interpreter automatically passes blahobj as the self argument to blahblah. Sometimes; however, you want a Java + C style static functions that belong to the whole class, not just to a single instance (generally utility functions related to the purpose of the class). In this case you can declare a function to be a classmethod, which receives the class object it is called on as the implicit first argument; or with staticmethod, which receives no implicit first argument at all. Static methods should be used when the function will always be called on the same class. Class methods should be used when the function will be called on different classes with different implementations of the same function. To declare a class or static method, you have two options. Decorator syntax:
Code:
class Blah:
@staticmethod
def staticMethod1():
print "staticMethod1"
@classmethod
def classMethod1(cls):
print "classMethod1 called on" + str(cls)
or the traditional way:
Code:
class Blah:
def staticMethod2():
print "staticMethod2"
staticMethod2 = staticmethod(staticMethod2)
def classMethod2(cls):
print "classMethod2 called on" + str(cls)
classMethod2 = classmethod(classMethod2)
unpacking + zip
say you want to return multiple values from a function.
Code:
def getMinMedianMax(list):
return (min(list), max(list), sorted(list)[len(list) / 2])
list = (1, 3, 6, 6, 9, 2)
min, median, max = getMinMedianMax(list)
min = 1
median = 6
max = 9
This works for tuples and lists.
if for some strange reason you want one-tuples, you can create them like this:
Code: onetuple = (1, )
and to unpack the one-tuple
Code: firstval, = onetuple
You can also unpack lists, tuples, and dictionaries into a function call.
Code:
def sumTwoValues(one, two):
return one + two
list = [1, 2]
sum = sumTwoValues(*list)
to pack an arbitrary number of arguments into a list you can do the reverse.
Code:
def sumArgs(*args):
return sum(args)
sum = sumArgs(1, 2, 3)
The same works for dictionaries and keyword arguments. It's hard to think of trivial examples for keyword arguments, so for this I'm just gonna link you to the python tutorial. http://www.network-theory.co.uk/docs/pytut/KeywordArguments.html
Because python is an interpreted language, you can actually dump your programs configuration settings to a text file, and then use the eval() function to read it back later. This should be used with caution, since eval will execute any valid python code in the input.
One last thing: zip(). It will take its arguments and zip them together. The easiest way to explain this is to see it in action.
Code:
l1 = [1, 2, 3]
l2 = [4, 5, 6]
zlist = zip(l1, l2)
At this point, zlist equals [(1, 4), (2, 5), (3, 6)]. To unzip this back into it's constituent parts, you can do this:
Code:
l2, l1 = zip(*zlist)
l2 now equals [1, 2, 3] and l1 now equals [4, 5, 6]
list comprehensions
basically, a one-line way of building a list from some input.
for example, say you want a list of the ascii values of every character in a string.
Code:
input = "Omghaiguys"
output = [ord(letter) for letter in input]
output would now equal [79, 109, 103, 104, 97, 105, 103, 117, 121, 115]
You can also conditionally include parts of the list. For example, to remove all the vowels from a string you could do this.
Code:
input = "Omghaiguys"
output = "".join([letter for letter in input if letter.lower() not in "aeiou"])
output would now equal "mghgys"
magic slicing
Most of you should be aware of the ability to slice to the end of a list, or from the beginning of a list (e.g. list[:5] is equivalent to list[0:5] and list[5:] is equivalent to list[5:len(list)]), but there are a couple additional features that are nice. you can use a negative list index to get the last n items in a list. For example list[-5:] will retrieve the last 5 items in a list, and list[:-5] will retrieve all but the last 5. Better still is slicing with 2 colons. list[2::3] will retrieve every 3rd item in list, starting from an index of 2. For example
Code:
range(100)[2::3]
will return every multiple of 3 between 0 (inclusive) and 100 (exclusive), or to use mathematical notation all multiples of 3 in [0, 100). _________________ StickFigure Graphic Productions || VSHI: Vermont Sustainable Heating Initiative
 |
|
| Back to top |
|
|
magicdanw
Advanced Member

Joined: 26 Sep 2007 Posts: 282
|
Posted: 05 Mar 2009 03:48:33 pm Post subject: |
|
|
| Python scares me... |
|
| Back to top |
|
|
elfprince13

OVER NINE THOUSAND!

Joined: 23 May 2005 Posts: 10224 Location: A galaxy far far away......
|
|
| Back to top |
|
|
magicdanw
Advanced Member

Joined: 26 Sep 2007 Posts: 282
|
Posted: 05 Mar 2009 04:03:31 pm Post subject: |
|
|
I think a lot of it is the dynamic typing. It seems useless, inefficient, and could encourage one to code without thinking ahead.
Also, I like curly braces...  |
|
| Back to top |
|
|
elfprince13

OVER NINE THOUSAND!

Joined: 23 May 2005 Posts: 10224 Location: A galaxy far far away......
|
Posted: 05 Mar 2009 04:11:44 pm Post subject: |
|
|
| magicdanw wrote: | | I think a lot of it is the dynamic typing. It seems useless, inefficient, and could encourage one to code without thinking ahead. |
It's not just dynamic typing (variables can hold values of any type), it's Duck typing, which means that types are essentially irrelevant. Basically you can imitate class A closely enough with class B to pass objects of type B to a function that needs objects of type A without having to extend A.
| magicdanw wrote: | Also, I like curly braces...  |
The only thing I really miss from C-ish languages is the ?: operator, although I just had a brainwave for how to implement it
Not having {} leads to much more structured source code, which is a huge boon in preventing code-rot. _________________ StickFigure Graphic Productions || VSHI: Vermont Sustainable Heating Initiative
 |
|
| Back to top |
|
|
magicdanw
Advanced Member

Joined: 26 Sep 2007 Posts: 282
|
Posted: 05 Mar 2009 04:26:34 pm Post subject: |
|
|
| elfprince13 wrote: | | magicdanw wrote: | | I think a lot of it is the dynamic typing. It seems useless, inefficient, and could encourage one to code without thinking ahead. |
It's not just dynamic typing (variables can hold values of any type), it's Duck typing, which means that types are essentially irrelevant. Basically you can imitate class A closely enough with class B to pass objects of type B to a function that needs objects of type A without having to extend A. | Is that supposed to alleviate my fears? If I have no clue if I have a duck or not, I have no business passing it to a method that utilizes ducks!
| elfprince13 wrote: | | Not having {} leads to much more structured source code, which is a huge boon in preventing code-rot. | How is that? Braces mark which code is related to a certain header quite well, IMO. |
|
| Back to top |
|
|
elfprince13

OVER NINE THOUSAND!

Joined: 23 May 2005 Posts: 10224 Location: A galaxy far far away......
|
|
| Back to top |
|
|
magicdanw
Advanced Member

Joined: 26 Sep 2007 Posts: 282
|
Posted: 05 Mar 2009 05:01:58 pm Post subject: |
|
|
Code:
public int doSomeStuff(int i, int b){ i++; b++; i = i*b - 35;
b = Math.pow(b, 2);
return i - b
}
This makes me cringe sooooo hard. My code is never like that. I actually feel strong emotions against people who don't indent an opening brace correctly. Observe how my code looks with braces:
Code:
public int doSomeStuff(int i, int b)
{
i++; b++; i = i*b - 35;
b = Math.pow(b, 2);
return i - b
}
There, now isn't that nice?
As for the code without braces... Imagine if HTML were like that? Or BBCode? Instead of wrapping things in tags, you just prefaced them with a header. Imagine how quickly things would get ugly! |
|
| Back to top |
|
|
elfprince13

OVER NINE THOUSAND!

Joined: 23 May 2005 Posts: 10224 Location: A galaxy far far away......
|
Posted: 05 Mar 2009 05:05:00 pm Post subject: |
|
|
| magicdanw wrote: | This makes me cringe sooooo hard. My code is never like that. I actually feel strong emotions against people who don't indent an opening brace correctly. Observe how my code looks with braces:
Code:
public int doSomeStuff(int i, int b)
{
i++; b++; i = i*b - 35;
b = Math.pow(b, 2);
return i - b
}
There, now isn't that nice? |
I agree, unfortunately not everyone is so well mannered Thankfully Python forces well-manneredness
| magicdanw wrote: | | As for the code without braces... Imagine if HTML were like that? Or BBCode? Instead of wrapping things in tags, you just prefaced them with a header. Imagine how quickly things would get ugly! |
HTML and BBCode aren't programming languages, they're markup languages, which have a drastically different use, though quite honestly, I wish HTML did force polite indentation, because a lot of sites are pretty dirty looking if you read through the source. _________________ StickFigure Graphic Productions || VSHI: Vermont Sustainable Heating Initiative
 |
|
| Back to top |
|
|
Tari

Systems Integrator

Joined: 03 Jul 2006 Posts: 2106 Location: Always-winter, Michigan
|
Posted: 05 Mar 2009 06:28:24 pm Post subject: |
|
|
My favorite variety of Python crack is Django. With just 4 lines of code, I can implement and interface a new object into my templates.
 _________________
Ask questions the smart way · タリ |
|
| Back to top |
|
|
Kllrnohj

PH34R |\/|3

Joined: 24 May 2005 Posts: 8189
|
Posted: 05 Mar 2009 09:33:26 pm Post subject: |
|
|
| magicdanw wrote: | Code:
public int doSomeStuff(int i, int b)
{
i++; b++; i = i*b - 35;
b = Math.pow(b, 2);
return i - b
}
|
It is the same thing in python, just drop the braces. Oh, and you missed the ; after the return statement (see, python would have saved you, since they aren't needed )
Code:
def doSomeStuff(i, b):
i += 1; b += 1; i = i*b - 35;
b = math.pow(b, 2);
return i - b
And yes, the above actually runs in python. Semi-colons are perfectly acceptable in python. Go ahead, copy/paste it into an interpreter (after "import math", of course)
Oh, and you can get "strong" typing in Python. I had a code snippet somewhere here that you could something along the lines of
Code: @filter(int,(int,float))
def blah(a, b):
pass
And it would only allow you to pass in a type of 'int' for the first parameter, but the second parameter could take a type of 'int' or 'float'
@Elf: You mentioned list comprehensions, what about dictionary comprehensions? Don't be hating now
My favorite uses of python are its extreme flexibility at runtime. For example:
Code: >>> class foo:
... __name__ = "wouldn't you like to know"
...
>>> f = foo()
>>> def t(self):
... print(self.__name__)
...
>>> f.printName = types.MethodType(t,f)
>>> f.printName()
wouldn't you like to know
Now that is self modifying code
Or the ability to override just about anything. Example:
Code: >>> class foo:
... def __getattr__(self, attr):
... return "Get it yourself, yeesh..."
...
>>> f = foo()
>>> print(f.hello)
Get it yourself, yeesh...
>>>
_________________ There are only two kinds of programming languages: those people always bitch about and those nobody uses. (Bjarne Stroustrup) |
|
| Back to top |
|
|
magicdanw
Advanced Member

Joined: 26 Sep 2007 Posts: 282
|
|
| Back to top |
|
|
elfprince13

OVER NINE THOUSAND!

Joined: 23 May 2005 Posts: 10224 Location: A galaxy far far away......
|
Posted: 05 Mar 2009 10:25:40 pm Post subject: |
|
|
| magicdanw wrote: | I left it out cause Elfprince did in his original example. Perhaps Python is making him too complacent to program in other languages?  |
Don't even talk until you switch from writing utility scripts in Python to multi-threaded data processing apps in Java (not my choice, requirement of the research project). <bad pun>That's what we call a "jar"ring transition </bad pun>
@Kllrnohj: I haven't used Python 3.0 yet, so no dict or set comprehensiony goodness for me. _________________ StickFigure Graphic Productions || VSHI: Vermont Sustainable Heating Initiative
 |
|
| Back to top |
|
|
Kllrnohj

PH34R |\/|3

Joined: 24 May 2005 Posts: 8189
|
Posted: 06 Mar 2009 12:22:31 am Post subject: |
|
|
| elfprince13 wrote: | | @Kllrnohj: I haven't used Python 3.0 yet, so no dict or set comprehensiony goodness for me. |
You are missing out. Check out this hotness:
Code: >>> class book:
... author = "bob"
... title = "python is awesome"
...
>>> b = book()
>>> print("Book: '{0.title}' by {0.author}".format(b))
Book: 'python is awesome' by bob
>>>
Format, of course, takes a variable number of arguments. First argument is {0}, second is {1}, etc.... _________________ There are only two kinds of programming languages: those people always bitch about and those nobody uses. (Bjarne Stroustrup) |
|
| Back to top |
|
|
KermMartian

Site Admin

Joined: 14 Mar 2005 Posts: 55732 Location: Earth, Sol, Milky Way
|
|
| Back to top |
|
|
elfprince13

OVER NINE THOUSAND!

Joined: 23 May 2005 Posts: 10224 Location: A galaxy far far away......
|
|
| Back to top |
|
|
Kllrnohj

PH34R |\/|3

Joined: 24 May 2005 Posts: 8189
|
Posted: 06 Mar 2009 10:05:53 am Post subject: |
|
|
| elfprince13 wrote: | | Reasonably cool, but why use format() instead of just print("Book: '%s' by %s" % (b.author, b.format)) |
Because then you have to specify the type, and that just doesn't make sense in a duck typed language. The {n} method doesn't care what type of object you give it. I could have passed in anything for {0}, and I don't have to reflect that in the print string. Also, you are passing in 2 objects, I only had to pass in one
| KermMartian wrote: | | to show that even in C it's not that bad, but that's cute too. |
yeah, but again, you have to know the type, and in C if you get the type wrong you don't get an error stating as such, you get a hard crash. Heck, C++ has an output that doesn't require the type to be specified, so its about time Python caught up in that regard  _________________ There are only two kinds of programming languages: those people always bitch about and those nobody uses. (Bjarne Stroustrup) |
|
| Back to top |
|
|
elfprince13

OVER NINE THOUSAND!

Joined: 23 May 2005 Posts: 10224 Location: A galaxy far far away......
|
Posted: 06 Mar 2009 12:43:22 pm Post subject: |
|
|
| Kllrnohj wrote: | Because then you have to specify the type, and that just doesn't make sense in a duck typed language. The {n} method doesn't care what type of object you give it. I could have passed in anything for {0}, and I don't have to reflect that in the print string. Also, you are passing in 2 objects, I only had to pass in one  |
How do you deal with formatting numbers that you want rounded to some number of significant digits? _________________ StickFigure Graphic Productions || VSHI: Vermont Sustainable Heating Initiative
 |
|
| Back to top |
|
|
Kllrnohj

PH34R |\/|3

Joined: 24 May 2005 Posts: 8189
|
Posted: 06 Mar 2009 01:07:47 pm Post subject: |
|
|
| elfprince13 wrote: | | How do you deal with formatting numbers that you want rounded to some number of significant digits? |
Code: >>> print("{0:0.2f}".format(1.1123123))
1.11
>>> for i in range(6):
... print("{0:0.{1}f}".format(1.1123123, i))
...
1
1.1
1.11
1.112
1.1123
1.11231
There are a *lot* of cool things that the new format can do. Check it out here: http://www.python.org/dev/peps/pep-3101/ _________________ There are only two kinds of programming languages: those people always bitch about and those nobody uses. (Bjarne Stroustrup) |
|
| Back to top |
|
|
elfprince13

OVER NINE THOUSAND!

Joined: 23 May 2005 Posts: 10224 Location: A galaxy far far away......
|
|
| Back to top |
|
|
|
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.
» Go to Registration page
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
© Copyright 2000-2013 Cemetech & Kerm Martian :: Page Execution Time: 0.059426 seconds.
|