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
latexenthusiast
Apr 22, 2008
I'm running Mac OS X Tiger, and Python 2.5, and I wanted to update my PYTHONPATH to permanently look in a scripts folder, so I typed into Terminal:
code:
vi .bash_profile
and found it to be empty. I was pretty sure that in the process of installing Python 2.5, or perhaps when installing iPython/NumPy/SciPy/Pytz/matplotlib and all that fun stuff, I had at some point edited my .bash_profile, but whatevs, I went on. So then in editing mode, I typed
code:
export PYTHONPATH=/Users/latexenthusiast/python/scripts
and :wq'd it. So I quit Terminal to make sure this wasn't a temporary change like sys.path.append() or whatever, opened Python, found that I could import the script from my scripts directory, and then tried to test it out. That involves numpy, which wasn't found. After freaking out for a bit (the install took hours, and I followed no less that two sets of instructions no less than three times each to get everything to work), I noticed that the version of Python I get when typing "python" into the bash is 2.3.5, which is what's bundled with Tiger, I think. So I still have 2.5 floating around on my computer with all the lovely NumPy/SciPy/etc., but I want to know how to get that build to run when I call Python from the bash. Probably an easy fix, but I wasn't really sure what to search for with Google or anything.

Adbot
ADBOT LOVES YOU

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.
^^^
Try typing 'python2.5' and see if that brings anything up. It's probably in /Library/Frameworks/Python.framework/Versions/2.5/bin, which you should add to your $PATH ahead of everything else. Also, since it sounds like you're an admin on the computer, you should instead add a .pth file to your site-packages folder instead of using $PYTHONPATH. You'll be able to see the directory always, instead of just with the right mix of environment variables.

Does .profile exist? That could be what was adding the aforementioned directory to $PATH previously.

IntoTheNihil posted:

I literally just (an hour ago) jumped into programming with Python. Right now i'm using this and am up to the 5th part. I'm understanding it so far but I'm not holding much in my memory. Is there a better online tutorial or even book I should use or is this just normal confusion that goes away after using Python for a few weeks.

I've seen that tutorial before, and while it's okay for the most part, it explains things badly. Think Python is great for new programmers, and if you want to read another tutorial after that, the official tutorial is also pretty good. Dive Into Python is behind the times, being written for python 2.2, as well as not as clear as other tutorials I've seen. I think its only strong point is that it covers more of the standard library. Think Python and the official tutorial cover some of the shiny new things that have been added to the language since.

Habnabit fucked around with this message at 09:02 on Dec 18, 2008

latexenthusiast
Apr 22, 2008
It seems that just running python2.5 caused it to unfuck itself, because when I opened .bash_profile, the proper Python path was in there. I removed the /Users/latexenthusiast/python/scripts from my PYTHONPATH and used the .pth file instead. I was kind of unsure where my site-packages were before this, but in the process of searching for Python 2.5 earlier, I found it, so now I know how to properly use those. After restarting Terminal, everything seems to be in order. Thank you so much for your help! I was expecting to have to wait quite a bit longer for a proper response, but people like you make this place worth :10bux:.

chemosh6969
Jul 3, 2004

code:
cat /dev/null > /etc/professionalism

I am in fact a massive asswagon.
Do not let me touch computer.
If you're like me, you know that computer programs aren't really doing anything unless the computer's beeping.

After discovering this

code:
# play music on the PC internal speaker
# tested with Python24 on a Windows XP computer  vegaseat  15aug2005

import winsound
import time

# the notes
P = 0   # pause
C = 1
CS = 2  # C sharp
D = 3
DS = 4
E = 5
F = 6
FS = 7
G = 8
GS = 9
A = 10
AS = 11
B = 12

EN = 100  # eighth note
QN = 200  # quarter note
HN = 400  # half note
FN = 800  # full note

def play(octave, note, duration):
    """play note (C=1 to B=12), in octave (1-8), and duration (msec)"""
    if note == 0:    # a pause
        time.sleep(duration/1000)
        return
    frequency = 32.7032           # C1
    for k in range(0, octave):    # compute C in given octave
        frequency *= 2

    for k in range(0, note):      # compute frequency of given note
        frequency *= 1.059463094  # 1.059463094 = 12th root of 2
    time.sleep(0.010)             # delay between keys 

    winsound.Beep(int(frequency), duration)

def bigben():
    play(4,E,HN)
    play(4,C,HN)
    play(4,D,HN)
    play(3,G,HN+QN); play(3,P,QN)
    play(3,G,HN)
    play(4,D,HN)
    play(4,E,HN)
    play(4,C,HN+QN)

bigben()
http://www.daniweb.com/code/snippet359.html

I now have the basis for adding random beeps to be played during any, and all, loops.

I hope this helps someone else.

chemosh6969 fucked around with this message at 22:45 on Dec 22, 2008

UnNethertrash
Jun 14, 2007
The Trashman Cometh
EDIT: Nevermind, I got it up and running.

UnNethertrash fucked around with this message at 07:59 on Dec 20, 2008

Plastic Snake
Mar 2, 2005
For Halloween or scaring people.
Alright, I'm not having a problem per-se, but I'm sure that the way I'm going about this program is inefficient. Here's what I've got so far.

code:
#/usr/bin/python
import string
import random

# Create list of Notes and Intervals for random choice
NoteList = ['A', 'A#', 'Bb', 'B', 'C', 'C#', 'Db', 'D', 'D#', 'Eb', 'E', 'F', 'F#', 'Gb', 'G', 'G#', 'Ab']
IntervalList = ['m2', 'M2', 'm3', 'M3', '4', 'T', '5', 'm6', 'M6', 'm7', 'M7']

def quiz():
	# Choose a random entry from NoteList and IntervalList
	Note = random.sample(NoteList, 1)
	Interval = random.sample(IntervalList, 1)
	
	# Convert Note and Interval to a string and strip ['']
	NoteString = str(Note).strip('\[\]\'')
	IntervalString = str(Interval).strip('\[\]\'')
	
	# Prints the chosen Note and Interval as a string
	print 'The Note is ', NoteString
	print 'The Interval is ', IntervalString
	
	# Prompts for the answer
	UserNote = input('Enter the correct ascending interval: ')
	
	# Determine if answer is correct
	if NoteString = 'A':
		if IntervalString = 'm2':
			if UserNote = 'A#':
				print 'Correct'
			elif UserNote = 'Bb':
				print 'Correct'
			else:
				print 'Incorrect'
				break
		if IntervalString = 'M2':
			if UserNote = 'B':
				print 'Correct'
			else:
				print 'Incorrect'
				break
		if IntervalString = 'm3':
			if UserNote = 'C':
				print 'Correct'
			else:
				print 'Incorrect'
				break
Everything up to the if/elif/else statements is fine, it's just those statements themselves that I'm hoping I don't need to do. As you can see, I've only done a couple so far, and I'd really like to not have to go through and do it manually for every note. This seems like the type of thing that would be easily automated with python, but I have no idea how to go about doing this. Anybody have suggestions?

hey mom its 420
May 12, 2007

I'm not so hot on music theory, but maybe you could do something like this:
code:
 note_num = {'A':0, 'A#':1, 'Bb':1, 'B':2, 'C':3, 'C#':4, 'Db':4, 'D':5 ... 
So basically a mapping from a note to a numeric value, going up by one on each half-step. For intervals, you just do a mapping of interval name to how many half-steps the interval is.
code:
 interval_num = {'m2':1, 'M2':2, 'm3':3, 'M3':4 ...
To access the list of note names, you do note_num.keys(), same for interval names. Anyway, then if the random chosen note is, say, B and the interval is M2, you do note_num['A#'] to get 1 and interval_num['M2'] to get 2. So then, the user enters 'C', which is the correct value. To check that, you just check if note_num['C'] equals 1 + 2. So basically you'll do
code:
note_num = {'A':0, 'A#':1, 'Bb':1, 'B':2, 'C':3, 'C#':4, 
'Db':4, 'D':5, 'D#':6, 'Eb':6, 'E':7, 'F':8, 'F#':9, 'Gb':9, 'G':10, 'G#':11, 'Ab':11}
interval_num = {'m2':1, 'M2':2, 'm3':3, 'M3':4, '4':5, 'T':6, '5':7, 'm6':8, 'M6':9, 'm7':10, 'M7':11}
Note = random.sample(note_num.keys(), 1)
Interval = random.sample(interval_num.keys(), 1)
NoteString = str(Note).strip('\[\]\'')
IntervalString = str(Interval).strip('\[\]\'')
print 'The Note is ', NoteString
print 'The Interval is ', IntervalString
UserNote = raw_input('Enter the correct ascending interval: ')
if note_num[NoteString] + interval_num[IntervalString] == note_num[UserNote]: 
  print 'Correct!'
else:
  print 'Incorrect!'
But what happens if we get an overflow? Basically if the note is G# and the interval is M2, that nets us a 11 + 2, which is 13, but 13 is not in there. But that comes to an A#, so we obviously have to wrap around, so we do a modulo with 12. So we change the condition to
code:
if (note_num[NoteString] + interval_num[IntervalString])%12 == note_num[UserNote]: 
I haven't tested this, but you probably get the gist of it. Get the numeric value of the note, get the number of half steps for the interval, add those two and see if they respond to the numeric value of the note that the user has entered.
Also I don't think there's much point in putting this into a function, because it doesn't take any parameters or return anything, it just does input and output, so that's better suited to just be in the top level code of the module.

hey mom its 420 fucked around with this message at 04:12 on Dec 21, 2008

Plastic Snake
Mar 2, 2005
For Halloween or scaring people.
That looks great! Thanks a ton. I knew there had to be some way to do it.

Edit: Works perfectly so far! Thank you.

Plastic Snake fucked around with this message at 08:08 on Dec 21, 2008

Kire
Aug 25, 2006
That big ben song is hilarious.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

Kire posted:

That big ben song is hilarious.

What on earth are you talking about

tbradshaw
Jan 15, 2008

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

m0nk3yz posted:

What on earth are you talking about

Above, the code example plays "big ben".

Jo
Jan 24, 2005

:allears:
Soiled Meat
Silly question.

The following code always returns a 400 error. Seems the request/header information sent to the headers isn't right. It's using the built in HTML/HTTP library, so I think I'm using it wrong. What's the issue?

Python 3k
code:
def getWebPage( website, webpage ):
	try:
		print( " -- Connecting" )
		connection = http.client.HTTPConnection( host=website, post=80 )
		connection.request( "GET", webpage )
		print( " -- Connected.  Grabbing site response" )
		response = connection.getresponse()
		page = response.read()
		print( " -- Closing connection" )
		connection.close()
	except:
		page = "";
		
	return page

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
host=website, post=80

I assume that should be port

ATLbeer
Sep 26, 2004
Über nerd
Anyone know a module that does MIME decoding for email?

I'm working on an app that is reading messages from a POP3 server and just need the from address, subject, and body of the message. Unfortunately email I've found some email clients (Blackberries, Outlook) do loving horrible things to email. I just need a way to reliably extract plain text from the email.

No Safe Word
Feb 26, 2005

ATLbeer posted:

Anyone know a module that does MIME decoding for email?
Does the one that comes in the standard lib not cut it? Or was it just overlooked?

ATLbeer
Sep 26, 2004
Über nerd

No Safe Word posted:

Does the one that comes in the standard lib not cut it? Or was it just overlooked?

It didn't cut it for some reason. Maybe I was misusing it but, it for some cases (BB email in particular) would just pass back the plain encoded text.

I'm using poplib to retrieve the email and tried passing it to the email lib. Maybe I'm just using it wrong.

chemosh6969
Jul 3, 2004

code:
cat /dev/null > /etc/professionalism

I am in fact a massive asswagon.
Do not let me touch computer.

ATLbeer posted:

It didn't cut it for some reason. Maybe I was misusing it but, it for some cases (BB email in particular) would just pass back the plain encoded text.

I'm using poplib to retrieve the email and tried passing it to the email lib. Maybe I'm just using it wrong.

I'm not 100% sure, but I was doing a similar thing and asked a question here and I may have pasted the code I was trying.

If not, I'll link to the guide I was working off of.

My problem was the body of the email. I could get it but it was one big blob that I couldn't do anything with. I couldn't get a single word out of the thing. I tried converting it to strings, using indexes, and other stuff I can't remember and I couldn't get anywhere with that thing.

The entire thing would shoot out of whatever blender I was trying to chop it up in and then it would laugh at me.

If you're able to do anything with the body you're getting, could show me how you did it?

ATLbeer
Sep 26, 2004
Über nerd

chemosh6969 posted:

I'm not 100% sure, but I was doing a similar thing and asked a question here and I may have pasted the code I was trying.

If not, I'll link to the guide I was working off of.

My problem was the body of the email. I could get it but it was one big blob that I couldn't do anything with. I couldn't get a single word out of the thing. I tried converting it to strings, using indexes, and other stuff I can't remember and I couldn't get anywhere with that thing.

The entire thing would shoot out of whatever blender I was trying to chop it up in and then it would laugh at me.

If you're able to do anything with the body you're getting, could show me how you did it?

This is the exact problem I'm having :(

chemosh6969
Jul 3, 2004

code:
cat /dev/null > /etc/professionalism

I am in fact a massive asswagon.
Do not let me touch computer.

ATLbeer posted:

This is the exact problem I'm having :(

http://stackoverflow.com/questions/315362/properly-formatted-example-for-python-imap-email-access#316457

This example died on me at the end but when combined with the knowledge from
http://www.devshed.com/c/a/Python/Python-Email-Libraries-part-2-IMAP/

I was able to get an email into the data variable of the first link.

data[0][1] will return it as a string.

edit: Then you'll have a string with a bunch of /r/n
After a quick twist(if you don't want them)...
code:
a = data[0][1]
b = a.replace('\r\n', '')
...and you'll have a better looking string that I couldn't figure out until today.

It's not pretty but it's a start.

chemosh6969 fucked around with this message at 22:36 on Dec 23, 2008

dwayne_dibbley
Nov 26, 2005
On Windows XP I'm trying to get the output from a command using the subprocess module in Python 3.0

The subprocess docs say this:
output=`mycmd myarg`
==>
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]

So I try it:
>>> output = subprocess.Popen(["a.bat"], stdout=PIPE).communicate()[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'PIPE' is not defined

I then tried getoutput:
>>> subprocess.getoutput("a.bat")
"'{' is not recognized as an internal or external command,\noperable program or batch file."

What's going on? How do you guys get the output from a command back into Python?

Thanks.

nbv4
Aug 21, 2002

by Duchess Gummybuns
code:
def was_forty(self, exam_date):
    import datetime
    birthday = Profile.objects.get(user=self.user).dob # this is django code that returns a datetime.date object

    fortieth_birthday = datetime.date(birthday.year + 40, birthday.month, birthday.day)

    return fortieth_birthday > exam_date
This function determines whether or not you were forty years old when you had an exam. When I open a python shell, the code works fine, but when I use it in my application, I get an error saying "global name date is not defined" (or something to that effect, i'm writing this post from a different computer) on the line where fortieth_birthday is defined. Whats weird is that if I change "datetime.date(..." to datetime.datetime(..." is works, but gives me a "can't compare date and datetime objects" on the last line. Whats going on here?

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"

dwayne_dibbley posted:

>>> output = subprocess.Popen(["a.bat"], stdout=PIPE).communicate()[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'PIPE' is not defined

Looks like a typo in the docs: try stdout=subprocess.PIPE

tef
May 30, 2004

-> some l-system crap ->

nbv4 posted:

a "can't compare date and datetime objects" on the last line. Whats going on here?

date and datetime are seperate objects, date doesn't include a time, and datetime does.

helpful, eh?

from the python docs

quote:

In other words, date1 < date2 if and only if date1.toordinal() < date2.toordinal(). In order to stop comparison from falling back to the default scheme of comparing object addresses, date comparison normally raises TypeError if the other comparand isn’t also a date object. However, NotImplemented is returned instead if the other comparand has a timetuple() attribute. This hook gives other kinds of date objects a chance at implementing mixed-type comparison. If not, when a date object is compared to an object of a different type, TypeError is raised unless the comparison is == or !=. The latter cases return False or True, respectively.

I would assume that the reason you can't compare date and datetimes, is that the start time of a date can vary from culture to culture.

dwayne_dibbley
Nov 26, 2005

Janin posted:

Looks like a typo in the docs: try stdout=subprocess.PIPE

Unfortunately no dice...

>>> output = subprocess.Popen(["a.bat"], stdout=subprocess.PIPE).communicate()[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'subprocess' is not defined

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"
Is this your first time using Python? You will have to import the subprocess module before it may be used.

dwayne_dibbley
Nov 26, 2005
Thanks.
Dammit how can I forget to import. Yeah, these are my first few hours using Python.

Mmmm... so what I get back is a big bunch of bytes/characters. I was hoping for something easier to deal with. Back to the drawing board.

tripwire
Nov 19, 2004

        ghost flow

dwayne_dibbley posted:

Thanks.
Dammit how can I forget to import. Yeah, these are my first few hours using Python.

Mmmm... so what I get back is a big bunch of bytes/characters. I was hoping for something easier to deal with. Back to the drawing board.

What kind of bytes/characters? What are you expecting the output to be? Python has functionality for switching between character encodings if that's the problem.

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

nbv4 posted:

This function determines whether or not you were forty years old when you had an exam. When I open a python shell, the code works fine, but when I use it in my application, I get an error saying "global name date is not defined" (or something to that effect, i'm writing this post from a different computer) on the line where fortieth_birthday is defined. Whats weird is that if I change "datetime.date(..." to datetime.datetime(..." is works, but gives me a "can't compare date and datetime objects" on the last line. Whats going on here?

If you're getting a NameError saying "global name 'date' not defined" then you're not doing "datetime.date". Seeing the full traceback would definitely help here. See also: datetime.date.replace.

nbv4
Aug 21, 2002

by Duchess Gummybuns

Habnabit posted:

If you're getting a NameError saying "global name 'date' not defined" then you're not doing "datetime.date". Seeing the full traceback would definitely help here. See also: datetime.date.replace.

actually the problem was when I had datetime.date, the function would execute correctly, and the error was being thrown from within another function. I assumed changing "datetime" to "date" would be the cause of that error. My dumb rear end didn't read the line number of the error :blush:

awesomepanda
Dec 26, 2005

The good life, as i concieve it, is a happy life.
hey guys, here is a really simple question. when i am trying to use IDLE, i cant use nested elif statements. for example,

x=2
if x==1:
print(x) *there should be a tab in this line but for some reason its not showing up in the post
elif x==2:
print(x)
else:
print(x)

that generates an error, does anyone have any idea why?

awesomepanda fucked around with this message at 07:28 on Dec 26, 2008

awesomepanda
Dec 26, 2005

The good life, as i concieve it, is a happy life.
sorry for the double post.

ionn
Jan 23, 2004

Din morsa.
Grimey Drawer

CrazyPanda posted:

code:
x=2
if x==1:
    print(x)
elif x==2:
    print(x)
else:
    print(x)

The above code works fine provided the whitespace is where it should be.

dwayne_dibbley
Nov 26, 2005

tripwire posted:

What kind of bytes/characters? What are you expecting the output to be? Python has functionality for switching between character encodings if that's the problem.

I've just starting learning Python and my current learning target is to use the logging module to make one nice logfile for everything my script does. So I want to get the output of external commands run in my script and shove them into the logfile.

a.bat:
@echo off
echo Output from external command line 1
echo Output from external command line 2

>>> output = subprocess.Popen("a.bat", stdout=subprocess.PIPE).communicate()[0]
>>> print(output)
b'Output from external command line 1\r\nOutput from external command line 2\r\n'

I guess I can do this but the output is not tidy:
>>> for i in str(output).split("\\r\\n"):
... print(i)
b'Output from external command line 1
Output from external command line 2
'

Looking around the docs I found this:
>>> output=os.popen("a.bat")
>>> for i in output.readlines():
... print(i)
...
Output from external command line 1

Output from external command line 2

Apart from the extra blank lines this is what I need so I can go with this. It seems the subprocess module is the 'proper' way to do this but I can't get it to work nicely...

ChiralCondensate
Nov 13, 2007

what is that man doing to his colour palette?
Grimey Drawer

dwayne_dibbley posted:

>>> print(output)
b'Output from external command line 1\r\nOutput from external command line 2\r\n'

I guess I can do this but the output is not tidy:
>>> for i in str(output).split("\\r\\n"):
... print(i)
b'Output from external command line 1
Output from external command line 2
'
I don't have 3.0 installed on this box yet but I imagine the "problem" lies in the fact that subprocess is returning a bytes object (the prefix on "b''" tells you this). Reading the "What's new in 3.0" docs:

quote:

As the str and bytes types cannot be mixed, you must always explicitly convert between them. Use str.encode() to go from str to bytes, and bytes.decode() to go from bytes to str. You can also use bytes(s, encoding=...) and str(b, encoding=...), respectively.
Did you try calling split() directly on the bytes object? (I don't know if it has such a method.)
code:
>>> for i in output.split("\\r\\n"):
...     print(i)
Making it into a str object should work:
code:
>>> for i in output.decode().split("\\r\\n"):
...     print(i)

dwayne_dibbley posted:

>>> output=os.popen("a.bat")
>>> for i in output.readlines():
... print(i)
...
Output from external command line 1

Output from external command line 2

Apart from the extra blank lines this is what I need so I can go with this. It seems the subprocess module is the 'proper' way to do this but I can't get it to work nicely...
The extra blank lines here are due to the fact that readlines() doesn't strip the ending \n from each line, and the print function automatically appends a \n to what it is printing.

ChiralCondensate fucked around with this message at 14:42 on Dec 26, 2008

dwayne_dibbley
Nov 26, 2005

ChiralCondensate posted:

Did you try calling split() directly on the bytes object? (I don't know if it has such a method.)
No, there is no method:
TypeError: Type str doesn't support the buffer API

ChiralCondensate posted:

code:
>>> for i in output.decode().split("\\r\\n"):
...     print(i)

Aaaahaaaa! That's what I wanted! Thanks! (Now I'll read up on this encoding/decoding stuff.)

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.
You can also use str.splitlines, or keep your Popen object around and iterate over its stdout attribute or call readlines on the stdout attribute.

Jo
Jan 24, 2005

:allears:
Soiled Meat

Lord Uffenham posted:

host=website, post=80

I assume that should be port

:doh: Yes. It's working now. Thank you so much.

UnNethertrash
Jun 14, 2007
The Trashman Cometh
I'm trying to write a simple script that solves:

code:
    FUR
x   DOG
-------
   AGER
  DRIP
  FUR
-------
  RIPER
Where each letter represents a number from 0-9. It's pretty immediately obvious that D = 1 and P = 0. So the remaining numbers = range(2,10).
code:
d = 1
p = 0
numbers = range(2,10)
numbers2 = [] #I actually don't even know why I have to define these all here
numbers3 = []
numbers4 = []
numbers5 = []
numbers6 = []
numbers7 = []
for f in numbers:
    numbers2 = numbers
    numbers2.remove(f)
    print 'f loop',
    print numbers #notice when it prints that numbers no longer has a 2
    for u in numbers2:
        numbers3 = numbers2
        numbers3.remove(u)
        for o in numbers3:
            numbers4 = numbers3
            numbers4.remove(o)
            for g in numbers4:
                numbers5 = numbers4
                numbers5.remove(g)
                for r in numbers5:
                    numbers6 = numbers5
                    numbers6.remove(r)
                    for i in numbers6:
                        numbers7 = numbers6
                        numbers7.remove(i)
                        for e in numbers7:
                            fur = 100*f + 10*u + r
                            dog = 100*d + 10*o + g
                            riper = r + 10*e + 100*p + 1000*i + 10000*r
                            print e,
                            print numbers,
                            print numbers7
                            if fur*dog == riper:
                                print fur
                                print dog
                                print riper
Clearly what I am doing is using a bunch of for loops that get smaller and smaller because numbers cannot be repeated. The problem is that each time the list gets smaller the original list (numbers) also gets smaller. So it actually only runs through the top for loop once, even though I never remove anything from that list.

It's hard to explain but with the print commands it's pretty clear, if you run it, that the list 'numbers' gets smaller even though I never remove anything from it. It's got to be some stupid little mistake, but I can't seem to figure it out.

a = 2, d = 1, e = 6, f = 3, g = 7, i = 8, o = 4, p = 0, r = 5, u = 9 I did it by hand first:ssh:, then bet myself I could do it faster on python.:doh: I would greatly appreciate any help. Thanks.

No Safe Word
Feb 26, 2005

UnNethertrash posted:

It's hard to explain but with the print commands it's pretty clear, if you run it, that the list 'numbers' gets smaller even though I never remove anything from it. It's got to be some stupid little mistake, but I can't seem to figure it out.
That's because:

code:
    numbers2 = numbers
    numbers2.remove(f)
Everything that does this actually removes stuff from numbers as well. Assignment on lists and other complex datatypes pretty much always makes a reference instead of a copy. Luckily, python ships with the copy module to do what you want!

Adbot
ADBOT LOVES YOU

nbv4
Aug 21, 2002

by Duchess Gummybuns
In Django, you can format dates in the template system by using PHP-style date format strings like so: "{{ my_date|"n-j-Y" }}" but how do you do the same thing from within python itself? I know about datetime.date.strftime() and strptime(), but those functions take a completely different date formatting "language"...

  • Locked thread