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
Jo
Jan 24, 2005

:allears:
Soiled Meat

tripwire posted:

You too huh? Using pyopengl?

Right on.

Adbot
ADBOT LOVES YOU

fnordcircle
Jul 7, 2004

PTUI
code:
    new_word=raw_input("Gimme a word: ")

    for i in range(len(new_word)):
        print new_word[i]
        i=i+1
I decided to play around with python when I had the spare time 2 days ago. I read a bit and then started trying to fiddle around with what I knew and pieced together the above based on what I knew and some guessing as to how things might work. It's nothing special, just a baby step. But still I'm psyched that after just a couple hours I feel like I'm getting a grasp of this language that quickly despite never having come close to mastering any of the other languages I've toyed around with (C/C++, Perl, VB and Java.)

I dunno I'm just really happy with this language's accessibility so far and I wanted to say so. I feel like I'll be able to do things of substance towards my ultimate goal of making a roguelike within a few short weeks.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

fnordcircle posted:

code:
    new_word=raw_input("Gimme a word: ")

    for i in range(len(new_word)):
        print new_word[i]
        i=i+1
I decided to play around with python when I had the spare time 2 days ago. I read a bit and then started trying to fiddle around with what I knew and pieced together the above based on what I knew and some guessing as to how things might work. It's nothing special, just a baby step. But still I'm psyched that after just a couple hours I feel like I'm getting a grasp of this language that quickly despite never having come close to mastering any of the other languages I've toyed around with (C/C++, Perl, VB and Java.)

I dunno I'm just really happy with this language's accessibility so far and I wanted to say so. I feel like I'll be able to do things of substance towards my ultimate goal of making a roguelike within a few short weeks.

Beware the blub paradox. http://www.paulgraham.com/avg.html

wrok
Mar 24, 2006

by angerbotSD

fnordcircle posted:

I'm psyched that after just a couple hours I feel like I'm getting a grasp of this language that quickly despite never having come close to mastering any of the other languages I've toyed around with (C/C++, Perl, VB and Java.)

I dunno I'm just really happy with this language's accessibility so far and I wanted to say so. I feel like I'll be able to do things of substance towards my ultimate goal of making a roguelike within a few short weeks.

That's Python for you. I went from "Python sounds like a cool language, I should check it out" to "I never want to write code in any other language ever again" over the span of days (if not hours). It really does just 'click' unlike a lot of other languages.

m0nk3yz posted:

Beware the blub paradox. http://www.paulgraham.com/avg.html

Very true. I'm still honeymooning with Python (and work 45 hours a week with not-Python) -- so I've consciously let myself put on the Blub blinders and get a little carried away, at least for the time being. :D

wrok fucked around with this message at 14:11 on Feb 23, 2009

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

wrok posted:

That's Python for you. I went from "Python sounds like a cool language, I should check it out" to "I never want to write code in any other language ever again" over the span of days (if not hours). It really does just 'click' unlike a lot of other languages.


Very true. I'm still honeymooning with Python (and work 45 hours a week with not-Python) -- so I've consciously let myself put on the Blub blinders and get a little carried away, at least for the time being. :D

My background is primarily as a test-engineer, some scripting in various languages but not a lot of coding - about 7 years ago, I had a task which called for me to start writing a fair amount of code. I ended up picking up python as it was approachable, and let me simply get a lot of things done.

I had exposure to Java and C prior - but not enough to be competent, after I got started with python, I ended up writing an amazing amount of code in it, and really picked up a passion for coding. I've spent about a year doing Java coding since then (off and on) and I've been doing some C work as well, but it's hard - Python fundamentally spoiled my brain. Everything from the syntax, to the language constructs itself and the standard library has simply sucked me in. I miss things that are python givens. :(

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

fnordcircle posted:

code:
    new_word=raw_input("Gimme a word: ")

    for i in range(len(new_word)):
        print new_word[i]
        i=i+1

You think that's cool?
code:
for letter in new_word:
    print letter

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

Lord Uffenham posted:

You think that's cool?
code:
for letter in new_word:
    print letter

I was huffing paint this morning
code:
Python 2.6 (r26:66714, Nov  7 2008, 16:28:10) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import print_function
>>> new_word = 'hooray python'
>>> [print(i) for i in new_word]
h
o
o
r
a
y
 
p
y
t
h
o
n
[None, None, None, None, None, None, None, None, None, None, None, None, None]
>>> 

bitprophet
Jul 22, 2004
Taco Defender
^^^^ LORD UFFENHAM :argh:

fnordcircle posted:

code:
    new_word=raw_input("Gimme a word: ")

    for i in range(len(new_word)):
        print new_word[i]
        i=i+1

Maybe I'm missing something, since nobody else corrected you on this, but you don't need to do that i=i+1 there. Python for loops iterate over some sort of collection, and thus rarely need any sort of counter variable.

In fact, Python strings are themselves iterable objects (returning single-character strings -- there's no "char" type), so your code can be simply rewritten as:

code:
new_word = raw_input("Gimme a word: ")
for character in new_word:
    print character

wrok
Mar 24, 2006

by angerbotSD
I was huffing paint sniffing glue this morning

code:
>>> from __future__ import print_function
>>> new_word = 'hooray python'
>>> [x[0] for x in [[x,print(x)] for x in new_word]]
h
o
o
r
a
y
 
p
y
t
h
o
n
['h', 'o', 'o', 'r', 'a', 'y', ' ', 'p', 'y', 't', 'h', 'o', 'n']
>>> 
I'm really going to hell now:

code:
>>> new_word = "print(new_word)"
>>> eval("".join([x[0] for x in [[x,print(x)] for x in new_word]]))

wrok fucked around with this message at 16:35 on Feb 23, 2009

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

wrok posted:

I was huffing paint sniffing glue this morning

I'm really going to hell now:

code:
>>> new_word = "print(new_word)"
>>> eval("".join([x[0] for x in [[x,print(x)] for x in new_word]]))

It's sadistic code golf.

ATLbeer
Sep 26, 2004
Über nerd

wrok posted:

code:
>>> new_word = "print(new_word)"
>>> eval("".join([x[0] for x in [[x,print(x)] for x in new_word]]))

3.0 snob... 2.6 fo lyfe

This is hysterical code though.. Reminded me about a turned down consulting gig back in my PHP days where there were "stored procedures" of code that were stored as text in a DB which was called and eval()'d. I couldn't find anywhere in the code where the stored data ("function") was altered.. The originally programmer just used the DB to store code as opposed to just creating a new file. It was more than I wanted to try to peel apart for what they were willing to spend.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

ATLbeer posted:

3.0 snob... 2.6 fo lyfe

This is hysterical code though.. Reminded me about a turned down consulting gig back in my PHP days where there were "stored procedures" of code that were stored as text in a DB which was called and eval()'d. I couldn't find anywhere in the code where the stored data ("function") was altered.. The originally programmer just used the DB to store code as opposed to just creating a new file. It was more than I wanted to try to peel apart for what they were willing to spend.

Reminds me of another weird urge I had the other day; given stackless tasklets are picklable (as well as the channel), you could serialize them and put them into a database, and in theory, a SQL query of the objects in the database could actually dictate the "program structure". You just need an ORM that auto-depickles the objects and adds them to the scheduler. Store your channels in another table, and select those with the query too.

Yeah, no.

fnordcircle
Jul 7, 2004

PTUI

bitprophet posted:

Maybe I'm missing something, since nobody else corrected you on this, but you don't need to do that i=i+1 there. Python for loops iterate over some sort of collection, and thus rarely need any sort of counter variable.

In fact, Python strings are themselves iterable objects (returning single-character strings -- there's no "char" type), so your code can be simply rewritten as:

code:
new_word = raw_input("Gimme a word: ")
for character in new_word:
    print character

Yeah I'm sure you're not missing anything, I'm ridiculously new to python, maybe 4 hours in at this point, I was just proud of myself for figuring out a way to access a string's elements without knowing the length of the string beforehand.

I had no doubts there was a simpler, more elegant solution. Good to know about the iteration thing, though. Thanks.

king_kilr
May 25, 2007

m0nk3yz posted:

Reminds me of another weird urge I had the other day; given stackless tasklets are picklable (as well as the channel), you could serialize them and put them into a database, and in theory, a SQL query of the objects in the database could actually dictate the "program structure". You just need an ORM that auto-depickles the objects and adds them to the scheduler. Store your channels in another table, and select those with the query too.

Yeah, no.

Isn't that part of the seaside framework, it pickles poo poo, stores it in the session or something like that, maybe I need to stop reading reddit while tired.

ATLbeer
Sep 26, 2004
Über nerd

m0nk3yz posted:

Reminds me of another weird urge I had the other day; given stackless tasklets are picklable (as well as the channel), you could serialize them and put them into a database, and in theory, a SQL query of the objects in the database could actually dictate the "program structure". You just need an ORM that auto-depickles the objects and adds them to the scheduler. Store your channels in another table, and select those with the query too.

Yeah, no.

I had a similar thought a while ago (and I wasn't the first one, there are modules out there that people have written already for it) to pickle python functions and send them over the wire with parameters to "workers" to have a distributed work farm in processing large amounts of information. I don't recall what the modules that actually did it were called as my need for such a system disappeared. But, you can do all sorts of fun things with that type of "meta" Python

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

ATLbeer posted:

I had a similar thought a while ago (and I wasn't the first one, there are modules out there that people have written already for it) to pickle python functions and send them over the wire with parameters to "workers" to have a distributed work farm in processing large amounts of information. I don't recall what the modules that actually did it were called as my need for such a system disappeared. But, you can do all sorts of fun things with that type of "meta" Python

Oh, that's common/widespread. That's essentially RPC of a sort. As long as you can pickle it (and you could even pickle threads + threadpools) you can send them over the wire for farming out to a group of boxes. My particular insanity was making something that let you construct an application from a series of SQL queries. I call it WTF driven development, or SOLIDPOOP.

PS: Multiprocessing can be used to farm out jobs

m0nk3yz fucked around with this message at 02:50 on Feb 24, 2009

tef
May 30, 2004

-> some l-system crap ->

ATLbeer posted:

I had a similar thought a while ago (and I wasn't the first one, there are modules out there that people have written already for it) to pickle python functions and send them over the wire with parameters to "workers" to have a distributed work farm in processing large amounts of information.

http://discoproject.org/ ?

quote:

Disco is an open-source implementation of the Map-Reduce framework for distributed computing. As the original framework, Disco supports parallel computations over large data sets on unreliable cluster of computers.

The Disco core is written in Erlang, a functional language that is designed for building robust fault-tolerant distributed applications. Users of Disco typically write jobs in Python, which makes it possible to express even complex algorithms or data processing tasks often only in tens of lines of code. This means that you can quickly write scripts to process massive amounts of data.

Mashi
Aug 15, 2005

Just wanted you to know your dinner's cold and the children all agree you're a shitheel!
Ok, I'm making GBS threads bricks. I am making a site with Django and I have to present data according to the user's timezone.

Basically, what I need is an easy way to convert a time between a non UTC timezone and a user's timezone, and I need it to compensate for daylight saving, if applicable.

I know it doesn't sound that hard, but there are several ways to do it. This is my first time using timezones in Python. What would be the best way to go about it so that I don't shoot myself in the foot?

The way I see it, my options are:

* Use the pytz module (looks promising)
* Use the built in time module (I have a feeling I'll run into problems with this one).
* Keep python naive about the timezone and use timedeltas to calculate localised time (might be complex with the DST).

Thanks in advance.

king_kilr
May 25, 2007
http://code.google.com/p/django-timezones/ may be just what you're looking for.

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.
That's just a django wrapper around pytz. pytz is most certainly what you should be using, though. It works in conjunction with the stdlib datetime module. There's really no reason to be using the time module for this; it would be a lot of extra work that would just be duplicating what's already been done in datetime and pytz. Doing it all naïve is even stupider. pytz is rather easy to use as long as you read the documentation.

Kire
Aug 25, 2006

Lord Uffenham posted:

You think that's cool?
code:
for letter in new_word:
    print letter

Why does this not work when I type it in? 2.6:
code:
word = "Hurrah!"
for letter in word:
    print letter

SyntaxError: invalid syntax
It highlights "letter" in line 2.

Or did I miss some kind of joke, with a whoosh over my head?

Edit: monk3yz, that article about Lisp was really interesting.

Kire fucked around with this message at 23:07 on Feb 24, 2009

hey mom its 420
May 12, 2007

Are you sure that's the exact code? This
code:
word = "Hurrah!"
for letter in word:
    print letter
works as expected for me and it's really weird that you're getting problems with this piece of code.

deimos
Nov 30, 2006

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

Kire posted:

Why does this not work when I type it in? 2.6:
code:
word = "Hurrah!"
for letter in word:
    print letter

SyntaxError: invalid syntax
It highlights "letter" in line 2.

Or did I miss some kind of joke, with a whoosh over my head?

Edit: monk3yz, that article about Lisp was really interesting.

:psyduck:

code:
C:\>python
ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
Python 2.6.1 (r261:67515, Dec  5 2008, 13:58:38) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> word = "Hurrah!"
>>> for letter in word:
...     print letter
...
H
u
r
r
a
h
!
>>>
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV

No Safe Word posted:

I'm guessing he has a space before "for" and it's giving an indentation error.

That would be a IndentationError: unexpected indent


VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV

tripwire posted:

It could also be mixing tabs and spaces.

On a single line inside the for loop?

deimos fucked around with this message at 23:56 on Feb 24, 2009

No Safe Word
Feb 26, 2005

I'm guessing he has a space before "for" and it's giving an indentation error.

tripwire
Nov 19, 2004

        ghost flow
It could also be mixing tabs and spaces.

hey mom its 420
May 12, 2007

Maybe he's running it with the perl command, haha.

Mashi
Aug 15, 2005

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

Habnabit posted:

That's just a django wrapper around pytz. pytz is most certainly what you should be using, though. It works in conjunction with the stdlib datetime module. There's really no reason to be using the time module for this; it would be a lot of extra work that would just be duplicating what's already been done in datetime and pytz. Doing it all naïve is even stupider. pytz is rather easy to use as long as you read the documentation.

Cheers, I'll go with pytz and sacrifice a lamb...

darknife
Feb 23, 2009
So I trying to write a short script to determine if a triangle is a right triangle given the three vertices.

First I have to find the distances. Done:

code:
def isright(x1,y1,x2,y2,x3,y3):
	a = ((x2-x1)**2 + (y2-y1)**2)**.5
	b = ((x3-x2)**2 + (y3-y2)**2)**.5
	c = ((x1-x3)**2 + (y1-y3)**2)**.5
Now how would I figure out what is the smallest integer out of a, b, and c. Then the next smallest integer?

Possibly using < or > but I think that would be too much of a hassle.

wrok
Mar 24, 2006

by angerbotSD

darknife posted:

So I trying to write a short script to determine if a triangle is a right triangle given the three vertices.

First I have to find the distances. Done:

code:
def isright(x1,y1,x2,y2,x3,y3):
	a = ((x2-x1)**2 + (y2-y1)**2)**.5
	b = ((x3-x2)**2 + (y3-y2)**2)**.5
	c = ((x1-x3)**2 + (y1-y3)**2)**.5
Now how would I figure out what is the smallest integer out of a, b, and c. Then the next smallest integer?

Possibly using < or > but I think that would be too much of a hassle.

code:
mysortedlist = sorted([a,b,c])

smallest = mysortedlist[0]
next = mysortedlist[1]
biggest = mysortedlist[2]
Right?

darknife
Feb 23, 2009

wrok posted:

code:
mysortedlist = sorted([a,b,c])

smallest = mysortedlist[0]
next = mysortedlist[1]
biggest = mysortedlist[2]
Right?

Works!

Thanks!

code:
def isright(x1,y1,x2,y2,x3,y3):
	a = ((x2-x1)**2 + (y2-y1)**2)**.5
	b = ((x3-x2)**2 + (y3-y2)**2)**.5
	c = ((x1-x3)**2 + (y1-y3)**2)**.5
	#sort smallest to largest thanks wrok
	mysortedlist = sorted([a,b,c])
	smallest = mysortedlist[0]
	next = mysortedlist[1]
	biggest = mysortedlist[2]
	#calculate 
	if (smallest**2 + next**2) == biggest**2:
		print "Yes, it is a right triangle."
	else: print " No it is not a right triangle."

	
>>> isright(-2,2,-1,6,3,5)
Yes, it is a right triangle.
Janky function but works for what I need it to do.


darknife fucked around with this message at 05:23 on Feb 25, 2009

other people
Jun 27, 2004
Associate Christ
I have a simple list that has pairs of directory names and file names.

So for example: ['/etc/apache2/', 'apache2.conf'] or something like that, over and over.

I want to perform an action on each item in the list, but only if the first list[0] is unique. If a directory is in the list more than once, I don't want to muck with it. Googling about I have figured out I may want to do something with sets? I don't quite understand what a set is. Lists have always worked for me.



As a side note, there is something wrong with my browser or the python web site. The documentation pages are using some horrendous font. I had to tell firefox to not let web pages define their own fonts. Is this just me?


edit: I am trying to do something like:
code:
for item in fileList:
	if fileList.count(item[0]) == 1:
		do something
	else:
		print "%s appears more than once :o" % item[0]
But fileList.count(item[0]) always returns zero. Huh?

other people fucked around with this message at 06:07 on Feb 25, 2009

such a nice boy
Mar 22, 2002

Kaluza-Klein posted:

edit: I am trying to do something like:
code:
for item in fileList:
	if fileList.count(item[0]) == 1:
		do something
	else:
		print "%s appears more than once :o" % item[0]
But fileList.count(item[0]) always returns zero. Huh?

Haven't tried this, but I think it would work...

code:
directoryList = [item[0] for item in fileList]
for item in fileList:
	if directoryList.count(item[0]) == 1:
		do something
	else:
		print "%s appears more than once :o" % item[0]

other people
Jun 27, 2004
Associate Christ

such a nice boy posted:

Haven't tried this, but I think it would work...

code:
directoryList = [item[0] for item in fileList]
for item in fileList:
	if directoryList.count(item[0]) == 1:
		do something
	else:
		print "%s appears more than once :o" % item[0]

Ha, I just came here to edit my post with this:
code:
	dirList = []
	for item in fileList:
		dirList.append(item[0])

	for item in fileList:
		num = dirList.count(item[0])
		print "%s appears %s time(s)" % (item[0], num)
#		if fileList.count(item[0]) == 1:
#			uniquelist.append([item[0], item[1]])
#		else:
#			print "The directory %s appears more than once" % item[0]
Who knew.

uncleTomOfFinland
May 25, 2008

Kaluza-Klein posted:

Googling about I have figured out I may want to do something with sets? I don't quite understand what a set is. Lists have always worked for me.

Set is an unordered collection of unique objects. There is no particular order for the objects in the set and all the members of the set have to be different from each other. It's quite handy sometimes.

uncleTomOfFinland fucked around with this message at 10:07 on Feb 25, 2009

Benji the Blade
Jun 22, 2004
Plate of shrimp.

Kaluza-Klein posted:

Ha, I just came here to edit my post with this:
code:
	dirList = []
	for item in fileList:
		dirList.append(item[0])

	for item in fileList:
		num = dirList.count(item[0])
		print "%s appears %s time(s)" % (item[0], num)

For what it's worth, here's what I came up with:

code:
def f(file_list):
    from itertools import groupby
    for d, f_itr in groupby(sorted(file_list), lambda item: item[0]):
        files = [item[1] for item in f_itr]
        if len(files) == 1:
            pass # do stuff
        else:
            print "%s appears %i times" % (d, len(files))
This has the benefit of having better performance for large file_lists (O(n log(n)) instead of O(n^2)), but if it's just gonna be a small number, my gut tells me the shorter version will run faster.

Mostly, I wanted to introduce the idea of using "sorted" and "groupby" to solve your problem. In this case, they're a lot like using the UNIX utils, "sort | uniq" only instead of just deleting multiples, groupby gives you all the values in the list where the key function (in this case "lambda item: item[0]") evaluates to be equal.

Kire
Aug 25, 2006
A question about IDLE: When I type something in the shell and hit enter, is there a conveienent way to re-enter the same thing? Like how at the DOS prompt the user can push up-arrow to get back the last thing entered.

I hate typing in a few lines with a small error, and having to cut-and-paste to get it all back to edit it.

wrok
Mar 24, 2006

by angerbotSD

Kire posted:

A question about IDLE: When I type something in the shell and hit enter, is there a conveienent way to re-enter the same thing? Like how at the DOS prompt the user can push up-arrow to get back the last thing entered.

I hate typing in a few lines with a small error, and having to cut-and-paste to get it all back to edit it.

By default Alt-P goes back in history and Alt-N goes forward. You can change that in the options.

pankus
Jul 30, 2003
Okay this may be a stupid question but I don't know the correct terminology to be able to google it. I have a loop where I store something in a variable, and append that variable to a list. The problem is that every time I change this variable in the loop, it changing all the values in the list ( since they were all assigned to the same variable at one point ) Is there a correct way to accomplish what I want to do?

tef
May 30, 2004

-> some l-system crap ->
Python variables are references, not values. You want to copy the variable before adding it to the list in this instance. Can you post some code?

Also: http://docs.python.org/library/copy.html

Here is an example of references - both b and a refer to the *same* list. = does not copy the value.
code:
>>> a= []
>>> a.append(1)
>>> a
[1]
>>> b= a
>>> b
[1]
>>> b.append(2)
>>> a
[1, 2]
>>> 
Example 2:

code:
>>> a= []; c=[]
>>> c.append(a)
>>> c.append(a)
>>> a.append(1)
>>> c
[[1], [1]]


>>> import copy
>>> a= []; c=[]
>>> c.append(copy.copy(a))
>>> c.append(copy.copy(a))
>>> a.append(1)
>>> c
[[], []]

tef fucked around with this message at 06:10 on Feb 27, 2009

Adbot
ADBOT LOVES YOU

pankus
Jul 30, 2003

tef posted:

Python variables are references, not values. You want to copy the variable before adding it to the list in this instance. Can you post some code?

Sure. This isn't all of the code, but I'm certain it's the relevant part.

code:
for line in file:
     listEntry.name = line[ searchPos_a + 9 : searchPos_b ]
     ranges.append(listEntry)

for item in ranges:
     print(item.name)
Obviously this prints the same name from the last one that was read in.

EDIT: I changed the following line
code:
ranges.append( copy.copy( listEntry ) )
and it works now. Is copy a bad thing? I should probably sit down and read some technical overviews before just jumping right in.

pankus fucked around with this message at 06:19 on Feb 27, 2009

  • Locked thread