Re: [Tutor] Searching a text file's contents and comparing them toalist

2010-07-14 Thread christopher . henk
Eric Hamiter wrote on 07/14/2010 04:57:57 PM:

> Thanks for the pointers! This is now working, albeit probably ugly and 
clunky:
> 
> 
> aisle_one = ["chips", "bread", "pretzels", "magazines"]
> aisle_two = ["juice", "ice cream"]
> aisle_three = ["asparagus"]
> 
> def find_groceries():
> with open("grocery_list.txt") as grocery_list:
> 
> first_trip = ["Located on aisle 1: "]
> second_trip = ["Located on aisle 2: "]
> third_trip = ["Located on aisle 3: "]
> no_trip = ["Not found in the database: "]
> 
> for item in grocery_list:
> item = item.rstrip()
> if item in aisle_one:
> first_trip.append(item)
> elif item in aisle_two:
> second_trip.append(item)
> elif item in aisle_three:
> third_trip.append(item)
> else:
> no_trip.append(item)
> 
> sorted_list = first_trip, second_trip, third_trip, no_trip
> print sorted_list
> 
> find_groceries()
> 
> 
> Last question (for today, at least): Right now, the output is less
> than aesthetically pleasing:
> 
> (['Located on aisle 1: ', 'bread', 'magazines'], ['Located on aisle 2:
> ', 'juice', 'ice cream'], ['Located on aisle 3: ', 'asparagus'], ['Not
> found in the database: ', 'butter', 'soap'])
> 
> How can I format it so it looks more like this:
> 
> Located on aisle 1:
> bread
> magazines
> 
> Located on aisle 2
> [etc...]
> 
> 
> I tried putting "\n" into it but it just prints the literal string.
> I'm sure it has to do with the list format of holding multiple items,
> but so far haven't found a way to break them apart.
> 


your sorted_list is a tuple of lists so when you print it python is 
showing you that structure.
You want the contents of each of those lists printed in a more readable 
format, so you need to loop through the tuple to get each list(trips down 
an aisle)and then within that loop, loop through each list to print each 
item.

in pseudo code to output like you suggest

for each aisle_list in sorted_list
for each item in the aisle_list
print the item
print the space (to separate the aisles, this is part of the loop 
through the tuple, so will run once for each aisle)


Instead of replacing the print statement with the above, I would have this 
as another function which takes sorted_list as a parameter, changing 
find_groceries to return sorted_list instead of printing it.  This keeps 
the two tasks separate and easier to understand and/or debug.

so the last lines of your program are:
sorted_list=find_groceries()
print_shoppinglist(sorted_list)

instead of just calling find_groceries()


Chris___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Databases in Python

2010-08-24 Thread christopher . henk
aug dawg wrote on 08/24/2010 01:13:01 PM:

> It's not catching that, but I haven't gotten there with the bugs yet. 
One more thing I can't figure out.
> 
> line 11
> select-db = raw_input("Which database to add to? >> ")
> SyntaxError: can't assign to operator
> 
> I think it might be the >> at the end, but when I try it in the Python 
interpreter, it works fine.
> 
The error is triggered by your variable name.  You can't use a dash, 
Python is interpreting that as a minus sign.  You can use the underscore 
"_" instead.

more here:
http://www.pasteur.fr/formation/infobio/python/ch02s03.html
http://docs.python.org/reference/lexical_analysis.html#identifiers


Chris___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Databases in Python

2010-08-24 Thread christopher . henk
aug dawg  wrote on 08/24/2010 01:55:14 PM:

> Now it says that the variable adder is not defined. Does anyone know 
about this?
> 
It is best if you send the full error message, it helps pinpoint the 
problem.
my copy of your code was:
database = []
datafile = open('/home/~/the-db/data')
for line in datafile:
database.append(line)

while tf2 != True:
command = raw_input("Enter a command. >> ")

while tf != True:
if "add" in command:
adder = raw_input("What to add? >> ")
data_base.append(adder)
if "no more" in adder:
tf = True

if "read" in command:
print(database)
if "search" in command:
searcher = raw_input("Enter term to search >> ")
if searcher in database:
# Figure this out.
if "exit database" in command:
print "Bye!"
sys.exit()

I am not sure what you typed in as your command or how your source was 
formatted (the tabs did not come through to me) so I cannot say for sure.
If "add" was not your command, adder does not get defined. 
My guess is that you typed in a different command so you skipped the 
assignment but are checking for "no more" in adder, or attempting to 
append adder.  This would trigger that error.  Did you get the "What to 
add? >>" message?

Chris___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise problem

2010-08-27 Thread christopher . henk
Roelof Wobben wrote on 08/27/2010 12:18:01 PM:

> 
> 
> > Date: Fri, 27 Aug 2010 12:00:23 -0400
> > From: bgai...@gmail.com
> > To: rwob...@hotmail.com
> > CC: tutor@python.org
> > Subject: Re: [Tutor] exercise problem
> > 
> > I have been reading your posts and responses. I find myself frustrated 

> > with your lack of understanding of Python fundamentals and the time 
and 
> > energy others are putting in that seems to help only a little.
> > 
> > I recommend you take a very basic tutorial, and be sure you understand 

> > the basic concepts before tackling what seems too hard for you
> 
> 
> I follow this basic tutorial : 
http://openbookproject.net/thinkcs/python/english2e/ch09.html
> 
> 
> > 
> > Also I encourage you to take each error message and look up the topic. 

> > In this case
> > 
> > getal1 = getal1 + u[teller,0] + v[teller,0]
> > TypeError: list indices must be integers, not tuple
> > 
> > What does this error tell you?
> 
> That the list index must be a integer.
> 
> > 
> > What is a tuple? What is an integer? Where is there a tuple in this 
> > expression? What are you trying to do?
> 
> What a tuple is i can't tell you. it's in the next chapter.
> A integer is a number.
> What Im trying to do is that I want all the first numbers of the vectors 
are added and all the second numbers.
> 
> So if I have this vector [1.0] [1,1]

You seem still confused on how your parameters to your function are 
working or the assignment in general.  You do not have a vector [[1,0] 
[1,1]] being passed into your function.  You are passing in two lists 
(vectors).  The first one 'u' is [1,0] , the second 'v' is [1,1] 
part of your code below:
vector= [[1,0], [1,1]]
v=vector[0]
u=vector[1]
print u, v
uitkomst = add_vectors(u,v)

if you just print u it will show [0,1]
if you just print v it will print [1,1]

thus your code:
getal1 = getal1 + u[teller,0] + v[teller,0]
getal2 = getal2 + v[teller,1] + v[teller,1]

is not doing what you thought it would.  (the syntax is wrong also).  I am 
guessing you are trying to index a 2D matrix with this.  Section 9.18 
would show you how to do that in python.  However there is no 2D matrix in 
your function, there are 2 vectors u and v.
 
So to add the vectors you loop over the index numbers (see 9.13) in your 
tutorial. in this loop add the value referenced by the index in each list 
to each other (section 9.2), and assign it to your new list at the same 
index value (9.8).  The one thing that would catch you on the assignment 
part, is that the list you are assigning to must have an element at that 
index (I didn't see the append function mentioned in your tutorial yet). 
Therefore you must initialize the list to which you are assigning to make 
sure it is the same length as the vectors you are adding (9.12 gives a 
method for this). 
 
Hopefully that will get you a bit closer to your answer.  I would suggest 
spending time in this section and make sure you understand what each line 
is doing, since these concepts are fundamentals in python programming. 
Use the interactive session in python to quickly see what each command 
does.  Python is great in that it will give you instant feedback.

Chris___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] import problem

2010-08-28 Thread christopher . henk
tutor-bounces+christopher.henk=allisontransmission@python.org wrote on 
08/28/2010 12:54:28 PM:

> Hello, 
> 
> Im trying to do a import on a linux machine.
> But now Im gettting this message :
> 
> Python 2.6.5 (r265:79063, Apr  1 2010, 05:28:39) 
> [GCC 4.4.3 20100316 (prerelease)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import calender
> Traceback (most recent call last):
>   File "", line 1, in 
> ImportError: No module named calender
> >>> 

Did you try calendar (with an 'a')?  it might have just been a spelling 
mistake in your import

Can you do other imports from site-packages?


Chris___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input problem

2010-09-13 Thread christopher . henk
ANKUR AGGARWAL wrote on 09/13/2010 04:45:41 PM:

> Suppose i am taking input or various variables like
> a=raw_input("...") //hello
> b=raw_input("")//hi
> c=raw_input("...")//hello
> d=raw_input("..")//hello
> but i want to run a common function when input is hello
> 
> so instead of
> if a=="hello":
>  fun()
> then again for b and then again for c then d and so on i have to apply 
the code for the specific variable , 
> i want to run the function whenever in the code input is "hello"
> i am wondering is there is any way like
> if input=="hello":
>  fun()
> i hope you get my point.. Help me out please

You put your inputs into a list and see if "hello" is in the list.
 
inputlist=[a,b,c,d]
if "hello" in inputlist:
fun()

or if you want to run fun() once for every "hello" you can then loop over 
the list.

inputlist=[a,b,c,d]
for inputitem in inputlist: 
if "hello" == inputitem:
fun()

Chris___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] LCM

2010-10-20 Thread christopher . henk
benderjaco...@gmail.com wrote on 10/20/2010 07:30:32 PM:

> 
> thing = raw_input("What is the first number?\n\n")
> 
> thing2 = raw_input("What is the second number?\n\n")
> 
> int(thing)
> int(thing2)
> 
The two lines above do the calculation of turning your input 
strings into int's but do not save the value anywhere.
You want to assign the calculation to a variable (can reuse thing 
and thing2 if you wish) and then use that calculation later on.



> 
> The only problem is that when I tell it that thing3 = x/thing it gives 
> an error. Here it is:
> 
> Traceback (most recent call last):
>File "C:/Documents and Settings/Family/My Documents/LCM.py", line 10, 

> in 
>  thing3 = x/thing
> TypeError: unsupported operand type(s) for /: 'int' and 'str'

the error here is telling you that thing is a string and python cannot 
divide an int by a string.

> 
> Same with thing4...
> 
> Can you please help! Thanks in advance...

I didn't check the rest of the program.  But that should at least get you 
moving along.

Chris___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if statement

2010-11-02 Thread christopher . henk
Glen Clark wrote on 11/02/2010 03:07:18 PM:

in general you should use raw_input instead of input.


> confirmed = int(input("Are you happy with this? (y/n): ")
> 

you are missing a closing parenthesis above, and converting a string (y,n) 
to and int
> if confirmed == "y":

you are comparing an int and a string here, probably not what you want 
(see above).

>for In in range(0,NumItems):
>   print(Entries[In] + ": " + str(In))
>change = int(input("Which item would you like to change: ") 

again, you are missing a closing parenthesis above

>Entries[change]=str(input("Please enter a nem name: ")

again, you are missing a closing parenthesis above

> else:
> #do nothing

you need to put pass here, you can't just have a comment in a block
> 
> print(Entries)
> 


Chris
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] HELP ON A ANAGRAM PYTHON PROGRAM

2009-03-09 Thread christopher . henk
Just glancing at your program, I would guess that you have a ":" where you 
want a "]" on the line below.

prod = prod * letter_to_prime[word_list[j] [i]:

HTH,
Chris



jessica cruz  
Sent by: tutor-bounces+christopher.henk=allisontransmission@python.org
03/09/2009 02:38 PM

To
Tutor@python.org
cc

Subject
[Tutor] HELP ON A ANAGRAM PYTHON PROGRAM







I made this program but it says that there is an error and I have a hard 
time trying to solve the problem with program. Here is the program:


#this reads all of the words in the file into a list
infile = open('/afs/cats/courses/cmps012a-cm/pa1/wordList.txt')
wdcount = int(infile.readline()) #first item is count of all the words
word_list = infile.readlines()

#print them out from the internal list
i = 0
while i < wdcount:
print word_list[i],
i = i + 1

#map of alphabet to prime numbers with respect to frecuency
#more frequent the letter the smaller the assigment prime
letter_to_prime = {
'a':7,
'b':59,
'c':29,
'd':31,
'e':2,
'f':67,
'g':41,
'h':53,
'i':3,
'j':97,
'k':73,
'l':23,
'm':47,
'n':13,
'o':19,
'p':43,
'q':101,
'r':11,
's':5,
't':17,
'u':37,
'v':71,
'w':79,
'x':89,
'y':61,
'z':83},

j = 0
while j < wdcount:
print word_list [j],
prod = 1
i = 0
while i < len(word_list[j])-2:
prod = prod * letter_to_prime[word_list[j] [i]:
i = i + 1
print prod (right here is where it says that there's an error I try to 
fix it )
j = j =1
 
# code that will be compared will be a histogram type code with frequency
# characters
def code(w):
hist = []
chars = list(w) 
chars.sort() 
for letter in chars: 
if not letter in hist:  # when the letter is not already in hist, 
hist.extend([letter, str(w.count(letter))])  # its added to 
hist along with its freq.
else: 
continue
coding = "".join(hist) # then they are joined as one string
return coding




# new list is made with words in word_list followed by its code
for word in  word_list:
wordList.append(word) 
wordList.append(code(word[:(len(word)-2)])) 


while True:
word1 = raw_input('Enter word:') 
word = word1.lower() 
sig = code(word) 
i = 1 
if sig in wordList: 
print "Anagrams:"
while i <= len(wordList):  # when the sig of the inputed word is 
in the word list, 
if sig == wordList[i]:
print wordList[i-1]  # the corresponding words are printed
i += 2 # then adds two because codes are every other entry
else:
print "No anagrams"
choice = raw_input("Continue? (yes/no)")
if choice == 'y' or choice == 'yes':
continue
else:
break
I don't know how to figure out the error since the only message that I get 
is that "there's an error: invalid syntax"

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help needed

2009-06-16 Thread christopher . henk
> My Original message:
> 
> I had previously emailed y'all regarding inverting a message input by 
the user of the program backwards. After much 
> contemplation on your earlier replies I came up with the code I have 
included in this email. The problem I am having 
> with this code is that the the first character of the message that is 
reversed does not come up. Is there a solution 
> to this? For my message that I input I used "take this" to test it, use 
the same message when the program prompts you 
> to enter the message and run it, you'll see what I mean. Also is there a 
way to say reverse the string in a way so the
> reversed string would result to "this take" if you use my example? And 
is there a way to stop the loop without the use
> of break? Thanks for the help!
> 

As to your second part of your request you can use the function split.

http://www.python.org/doc/2.4.4/lib/string-methods.html

>>> mystring="Mary had a little lamb."
>>> mystring.split()
['Mary', 'had', 'a', 'little', 'lamb.']
>>>

And then you can use slicing to reverse the created list the same way you 
did with the full string.


Chris___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Poorly understood error involving class inheritance

2009-09-10 Thread christopher . henk
tutor-bounces+christopher.henk=allisontransmission@python.org wrote on 
09/10/2009 04:13:23 PM:

> I'm not sure why I'm getting an error at the end here:
> 
>  >>> class dummy:
> ... def __init__(self,dur=0):
> ... self.dur=dur
> ...
>  >>> z=dummy(3)
>  >>> z.dur
> 3
>  >>> z=dummy(dur=3)
>  >>> z.dur
> 3
> 
> That worked fine, of course.
> 
>  >>> class dummy2(str):
> ... def __init__(self,dur=0):
> ... self.dur=dur
> ...
>  >>> z=dummy2(3)
>  >>> z.dur
> 3
> 
> So far so good.  But:
> 
>  >>> z=dummy2(dur=3)
> Traceback (most recent call last):
>File "", line 1, in 
> TypeError: 'dur' is an invalid keyword argument for this function
>  >>>
> 
> Why doesn't that last bit work?  I'm not sure where to begin to look 
> this up.
> Thanks!
> 
> --
> -dave
> "Pseudo-colored pictures of a person's brain lighting up are
> undoubtedly more persuasive than a pattern of squiggles produced by a
> polygraph.  That could be a big problem if the goal is to get to the
> truth."  -Dr. Steven Hyman, Harvard
> 

I believe it has to do with the fact that str is immutable and thus should 
use __new__ instead of __init__. 
>>> class bob(str):
... def __new__(self, fred=3):
... self.fred=fred
... return self
...
>>> george=bob()
>>> george.fred
3
>>> george=bob(fred=7)
>>> george.fred
7

Don't have a chance to read it now but maybe pep 253 explains it.
http://www.python.org/dev/peps/pep-0253/

Chris
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unknown reason for error.

2009-09-24 Thread christopher . henk
> Hello, python tutors, its Corey.

Hi, Corey.

> candyNumber = raw_input("How many candies do you want? :"

You dropped a closing parenthesis in the line above.  Having the syntax 
error occur one line up from where it is indicated is not uncommon.

Another thing as long as we are here, in the code below.

> Anyway, I'm getting a syntax error for an unknown reason. Here is my 
code...
> name = raw_input("What is your name?")
> print "Hello, ", name
> wellness = raw_input("How are you?")
> if wellness != "Good":
> if wellness != "Well":
> if wellness != "Fine":
> print "Oh, I'm sorry you are not feeling well. I guessed 
correct, right?"
> else: print "Great!"

The else will only apply if they type in Fine 
If you want it too apply to all three you would need to join the checks 
together into one if statement with Boolean operators.

Chris
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] invalid syntax (reply)

2009-09-24 Thread christopher . henk
tutor-bounces+christopher.henk=allisontransmission@python.org wrote on 
09/24/2009 05:43:24 PM:

> Robert, that is my code. The error? "Theres an error in your program : 
> invalid syntax"
> Closing the parenthesis helped that one, but my else statement is not 
> working...heres the code chunk...
> if wellness != "Good":
> elif wellness != "Well":
> elif wellness != "Fine":
> print "Oh, I'm sorry you are not feeling well. I guessed 
> correct, right?"
> else print "Great!"
> candyNumber = raw_input("How many candies do you want? :")
> fatness = raw_input("How many candies do you want to eat? :")
> if fatness > candyNumber:
> print "HA! Nice try, but no. You don't have that many candies"
> else print "HA! You ate the candy! Sucker. You are now", 
> fatness, "lbs overweight"
> 
> 
> 
> my IDLE highlights the print, in each of them. Why? (oh, and thanks for 
> helping, all)


I am not sure why Idle is higlighting your print statements ( I don't use 
Idle, so will leave that to someone else).

However your if-elif-else construction should raise a syntax error.  elif 
means "else if" and should be matched up (at the same indentation level) 
with an if statement just like an else statement.  It is used when you 
have more then two paths that the code can take depending on the test 
results.

if test: (if test is true)
do something
elif another test: (else if another test is true)
do something else
else:
do a third thing

What you are trying to test is that wellness is not "Well", is not "good", 
and is not "Fine" 
If all of those is true (they are not good, not well and not fine) you 
print your sorry message, otherwise you print great.
You have one fork in the path, and should have one if statement with one 
else. 

Hope that helps,
Chris___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help with conditionals

2009-09-25 Thread christopher . henk
> Hello all, 
> I am still very new to Python and am working on conditionals. Im stuck 
on this 
> problem and I'm sorry if this is something really simple that I'm 
missing but its 
> been really frustrating me. Here's a copy of the problem, and sorry if 
its really 
> long but its the end question about the logically equivalent expressions 
I'm 
> stuck on. Anyways, heres a copy of the problem
> 
> ---
> 


> >>> from p_and_q import *
> >>> truth_table("p or q")


Are you calling the function as shown above?



> 
> Whenever I try to enter the expressions listed into the prompt it tells 
me the 
> string object is not callable


It would be helpful if you showed us exactly what you type into the prompt 
and the exact error you get.  You should be calling the function as it is 
shown in the problem.
Assuming the function is entered and imported correctly you should get a 
true table output.

two examples:
>>> truth_table("p or q")
 p  q  p or q
=
TrueTrueTrue
TrueFalse   True
False   TrueTrue
False   False   False
>>> truth_table("not(p or q)")
 p  q  not(p or q)
==
TrueTrueFalse
TrueFalse   False
False   TrueFalse
False   False   True

Without a bit more info its hard to guess what is happening.

Chris___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Recursive user input collection problem

2009-10-13 Thread christopher . henk
> I need to collect a couple of integers from a user, but I want to make
> sure that I actually get integers.  I tried this, but subsequent calls
> to the function don't update variable.  I'm not sure this is terribly
> clear - here's the code:
> 
> num_of_articles = 0
> num_of_reviewers = 0
> 
> def getinput(variable,prompt):
>   """
>   Get the input by prompting the user and collecting the response - if 
it is 
>   a non-integer, try again.
>   """
>   variable = 0
>   variable = raw_input(prompt)
> 
>   try:
> int(variable)
> return variable
> 
>   except ValueError:
> print("We need an integer (number) here.")
> getinput(variable,prompt)
> 
> 
> num_of_articles = getinput(num_of_articles,"Enter number of articles: ")
> num_of_reviewers = getinput(num_of_reviewers,"Enter number of reviewers: 
")
> 
> print(num_of_articles)
> print(num_of_reviewers)
> 
> 
> This works fine if I put in good input, but not if I pass in a bad
> value.  Can anyone show me where I have gone astray?  Thanks.
> -- 
> 
> yours,
> 
> William


When the exception is thrown the "return variable" line is not executed. 
The path jumps down to the except block and runs that.  Thus when you are 
unrolling the recursion the first getinput() does not return a value. 
A finally block after the exception block will execute whether or not the 
exception is thrown after the other code runs. 

You also need to assign the return value of getinput() within your except 
block.

Finally there is no need to pass variable into the function as you 
immediately change it to zero. 

Chris

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help on finding the 1000th prime

2009-11-16 Thread christopher . henk
mrhol...@sbcglobal.net wrote on 11/16/2009 10:56:07 AM:

> I have posted this on other lists, but have just discovered this one. 

Welcome to the list.  I am sure you will find plenty of folks here 
who will be happy to help you.

> Can someone give me help on writing the code 
> necessary to find the 1000th. prime number.

I seem to recall this problem was recently discussed on the list. 
If you do a quick search you should be able to find a few pointers on one 
way to solve it. 

> I know I will have to use a while loop, but I can't seem to get the body 

> of the code to function rightly. I would appreciate any help. 

The way this list works you will have to give us something to work 
from.  Show us what you tried, how it failed (any error messages, etc), 
what you re thinking, and where you are stuck.  We won't do the work for 
you but try and lead you to the answers. 


> I am taking the online course Introduction to Computer 
> Science and Programming from the MIT website and this is one of their 
assignments. The on campus students are able to 
> collaborate with one another, but I live in Ohio. Thanks, Ray 
___

Good luck with the class, and feel free to ask questions here.

Chris___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Help on finding the 1000th prime

2009-11-16 Thread christopher . henk
Kent Johnson  wrote on 11/16/2009 04:00:02 PM:

> -- Forwarded message --
> From: Ray Holt 
> Date: Mon, Nov 16, 2009 at 1:55 PM
> Subject: RE: [Tutor] Help on finding the 1000th prime
> To: Kent Johnson 
> 
> 
> I hit the send button before I was ready. Here is the code that doesn't
> work.
Not to nit pick, but try and copy the code exactly as you have it. 
 The code below has capitalization where it doesn't belong and indenting 
is not consistent, so there should be plenty of syntax errors if you tried 
to run it.  This makes it hard to figure out where your particular problem 
is.  Not sure if its a syntax problem or a algorithm problem.  Indentation 
is key in Python so without showing exactly what you have loops and 
branching is hard or impossible to follow.  This is also why it is good to 
include exactly what error you are experiencing.

> primeCount = 0
> primeCandidate = 2

You might find it easier to start with a different primeCandidate 
and handle 2 as a special case.

> While primeCount <= 1000:
> isPrime = True
>primeCandidate = primeCandidate + 2

primeCandidate is going to be 4,6,8,10,12,14,16,18,...
which won't yield many primes. see comment above

>for x in range(2, primeCandidate):
>if primeCandidate % x == 0:
>print primeCandidate, "equals", x, "*", primeCandidate/x
>isPrime = False
> Print primeCandidate
>break
> If isPrime:
>primeCount = primeCount + 2
> Print primeCandidate
> 

It is hard to follow what is in which loop with the rest of the 
code, so I can't say much more on where you are having problems.  It looks 
like you have the parts there just a question of what goes where.

Chris
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Equivalent exception of os.path.exists()

2009-11-30 Thread christopher . henk
biboy mendz  wrote on 11/30/2009 03:04:52 PM:

> 
> 
> spir wrote:
> >
> > What is your question?
> > If it's about the type of exception raised when os.path.exists fails, 
well, sure it's hard to find:
> >
> >   print os.path.exists("foo".bar)
> >   ==> False
> >
> > 
> My question is: i'm looking for type of exception that more or less 
> equivalent to os.path.exists attribute. I know for a fact that this 
> method yields true or false. The exercise in the book says use 
> try-except in place of os.path.exists(). That sure is (to me) quite 
> difficult task. Instead of using the available function you're are 
> tasked to do the alternative.
> 

Looking at my copy of Core Python the exercise says to follow the example 
3.2 (readTextFile.py).  There he uses the try except block around the open 
function call. 

This as mentioned could raise an IOError.  It will be triggered in a 
different manner then os.path.exist since you are now trying to open a 
file to write, instead of checking if it exist.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fw: loops

2009-12-08 Thread christopher . henk
You should probably read some of the links sent to you earlier but here is 
a stab at an explanation.


Richard Hultgren wrote on 12/08/2009 10:36:08 AM:

> - Forwarded Message 
> From: Richard Hultgren 
> To: tutor@python.org
> Sent: Mon, December 7, 2009 2:53:40 PM
> Subject: loops
> I'm quite new but determined.  Can you explain to me, step by step, what 
is going on in the computer in this loop.  I 
> hope I am not being too dumb!

> a = 0
> b = 1
> count = 0
> max_count = 20

The above steps are initialization of your variables.  'a' points to the 
value 0, 'b' points to 1, etc.
Since the values of the variables are used within the loop we need to give 
it somewhere to start, otherwise we will get an error. 

> while count < max_count:

The while loop will continue until 'count < max_count' evaluates to False 
(20 loops, due to line below)
the loop is defined as everything that is indented below this line.

> count = count + 1

Increase the value of count by one each loop iteration, otherwise the 
statement 'count < max_count' will never change value, and the loop will 
never end.

> # we need to keep track of a since we change it
> old_a = a# especially here
> old_b = b

Keep the old values of the variables since we want to add them together 
for the new value of b and will change the values in the next steps. 

> a = old_b
> b = old_a + old_b

reassign 'a' to the value of 'old_b'.  If we didn't save the value of 'a' 
into 'old_a' above we wouldn't know what it was anymore.
reassign 'b' to the sum of 'old_a' and 'old_b'

> # Notice that the , at the end of a print statement keeps it
> # from switching to a new line
> print old_a,
prints the value of old_a followed by a space.  Without the comma at the 
end the print statement each loop would print on a new line.


The best way to follow what is happening is to trace the variables through 
the program.  you would get a table that loops something like :

max_count   count   a   b   old_a   old_b 
count___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class question

2007-07-13 Thread christopher . henk
However if you try to withdraw any money after you took out the $25 it 
would raise the error.

The overdrawn function checks if you are in the negatives.
Since the balance is checked before the money is taken out, there is no 
error when you take out the $25.

If you wan the error to be raised whenever you go negative simply switch 
the withdrawal and the function call in withdraw

 def withdraw(self, amount):
self.balance -= amount
if self.overdrawn():
   raise "Insufficient Funds Error"

and if you don't want the money taken out if there is insufficient funds,
just add the withdrawn amount back:

 def withdraw(self, amount):
self.balance -= amount
if self.overdrawn():
self.balance += amount
   raise "Insufficient Funds Error, no money withdrawn"

 Chris Henk
Allison Transmission
phone:  317.242.2569
fax:  317.242.3469
e-mail:  [EMAIL PROTECTED]



Dick Moores <[EMAIL PROTECTED]> 
Sent by: [EMAIL PROTECTED]
07/13/2007 03:04 PM

To
Tiger12506 <[EMAIL PROTECTED]>, 
cc

Subject
Re: [Tutor] class question






At 05:35 AM 7/13/2007, Tiger12506 wrote:
> > ===
> > class BankAccount(object):
> >def __init__(self, initial_balance=0):
> >self.balance = initial_balance
> >def deposit(self, amount):
> >self.balance += amount
> >def withdraw(self, amount):
> >self.balance -= amount
> >def overdrawn(self):
> >return self.balance < 0
> > my_account = BankAccount(15)
> > my_account.withdraw(5)
> > print my_account.balance
> > =
> >
> > This prints the expected "10".
> >
> > My question is, of what use can "overdrawn" be put? If I change the
> > withdrawal amount to 25, it prints the expected "-10", whether the 
class
> > contains the "overdrawn" function or not.
> >
> > Thanks,
> >
> > Dick Moores
>
>A very good question. Now I have one for you. What does your bank do when
>you try to withdraw money? First, it checks to see if you have the money 
in
>your account. If you do, it subtracts that out of your balance. Whoever
>wrote that code failed to do the check within the withdraw function.
>
>===
>class BankAccount(object):
>def __init__(self, initial_balance=0):
>self.balance = initial_balance
>def deposit(self, amount):
>self.balance += amount
>def withdraw(self, amount):
>if self.overdrawn():
>   raise "Insufficient Funds Error"
>self.balance -= amount
>def overdrawn(self):
>return self.balance < 0
>my_account = BankAccount(15)
>my_account.withdraw(5)
>print my_account.balance
>=

But when I run that with a withdrawal of 25, it still prints only 
"-10". How have you involved the "overdrawn" function?

Dick


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] odd bug

2007-07-20 Thread christopher . henk
try adding:
print "current block:", one_char_box
print "zeros: ", zero_count 

to the lines just below your if statement that you think is called only 
once.  This way you know how many times its called and you might be able 
to find the error.

Chris Henk
Allison Transmission
phone:  317.242.2569
fax:  317.242.3469
e-mail:  [EMAIL PROTECTED]



"elis aeris" <[EMAIL PROTECTED]> 
Sent by: [EMAIL PROTECTED]
07/20/2007 02:36 AM

To
"Luke Paireepinart" <[EMAIL PROTECTED]>
cc
python tutor 
Subject
[Tutor] odd bug






I ran the code attached at the end of the email, it' supposed to out put a 
string of characters,

yet I got only this 

###
2.4.3.3.8.5.
definition check:
3


###


now, it's proper output, however, this part got run only once, when it's 
supposed to run multiple times to produce more portions like the one 
above, i don't know why this part got run only once: 





when that happens
   if box_v == 0:
   zero_count = zero_count + 1
   if zero_count == 2:
   zero_count = 0
   if one_char_box in
loc_window_loc_definition:
   print one_char_box
   box_string = box_string +
str(loc_window_loc_definition 
[one_char_box])
   print "definition check:"
   print box_string







##

for b in range(1,50,1): 

   ## Next point to check
   x = radar_loc_window_xx + b
   y = radar_loc_window_yy

   ## omit 0 when there are 2 zeros, and check def
when that happens
   if box_v == 0:
   zero_count = zero_count + 1 
   if zero_count == 2:
   zero_count = 0
   if one_char_box in
loc_window_loc_definition:
   print one_char_box
   box_string = box_string +
str(loc_window_loc_definition 
[one_char_box])
   print "definition check:"
   print box_string

   else:
   one_char_box = one_char_box + str(box_v) + "."
   box_v = 0
   for a in range(0,10,1):
   r, g, b = pixels[1030*(y-a) + x]
   if g > r and g > b:
   box_v = box_v + 1
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Livewires - stuck on a class

2007-08-14 Thread christopher . henk
[EMAIL PROTECTED] wrote: ->To: tutor@python.org>From: Tonu Mikk <[EMAIL PROTECTED]>>Sent by: [EMAIL PROTECTED]>Date: 08/14/2007 03:23PM>Subject: [Tutor] Livewires - stuck on a class>>I made some progress on the Livewires robots game - I got as far as>page >10 on the attached 5-robots.pdf file.  I am stuck on creating more>than >one robot and having all the robots follow the player.>>I create more robots in this way which seems to work:>class Robot:>pass>def place_robots():>global robot>global robots>robots = []>for x in 1,2,3:>robot = Robot()>robot.y = random_between(0,47)-0.5>robot.x = random_between(0,63)-0.5>robot.shape = box(10*robot.x, >10*robot.y,10*robot.x+10,10*robot.y+10)>robot.junk = 0>robots.append(robot)>>Then I was hoping to repeat the sequence for moving the robots placed>in >the robots list by using this code:>for x in robots:># code for moving the robotsGlancing at your code to move the robots.  I don't see you using you x from for x in robots.  Since in your placement code robot is assigned to a new robot each time through the loop, the placement works.  In your movement you don't change what robot is representing.I think you want to change you line:for x in robots:to become...for robot in robots:Chris HenkAllison Transmissionphone:  317.242.2569fax:  317.242.3469e-mail:  [EMAIL PROTECTED]___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fw: Starting classes

2007-08-31 Thread christopher . henk
Oops, forgot to reply all.

Chris Henk
- Forwarded by Christopher Henk/US/ATD/GMC on 08/31/2007 04:55 PM 
-

Christopher Henk/US/ATD/GMC
08/31/2007 04:13 PM

To
"Ara Kooser" <[EMAIL PROTECTED]>
cc

Subject
Re: [Tutor] Starting classes





The class definition will only have the methods and/or the variables in 
its definition.
So these two functions make up your class
class Area:
def _init_(self, name, description):
self.name = name

def look(here):
"Look around the place you are in"
print here.description

looking at the class code:
your init function only has one underscore before and after init, you want 
two, that is why you are getting the error.
def __init__(self, name, description):

Also you are requiring two arguments to make an Area class, the name and 
the description.
If you try to create an instance using only the name (as you do below) the 
interpreter will again raise an error. 

 def look(here):
"Look around the place you are in"
print here.description

Not sure if this works as is, I believe it depends on the interpreter, but 
it is customary to use the word self as the first parameter, and then also 
change here in the function body 
 def look(self):
"Look around the place you are in"
print self.description

Getting into the code below the class definition:
>outside1 = Area("Outside")

This will raise an error since you required two parameters to create an 
Area class and you only provide one.
You can either add the description here or leave it off in the __init__ 
function. 
Since most likely every area will have a description , I would add it 
here.
outside1 = Area("Outside","You are standing outside with the town gate to 
your back")

outside1.description = "You are standing outside with the town gate to
your back"

(see above, and below)

self.contents.append("dirt")

Here we have two problems.  The first is the class doesn't have the 
"contents" attribute yet  That's only a problem since you are trying to 
call a function with it. 
When you assign to an attribute (like with "description" in the line 
above), you are adding the attribute to you class instance ("outside1"), 
however you need to add it before you can use it.
Second, you only use self from within the function definition.  In this 
case you would want to use outside1.contents.

look(bedroom)

Since look was defined in the class definition, you would want to call it 
like this.
bedroom.look()

But as of right now there is no bedroom created, so this will give an 
error.
however you can instead look outside.
outside1.look()


Looking at your code I would have a class something like this:
class Area:
#what does an area have that makes it an area?
contents=None 
name=None 
description=None 
paths=None  #where you can go

def __init__(self, name, description):
#define what everything will start as
self.name = name
self.discription=None 
self.contents=[]
self.paths={}
 
#Methods:
#what can you do to an Area?
 
def look(self):
"Look around the place you are in"
print self.description
 
def addSomething(self,thing):
"adds something to the contents"

def removeSomething(self,thing)
"remove from contents"
 
def addPath(self,direction,area)
"Adds a connection to area"
 
#...
#more as needed
 
 

Chris Henk



"Ara Kooser" <[EMAIL PROTECTED]> 
Sent by: [EMAIL PROTECTED]
08/31/2007 03:06 PM

To
tutor@python.org
cc

Subject
[Tutor] Starting classes






Hello,
  I read Alan Gauld's and How to Think Like a Computer Scientist
section on classes. So I tried to write a simple room class. My goal
is to write a short text adventure using classes. Here is the code:

class Area:
def _init_(self, name, description):
self.name = name


def look(here):
"Look around the place you are in"
print here.description


outside1 = Area("Outside")
outside1.description = "You are standing outside with the town gate to
your back"
self.contents.append("dirt")


look(bedroom)

I get the following error.
Traceback (most recent call last):
  File "/Users/ara/Documents/text_advent.py", line 11, in 
outside1 = Area("Outside")
TypeError: this constructor takes no arguments

Do the outside1 = Area("Outside) need to be nested in the class or can
they be outside of it?

Thank you.

Ara



-- 
Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis
an sub cardine glacialis ursae.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Livewires

2007-09-10 Thread christopher . henk
[EMAIL PROTECTED] wrote on 09/10/2007 07:29:24 AM:

> Hi all
> 
> just learning python really and been using the livewires tutorial / 
worksheets to get some experience.
> 
> I have hit an issue which is just my lack of understanding around 
looping concepts and execution.
> 
> My issue:
> 
> in worksheet 5-robots.pdf attached, page 4 the challenge
> 
> "Challenge: Write a loop that makes the circle move smoothly from (0,0) 
to (640,480): in other words, from the bottom left
> to the top right of the screen."
> 
> this has got me a bit stumped because its an (x,y) co-ordinate pair that 
I want to update.
> I think in a loop i need to draw a circle, move a circle, remove the 
circle.
> 
> I thought I needed to for loops to iterate through two ranges but this 
is wrong, here is my code though!
> 
> from livewires import *
> begin_graphics()
> 
> allow_moveables()
> x=range(10,640,10)
> y=range(10,480,10)
> for xco in x:
> for yco in y:
> c = circle(xco,yco,5)
> move_to(c, xco,yco)
> #remove_from_screen(c) /*commented this out to see output on 
graphics window */
> end_graphics()
> 


If I understand the requirements correctly: you are moving along the 
diagonal of the map.
So say 100 time steps to move the distance.

time step: 0position:  (0,0)
time step: 1position: (64,48)
time step: 2position: (128,96)
...

so the new x and y move together with a different delta so that they reach 
their max at the same time.
Your only loop would be what time step you are on.

timesteps=100
x,y =0,0
deltax=640/timesteps
deltay=480/timesteps
for time in range (timesteps):
c=circle(x,y,5)
x+=deltax
y+=deltay
move_to(c,x,y)
remove_from_screen(c)

I would think that would do the trick.
But I haven't had any coffee yet this morning, so if I missed something, 
let me know.

Chris


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Finding prime numbers

2007-09-19 Thread christopher . henk
[EMAIL PROTECTED] wrote on 09/19/2007 12:38:49 PM:

> Sorry about that.
> 
> I have posted the code below:
> 
> #!/usr/bin/env python
> 
> '''A program to generate prime numbers when given 2 numbers'''
> 
> def isPrime(number):
> number=abs(int(number))
> #1 is not considered a prime number
> if number<2:
> return False
> #2 is the only even prime number
> if number==2:
> return True
> #no even prime numbers after 2
> if not number&1:
> return False
> #to find all prime numbers we need to go up to the
> #square root of the highest odd number
> for x in range(3,int(number**0.5)+1,2):
> if number%x==0:
> return False
> return True

Looks like you want to move the return True out one level of indentation.

> > -- 
> > Michael Langford
> > Phone: 404-386-0495
> > Consulting: http://www.TierOneDesign.com/
> > Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

Chris Henk
Allison Transmission
phone:  317.242.2569
fax:  317.242.3469
e-mail:  [EMAIL PROTECTED]___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Updating MySQL Database

2007-10-10 Thread christopher . henk
That Slashdot comment makes so much more sense now.

Chris Henk
Allison Transmission
phone:  317.242.2569
cell: 765.337.8769
fax:  317.242.3469
e-mail:  [EMAIL PROTECTED]



Kent Johnson <[EMAIL PROTECTED]> 
Sent by: [EMAIL PROTECTED]
10/10/2007 08:52 AM

To
Python Tutorlist 
cc

Subject
Re: [Tutor] Updating MySQL Database






Kent Johnson wrote:

> It 
> also looks like you are embedding the data in the SQL command, this is 
> very bad practice, it opens you to SQL injection attacks

For a humorous explanation of why you don't want to directly embed data 
into SQL commands, see today's xkcd:
http://xkcd.com/327/

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Decimal Conversion

2007-10-15 Thread christopher . henk
However since r is an int and b is a string, you will get an error when 
you try and concatenate them.
>>> b=''
>>> b+=1
Traceback (most recent call last):
  File "", line 1, in 
TypeError: cannot concatenate 'str' and 'int' objects

So you need to convert r to a string before you assign it to b
>>> b=""
>>> n=5
>>> r=str(n%2)
>>> b=r+b
>>> print b
1
>>> n=n/2
>>> r=str(n%2)
>>> b=r+b
>>> print b
01
>>> n=n/2
>>> r=str(n%2)
>>> b=r+b
>>> print b
101


Chris Henk


[EMAIL PROTECTED] wrote on 10/15/2007 03:17:13 PM:

> After sending the last email, I was more and more unsatisfied with it's 
level of detail I provided.
> 
> Your original statement:
> 
> b=b,r
> 
> was doing nothing like you intended. The comma operator in this instance 
is making a tuple. The name b was being 
> reassigned to the new tuple created by the comma operator.
> 
> b+="," + r 
> 
> Was not doing exactly what I said. What it's doing is creating a new 
string from the one named by b, the string 
> literal "," , and the one named by r. After creating the string it 
assigns the name b to the new string. 
> 
>   --michael
> 
> -- 
> Michael Langford
> Phone: 404-386-0495
> Consulting: http://www.TierOneDesign.com/ 

> On 10/15/07, Michael Langford < [EMAIL PROTECTED]> wrote:
> Use 
> b+=","+r 
> instead. That will add the , to the string named by b, and will 
concatenate the string named by r to the end.
> 
>--Michael
> 
> -- 
> Michael Langford
> Phone: 404-386-0495 
> Consulting: http://www.TierOneDesign.com/ 
> 

> On 10/15/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi,
> 
> I'm new to Python, and found some problems on the internet that would be 
a
> good start to begin. The problem I have is that my conversion program 
(which
> currently only converts unsigned integers) also prints all these 
brackets 
> and commas. Here is my code and the result:
> CODE:
> print ""
> print ""
> print "Unsigned Binary"
> print ""
> print "" 
> n = int(raw_input("Please enter an integer: "))
> b = ''
> while n > 0:
> r = n%2
> n = n/2
> b = r,b
> print b
> 
> (ex: n = 15)
> RESULT:
> (1, (1, (1, (1, ''
> 
> I think the problem is in the line of code 'b = r,b', but am not sure 
how to
> fix it. The tip given for the problem says I should 'append' r to b, but
> since b is not a list, 'b = r,b' was the only thing that came to my 
mind. 
> 
> Thanks in advance.
> ___
> Tutor maillist  -  Tutor@python.org 
> http://mail.python.org/mailman/listinfo/tutor 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New Introductory Book

2007-11-08 Thread christopher . henk
[EMAIL PROTECTED] wrote on 11/08/2007 05:19:59 PM:

> "Chris Calloway" <[EMAIL PROTECTED]> wrote
> 
> > teach languages. Teaching languages is frowned upon in some computer
> > science departments under the logic that if you belong in a computer
> > science class, you'd better show up for class already knowing 
> > something
> > as easy to grasp as an implementation language.
> 
> I don't like CS courses to focus on a language either, but neither do 
> I think
> we should expect students to already know one. But learning a computer
> language should be a trivial exercise once you understand the CS 
> concepts
> of algorithms and data and I/O etc.
> 
> One of the worst things I find as an employer is the number of CS
> grads I get to interview who insist they only know one language. I 
> wonder
> what they learned at college. That's like an electronics engineer 
> saying
> he only knows how to solder, or a civil engineer who only knows how
> to lay bricks! A CS course should concentrate on principles and
> theory and learning languages should be a practical detail that the
> student does almost by osmosis.
> 
> And this is, of course, why my tutorial teaches three languages
> not just python ;-)
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld

One of the worse things I found as a recent job hunter, was the number of 
employers who are not willing to accept that after completing a CS program 
that focuses on the science of CS, learning the language they are using is 
a trivial exercise.  On the plus side it helps identify the companies I 
didn't want to work for.

Chris Henk___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using 'join ' function to create a string

2007-12-21 Thread christopher . henk
this works for me.

Z=", ".join(["%s:%s" %(a,Y[b]) for b,a in enumerate(X)])






lechtlr <[EMAIL PROTECTED]> 
Sent by: [EMAIL PROTECTED]
12/21/2007 11:00 AM

To
tutor@python.org
cc

Subject
[Tutor] Using 'join ' function to create a string






Hi there,

I would like to know what is the best way to create a string object from 
two different lists using 'join' function. For example, I have X = ['a', 
'b', 'c', 'd', 'e'] and Y = [1, 2, 3, 4, 5]. From X and Y, I want to 
create a string Z = 'a:1, b:2, c:3, d:4, e:5'.
Any help would greatly be appreciated.
-Lex 
 Looking for last minute shopping deals? Find them fast with Yahoo! 
Search.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Random module error

2008-05-15 Thread christopher . henk
Your original post showed this traceback:
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\swampy.1.1\TurtleWorld.py", line 1, in 
from World import *
  File "C:\Python25\swampy.1.1\World.py", line 29, in 
import random
  File "C:\Python25\random.py", line 4, in 
i = random.randrange(10,50)
AttributeError: 'module' object has no attribute 'randrange'

Which would suggest that the file World.py imported a file called 
random.py from the directory  C:\Python25\random.py
The random module that comes with python is typically stored in  the 
directory C:\Python25\Lib
and never contains the line:  i = random.randrange(10,50)

So I would look for a .py or .pyc file in your Python25 folder called 
random and remove it like Kent said.

Hope that works.

Chris 




"Guess?!?" <[EMAIL PROTECTED]> 
Sent by: [EMAIL PROTECTED]
05/15/2008 03:48 PM

To
"Kent Johnson" <[EMAIL PROTECTED]>
cc
tutor@python.org
Subject
Re: [Tutor] Random module error






Hello Kent,
 
I dont have any program with name random.py. I am using swampy API (
http://allendowney.com/swampy/install.html)
As instructed by author, I do following steps
 
1> unzip/extract the folder into Python directory
2> go to the swampy directory
3> and invoke python command to start interpreter
4> as soon as I write from TurtleWorld import *
 
I get that error . I checked inside the folder ...there is no 
random.py and 
i checked TurtleWorld.py there is only reference to standard module 
"random"
 
Thnks
G
 
 


 
On Thu, May 15, 2008 at 5:00 AM, Kent Johnson <[EMAIL PROTECTED]> wrote:
On Thu, May 15, 2008 at 3:00 AM, Guess?!? <[EMAIL PROTECTED]> wrote:
> Hello All,
>
> I am importing module "random" and it is giving me this error
> below  AttributeError: 'module' object has no attribute 'randrange'

You have named your program random.py. The import finds your program
rather than the random module. Rename your program and delete the
associated .pyc file and it will work.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 180MB

2008-05-27 Thread christopher . henk
Looking at my system, it looks like you 180MB is for all your python 
packages together, not each one.
I get 68.67MB under my add/remove which is the size of my Python folder.

Chris




"Switanek, Nick" <[EMAIL PROTECTED]> 
Sent by: [EMAIL PROTECTED]
05/27/2008 04:54 PM

To

cc

Subject
[Tutor] 180MB






I?m running windows XP. Judging from the Add/Remove programs interface, it 
appears that many python packages I?ve installed over the years are each 
taking up right around 180MB. This includes pyreadline, winpdb, pywordnet, 
numarray, numpy, and many others besides. It seems an uncanny coincidence 
that each package would be within a few MB of the next. Any insight into 
whether there is something wrong here, and if so, what I?ve done? 
 
Thanks,
Nick
 ___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Message 'list' object has no attribute 'strptime ?

2008-09-04 Thread christopher . henk
It looks to me that your variable:

time = in_time.split(":")

is hiding the time module.

Chris




Wayne Watson <[EMAIL PROTECTED]> 
Sent by: [EMAIL PROTECTED]
09/04/2008 04:05 PM

To
"tutor@python.org" 
cc

Subject
Re: [Tutor] Message 'list' object has no attribute 'strptime ?






Further info. If I put
y = time.strptime("11 01 05", "%H %M %S")
both in the function and in the main body. Only the line above in the 
function produces an error message.

Here's a simple program that creates the problem.

import datetime

def verify_time(in_time):
time = in_time.split(":")
if len(time) <> 3:
print
print "Invalid format. Try again. hh:mm:ss, hh is 24 hour time."
return False
y = time.strptime("11 01 05", "%H %M %S")
print y, "Yes, y"
hour,minute,second = time
fmt_time = hour+" "+minute+" "+second
print "FMT TIME:", fmt_time
x = time.strptime(fmt_time, "%H %M %S")
print "fmt time:", fmt_time
try:
time.strptime(fmt_time, "%H %M %S")
nhour   = int(hour)
nminute = int(minute)
nsecond = int(second)
except:
print
print "Invalid date values or format (hh:mm:ss): ", in_time
print "Valid examples: 15:55:02, 8:20:5"
print "Invalid examples: 14: 2:33, 7:11: 4, 11::7"
return False 
return True

y = time.strptime("11 01 05", "%H %M %S")
atime = "11:12:13"
print verify_time(atime)

Wayne Watson wrote: 
The line
x = time.strptime(fmt_time, "%H %M %S")
with fmt_time = "11 12 40" 
in function produces the msg:
Traceback (most recent call last):
  File 
"C:\Sandia_Meteors\Improved_Sentinel\Sentinel_Playground\Utility_Dev\SU_DateTimeAdjust.py",
 
line 209, in ?
if not verify_time(bump_time):
  File 
"C:\Sandia_Meteors\Improved_Sentinel\Sentinel_Playground\Utility_Dev\SU_DateTimeAdjust.py",
 
line 69, in verify_time
x = time.strptime(fmt_time, "%H %M %S")
AttributeError: 'list' object has no attribute 'strptime'

However, in another function the line
  x = time.strptime(fmt_date, "%m %d %Y")
with fmt_date = "10 02 2008" works just fine.
Does my format string in strptime for time have a problem?

If I use the shell to set fmt_time and x = time.strptime(fmt_time, ..., I 
have no trouble.

 -- 

   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
 
  Interesting government experience prior their candidacy:

 Abraham Lincoln: 2 years; George Washington: 0 years;
  Dwight Eisenhower: 0 years; James Buchanan: 29 years*
 Barack Obama: 11 years; John McCain: 26 years

  * Not a particularly good president at all
 
Web Page: 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
 

-- 
   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
 
  Interesting government experience prior their candidacy:

 Abraham Lincoln: 2 years; George Washington: 0 years;
  Dwight Eisenhower: 0 years; James Buchanan: 29 years*
 Barack Obama: 11 years; John McCain: 26 years

  * Not a particularly good president at all
 
Web Page: 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with checking for a data type

2008-09-04 Thread christopher . henk
try and convert the first value in the split list to a int (or float), if 
that works then post the value.
if it throws an exception (ValueError) then catch that and pass, or do 
whatever else needs doing with the listing.

def postData(inputData):
fields=inputData.split("-")
try:
numberfield=int(fields[0])
#do whatever voodoo needed
print "%s posted" %inputData
except ValueError:
print "%s not posted" %inputData
pass
#move on to other fields
 
inputValue=["12-Foo-Fee","Bla-Ble-blu"]

for entry in inputValue:
postData(entry)




"Spencer Parker" <[EMAIL PROTECTED]> 
Sent by: [EMAIL PROTECTED]
09/04/2008 04:56 PM

To
tutor@python.org
cc

Subject
[Tutor] Help with checking for a data type






I have a script that is taking a directory list, the script then splits 
the name up by the hyphens in the name.  The first part of the name should 
be a number, but it isn't always a number.  Is there a way to say: if its 
a number then post this dataif not discard?

-- 
Spencer Parker
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hay Variables

2008-09-12 Thread christopher . henk
I would use a list of grades and the length of the list.

Chris




"Jeremiah Stack" <[EMAIL PROTECTED]> 
Sent by: [EMAIL PROTECTED]
09/12/2008 02:08 PM

To
"Python Tutor" 
cc

Subject
[Tutor] Hay Variables






Sorry,


Okay,
Say i want to calculate the average for Math = 91 Science = 97 and English 
= 96, 

I Declare a variable = Number of classes to divide by.

So instead say later I want to add another class.

Instead of adding a variable And changing the (Number of Classes = 3) 
variable.

I would like to just add another variable and have the Number of classes 
variable change automatically.

So NumberOfClasses = (Number variables).

Hope that makes sense and without user keyboard input
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] not operator

2008-09-18 Thread christopher . henk
[EMAIL PROTECTED] wrote on 09/18/2008 06:12:30 PM:

> i want to check if a dir does not exist. how do i change this statement
> to evaluate is NOT existing? ==False or ! operator. Also, is sys.exit
> appropriate to use to quit out of the program?
> 
> if(os.access(target_dir, os.F_OK)):
>print "File does not exist!"
>sys.exit 
> 

os.access(target_dir, os.F_OK) is going to return False if the directory 
does not exist so take your pick how you want to check it.

if not os.access(target_dir, os.F_OK):

or 

if os.access(target_dir, os.F_OK)==False:

or

if os.access(target_dir, os.F_OK)!=True:


I like the first one, others like the second.

the below doesn't work in python
>>> if !(os.access(target_dir, os.F_OK)):
SyntaxError: invalid syntax


sys.exit is fine as long as you call it. 
sys.exit()
you left off the () in your sample code, and I wasn't sure if that was a 
typo or not. 
Python will not raise an error.



Chris___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dealing with user input whose value I don't know

2008-10-02 Thread christopher . henk
[EMAIL PROTECTED] wrote on 
10/02/2008 01:06:29 PM:

> Hello,
> 
> I am trying to do some exercises in John Zelle's book (chapter 4).
> I got stuck:
> 
> "Write a program that finds the average of a series of numbers entered 
> by the user. The program should first ask the user how many numbers 
> there are. Note: the average should always be a float, even if the user 
> inputs are all ints."
> 
> Okay, I can ask how many number are to be added:
> 
> numbers = input("How many number do you want me to calculate? ")

you should really use raw_input to get the info from the user, and 
then convert it to a number.
numbers=int(raw_input("How many number do you want me to 
calculate? "))

> 
> If I then get a reply, say "5", what I would have to do next is to ask 
> for the five numbers so that I can calculate the average.

Write the code like you knew it was going to be a 5 and then 
replace anywhere the 5 appears with the variable 'numbers'.



> But given that I don't know the the value of 'numbers' ex ante, how 
> could I ask for the right amount of numbers?
> I don't see how this can be achieved with the tools I have learned so 
far...

Looking at the table of contents it looks like you should have 
learned about loops by now.



> I am currently thinking along the lines of
> 
> ans1, ans2 = input("Enter the numbers separated by a comma: ")
> average = (ans1 + ans2) / 2.0

have each number be its own input and repeat it depending on how 
their input for numbers, and then do the averaging at the end.

> 
> But as I say - I don't know how many assignment there have to be, nor do 

> I know how Python could then create these assignments.
> 
you don't need to keep the individual numbers only the sum, but if 
you want to, use a list and append each new number to the end of the list.

> It would be great if someone could guide me towards the right track!!
> 
> Thanks,
> 
> David
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dealing with user input whose value I don't know

2008-10-02 Thread christopher . henk
I am not sure how you got from the input to your variable i, it is a good 
idea to post your code as well.

That said raw_input will return the user's input as a string which you 
then need to convert to integers.
So the commas are brought in as well.
You can solve this in a couple of ways:
First, you can split the string on the commas and get a list of strings 
each representing one of the numbers.

numberlist=numbers.splt(",")
will give you: 
numberslist=["1","2"]
which you can then loop over and convert to integers and add up.

Secondly, you can have the users input the numbers one at a time inside 
the loop.
add = add + int(raw_input("Please type the next number:"))

Chris





David <[EMAIL PROTECTED]> 
Sent by: [EMAIL PROTECTED]
10/02/2008 02:06 PM

To
tutor@python.org, 
[EMAIL PROTECTED]
cc

Subject
Re: [Tutor] dealing with user input whose value I don't know






Cheers for the insights!

However, I just found out that changing input() to raw_input() breaks my 
code:

This program takes the average of numbers you supply!!
How many numbers do you want me to work with? 2
You want me to take the average of 2 numbers.
Please type the numbers, separated by commas: 1,2
You want to know the average of the numbers: 1,2
Traceback (most recent call last):
  File "avgInput.py", line 13, in 
add = add + i
TypeError: unsupported operand type(s) for +: 'int' and 'str'

 End of process output 

The reason being, I take, that

numbers = raw_input("Please type the numbers, separated by commas: ")

also returns the comma (1,2) and thus the for loop can't cope...
So should I therefore retain

numbers = input("Please type the numbers, separated by commas: ") ?

Otherwise I don't know (yet) what to do

David


Bill Campbell wrote:
> On Thu, Oct 02, 2008, Steve Willoughby wrote:
> 
>> On Fri, Oct 03, 2008 at 01:38:48AM +0800, David wrote:
>> 
>>> Does that mean input() is obsolete (after all, Zelle's book is not the 

>>> freshest on the shelf)? Or do they have different uses?
>>> 
>> Depends on how you look at it.
>>
>> input() automatically evaluates whatever the user types as a Python
>> expression and returns the result.  So if they type 5, the integer
>> 5 is returned.  For your program, that's probably what you want, and
>> has the advantage of letting you type something like 2+3 so your user
>> can let Python evaluate math expressions.
>>
>> On the other hand, you'd think that you could ask a user for a text
>> response using input():
>>   name = input("What is your name? ")
>>   print "Hello, ", name
>>
>> But if they just type the answer, Python will crash with an error
>> because it's expecting a legal Python expression there (so a 
>> string value would have to be typed in quotes).
>> 
>
> Remember the cardinal rule NEVER TRUST USER INPUT!  Always check
> for validity, and use methods that prevent malicious strings from
> allowing the user to get unauthorized access or change things
> they shouldn't.
>
> Many of the common exploits of web pages are the result of poor
> checking of input resulting in sql injection attacks, and other
> breaches.
>
> Bill
> 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] decision structures

2008-10-21 Thread christopher . henk
> Perhaps someone else will help you. I won't offer anything more until 
you respond to a lot more of my questions and comments.
> 

Read what Bob has written back to you and try it or ask questions related 
to it if you don't understand something he said.

> AND PLEASE reply to tutor@python.org as well as whoever responds to you.
> 
> Brummert_Brandon wrote: 
> here is the one that I am still stuck on.  not much has changed since 
last time.

> def main():
> currentdate= input ("What is the date (mm/dd/)?:")

Try printing out the value of currentdate here and see what you get. Bob 
has mentioned that you may have some issues with your result and gave a 
suggestion on how to fix it.  It has also been mentioned several times in 
other current threads on the list, since it is a common point of 
confusion.

Also, one of the nice things about Python is you can use the interactive 
interpreter to see what you would get as a response to your code.
Try starting up Python and just typing in the line:
input ("Type something here:")

and then enter a date.

What do you get as an answer?
Is it what you expected?

try is again with typing different things in and see what answers you get.

What is different between what the user is typing in this program and your 
previous program and what you are doing with that input?

Once you get past this point we can address the rest of the program. 

The people on the list are very happy to help but will not do the work for 
you.  You need to read what the responses are and work with the tutors.

hope that helps get you started,

Chris___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reciprocal import

2008-12-16 Thread christopher . henk
Although you generally would want to design so that this does not happen, 
if the import of the first module is only needed in some of the functions 
in the second module, you can include the import within the function 
definition and that would  work ok.
But you can't have the second import at the module level.

Chris




Steve Willoughby  
Sent by: tutor-bounces+christopher.henk=allisontransmission@python.org
12/16/2008 03:08 PM

To
spir 
cc
*tutor 
Subject
Re: [Tutor] reciprocal import






spir wrote:
> Is it legal or possible  at all for two modules to import each other? I
> tried several ways and had several kinds of error messages. Usually
> "can't import...".

My first impression here is that this sounds like a bad class/module 
design if they're really that interdependent.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor