Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
tef
May 30, 2004

-> some l-system crap ->

Sylink posted:

Can someone explain parsing with elementtree to me, it makes no sense and the effbot stuff seems to all be about making xml, I just want to get information.

Like if I have an element <title>, how do I get the actual content between the tags?

gently caress element tree, learn xpath - it's a standard simple query language for xml documents that is supported on a number of platforms, and it makes xml significantly less painful.

http://codespeak.net/lxml/xpathxslt.html

http://en.wikipedia.org/wiki/XPath_1.0
if you have
code:
<products>
  <product>
    <title lang="en">foo</title>
    <price>0.99</price>
  </product>
</products>
You can access all of the titles using /products/product/title, and attributes with /products/product/title/@lang, as well as indexing the entries: /products/product[1]/title.

It's fairly terse, readable and expressive - and a lot simpler to use than things like dom or sax or object models.

Adbot
ADBOT LOVES YOU

Clanpot Shake
Aug 10, 2006
shake shake!

I'm having a hard time wrapping my head around how Python handles string concatenation. Here's some code I'm working with:
pre:
def getHigh(self, event):
	"""Called when high score list is to be displayed"""
	filename = "high.txt"
	scores = []
	message = ""
	FILE = open(filename,"r")
	while FILE:
		line = FILE.readline()		# format: '[name]_[score]' where _ = space
		s = line.split()
		n = len(s)
		if n == 0:
			break
		scores.append(s)
	# assemble the list to be readable
	for i in range(len(scores)):
>>		message += str(i),".   %s   %s\n" % (scores[i][0], scores[i][1])
	dialog = wx.MessageDialog(None, message, "Biggest Losers", wx.OK)
        dialog.ShowModal()
The idea is to display a list of high scores read from a file. I keep getting this error: 'TypeError: cannot concatenate 'str' and 'tuple' objects' on the line marked with >>
I've tried casting with str() and some other stuff, but nothing seems to take. How do I convert items from a 2D array to drop them into a string?
(the wx stuff is a GUI package)

tripwire
Nov 19, 2004

        ghost flow

Clanpot Shake posted:

I'm having a hard time wrapping my head around how Python handles string concatenation. Here's some code I'm working with:
pre:
def getHigh(self, event):
	"""Called when high score list is to be displayed"""
	filename = "high.txt"
	scores = []
	message = ""
	FILE = open(filename,"r")
	while FILE:
		line = FILE.readline()		# format: '[name]_[score]' where _ = space
		s = line.split()
		n = len(s)
		if n == 0:
			break
		scores.append(s)
	# assemble the list to be readable
	for i in range(len(scores)):
>>		message += str(i),".   %s   %s\n" % (scores[i][0], scores[i][1])
	dialog = wx.MessageDialog(None, message, "Biggest Losers", wx.OK)
        dialog.ShowModal()
The idea is to display a list of high scores read from a file. I keep getting this error: 'TypeError: cannot concatenate 'str' and 'tuple' objects' on the line marked with >>
I've tried casting with str() and some other stuff, but nothing seems to take. How do I convert items from a 2D array to drop them into a string?
(the wx stuff is a GUI package)

Look at what you are doing on that line.

If the variable to the left of the += operator is a string then the expression on the right hand side has to be a string as well. You have a string with a comma after it followed by a format string and variables as if you are combining it with the syntax for the print statement.
code:
str(i),".   %s   %s\n" % (scores[i][0], scores[i][1])
Should be
code:
str(i) + ".   " + scores[i][0] + "   " + scores[i][1] + "\n"

Clanpot Shake
Aug 10, 2006
shake shake!

I looked at my course notes and the instructor never seems to use + to concatenate things. What exactly is the difference between , and +?

ahobday
Apr 19, 2007

sw-itch posted:

A wrapper for this was actually posted yesterday on http://planet.python.org , maybe they read this thread.

This is awesome. I'm guessing the easiest way of using this be to just copy-paste this code into whatever Python I'm writing?

tripwire
Nov 19, 2004

        ghost flow

Clanpot Shake posted:

I looked at my course notes and the instructor never seems to use + to concatenate things. What exactly is the difference between , and +?

comma doesn't concatenate things, its for declaring tuples. The print statement interprets tuples specially.

When you have something like this:
code:
>>> print 'something', 'somethingelse'
You are giving the print statement a tuple.
You can also use format strings with the print statement like you may be used to doing with printf() in c.

You are merely concatenating strings however, not printing them. You shouldn't be placing tuples or format strings after the += operator. If you want to concatenate two strings in an expression, you can use the + operator. In python the plus operator does different things depending on the type of its operands- given two integers or two floats, it will return their sum; given two lists it will return the second list appended to the first list; given two strings, it will return the second concatenated with the first. A += B is the same thing as saying A = A + B.

For consistencies sake, python 3000 is moving away from the print statement and uses a print function instead.

tripwire fucked around with this message at 21:58 on May 9, 2009

tripwire
Nov 19, 2004

        ghost flow

Centipeed posted:

This is awesome. I'm guessing the easiest way of using this be to just copy-paste this code into whatever Python I'm writing?

Even easier: save it as "whatever.py" in the same directory as your current python project. Import "whatever" and use as needed.

Sylink
Apr 17, 2004

tef posted:

gently caress element tree, learn xpath - it's a standard simple query language for xml documents that is supported on a number of platforms, and it makes xml significantly less painful.

http://codespeak.net/lxml/xpathxslt.html

http://en.wikipedia.org/wiki/XPath_1.0
if you have
code:
<products>
  <product>
    <title lang="en">foo</title>
    <price>0.99</price>
  </product>
</products>
You can access all of the titles using /products/product/title, and attributes with /products/product/title/@lang, as well as indexing the entries: /products/product[1]/title.

It's fairly terse, readable and expressive - and a lot simpler to use than things like dom or sax or object models.


This is much better, the loving dom models are annoying as gently caress, I was tempted just to make my own xml library.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

Clanpot Shake posted:

pre:
def getHigh(self, event):
	"""Called when high score list is to be displayed"""
	filename = "high.txt"
	scores = []
	message = ""
	FILE = open(filename,"r")
	while FILE:
		line = FILE.readline()		# format: '[name]_[score]' where _ = space
		s = line.split()
		n = len(s)
		if n == 0:
			break
		scores.append(s)
	# assemble the list to be readable
	for i in range(len(scores)):
>>		message += str(i),".   %s   %s\n" % (scores[i][0], scores[i][1])
	dialog = wx.MessageDialog(None, message, "Biggest Losers", wx.OK)
        dialog.ShowModal()
Or you could just use message += "%s. %s %s\n" (str(i), scores[i], scores[i][1])

also you can loop over a file with
code:
FILE = open(filename, 'r')
for line in FILE:
    scores.append(line.split())
And if you need the index of an iterable during iteration you can use enumerate, along with some tuple unpacking to do
code:
for i, (name, score) in enumerate(scores):
   message += "%s.\t%s\t%s\n" % (i, name, score)

spankweasel
Jan 4, 2006

Lonely Wolf posted:

Or you could just use message += "%s. %s %s\n" (str(i), scores[i], scores[i][1])

Why would you cast i to a string?

message += "%d. %s %s\n" % (i, scores[i], scores[i][1])

Just go with the printf-esque replacement strings and don't waste time casting.

Ferg
May 6, 2007

Lipstick Apathy

Sylink posted:

It just seems like every time I want to parse xml its completely non-intuitive and voodoo. Not to mention they don't have practical examples most of the time it seems. :(

I completely agree. While it's probably not practical for most applications of XML, I prefer the lazy man's way of using JSON with a simple call to parse it into an associative array or whatever. I personally haven't used JSON with Python (only PHP) but I would imagine it dumps the data into a dictionary.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

spankweasel posted:

Why would you cast i to a string?

message += "%d. %s %s\n" % (i, scores[i], scores[i][1])

Just go with the printf-esque replacement strings and don't waste time casting.

I was just keeping it close to his code there. If you'll notice the second time I didn't, though I did keep it as %s in the format string, implicitly casting it to repr, because I was far too lazy to remember that it was supposed to be %d.

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
I don't get it...

Doesn't ElementTree support xpath? What's the problem?

ShizCakes
Jul 16, 2001
BANNED
Does anyone have a retard-proof, step-by-step guide for getting ANYTHING running on python running under lighttpd?

web.py was the only deployment guide that I can find, and I just can NOT get it working. I've been trying for about 12 hours at this point.

code:
2009-05-10 01:03:04: (log.c.75) server started 
2009-05-10 01:03:04: (mod_fastcgi.c.1325) --- fastcgi spawning local 
	proc: /var/www/hello.py 
	port: 0 
	socket /tmp/fastcgi.socket 
	min-procs: 1 
	max-procs: 1 
2009-05-10 01:03:04: (mod_fastcgi.c.1350) --- fastcgi spawning 
	port: 0 
	socket /tmp/fastcgi.socket 
	current: 0 / 1 
: No such file or directory
2009-05-10 01:03:04: (mod_fastcgi.c.1047) the fastcgi-backend /var/www/hello.py failed to start: 
2009-05-10 01:03:04: (mod_fastcgi.c.1051) child exited with status 127 /var/www/hello.py
1) /var/www/hello.py exits, and is CHMOD 777.
2) /tmp/fastcgi.socket exists, and is generated and owned by lighttpd.
3) hello.py is the python file copy/pasted from the web.py tutorial

code:
## fastcgi configuration
 fastcgi.server = ( "/hello.py" =>
 (( "socket" => "/tmp/fastcgi.socket",
    "bin-path" => "/var/www/hello.py",
    "max-procs" => 1
 ))
 )
code:
#!/usr/bin/env python
import web

urls = (
  '/', 'hello')

app = web.application(urls, globals())

class hello:
    def GET(self):
        return 'Hello, web!'

if __name__ == "__main__":
    app.run()
Finally, I can find NOTHING of use on google at this point. Any suggestions? Perhaps point me to a guide that explains the ultra-basic concepts of how this stuff is supposed to work?

The only guides I have found say something like "oh, just point it to your fcgi socket and then..." -- too advanced. I don't have a socket. I don't have anything.

:cries from frustration:

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
You probably don't want Lighttpd running on port 0. I'm honestly not even sure if that's a valid port number. You should be setting a port number, etc. in lighttpd.conf.

ahobday
Apr 19, 2007

This is going to sound super-stupid if I've missed something, because I've never gotten into Python web programming, but don't you need mod_python installed? I know I can't get into it personally because my host won't install mod_python.

sw-itch
Apr 6, 2008

ShizCakes posted:

Finally, I can find NOTHING of use on google at this point. Any suggestions? Perhaps point me to a guide that explains the ultra-basic concepts of how this stuff is supposed to work?

The only guides I have found say something like "oh, just point it to your fcgi socket and then..." -- too advanced. I don't have a socket. I don't have anything.

:cries from frustration:

Could hello.py be in the wrong format? I.E. Windows format instead of UNIX format. That is usually the case for me when pasting things directly from the docs don't work.

Easiest way I know to change it is to install notepad++ and Format>Convert to UNIX format, save then re-upload.

ctz
Feb 6, 2003

Centipeed posted:

This is going to sound super-stupid if I've missed something, because I've never gotten into Python web programming, but don't you need mod_python installed?

Not really. mod_python is just the python interpreter as an apache module with some exposure of apache internals in python to allow clever things to be done.

Centipeed posted:

I know I can't get into it personally because my host won't install mod_python.
If your host supports CGI (most do) and has python installed (all non-windows hosts will) then you can. It's generally much easier to work with too, the main downside is performance (as each page view will cause a python interpreter to be invoked as a subprocess).

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"

Centipeed posted:

This is going to sound super-stupid if I've missed something, because I've never gotten into Python web programming, but don't you need mod_python installed? I know I can't get into it personally because my host won't install mod_python.

mod_python is for Apache (and it sucks, use mod_wsgi)

Shiz: I've never used lighttpd or web.py, but I found this basic configuration through Google. It works when I run lighttpd -f lighttpd.conf -D -- does it work for you?

code:
server.modules = ("mod_accesslog", "mod_fastcgi", "mod_rewrite", "mod_redirect")

server.document-root = "/var/www"

server.error-handler-404 = "/home/john/hello.py"

accesslog.filename          = "/home/john/fcgi-access.txt"
server.errorlog             = "/home/john/fcgi-error.txt"
server.username = "nobody"
server.groupname = "nogroup"

server.port = 3221
server.bind = "127.0.0.1"

fastcgi.debug = 1

fastcgi.server = ( "/hello.py" =>(
"/"=>(
    "bin-path" => "/home/john/hello.py",
    "socket" => "/tmp/fastcgi.socket",
    "check-local" => "disable",
    "max-procs" => 1
))
)

url.rewrite-once = (
   "^/static/(.*)$" => "/static/$1",
   "^/(.*)$" => "/hello.py/$1"
)
code:
#!/usr/bin/env python
import web

urls=('/','index')

class index:
    def GET(self):
        web.header("Content-Type","text/plain; charset=utf-8")
        return "testing"

app = web.application(urls, globals())

if __name__ == "__main__":
    app.run()

ShizCakes
Jul 16, 2001
BANNED

Janin posted:

Shiz: I've never used lighttpd or web.py, but I found this basic configuration through Google. It works when I run lighttpd -f lighttpd.conf -D -- does it work for you?

Thank you for this to check my conf against - the guides I found on google had me set up my conf the same way. I appreciate the work in throwing that out there to help me double check.

sw-itch posted:

Could hello.py be in the wrong format? I.E. Windows format instead of UNIX format. That is usually the case for me when pasting things directly from the docs don't work.

Easiest way I know to change it is to install notepad++ and Format>Convert to UNIX format, save then re-upload.

Holy poo poo.

Holy loving poo poo.

So obvious, yet I wasn't even CLOSE to thinking along those lines. You are completely correct. One dos2unix command later, BAM functioning server. In fact, I appreciate this so much I would be happy to purchase a custom title for you or a platinum upgrade - whichever you prefer. My email is shizcakes - gmail.com.

The Evan
Nov 29, 2004

Apple ][ Cash Money
Am I crazy or does Python not support increment/decrement? Is i += 1 the only way to do it?

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH

The Evan posted:

Am I crazy or does Python not support increment/decrement? Is i += 1 the only way to do it?
You're not crazy. This is by design and IIRC it is because post/pre increment/decrement operators are seen to promote cryptic code.

I think that is fairly accurate and agree with the choice, although I certainly do not disagree that the operator can be (and most commonly is) used in non-cryptic ways.

supster fucked around with this message at 13:07 on May 11, 2009

The Evan
Nov 29, 2004

Apple ][ Cash Money
Fair enough; thanks.

Modern Pragmatist
Aug 20, 2008
I would like to return the elements of an array that satisfy a given condition. I know that I can do this with the following:

code:
var = scipy.arange(10)
limit = 8
result = [item for item in var if item <= limit]
However, it seems that there should be a more elegant solution. For example using the bool array returned by:

code:
var <= 8
I have multiple arrays that need to be sliced using the same indeces and feel that the bool array could be determined by one and applied to the others.

Any suggestions would be appreciated.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
code:
>>> import numpy
>>> f = numpy.array([1,2,3,4,5,6,7,8,9])
>>> f
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> f[f>5]
array([6, 7, 8, 9])

Modern Pragmatist
Aug 20, 2008

Avenging Dentist posted:

code:
>>> import numpy
>>> f = numpy.array([1,2,3,4,5,6,7,8,9])
>>> f
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> f[f>5]
array([6, 7, 8, 9])

Wow, completely missed that one. Thanks.

ATLbeer
Sep 26, 2004
Über nerd

Avenging Dentist posted:

code:
>>> import numpy
>>> f = numpy.array([1,2,3,4,5,6,7,8,9])
>>> f
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> f[f>5]
array([6, 7, 8, 9])

wow.... i had no idea you could do that...

insanity and very powerful

No Safe Word
Feb 26, 2005

ATLbeer posted:

wow.... i had no idea you could do that...

insanity and very powerful

Only with numpy, as far as I can tell.

tripwire
Nov 19, 2004

        ghost flow

No Safe Word posted:

Only with numpy, as far as I can tell.

Isn't it the exact same thing as doing filter( lambda something: something > 5, whatever_sequence)?

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

tripwire posted:

Isn't it the exact same thing as doing filter( lambda something: something > 5, whatever_sequence)?

Not really.
code:
>>> good = numpy.arange(10)
>>> good
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> good[good>5] = 0
>>> good
array([0, 1, 2, 3, 4, 5, 0, 0, 0, 0])
code:
>>> bad = range(10)
>>> bad
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> filter(lambda x: x>5,bad) = 42
  File "<stdin>", line 1
SyntaxError: can't assign to function call
>>> def truncate(x):
...     if x>5:
...         return 0
...     else:
...         return x
... 
>>> map(truncate,bad)
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]

tripwire
Nov 19, 2004

        ghost flow

Avenging Dentist posted:

Not really.
code:
>>> good = numpy.arange(10)
>>> good
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> good[good>5] = 0
>>> good
array([0, 1, 2, 3, 4, 5, 0, 0, 0, 0])
code:
>>> bad = range(10)
>>> bad
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> filter(lambda x: x>5,bad) = 42
  File "<stdin>", line 1
SyntaxError: can't assign to function call
>>> def truncate(x):
...     if x>5:
...         return 0
...     else:
...         return x
... 
>>> map(truncate,bad)
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]
Ok, so with the f[f>5] form you can assign to a range, but I think that's just numpy magic going on behind the scenes. The original question was how to see the contents of a sequence that match a given condition, and thats exactly what filter is for.

If you aren't using numpy you can still assign conditionally to elements in a range pretty easily by using a loop like so:
code:
foo = range(10)
for index, element in enumerate(foo):
    if element > 5: foo[index] = 0

tripwire fucked around with this message at 23:47 on May 11, 2009

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

tripwire posted:

The original question was how to see the contents of a sequence that match a given condition, and thats exactly what filter is for.

Not if you read the rest of his post:

quote:

I have multiple arrays that need to be sliced using the same indeces and feel that the bool array could be determined by one and applied to the others.

tripwire
Nov 19, 2004

        ghost flow

Avenging Dentist posted:

Not if you read the rest of his post:

Touché. Carry on then

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.

Avenging Dentist posted:

Not really.
code:
>>> good = numpy.arange(10)
>>> good
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> good[good>5] = 0
>>> good
array([0, 1, 2, 3, 4, 5, 0, 0, 0, 0])
code:
>>> bad = range(10)
>>> bad
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> filter(lambda x: x>5,bad) = 42
  File "<stdin>", line 1
SyntaxError: can't assign to function call
>>> def truncate(x):
...     if x>5:
...         return 0
...     else:
...         return x
... 
>>> map(truncate,bad)
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]

Don't mean to nitpick, but:

code:
>>> notsobad = range(10)
>>> map(lambda x: 0 if x > 5 else x, notsobad)
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

jupo posted:

Don't mean to nitpick, but:

code:
>>> notsobad = range(10)
>>> map(lambda x: 0 if x > 5 else x, notsobad)
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]

I always forget that syntax, but in my defense it is because that is the worst version of the ternary operator I can think of. It's not even in the right order.

(Also, the really important thing in my opinion is that numpy doesn't make a copy of the array, which would kill the performance of the software I work on.* Honestly, I would hate Python if it weren't for Numpy, which makes it at least somewhat tolerable. Of course, like nearly every scripting language I know, I'm more familiar with the C API than the language itself. The C API is for Python is a huge pain in the rear end, by the way.)

* Granted, it has to make an instance of the boolean array, but at least that's a C array under the hood, and it's not so bad if you're reusing it as the original question was talking about.

Avenging Dentist fucked around with this message at 07:40 on May 12, 2009

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.

Avenging Dentist posted:

I always forget that syntax, but in my defense it is because that is the worst version of the ternary operator I can think of. It's not even in the right order.

Well in your defense I believe it's a relatively new addition to the language, 2.5 if I recall.

I also remember when they added it to the language they ran a bunch of test cases across the standard library and found that most of the time the condition would evaluate to the same value for each test case which is the reasoning for the (apparently) weird order:

code:
common_value if condition else uncommon_value
Makes sense if you think about it 1000 times.

darknife
Feb 23, 2009
Okay, I'm learning recursion and this is my first real function using it.


I'm trying to create a recursvie function that takes decimal and converts to binary.


Here is what I have. I'm doing something wrong because it loops forever and then ends with "RuntimeError: maximum recursion depth exceeded".

I think I might just be doing recursion completely wrong.

code:
def binto(num, x = 1, bstr="")
	if num == 0:
		return
	else:
		#get largest power of 2(x) below num
		if x == 1:
			while x < num:
				x += x
			x /= 2
		# if x can fit evenly in num add 1 to bstr else 0
		if num - x > 0:
			num -= x
			bstr = bstr+ "1"
			x /= 2
		else:
			bstr = bstr+ "0"
			x /= 2
		bstr = binto(num, x, bstr)
		return bstr
I'm going to try tracing it to get my head around recursive fully. The hell's wrong with this?

darknife fucked around with this message at 01:29 on May 13, 2009

hlfrk414
Dec 31, 2008
Everything. That code is confusing, without the recursion. What the heck is x and bstr for when you could just compute them in the function? Why is it returning None, "return", for the number zero? I thought it was "0" for zero. Here is a working recursive version:

code:
>>> def binary(num):
	if num == 0:
		return '0'
	if num == 1:
		return '1'
	lowdigit = '0' if num % 2 == 0 else '1'
	return binary(num // 2) + lowdigit

>>> for i in range(10):
	print(bin(i), '->', binary(i))

	
0b0 -> 0
0b1 -> 1
0b10 -> 10
0b11 -> 11
0b100 -> 100
0b101 -> 101
0b110 -> 110
0b111 -> 111
0b1000 -> 1000
0b1001 -> 1001

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"
Python 3 rules, just finished testing the port of a library I wrote and it's about 25% faster. I was also able to simplify the code immensely.

code:
$ python3 speedtest.py 
Reading data
old jsonlib:  1.103366
new jsonlib:  0.867395
stdlib json: 71.427396

Writing data
old jsonlib:  1.293511
new jsonlib:  0.828123
stdlib json: 29.775200
Feeling :smug: as gently caress

Adbot
ADBOT LOVES YOU

darknife
Feb 23, 2009

hlfrk414 posted:

Everything. That code is confusing, without the recursion. What the heck is x and bstr for when you could just compute them in the function? Why is it returning None, "return", for the number zero? I thought it was "0" for zero. Here is a working recursive version:

code:
>>> def binary(num):
	if num == 0:
		return '0'
	if num == 1:
		return '1'
	lowdigit = '0' if num % 2 == 0 else '1'
	return binary(num // 2) + lowdigit

>>> for i in range(10):
	print(bin(i), '->', binary(i))

	
0b0 -> 0
0b1 -> 1
0b10 -> 10
0b11 -> 11
0b100 -> 100
0b101 -> 101
0b110 -> 110
0b111 -> 111
0b1000 -> 1000
0b1001 -> 1001


Yea, I didn't really know how it worked either.

How does yours work?

  • Locked thread