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
hlfrk414
Dec 31, 2008
The boggle problem interested me, so I solved with what I believe is some efficiency. I'll give you the benefit of a doubt and trust you when you say you just want to practice classes. Here is some (probably) working code that you can either convert to classes or just use to test your own code.
http://pastebin.com/f32924a7c *fixed*
Edit: Of course I find a bug after I post.
Edit: Also forgot to check for cycles, even though I explicitly passed around a list to do that. That's what I get for coding at 2 in the morning. Now with comments. I'll stop picking at it now.

hlfrk414 fucked around with this message at 21:36 on May 2, 2009

Adbot
ADBOT LOVES YOU

tripwire
Nov 19, 2004

        ghost flow

hlfrk414 posted:

The boggle problem interested me, so I solved with what I believe is some efficiency. I'll give you the benefit of a doubt and trust you when you say you just want to practice classes. Here is some (probably) working code that you can either convert to classes or just use to test your own code.
http://pastebin.com/f52aadc6c
Edit: Of course I find a bug after I post.

Whats the bug

hlfrk414
Dec 31, 2008
Fixed it before you could see it! I'm tricky like that. Prove me otherwise and I'll fix those bugs too.

The Evan
Nov 29, 2004

Apple ][ Cash Money

outlier posted:

ipython has dreload (deep reload) but with normal python, I think you have to reload all.

yeah this is just the standard python implementation that comes with os x. dumb question: when you say "reload all", is there a keyword to do that? if module_a imports module_b, and i only import module_a, reload(module_b) will fail.

Tetramin
Apr 1, 2006

I'ma buck you up.
I started learning python yesterday, and bumped in to some pretty expansive python IRC bot guides on http://www.devshed.com, and had tons of fun with that all day. Only problem now is, I don't know what I want to(or what I'd even be capable of) outside of that. Lots of people say that's the hardest part of learning to program, which sucks because when I'm trying to make stuff and have ideas I'm having a blast, but after screwing around making various IRC bots to do different things all day I don't know where to go next.. This is probably a really stupid question, but does anybody have maybe a suggestion or two on fairly beginner friendly projects to work on?

I think I just started learning the wrong way, and I know barely anything about the offline side of python, and just started doing IRC poo poo after leaning basic syntax.

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

Funnehman posted:

I started learning python yesterday, and bumped in to some pretty expansive python IRC bot guides on http://www.devshed.com and had tons of fun with that all day. Only problem now is, I don't know what I want to(or what I'd even be capable of) outside of that. Lots of people say that's the hardest part of learning to program, which sucks because when I'm trying to make stuff and have ideas I'm having a blast, but after screwing around making various IRC bots to do different things all day I don't know where to go next.. This is probably a really stupid question, but does anybody have maybe a suggestion or two on fairly beginner friendly projects to work on?

I think I just started learning the wrong way, and I know barely anything about the offline side of python, and just started doing IRC poo poo after leaning basic syntax.

What are your interests, generally?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Funnehman posted:

I started learning python yesterday, and bumped in to some pretty expansive python IRC bot guides on http://www.devshed.com and had tons of fun with that all day. Only problem now is, I don't know what I want to(or what I'd even be capable of) outside of that. Lots of people say that's the hardest part of learning to program, which sucks because when I'm trying to make stuff and have ideas I'm having a blast, but after screwing around making various IRC bots to do different things all day I don't know where to go next.. This is probably a really stupid question, but does anybody have maybe a suggestion or two on fairly beginner friendly projects to work on?

I think I just started learning the wrong way, and I know barely anything about the offline side of python, and just started doing IRC poo poo after leaning basic syntax.

When I started learning python 6 months ago, I used it to solve little problems that I run in to every day.

For example, I had a directory with 10,000+ images that I wanted to sort in to different directories by resolution, so I wrote a script to do that. Another thing was that I wanted to graph the different stats reported by my cable modem's web interface, so I wrote a python script to fetch that stuff into a csv every five minutes.

Basically, think about things you do every day and figure out if there's a way to write a script to do it better.

Tetramin
Apr 1, 2006

I'ma buck you up.

Thermopyle posted:

When I started learning python 6 months ago, I used it to solve little problems that I run in to every day.

For example, I had a directory with 10,000+ images that I wanted to sort in to different directories by resolution, so I wrote a script to do that. Another thing was that I wanted to graph the different stats reported by my cable modem's web interface, so I wrote a python script to fetch that stuff into a csv every five minutes.

Basically, think about things you do every day and figure out if there's a way to write a script to do it better.

Yeah I have a few things like that, I do wish I had more though, I just can't wrap my head around OOP and poo poo, up until an hour or two ago, I had no clue how to call the functions in module files, and poo poo like that.

The worst part for me, I think... Is I'll try to think of a project, or hear one taht sounds cool, and I'll think about how I could do it for a while.. Then I'll be like nah I don't just wanna lay down the code, everyones doing OOP now, I'd look like a scrub!

edit: Speaking of which, right now I'm still working with IRC bots and whatnot, just curious if anybody knew like, the 'protocol' or if it is possible to get the channel name without typing it in yourself? I'm pretty sure the room's possible to get, just not so sure about when everyones using modules and poo poo.

Tetramin fucked around with this message at 21:12 on May 2, 2009

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Funnehman posted:

Yeah I have a few things like that, I do wish I had more though, I just can't wrap my head around OOP and poo poo, up until an hour or two ago, I had no clue how to call the functions in module files, and poo poo like that.

The worst part for me, I think... Is I'll try to think of a project, or hear one taht sounds cool, and I'll think about how I could do it for a while.. Then I'll be like nah I don't just wanna lay down the code, everyones doing OOP now, I'd look like a scrub!

Actually, I'm kind of in the same boat. I'll learn something only if I have a reason to, and I haven't really had a reason to use classes or any OOP stuff. I haven't really done anything where I could see a reason to use anything other than regular ole' functions.

I have wrote a little something that I've released into the wild, though! I've got to do a little hacking on it, because I didn't realize at the time that python now includes the json module...

Thermopyle fucked around with this message at 22:12 on May 2, 2009

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

The Evan posted:

yeah this is just the standard python implementation that comes with os x. dumb question: when you say "reload all", is there a keyword to do that? if module_a imports module_b, and i only import module_a, reload(module_b) will fail.

No. Don't use reload anyway; it works reliably, but very rarely how you expect or want it to.

Whatever you're doing is more than likely better done either with python -i or by writing a unit test.

The Evan
Nov 29, 2004

Apple ][ Cash Money

Habnabit posted:

No. Don't use reload anyway; it works reliably, but very rarely how you expect or want it to.

Whatever you're doing is more than likely better done either with python -i or by writing a unit test.

Thanks. I probably should have written this as a standalone module instead of relying on interactive mode, but it's moot now. Just finished up my paper and turned it in to the professor. If he likes it, I'll try submitting for publication. :ohdear:

Sylink
Apr 17, 2004

Can anyone explain what exactly is going on here?

code:
def Prime(primes, i=2):
    if i**2 < primes[-1]:
        primes[i:] = filter(lambda x: x % i, primes[i:])
    return primes
Called like so with a range Prime(range(2,1000))

Returns a list of primes using the Sieve method. I understand how the sieve works and I have made my own but this version is very efficient.

I don't completely understand the syntax involved and how lambda functions are used even after reading it.

What is the primes[i:] indicating?

The Evan
Nov 29, 2004

Apple ][ Cash Money
The [:] notation is for range indexing, e.g. arr[2:4] will give you elements 2 through 4 of arr. However, you can drop the numbers. arr[:x] would be first through xth, and arr[y:] would be the yth through the end.

I might have that backwards, I've only been using python for a few days. :)

bitprophet
Jul 22, 2004
Taco Defender

The Evan posted:

The [:] notation is for range indexing, e.g. arr[2:4] will give you elements 2 through 4 of arr. However, you can drop the numbers. arr[:x] would be first through xth, and arr[y:] would be the yth through the end.

I might have that backwards, I've only been using python for a few days. :)

No, you've got it correct. Omitting one end of a slice implicitly means "that end of the iterable", so [:10] is from the beginning to the 10th index, and [10:] is from the 10th index to the end.

Furthermore, you can omit both ([:]), which means exactly what you might expect: from the beginning to the end. This sounds silly but is useful for quickly making copies of iterables, e.g. my_new_list = my_old_list[:].

spankweasel
Jan 4, 2006

Sylink posted:

Can anyone explain what exactly is going on here?

code:
def Prime(primes, i=2):
    if i**2 < primes[-1]:
        primes[i:] = filter(lambda x: x % i, primes[i:])
    return primes
Called like so with a range Prime(range(2,1000))

Returns a list of primes using the Sieve method. I understand how the sieve works and I have made my own but this version is very efficient.

I don't completely understand the syntax involved and how lambda functions are used even after reading it.

What is the primes[i:] indicating?

It's useful to know 3 things about the code above:

1: filter (function, iterable) returns a list of elements in iterable for which function is true.

2: lambda x: x % i is simply returning True or False if x % i == 0

3: list[n:] is a convenient way of slicing the list ... ex:

code:

>>> a = range (10)
>>> a 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a [:5]
[0, 1, 2, 3, 4]
>>> a[5:]
[5, 6, 7, 8, 9]
>>> 
so,

code:
primes[i:] = filter(lambda x: x % i, primes[i:])
is saying that

for all indexes in primes > i, set "True" for each one where x % i is 0.

lambda functions can get brutal, very very fast. It's the primary reason I avoid them. That and I'm the only python guy in my group and if I start using tricky python (lambda, decorators, etc.) I get dinged hard in code review :)

drat KSH lovers ... :suicide:

PrBacterio
Jul 19, 2000

Sylink posted:

Can anyone explain what exactly is going on here?

code:
def Prime(primes, i=2):
    if i**2 < primes[-1]:
        primes[i:] = filter(lambda x: x % i, primes[i:])
    return primes
Called like so with a range Prime(range(2,1000))

Returns a list of primes using the Sieve method. I understand how the sieve works and I have made my own but this version is very efficient.

I don't completely understand the syntax involved and how lambda functions are used even after reading it.

What is the primes[i:] indicating?

That function won't work like this, though, as right now, all it does is remove all multiples of i from the given list. There is going to have to be some sort of loop or iteration in there for it to work.

Now for my actual question; I've been trying to get into a more pythonic (:v:) mindset when writing Python code, and looking at that I was wondering, wouldn't a version using generators instead of lambda and filter be considered to be more idiomatic in Python these days, ie. something like
code:
def Prime(primes, i=2):
    if i ** 2 < primes[-1]:
        primes[i:] = [k for k in primes[i:] if k % i != 0]
    return primes
Am I right in thinking that thats what would be considered a clean, idiomatic way of doing this in Python?

Mashi
Aug 15, 2005

Just wanted you to know your dinner's cold and the children all agree you're a shitheel!

PrBacterio posted:

code:
def Prime(primes, i=2):
    if i ** 2 < primes[-1]:
        primes[i:] = [k for k in primes[i:] if k % i != 0]
    return primes
Am I right in thinking that thats what would be considered a clean, idiomatic way of doing this in Python?

The only problem I can see is that you have a function name starting with a capital. In python the convention is something like functions and variables are underscore_separated_words and classes are CapWords.

edit: http://www.python.org/dev/peps/pep-0008/

Sylink
Apr 17, 2004

Ok, but is that function recursive somehow? Or is it comparing every item in prime[i:] to every other item and eliminating them if the modulus is zero.

Right now I look at it and don't see how it can possibly leave only primes.

My impression of the filter function is that it applies the given function to every item in the list once.It also seem sit should be dividing by 2 for every item and only odd items should be left.

spankweasel
Jan 4, 2006

Sylink posted:

Ok, but is that function recursive somehow? Or is it comparing every item in prime[i:] to every other item and eliminating them if the modulus is zero.

Right now I look at it and don't see how it can possibly leave only primes.

My impression of the filter function is that it applies the given function to every item in the list once.It also seem sit should be dividing by 2 for every item and only odd items should be left.

It's simply walking the list (range (2,1000)) and marking all multiples of a known prime. i.e. when it finds 3 to be prime, it walks your list and removes 6, 9, 12, 15, 18, etc. as possible candidates for being prime.

Sylink
Apr 17, 2004


Ok here is the real sieve utilizing what I didn't understand based off something from wikipedia.

code:
def primeSieve(upperlimit):
    numbers = range(2,upperlimit)
    primes = []
    while numbers:
        prime = numbers.pop(0)
        primes.append(prime)
        numbers = filter(lambda x: x%prime,numbers)
    return primes
I'm trying to do the project euler stuff but keep running into efficiency issues so I'm trying to make faster code.

Sylink fucked around with this message at 19:30 on May 3, 2009

spankweasel
Jan 4, 2006

project euler is so much fun. I need to go revamp my code and make a library of common stuff like this.

As to your post, what exactly are you asking?

Sylink
Apr 17, 2004

I thought the function originally was doing some sort of recursive magic but I didn't realize it was not actually finding all the primes. So my original question is pretty moot since the code was wrong.

EDIT: For anyone that cares here is a solution to problem 12:

code:

from math import *
def isPrime(num):
    if type(num) != int: return False
    if num == 2: return True
    if num < 2 or num % 2 == 0: return False
    return not any(num % i == 0 for i in range(3, int(sqrt(num))+1, 2))



def prime_factors(num):
    if num == 1: return[num]
    powers = []
    limit = (num/2)+1
    i = 2
    if isPrime(num): return [num]
    while i <= limit:
        while num % i == 0:
            powers.append(i)
            num = num/i
        i += 1
        if num == 1: break
    return powers


def num_factors(n):
    numfactors = 1
    factors = prime_factors(n)
    counts = []
    while len(factors)!=0:
        counts.append(factors.count(factors[0]))
        factors = filter(lambda f: f != factors[0],factors)
    for i in counts:
        numfactors *= i+1

    return numfactors


numfactors = 1
trianglenum = 1
i = 1
while numfactors < 500:
    trianglenum+=i+1
    numfactors = num_factors(trianglenum)
    i=i+1

print trianglenum
Takes about 2 seconds.

Sylink fucked around with this message at 21:11 on May 3, 2009

Geno
Apr 26, 2004
STUPID
DICK
any suggestions for a lib for reading excel files in python? right now, i'm looking at xlrd.

Tetramin
Apr 1, 2006

I'ma buck you up.
I was just about to post a pretty big post asking a bunch of questions regarding classes/subclasses and like, "when do i.." questions.

I just wanted to say that I ended up answering my own questions by just writing out the question, pretty badass, I'm not sure how often that happens in other languages, heh.

Anyways, I'm still hacking away with irclib.py*, This time I'm going to try starting my own bot complete from scratch, besides the module, before I was using a tutorial/kinda mixing it up, but now I think I understand the way things work with irc anyways better, and should hopefully do a decent job!


*I highly recommend it to anyone, but probably if you're still fairly new and want some fun projects to get started, there's quite a few different ways to do each thing so it's a good learning experience.

edit - Does anyone know of a good way to condense the add_global_handler methods(Not sure if these are pretty much just for this specific module, hope not), seems pretty lame having the space right before you connect to the server just loving lines and lines of those things*. also, why would you ever want to remove_global_handlers, I think I kind of get why, but maybe if anyone has an example or anything that would be sweet.

Dammit I ended up thinking of more questions while posting.

One last thing, as far as including modules, why would i include object from file, rather than just including the entire module?
Whoever did the documentation on the sample file with the library is a jerk.
code:
  nick = nm_to_n(e.source())
        if nick == c.get_nickname():
            self.channels[ch] = Channel()
Not terrible I guess, but the entire thing's like this, so I have to go through, figure out what something means, and just makes it kinda tiresome.

Tetramin fucked around with this message at 10:42 on May 4, 2009

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...

Geno posted:

any suggestions for a lib for reading excel files in python? right now, i'm looking at xlrd.

That's the one. Or rather, it's the generally best choice and works well. There also pyaccelerator (don't think it's being developed any more) and a series of COM solutions that will only work on Windows.

No Safe Word
Feb 26, 2005

Honestly the best choice is to have it exported to CSV and then just use Python's built-in csv module, but that may or may not be an option.

Geno
Apr 26, 2004
STUPID
DICK

No Safe Word posted:

Honestly the best choice is to have it exported to CSV and then just use Python's built-in csv module, but that may or may not be an option.

seems perfect for what i'm doing, thanks.

Tetramin
Apr 1, 2006

I'ma buck you up.
Made (kind of) my first program today, a pretty lovely contact list manager!

If anybody wants to check it out and point out anything I'm doing wrong(probably alot) that would be awesome.
Yeah I know, it only handles two values per entry, and if there's a space in the name you're hosed. I'll probably fix that tomorrow.
http://pastebin.com/m733ddafa

Tetramin fucked around with this message at 11:36 on May 5, 2009

The Evan
Nov 29, 2004

Apple ][ Cash Money
Can someone point me in the direction of a quick explanation of print and the % operator? I was trying today to do something like:

int i = 0
print "i is: %d" % (i)

But it kept giving me errors about concatenating strings and ints and such.

tef
May 30, 2004

-> some l-system crap ->

The Evan posted:

But it kept giving me errors about concatenating strings and ints and such.

code:
>>> i = 3
>>> print "i is %d" % i
i is 3
>>> i = 3.0
>>> print "i is %f" % i
i is 3.000000
>>> i = "three"
>>> print "i is %s" % i
i is three
>>> a,b = 1,2
>>> print "a is %d, b is %d" % (a,b)
a is 1, b is 2
>>> 

ahobday
Apr 19, 2007

Funnehman posted:

Made (kind of) my first program today, a pretty lovely contact list manager!

If anybody wants to check it out and point out anything I'm doing wrong(probably alot) that would be awesome.
Yeah I know, it only handles two values per entry, and if there's a space in the name you're hosed. I'll probably fix that tomorrow.
http://pastebin.com/m733ddafa

This reminded me of the address book I wrote to make use of a class. I've just gone through it and compacted it, because I love trying to make code as short as possible. A bit of a silly obsession, since I'm not even a good programmer. Still, I thought I'd share it with you as a "high-five over making address books":

http://pastebin.com/m7c49b59d

Edit: Even though I posted this to show you how short mine was compared to yours, I just read through your code some more and saw that you wrote in a lot more safety nets. Mine assumes that commands are entered correctly and that there's a file present in the directory, for example, whereas yours doesn't.

ahobday fucked around with this message at 15:59 on May 5, 2009

awesomepanda
Dec 26, 2005

The good life, as i concieve it, is a happy life.
can someone recommend me the appropriate module for python to interface with ms access 2007. im very new to programming and databases but i know some sql. i was trying to use MYSQLdb but i dont know how to create the appropriate connection string for a database on my desktop. please let me know if mysqldb is appropriate.

tbradshaw
Jan 15, 2008

First one must nail at least two overdrive phrases and activate the tilt sensor to ROCK OUT!

CrazyPanda posted:

can someone recommend me the appropriate module for python to interface with ms access 2007. im very new to programming and databases but i know some sql. i was trying to use MYSQLdb but i dont know how to create the appropriate connection string for a database on my desktop. please let me know if mysqldb is appropriate.

While I'm uncertain what library would be best for connecting to an Access database, I'm certain that MySQLdb isn't it. MySQLdb is a module for connecting to MySQL databases, and no others.

No Safe Word
Feb 26, 2005

CrazyPanda posted:

can someone recommend me the appropriate module for python to interface with ms access 2007. im very new to programming and databases but i know some sql. i was trying to use MYSQLdb but i dont know how to create the appropriate connection string for a database on my desktop. please let me know if mysqldb is appropriate.

You want some sort of ODBC lib, I forget which one is the best but here's a few:

http://wiki.python.org/moin/ODBC

ShizCakes
Jul 16, 2001
BANNED
I'm coming in from PHP, and I absolutely love Python (3.0.1) so far. It's so clean, things make sense, the code is far more beautiful when I am done, etc.

The only thing is, I can't stand the notion of WSGI. I really would like to stick with Python instead of PHP for simple web-apps, but I hate the whole approach to the problem. I like the way I can make a directory in Apache, insert a file called blah.php, and if all I want to do is echo a single variable, I can do that. If I want the file to be mostly HTML with just a tiny bit of PHP, I can do that.

It doesn't seem like anything along those lines exist for Python 3, or does it?

I am not trying to be a jerk, so I'd like to nip any "If you want it to be like PHP then use PHP" responses in the bud - I am just trying to see if that style of coding exists for Python 3, or if it's planned, or what.

In summary, how to do I write simple web applications of Python 3 that don't require the WSGI style of doing things. (That style being: application handles all paths, you have to handle things like response codes and all that - I want Apache to do the apache things, and Python to do the scripting, and HTML/CSS to do the HTML/CSS). Is it possible?

tbradshaw
Jan 15, 2008

First one must nail at least two overdrive phrases and activate the tilt sensor to ROCK OUT!

ShizCakes posted:

In summary, how to do I write simple web applications of Python 3 that don't require the WSGI style of doing things.

Really, the issue here is feature parity. Your interface to scripting in PHP isn't as low level as Python and you're not having to do any of the CGI yourself. In Python, WSGI is merely the more advanced CGI standard.

In the same way you let PHP do your CGI for you, you should let a Python framework do your WSGI for you. But you'll need to pick one, because Python doesn't necessarily come with a portion of web framework built-in-and-turned-on-by-default like PHP does.

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH

tbradshaw posted:

In the same way you let PHP do your CGI for you, you should let a Python framework do your WSGI for you. But you'll need to pick one, because Python doesn't necessarily come with a portion of web framework built-in-and-turned-on-by-default like PHP does.
A summarized breakdown/comparison of current widely used Python web frameworks may be useful to him. I would write it myself, but I don't really know much about Python frameworks other than Django. I am mostly posting this because I would be very interested in reading about other frameworks as well.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

supster posted:

A summarized breakdown/comparison of current widely used Python web frameworks may be useful to him. I would write it myself, but I don't really know much about Python frameworks other than Django. I am mostly posting this because I would be very interested in reading about other frameworks as well.

http://wiki.python.org/moin/WebFrameworks

geera
May 20, 2003

ShizCakes posted:

Is it possible?
I've not used it myself, but you might check in to web.py for a minimalist web framework.

Adbot
ADBOT LOVES YOU

The Evan
Nov 29, 2004

Apple ][ Cash Money

tef posted:

code:
>>> i = 3
>>> print "i is %d" % i
i is 3
>>> i = 3.0
>>> print "i is %f" % i
i is 3.000000
>>> i = "three"
>>> print "i is %s" % i
i is three
>>> a,b = 1,2
>>> print "a is %d, b is %d" % (a,b)
a is 1, b is 2
>>> 

Thanks!

Also I just noticed that I wrote "int i..." in that post; I'm still not used to the sparseness of Python. I keep putting "for each" in my code, too.

  • Locked thread