Re: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end

2011-10-04 Thread Andreas Perstinger

On 2011-10-05 05:13, lina wrote:

$ python3 counter-vertically.py

^^^

   File "counter-vertically.py", line 20
 print item
  ^
SyntaxError: invalid syntax


In Python 3 print is a function: print(item)

In another message in this thread you've said:
"Sorry, I am still lack deep understanding about something basic."

IMHO you should take the time to read the tutorial (as others have 
already told you) before continuing your work:

http://docs.python.org/py3k/tutorial/index.html

Bye, Andreas

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


Re: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end

2011-10-05 Thread Andreas Perstinger

On 2011-10-06 05:46, lina wrote:

On Thu, Oct 6, 2011 at 4:33 AM, Prasad, Ramitwrote:

 Dictionaries {} are containers for key/value based pairs like { key :
 value, another_key : value(can be same or repeated) }

 For example:
 {'B': [0, 0, 0, 0, 0, 0], 'E': [2, 1, 4, 0, 1, 0]}
 The keys here are 'B' and 'E'. The values here are [0, 0, 0, 0, 0, 0] (for

  ^

 key 'B') and [2, 1, 4, 0, 1, 0] (for key 'E')


  def writeonefiledata(outname,results):
 outfile = open(outname,"w")
 for key in results:
 return outfile.write(results[key])

$ python3 counter-vertically-v2.py
Traceback (most recent call last):
   File "counter-vertically-v2.py", line 43, in
 dofiles(".")
   File "counter-vertically-v2.py", line 12, in dofiles
 processfile(filename)
   File "counter-vertically-v2.py", line 29, in processfile
 writeonefiledata(base+OUTFILEEXT,results)
   File "counter-vertically-v2.py", line 39, in writeonefiledata
 return outfile.write(results[key])
TypeError: must be str, not list

^
The error message tells you, that "results[key]" is a list but "write" 
just excepts a string. (see Ramit's explanation above).

You have to convert the list values to a string.
BTW: You shouldn't return the write operation because that will exit 
your function after the first iteration.



def writeonefiledata(outname,results):
 outfile = open(outname,"w")
 for key, value in results.iteritems():
 return outfile.write(key)

$ python3 counter-vertically-v2.py
Traceback (most recent call last):
   File "counter-vertically-v2.py", line 43, in
 dofiles(".")
   File "counter-vertically-v2.py", line 12, in dofiles
 processfile(filename)
   File "counter-vertically-v2.py", line 29, in processfile
 writeonefiledata(base+OUTFILEEXT,results)
   File "counter-vertically-v2.py", line 38, in writeonefiledata
 for key, value in results.iteritems():
AttributeError: 'dict' object has no attribute 'iteritems'


In Python 3 there is no "dict.iteritems()" any more:
http://docs.python.org/py3k/whatsnew/3.0.html#views-and-iterators-instead-of-lists
Use "dict.items()" instead

Bye, Andreas

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


Re: [Tutor] vcf_files and strings

2011-10-05 Thread Andreas Perstinger

On 2011-10-05 21:29, Anna Olofsson wrote:

vcf file: 2 rows, 10 columns.

The important column is 7 where the ID is, i.e.
refseq.functionalClass=missense. It's a missense mutation, so then I
want to extract refseq.name=NM_003137492, or I want to extract only
the ID, which in this case is NM_003137492.

Then I want to do exactly the same thing for all the other mutations,
but only for the missense mutations not the other ones. How do I
accomplish that? Where do I start?


I would split the rows into the columns (analyze your file to find the 
seperator), then look for "missense" in the 7th column in every row and 
if found regex for the name/ID.


Are you able to code that yourself or do you need more hints?

Bye, Andreas

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


Re: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end

2011-10-06 Thread Andreas Perstinger

On 2011-10-06 16:11, lina wrote:

I still don't know how to (standard) convert the list values to a string.

def writeonefiledata(outname,results):
 outfile = open(outname,"w")
 for key, value in results.items():
 print(value)
 outfile.write(str(results[key]))
Is it a wrong way?


There isn't really a wrong way because it's completely up to you how the 
list (or its elements) should be represented. As you will have noticed, 
"str(list)" just gives you the standard representation in Python (all 
list elements separated by a comma inside square brackets):

>>> str([1, 2, 3, 4])
'[1, 2, 3, 4]'

But I think you want something else because earlier you wrote:

On 2011-10-04 18:38, lina wrote:
> For file:
>
> aaEbb
> aEEbb
> EaEbb
> EaEbE
>
> the expected output is
>
> 2 1 0 1

(Although I suppose, as Alan already noticed, that you've forgotten to 
mention the third column and the output should be: 2 1 4 0 1)


So you have to build your own string. You could use the join method. It 
takes a list and concatenates the list elements to a string separated by 
the given string object:

>>> "".join(["1", "2", "3"])
'123'
>>> "-".join(["1", "2", "3"])
'1-2-3'

The problem now is that "join" will only join the list elements if they 
are strings but in your case the list elements are integers. You have to 
convert them before you can concatenate them. In Python that's usually 
the job of a list comprehension but I'm not sure if you already know 
what that is. So for a start you can also use a for-loop:

>>> l = []
>>> for number in [1, 2, 3]:
... l.append(str(number))
...
>>> l
["1", "2", "3"]

You must also be aware that when you write your new strings into a file 
that "write" doesn't append a newline ("\n") to each string (in contrast 
to "print"). So you have to do it manually if you don't want to write 
just a long list of numbers.


Bye, Andreas

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


Re: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end

2011-10-07 Thread Andreas Perstinger

On 2011-10-07 14:21, lina wrote:

 I don't know why this gives a key error on 'E' (which basically means that
 there is no key 'E') since the code above should guarantee that it exists.
 Odd. I'm also not sure why the error occurs after it prints summary. Are you
 sure the output is in the sequence you showed in your message?

  One simple explanation:  it continued on to the next file, which has

 neither "E" nor "B" in it.


In this directory, I only kept one file. try.xpm


That's wrong.


  $ more try.xpm
aaEbb
aEEbb
EaEbb
EaEbE

$ ls
counter-vertically-v2.py  try.xpm
counter-vertically.py   try.txt


As "ls" proves, you have *4* files in the directory.

You start your script with "dofiles(".")". This function gets a list of 
*all* files in the directory in an *arbitrary* order and processes each 
of it.


In your function "processfile" you first create an empty dictionary 
("results = {}") and then you put values into the dictionary *only* for 
xpm-files ("if ext == INFILEEXT:"). *But* you print the summary for 
*every* file because the indentation at the end of the function is 
outside the if-branch where you check for the file extension. So for 
every file which isn't a xpm-file, "results" is an empty dictionary (see 
first line of the function) and therefore "zip(results['E'], 
results['B'])" will throw an exception.


How to solve it? I personally would check for the file extension in the 
function "dofiles" and would only continue with xpm-files (in other 
words move the if-statement from "processfile" to "dofiles".)


Bye, Andreas

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


Re: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end

2011-10-07 Thread Andreas Perstinger

On 2011-10-08 05:34, lina wrote:

Another minor derived questions:

 summary=[]
 for a,b in zip(results['E'],results['B']):
 summary.append(a+b)## now the summary is '[0,1, 3, 5,
6,0,0,0]'
 del summary[0]   ## here I wanna remove the first zero, which came
from the initial double quote "EB...E",
 summary.pop()## here I wanna remove the last three zeros
 summary.pop()
 summary.pop()
 print(summary)   ### output is [1,3,5,6]
 summary='\n'.join(str(summary).split(','))  ### wish the result in
one column,
 with open(base+OUTFILEEXT,"w") as f:
 f.write(str(summary))

the final result in the output.txt file is:
[1
3
5
6]

Q1: how can I remove the [1 "[" to only keep 1?


That's a job for a list comprehension (read 
http://docs.python.org/py3k/tutorial/datastructures.html#list-comprehensions 
for a short introduction):


new_summary = '\n'.join([str(element) for element in summary])


Q2 how can I improve above expressions?


-) As above, you could use a list comprehension for creating your 
summary list:


summary = [(a + b) for a, b in zip(results['E'], results['B'])]

-) Instead of

del summary[0]
summary.pop()
summary.pop()
summary.pop()

I suggest to slice your list:

summary = summary[1:-3]

But this assumes that your summary list will always have one leading 
zero and 3 trailing zeros.


-) In your last line

with open(base+OUTFILEEXT,"w") as f:
 f.write(str(summary))

you don't need to convert summary to a string because it is already one.

Bye, Andreas

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


Re: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end

2011-10-07 Thread Andreas Perstinger

On 2011-10-08 06:07, lina wrote:

Still have a reading "multiple" files issue:

Traceback (most recent call last):
   File "counter-vertically-WORKING.py", line 26, in
 results[ch][col]+=1
IndexError: list index out of range

only one file ss_1.xpm was processed and wrote file, for the rest ss_2.xpm,
ss_3.xpm and following keep intact,

any suggestions?


Could you provide links to your current script file 
(counter-vertically-WORKING.py) and your data files(ss_1.xpm, ss_2.xpm, 
...)?


Bye, Andreas

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


Re: [Tutor] vcf_files and strings

2011-10-07 Thread Andreas Perstinger

[I have already answered your first post but it seems you missed it]

On 2011-10-07 18:12, Anna Olofsson wrote:


Hi,

I'm a beginner at Python and would really appreciate some help in how
to extract information from a vcf file.


What does "beginner" mean?
Do you have experience in other languages?
Do you understand how different datatypes work (strings, integers,
lists, dictionaries, ...)?
Do you know the basic programming concepts (for-loops, if-then-else
conditions, ...)?


The important column is 7 where the ID is, i.e.
refseq.functionalClass=missense. It's a missense mutation, so then I
want to extract refseq.name=NM_003137492, or I want to extract only
the ID, which in this case is NM_003137492.

Then I want to do exactly the same thing for all the other mutations,
but only for the missense mutations not the other ones. How do I
accomplish that? Where do I start?


Can you show us some code snippets of your attempts?

Bye, Andreas

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


Re: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end

2011-10-07 Thread Andreas Perstinger

On 2011-10-08 08:25, lina wrote:

 Still have a reading "multiple" files issue:


 Traceback (most recent call last):
   File "counter-vertically-WORKING.**py", line 26, in
 results[ch][col]+=1
 IndexError: list index out of range

 only one file ss_1.xpm was processed and wrote file, for the rest
 ss_2.xpm,
 ss_3.xpm and following keep intact,

 any suggestions?


https://docs.google.com/leaf?id=0B93SVRfpVVg3MjIxZGI5YWQtN2NiYy00MWFkLWE0ZTctNjExNGJiNjYzYjQw&hl=en_GB

https://docs.google.com/leaf?id=0B93SVRfpVVg3YjQ1ZWRkMjUtNmZhYS00MTA4LTg3YTktY2JjYzEyMDU5OTI2&hl=en_GB

https://docs.google.com/leaf?id=0B93SVRfpVVg3YjQ1ZWRkMjUtNmZhYS00MTA4LTg3YTktY2JjYzEyMDU5OTI2&hl=en_US

you may rename ss_1.xpm to the ss_2 or 3, keep them the same is okay, just
different names.


Ok, I just ran your script with this files and don't get an error. 
Except some stylistic issues the code looks fine. The resulting 
txt-files still have the problem with the leading '[' and trailing ']' 
but I've already suggested a solution earlier today.


Do you still get an error?

Bye, Andreas

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


Re: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end

2011-10-08 Thread Andreas Perstinger

On 2011-10-08 09:12, lina wrote:

$ python3 counter-vertically-WORKING.py
[26, 22, 28, 30, 32, 27, 30, 29, 28, 30, 32, 24, 27, 27, 28, 30, 32, 30, 33,
27, 33, 32, 34, 31, 28, 34, 33, 32, 25, 35, 30, 32, 30, 32, 25, 30, 26, 24,
33, 28, 27, 26, 23, 27, 27, 28, 27, 25, 24, 23, 23, 27, 24, 27, 26, 23, 17,
25, 21, 28, 21, 15, 24, 21, 12, 11, 9, 15, 20, 15, 15, 22, 29, 30, 23, 21,
29, 31, 17, 26, 21, 23, 23, 19, 25, 21, 27, 23, 25, 30, 26, 23, 25, 23, 25,
30, 28, 29, 25, 26, 28, 23, 26, 30, 25, 25, 21, 23, 23, 25, 21, 25, 25, 23,
30, 29, 28, 27, 27, 29, 27, 23, 27, 29, 21, 24, 23, 21, 25, 23, 26, 23, 23,
23, 23, 24, 25, 21, 23, 23, 23, 25, 25, 30, 25, 23, 26, 24, 28, 25, 25, 23,
23, 19, 23, 23, 21, 25, 18, 23, 21, 25, 21, 23, 25, 23, 22, 23, 21, 28, 25,
24, 21, 20, 21, 14, 23, 21, 13, 14, 21, 23, 24, 29, 26, 26, 21, 17, 19, 23,
21, 24, 26, 24, 26, 29, 29, 28, 28, 21, 24]
Traceback (most recent call last):
   File "counter-vertically-WORKING.py", line 26, in
 results[ch][col]+=1
IndexError: list index out of range

still the same, and only one txt coming out. the others did not process.

$ ls *.xpm *.txt
ss_0.xpm   ss_1.xpm  ss_4.xpm  ss_7.xpm  ss_9.xpm
ss_10.xpm  ss_2.xpm  ss_5.xpm
ss_1.txt   ss_3.xpm  ss_6.xpm  ss_8.xpm


Strange, if I do

$ python3.2 counter-vertically-WORKING.py

it prints all results and also creates all txt-files:

$ ls *.xpm *.txt
ss_0.txt  ss_0.xpm  ss_1.txt  ss_1.xpm  ss_2.txt  ss_2.xpm

Please insert "print(fileName)" as the first line in your main for-loop 
so we can see on which file the program hangs.


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


Re: [Tutor] swapping list elements based on some criterion

2011-10-08 Thread Andreas Perstinger

On 2011-10-08 09:53, Peter Otten wrote:

Emad Nawfal (عمـ نوفل ـاد) wrote:

 Here is the function as I used it, and it works fine:

 def swap(sentence):
buffer = []
adjectives = []
for word in sentence.split():
if word.endswith('/ADJ'):
adjectives.append(word)
elif word.endswith('/N'):
buffer.append(word)
buffer.extend(adjectives)

adjectives = []
else:
buffer.append(word)
return ' '.join(buffer)


Does the classification scheme allow for adjectives that are not followed by
a noun? Example: if "good" in the sentence "That looks good" were classified
as an adjective it would be silently dropped.


As far as I know, adjectives are always in front of a noun in English. 
Therefore I suggest iterating backwards and everytime you come across a 
noun check if it is preceded by an adjective and swap the positions. 
Iterating backwards is necessary for cases where more than one adjective 
is in front of the noun. So the noun "floats" towards the beginning of 
the sentence while all adjectives without nouns (or behind nouns - I 
don't know if that's possible in English) will stay where they are:


def swap(sentence):
s = sentence.split()
for i in reversed(range(len(s))):
if s[i].endswith("/N") and s[i-1].endswith("/ADJ"):
s[i], s[i-1] = s[i-1], s[i]
return s

>>> swap("the/DET tall/ADJ man/N plays/VBZ well/ADV")
['the/DET', 'man/N', 'tall/ADJ', 'plays/VBZ', 'well/ADV']

>>> swap("That/DET looks/VBZ good/ADJ")
['That/DET', 'looks/VBZ', 'good/ADJ']

>>> swap("He/P is/VBZ a/ART big/ADJ old/ADJ man/N who/P went/VBZ 
crazy/ADJ")
['He/P', 'is/VBZ', 'a/ART', 'man/N', 'big/ADJ', 'old/ADJ', 'who/P', 
'went/VBZ', 'crazy/ADJ']


Bye, Andreas

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


Re: [Tutor] swapping list elements based on some criterion

2011-10-08 Thread Andreas Perstinger

On 2011-10-08 11:11, Andreas Perstinger wrote:

def swap(sentence):
  s = sentence.split()
  for i in reversed(range(len(s))):
  if s[i].endswith("/N") and s[i-1].endswith("/ADJ"):
s[i], s[i-1] = s[i-1], s[i]
  return s


Oops, noticed a little bug:

The for-loop should be "for i in reversed(range(1, len(s))):" so that 
sentences starting with a noun get processed correctly:


>>> swap("Joe/N went/VBZ crazy/ADJ")
['Joe/N', 'went/VBZ', 'crazy/ADJ']

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


Re: [Tutor] Crazy craps problem

2011-10-08 Thread Andreas Perstinger

On 2011-10-09 07:16, col speed wrote:

The part of the script that is causing the problem is as follows:

def point(num):
 while True:
 raw_input("Roll")
 uno, dos = random.choice(dice), random.choice(dice)
 three = uno+dos
 print "{0} + {1} = {2}".format(uno, dos, three)
 print "Point is {0}. You scored {1}.".format(num, three)
 if three == num:
 return "win"
 if three == 7:
 return "lose"
 else:
 print "Try again."

What I have tried to do is - simulate dice throws, if the total is the same
as originally thrown, return from the function(this works). If I throw a 7,
I also want to return(this does not work as you can see from this sample
output:


I'm pretty sure that your problem is not in the code snippet you have 
shown us. Here it works as expected (I've copied your code, added 
"import random" and "dice = [1, 2, 3, 4, 5, 6]" at the top and saved as 
"dice.py"):


Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import dice
>>> dice.point(1)
Roll
4 + 5 = 9
Point is 1. You scored 9.
Try again.
Roll
4 + 3 = 7
Point is 1. You scored 7.
'lose'
>>>

Please show us the part where you use the "point" function.

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


Re: [Tutor] Crazy craps problem

2011-10-08 Thread Andreas Perstinger

On 2011-10-09 08:25, col speed wrote:

Thanks for your prompt reply! Here's the whole thing:

import random

message = """Welcome to craps Place your bet
  and roll the dice.
  7 or 11 wins.
  2, 3 or 12 loses.
  Others are "point"."""
player = "Your"
dice = range(1, 7)
stake = 100
bet = 5
winmsg = "You have won!You have ${0} left.".format(stake)
losemsg = "You have lost! You have ${0} left.".format(stake)
players = ["Your", "My"]

def win(num):
 if num in [7,11]:
 return "win"
 elif num in [2,3,12]:
 return "lose"
 else:
 return "point"

def changePlayer(player):
 if player == "Your":
 return "My"
 else:
 return "Your"

def point(num):
 while True:
 raw_input("Roll")
 uno, dos = random.choice(dice), random.choice(dice)
 three = uno+dos
 print "{0} + {1} = {2}".format(uno, dos, three)
 print "Point is {0}. You scored {1}.".format(num, three)
 if three == num:
 return "win"
 if three == 7:
 return "lose"
 else:
 print "Try again."

print message
while stake:
 print "{0} throw! You have ${1}. How much do you bet?".format(player,
stake)
 bet = int(raw_input("$"))
 stake -= bet
 one, two = random.choice(dice), random.choice(dice)
 print "{0} + {1} = {2}".format(one, two, one+two)
 if win(one+two) == "win":
 stake += bet*2
 print winmsg
 elif win(one+two) == "lose":

 print losemsg
 else:
 if point(one+two) == "win":


Here you go into the function "point" the first time. Inside the 
function you are in an infinite while-loop where you only exit if the 
sum is either 7 ("lose") or equal the given parameter ("win"). Then you 
compare the return value. In the case of "lose" you continue to the next 
elif-statement:



 stake += bet*2
 print winmsg
 elif  point(one+two) == "lose":


Now you go into the function "point" a *second* time, in other words you 
have to throw another 7 to leave the function with the return value 
"lose". But just now you will print out the message for loosing the game:



 print losemsg
 player = changePlayer(player)


What you probably want is to go into "point" only once, save the result 
value and check if it's "win" or "lose".


HTH,
Andreas


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


Re: [Tutor] map one file and print it out following the sequence

2011-10-12 Thread Andreas Perstinger

On 2011-10-12 05:31, lina wrote:

I tried to write one (not working one) as below, so many problems here.


Just some quick remarks:


#!/usr/bin/python3

import os.path

LINESTOSKIP=0
CHAINID="CDEFGHI"
INFILENAME="pdbone.pdb"
DICTIONARYFILE="itpone.itp"
mapping={}
valuefromdict={}

def sortfile():
 for chainid in CHAINID:
 sortoneblock(chainid)


def generatedictionary(dictfilename):


You define the function with the parameter "dictfilename" but you'll 
never use it.



 text=fetchonefiledata(DICTIONARYFILE)
 for line in text:
 parts=line.strip().split()
 if len(parts)==8:
 mapping[parts[4]]=parts[0]
 print(mapping)


The if-branch is probably wrongly indented (should be inside the for-loop).


def sortoneblock(cID)
 text=fetchonefiledata(INFILENAME)
 for line in text:
 blocks=line.strip().split()
 if len(blocks)== 11 and  blocks[3] == "CUR" and blocks[4] == "cID":



"cID" is a string-variable but you compare block 4 to the literal string 
"cID". In "pdbone.pdb" you will never find "cID" so this function will 
do nothing. You probably mean "blocks[4] == cID".



 valuefromdict[blocks[2]]=mapping[block[2]]


You never fill up "mapping" because you never call your 
"generatedictionary"-function. Therefore "mapping" is still an empty 
dictionary and this line will raise an exception.



 return


Firstly, the indentation is wrong because you would leave "sortoneblock" 
after the first processed line. Secondly, as you return nothing, you 
don't need this line because you will leave the function anyway.





def fetchonefiledata(infilename):
 text=open("infilename").readlines()


Again, "infilename" is a variable, so no need for the quotes.


 if os.path.splitext(infilename)[1]=".itp"
 return text
 if os.path.splitext(infilename)[1]=".pdb"
 return text[LINESTOSKIP:]


if __name__=="__main__":
 sortfiles()


There is no "sortfiles()" in your script. The function you probably mean 
is called "sortfile()"


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


Re: [Tutor] map one file and print it out following the sequence

2011-10-12 Thread Andreas Perstinger

On 2011-10-12 10:27, lina wrote:

  $ python3 map-to-itp.py
{'O4': '2', 'C19': '3', 'C21': '1'}
{'C': '3'}
{'C': '2'}
{'C': '1'}

for print(mapping) part, {'O4': '2', 'C19': '3', 'C21': '1'} the value
doesn't keep the 1, 2, 3 order any more.


That's fine, because "mapping" is a dictionary which has no order. From 
the tutorial 
(http://docs.python.org/py3k/tutorial/datastructures.html#dictionaries):
"It is best to think of a dictionary as an unordered set of key: value 
pairs, with the requirement that the keys are unique (within one 
dictionary)."


What you want (as far as I understand it) is sorting the lines in 
"pdbone.pdb" based on the positions in file "itpone.itp". The connection 
between both files is the column with the values "O4", "C19", "C21", ... 
(= your keys). You've already succesfully built a dictionary in which 
you saved the position for every key.


For the sorting you could now build a list of tuples of all lines in 
"pdbone.pdb" you want to sort where the first element in the tuple is 
the position and the second the line itself. Then you can easily sort 
this temporary list and write the new ordered lines back to the file:


def sortoneblock(cID):
text = fetchonefiledata(INFILENAME)
temp = []# create an empty temporary list

for line in text:
blocks = line.strip().split()
if len(blocks) == 11 and blocks[3] == "CUR" and blocks[4] == 
cID and blocks[2] in mapping.keys():


temp.append((mapping[blocks[2]], line))  # add a tuple to 
the list which has the following format: (position from the dictionary, 
complete line)


# the following line just shows you, what we have done so far. You 
can delete it without consequences.


for line in temp: print(line)

temp.sort() # this sorts the list based on the position

# the following line prints the sorted list (just the original line 
without the position elements). If you want to write the result back to 
the file you have to exchange "print()"


for line in temp: print(line[1])

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


Re: [Tutor] map one file and print it out following the sequence

2011-10-13 Thread Andreas Perstinger

On 2011-10-13 15:09, lina wrote:

$ python3 map-to-itp.py
{'O4': '2', 'C19': '3', 'C21': '1'}
C
Traceback (most recent call last):
   File "map-to-itp.py", line 55, in
 sortfile()
   File "map-to-itp.py", line 17, in sortfile
 sortoneblock(chainid,intext,OUTFILENAME)
   File "map-to-itp.py", line 29, in sortoneblock
 f.write(line[1].strip() for line in temp)
TypeError: must be str, not generator

I don't know how to fix the writing issue.


You should start to learn how to read the error messages :-).
"write" just writes strings into files ("must be str") but you are 
calling it with an generator. I guess you wanted to use a list 
comprehension, but this is surrounded by square brackets:


f.write([line[1].strip() for line in temp])

But list comprehensions create lists so you would have to convert the 
list to a string:


f.write(str([line[1].strip() for line in temp]))

But this would convert the whole list into one single string which you 
probably don't want (try it for yourself).


IMHO it would be easier to iterate through "temp" and write each line 
separately:


for line in temp:
f.write(line[1])

"line[1]" is already a string including the newline ("\n"), so str() and 
strip() aren't necessary (remeber: "write" writes without automatic 
newlines).


Is that what you want?


can I write the different chainID one into the same OUTFILE?


I'm not sure what you mean. Do you want something like:
C



D
xxx
xxx
...
("xxx" meaning the different lines)?

Then you just have to write the corresponding chainID before the for-loop:

f.write(cID + "\n")

And you have to open the file in mode "a" (to append to an existing 
file) because otherwise you will overwrite the file with every new 
chainID you are processing:


with open(OUTFILE, "a") as f:


def sortoneblock(cID,TEXT,OUTFILE):

   
Just a stylistic remark: It's better to use just lowercase for variable 
names and parameters. Uppercase names are usually just used for 
constants. Thus it's easier to distinguish them while reading the code.


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


Re: [Tutor] string immutability

2011-10-24 Thread Andreas Perstinger

On 2011-10-24 20:04, Johan Martinez wrote:

Hi,

I am struggling to understand Python string immutability. I am able to
modify Python string object after initializing/assigning it a value.


 s = "First"
 print s.__class__



 print s

First

 s = "Second"
 print s

Second


Dave, Sander and Wayne have already explained why you aren't modifying 
string objects in your example.

With the id()-function you can also see what is happening:

>>> s = "First"
>>> id(s)
3077110080L# In CPython this is the memory address of the object
   # with the name 's' (in your case "First")
>>> s = "Second"
>>> id(s)
3077110304L# You see that 's' refers now to another address
>>> id("First")
3077110080L# But "First" is still on the same address as before
>>> id("Second")
3077110304L# And this proves that "Second" is at the address
   # which 's' refers to

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


Re: [Tutor] more trouble

2011-10-28 Thread Andreas Perstinger

On 2011-10-28 20:45, Eric Schles wrote:

The help steven gave me makes sense, except I don't know what it means.  How
do you run the command as root?
When I try to run the command in the command line, I get the following
error:
C:\>easy_install SQLObject
'easy_install' is not recognized as an internal or external command,
operable program or batch file.

What does that mean?


Windows can't find the "easy_install.exe" because it's not in C:\ and 
not in your PATH environment variable.


I've no windows here, but from reading the docs you've probably 
installed "easy_install" in your python scripts subdirectory. So you 
have to go there before you can run it:

C:\>cd \Python2x\Scripts (x depends on your installed python version)
C:\Python2x\Scripts>easy_install SQLObject

Or you add the scripts directory to your PATH:
http://peak.telecommunity.com/DevCenter/EasyInstall#id5

If you can't find out where it's installed, try searching for 
"easy_install.exe".


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


Re: [Tutor] Pickle Class Instances

2011-10-31 Thread Andreas Perstinger

On 2011-11-01 06:31, Rinu Boney wrote:

def add_book(b):
 fo=open('books.dat','wb')
 pickle.dump(b,fo)
 fo.close()

The Display After Unpickling Shows only the last Class Instance.
How To Display All The Data In The File ?


You haven't shown us the complete program (how to you call "add_book" 
and "display_books"?) but I guess that you call "add_book" with one 
instance (if not, you can ignore the rest). In that case there is no 
more data in the file.


In your "add_book" function you open the file "books.at" and just save 
one instance. The next time you call the function with another instance 
you overwrite the former, because opening the same file with the 
parameter "w" (or in your case "wb") deletes any already existing content.


What you probably want is to put all the instances into a list and save 
this list. When you later read the file, you'll get the list back and 
you can iterate over it for displaying.


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


Re: [Tutor] Help with re in Python 3

2011-11-05 Thread Andreas Perstinger

On 2011-11-04 20:59, Albert-Jan Roskam wrote:

It seems that you are not opening the file properly. You could do
f = file('///Users/joebatt/Desktop/python3.txt','r')
or:
withfile('///Users/joebatt/Desktop/python3.txt','r') as f:


OP is using Python 3, where "file" is removed. Thus, you have to use "open":

f = open('...')

with open('...') as f:

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


Re: [Tutor] how to remove the coming duplication

2011-11-10 Thread Andreas Perstinger

On 2011-11-10 09:26, lina wrote:

atoms=[]

def fetchonefiledata(infilename):
 for line in open(infilename,"r"):
 parts=line.strip().split()
 atoms=parts[2]
 print(atoms[0])


First you define "atoms" as an empty list, but in the line

atoms = parts[2]

you are redefining it by assigning a string to it. Thus, at the end of 
the for-loop, only the last string is stored (in every iteration you 
overwrite the former value with a new one).


You probably want to append the values:

atoms.append(parts[2])

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


Re: [Tutor] positional output

2011-11-10 Thread Andreas Perstinger

On 2011-11-10 21:54, Cranky Frankie wrote:

What is the easiest way in Python 3.x to write output positionally?
For example I have one literal I want in column 1, the next one in
column 40, the third one in column 50. I've tried usings tabs and I'm
not getting what I want. Is it something to do with C style printf
formatting? An example would be greatly appreciated.


Two ideas:

1) Using string formatting:
>>> print("x{0}x{1}x".format(" " * 38, " " * 9))

2) Using a helper list (assuming screen width = 80):
>>> line = [" "] * 80
>>> line[0] = "x"
>>> line[39] = "x"
>>> line[49] = "x"
>>> print("".join(line))

Bye, Andreas

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


Re: [Tutor] longest common substring

2011-11-11 Thread Andreas Perstinger

On 2011-11-11 05:14, lina wrote:

def LongestCommonSubstring(S1, S2):
 M = [[0]*(1+len(S2)) for i in xrange(1+len(S1))] ## creat 4*5 matrix
 longest, x_longest = 0, 0
 for x in xrange(1,1+len(S1)): ## read each row
 for y in xrange(1,1+len(S2)): ## read each coloumn
 if S1[x-1] == S2[y-1]:
 M[x][y] = M[x-1][y-1]+1
 if M[x][y]>  longest:
 longest = M[x][y]
 x_longest = x
 else:
 M[x][y] = 0
 return S1[x_longest-longest:x_longest]


That's still not the right version.

If you compare your version to the one at wikibooks ( 
http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Python 
), you'll see that the else-branch is wrongly indented (one level too 
deep). It belongs to the first if-comparison:


if S1 ...
 M[x][y] ...
 if M[x][y] ...
...
else: ...



if __name__=="__main__":

 a=open("atom-pair_4.txt","r").readline().strip()

 b=open("atom-pair_8.txt","r").readline().strip()

 
print(LongestCommonSubstring(LongestCommonSubstring(a,a),LongestCommonSubstring(b,b)))

^^^
??? What do you try to accomplish here ???
You call "LongestCommonSubstring" with identical strings, thus the 
result must be the same string.

Why not

print(LongestCommonSubstring(a, b))

as you did the line below with "c" and "d"?

Further more I think that your problems start with bad data files. In 
every file there is just one very long line which looks like a string 
representation of a list of two-digits strings. This complicates further 
processing because you have to deal with all the unnecessary commas, 
blanks and single quotes between your numbers and the square brackets at 
the beginning and the end of the line.




  $ python3 LongestCommonSubstring.py
2189
['
['82']

The results are wrong.
c, d are the string from file atom-pair_4,txt, exactly the same as a,
d is the same as b.

and even for (c,d) results are not correct, visually we can see some
similar groups, not mention the longest groups.


And even if you use the correct function from wikibooks I can anticipate 
another problem :-)
The implementation from wikibooks just returns the first common 
substring which it finds in the first string:


>>> WikibooksLongestCommonSubstring("ABAB","BABA")
'ABA'
>>> WikibooksLongestCommonSubstring("BABA", "ABAB")
'BAB'

If there are more possible substrings with the same length (as in the 
example above) only the first one is returned.


But in your example there are at least two different pathways (I've 
found three) which have the same length, as changing the order of the 
parameters will show you:


>>> WikibooksLongestCommonSubstring(c, d)
['61', '70', '61']
>>> WikibooksLongestCommonSubstring(d, c)
['83', '61', '83']

Bye, Andreas

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


Re: [Tutor] longest common substring

2011-11-11 Thread Andreas Perstinger

First, just a little rant :-)
It doesn't help to randomly change some lines or introduce some new 
concepts you don't understand yet and then hope to get the right result. 
Your chances are very small that this will be succesful.

You should try to understand some basic concepts first and build on them.
From your postings the last weeks and especially from today I have the 
impression that you still don't understand how fundamental programming 
concepts work: for-loops, differences between data types (strings, 
lists, sets, ...)
Honestly, have you already read any programming tutorial? (You'll find a 
big list at http://wiki.python.org/moin/BeginnersGuide/NonProgrammers )? 
At the moment it looks like you are just copying some code snippets from 
different places and then you hopelessly try to modify them to suit your 
needs. IMHO the problems you want to solve are a little too big for you 
right now.


Nevertheless, here are some comments:


Based on former advice, I made a correction/modification on the below code.

1] the set and subgroup does not work, here I wish to put all the
subgroup in a big set, the set like


That's a good idea, but you don't use the set correctly.

> subgroups=[]
> subgroup=[]
> def LongestCommonSubstring(S1, S2):

I think it's better to move "subgroups" and "subgroup" into the 
function. (I've noticed that in most of your scripts you are using a lot 
of global variables. IMHO that's not the best programming style. Do you 
know what "global/local variables", "namespace", "scope" mean?)


You are defining "subgroups" as an empty list, but later you want to use 
it as a set. Thus, you should define it as an empty set:


subgroups = set()

You are also defining "subgroup" as an empty list, but later you assign 
a slice of "S1" to it. Since "S1" is a string, the slice is also a 
string. Therefore:


subgroup = ""

>  M = [[0]*(1+len(S2)) for i in xrange(1+len(S1))]

Peter told you already why "xrange" doesn't work in Python 3. But 
instead of using an alias like


xrange = range

IMHO it's better to change it in the code directly.

>  longest, x_longest = 0, 0
>  for x in xrange(1,1+len(S1)):
>  for y in xrange(1,1+len(S2)):
>  if S1[x-1] == S2[y-1]:
>  M[x][y] = M[x-1][y-1]+1
>  if M[x][y]>  longest:
>  longest = M[x][y]
>  x_longest = x
>  if longest>= 3:
>  subgroup=S1[x_longest-longest:x_longest]
>  subgroups=set([subgroup])

Here you overwrite in the first iteration your original empty list 
"subgroups" with the set of the list which contains the string 
"subgroup" as its only element. Do you really understand this line?
And in all the following iterations you are overwriting this one-element 
set with another one-element set (the next "subgroup").
If you want to add an element to an existing set instead of replacing 
it, you have to use the "add()"-method for adding an element to a set:


subgroups.add(subgroup)

This will add the string "subgroup" as a new element to the set "subgroups".

>  print(subgroups)
>  else:
>  M[x][y] = 0
>
>  return S1[x_longest-longest:x_longest]

Here you probably want to return the set "subgroups":

return subgroups



2] I still have trouble in reading files, mainly about not read "" etc.


The problem is that in your data files there is just this big one-line 
string. AFAIK you have produced these data files yourself, haven't you? 
In that case it would be better to change the way how you save the data 
(be it a well-formatted string or a list or something else) instead of 
trying to fix it here (in this script).


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


Re: [Tutor] (no subject)

2011-11-11 Thread Andreas Perstinger

Please just post plain-text (no html) and use a meaningful subject!

On 2011-11-11 22:40, Nic Jaworski wrote:

def calc(days):
  n=0
  d=1
  while n>days:
n+1
d**(n)
d*2


You are just calculating some expressions with "n" and "d" but you don't 
assign the results. Thus "n" and "d" will never change.



x = array ([d,n])
print x


In "main()" you have the line

salary = calc(days)

but you just return "None" (the default value for functions without a 
"return" statement) from "calc()". Is that what you want?



main()


I don't know about windows but if you want to run the script from the 
command line you have to add:


if __name__ == "__main__":
   main()

See 
http://docs.python.org/py3k/tutorial/modules.html#executing-modules-as-scripts


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


Re: [Tutor] Hello again. Still the same problem, different question.

2011-11-11 Thread Andreas Perstinger

On 2011-11-12 05:16, Nathaniel Trujillo wrote:

They gave me a website to go and download a version of
livewires that would work (www.courseptr.com/downloads) and I went there
but I could not find that download anywhere.


http://www.delmarlearning.com/companions/content/1435455002/downloads/index.asp?isbn=1435455002
If you click on "Book related software" you'll get a zip-file which 
includes "livewires".


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


Re: [Tutor] (no subject)

2011-11-12 Thread Andreas Perstinger

On 2011-11-12 10:33, Alan Gauld wrote:

On 11/11/11 22:17, Andreas Perstinger wrote:


 I don't know about windows but if you want to run the script from the
 command line you have to add:

 if __name__ == "__main__":
 main()


No, you only need to do that if you plan on using the file as a module
at some point. If you don't need a module then the OPs style will work
just fine on any OS.


Of course you're right. Sorry for the misinformation. It was probably 
too late in the evening when I wrote this yesterday :-(.


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


Re: [Tutor] longest common substring

2011-11-12 Thread Andreas Perstinger

On 2011-11-12 16:24, lina wrote:

Thanks, ^_^, now better.


No, I'm afraid you are still not understanding.


I checked, the sublist (list) here can't be as a key of the results (dict).


"result" isn't a dictionary. It started as an empty list and later 
becomes a null object ("NoneType").


You must not forget that you are inside a for-loop. Simplified your 
situation is like this:


>>> result = []
>>> for i in range(1,10):
... print("Iteration {0}, result = {1}".format(i, result))
... result = result.append(i)
...
Iteration 1, result = []
Iteration 2, result = None
Traceback (most recent call last):
  File "", line 3, in 
AttributeError: 'NoneType' object has no attribute 'append'

As you see the error happens in the *second* iteration, because result 
is no list any more.
Dave gave you already the explanation: functions and method always 
return a value in Python. If the don't have a return statement they 
return "None".


Another simple example:

>>> a = print("Test")
Test

"print" is a function which prints out the text you passed to it and you 
usually aren't interested in its return value. But every function/method 
in Python returns something. You save this value in "a"


>>> print(a)
None

As you see the return value of "print" is "None".

>>> a.append(x)
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'NoneType' object has no attribute 'append'

Same error as above, because "NoneType" objects (null objects) don't 
have a method "append".


I also think you mix two different ways to add an element to a list:

result.append(x)

is equivalent to

result = result + [x] (that's what you will use in other languages)

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


Re: [Tutor] longest common substring

2011-11-13 Thread Andreas Perstinger

On 2011-11-11 14:44, lina wrote:

You are right, I did not think of this parts before. and actually the
initiative wish was to find possible paths, I mean, possible
substrings, all possible substrings. not the longest one, but at
least bigger than 3.


I had some time today and since you have changed your initial task (from 
finding the longest common path to finding all common paths with a 
minimum length) I've modified the code and came up with the following 
solution:


def AllCommonPaths(list1, list2, minimum=3):
""" finds all common paths with a minimum length (default = 3)"""

# First we have to initialize the necessary variables:
# M is an empty table where we will store all found matches
# (regardless of their length)

M = [[0] * (len(list2)) for i in range(len(list1))]

# length is a dictionary where we store the length of each common
# path. The keys are the starting positions ot the paths in list1.

length = {}

# result will be a list of of all found paths

result =[]

# Now the hard work begins:
# Each element of list1 is compared to each element in list2
# (x is the index for list1, y is the index for list2).
# If we find a match, we store the distance to the starting point
# of the matching block. If we are in the left-most column (x == 0)
# or in the upper-most row (y == 0) we have to set the starting
# point ourself because we would get negative indexes if we look
# for the predecessor cell (M[x - 1][y - 1]). Else, we are one
# element farther away as the element before, so we add 1 to its
# value.

for x in range(len(list1)):
for y in range(len(list2)):
if list1[x] == list2[y]:
if (x == 0) or (y == 0):
M[x][y] = 1
else:
M[x][y] = M[x - 1][y - 1] + 1

# To get everything done in one pass, we update the length of
# the found path in our dictionary if it is longer than the minimum
# length. Thus we don't have to get through the whole table a
# second time to get all found paths with the minimum length (we
# don't know yet if we are already at the end of the matching
# block).

if M[x][y] >= minimum:
length[x + 1 - M[x][y]] = M[x][y]


# We now have for all matching blocks their starting
# position in list1 and their length. Now we cut out this parts
# and create our resulting list

for pos in length:
result.append(list1[pos:pos + length[pos]])

return result

I've tried to explain what I have done, but I'm sure you will still have 
questions :-).


Is this close to what you want?

Bye, Andreas

PS: Here's the function again without comments:

def AllCommonPaths(list1, list2, minimum=3):
""" finds all common paths with a minimum length (default = 3)"""

M = [[0] * (len(list2)) for i in range(len(list1))]
length = {}
result =[]

for x in range(len(list1)):
for y in range(len(list2)):
if list1[x] == list2[y]:
if (x == 0) or (y == 0):
M[x][y] = 1
else:
M[x][y] = M[x - 1][y - 1] + 1
if M[x][y] >= minimum:
length[x + 1 - M[x][y]] = M[x][y]

for pos in length:
result.append(list1[pos:pos + length[pos]])

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


Re: [Tutor] longest common substring

2011-11-13 Thread Andreas Perstinger

On 2011-11-11 16:53, Jerry Hill wrote:

There's nothing wrong with writing your own code to find the longest common
substring, but are you aware that python has a module in the standard
library that already does this?  In the difflib module, the SequenceMatcher
class can compare two sequences and extract the longest common sequence of
elements from it, like this:


Thanks for the tip. I've played around with it, but I think it doesn't 
help in the OP's situation. "SequenceMatcher.find_longest_match()" just 
finds the first common block:


Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import difflib
>>> first = [0, 1, 2, 3, 0, 4, 5, 6, 0]
>>> second = [1, 2, 3, 4, 5, 6]
>>> match = difflib.SequenceMatcher(None, first, second)
>>> match.find_longest_match(0, len(first), 0, len(second))
Match(a=1, b=0, size=3)

Here it returns just [1, 2, 3] but misses [4, 5, 6]. So you would have 
to adjust the lower limits to get it. 
"SequenceMatcher.get_matching_blocks()" seems to be a better choice:


>>> match.get_matching_blocks()
[Match(a=1, b=0, size=3), Match(a=5, b=3, size=3), Match(a=9, b=6, size=0)]

Now you get [1, 2, 3] and [4, 5, 6]. But if the two blocks are in the 
reversed order, there is no longest common subsequence [1, 2, 3, 4, 5, 
6] any more and "SequenceMatcher" only finds one part (apparently it 
chooses the first it comes across in the first list if both have the 
same length):


>>> first = [0, 1, 2, 3, 0, 4, 5, 6, 0]
>>> second = [4, 5, 6, 1, 2, 3]
>>> match = difflib.SequenceMatcher(None, first, second)
>>> match.find_longest_match(0, len(first), 0, len(second))
Match(a=1, b=3, size=3)
>>> match.get_matching_blocks()
[Match(a=1, b=3, size=3), Match(a=9, b=6, size=0)]

From both methods you get [1, 2, 3].

As I've learnt during this tests, there is a difference between 
subsequences and substrings:

http://en.wikipedia.org/wiki/Subsequence#Substring_vs._subsequence

If I've understood the OP right, he/she wants to find all common 
substrings with a minimum length regardless of their order in the strings.


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


Re: [Tutor] Variables (with lists??)

2011-11-22 Thread Andreas Perstinger

On 2011-11-23 05:15, Chris Kavanagh wrote:

I was going over one of Derek Banas' tutorials on youtube, and came
across something I hadn't seen before. A variable with a list beside it
(see code below). He sets the variable, customer , equal to a dict. Then
uses the variable with ['firstname'],['lastname'], ect. I've never seen
this in my short programming life. What is this called?


That's the Python syntax to indexing dictionary keys (comparable to the 
index of lists, tuples, ...)


In general, you set a value with

dictionary[key] = value

where "key" can be any immutable type (strings, numbers, tuples if they 
just contain strings, numbers and other tuples) and "value" anything you 
want to save for that key.


To get the value of a key, just use

dictionary[key]

Example:
>>> customer = {}
>>> customer["name"] = "Chris"
>>> customer["name"]
'Chris'


And is there any documentation on it??


The tutorial on dictionaries:
http://docs.python.org/tutorial/datastructures.html#dictionaries

The library reference on dictionaries:
http://docs.python.org/library/stdtypes.html#mapping-types-dict

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


Re: [Tutor] how to delete some quasi-duplicated keys

2011-11-25 Thread Andreas Perstinger

On 2011-11-25 13:40, lina wrote:

On Fri, Nov 25, 2011 at 7:19 PM, Steven D'Aprano  wrote:

 f = open("some file")
 dehydrons = {}
 occurrence = {}
 pairs = {}
 for line in f.readlines():
 parts = line.split()
 # convert to ints
 parts = [int(s) for s in parts]
 pair = frozenset(parts[:2])  # order doesn't matter
 if pair in dehydrons:
 occurrence[pair] += 1
 else:
 dehydrons[pair] = parts[2]
 occurrence[pair] = 1
 pairs[pair] = pairs.get(pair, 0) + parts[2]
 f.close()


 for line in f.readlines():
 parts = line.split()
 #pair=set((parts[0],parts[1]))
 #convert to ints
 parts = [int(s) for s in parts]
 pair = frozenset(parts[:2])
 print(pair)
 if pair in dehydrons:
 occurence[pair] += 1
 else:
 dehydrons[pair] = parts[2]
 pairs[pair] = pairs.get(pair,0) + parts[2]
 print(pairs)


$ python3 dehydron_data_frozenset_version.py
frozenset({2, 15})
frozenset({2, 15})
Traceback (most recent call last):
   File "dehydron_data_frozenset_version.py", line 35, in
 occurence[pair] += 1
KeyError: frozenset({2, 15})


You want to add one to "occurence[frozenset({2, 15})]" but there is no 
such key in "occurence" yet.


If you carefully re-read Steven's code snippet you will see that you 
missed the line


occurence[pair] = 1

in the else-branch.

Therefore "occurence[frozenset({2, 15})]" wasn't set in the first 
iteration and you get the error in the second. You can see that you are 
already in the second iteration by looking at the output of your program 
before the error message.


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


Re: [Tutor] Do loop in Python

2011-11-25 Thread Andreas Perstinger

On 2011-11-25 14:46, stm atoc wrote:

Here is the new version of the program:

zvalues = [-200]  # starting value
hvalues = [10]  # starting value
increments = [1, 1, 1, 1, 1, 1, 1, 1]
for N in increments:
h = hvalues[-1] - N
hvalues.append(h)
z = zvalues[-1] + h
zvalues.append(z)
height = arange((z)*dz,0,dz)


There is no "arange" in python. Could it be that you use numpy and 
import it with "from numpy import *"?



for z,when in enumerate(height):


I'm pretty sure this line doesn't do what you expect it to do. You have 
a sequence (a numpy array) named "height" and after calling "enumerate" 
you get a list of tuples in the form of [(0, height[0]), (1, height[1]), 
...]. Now the for-loop iterates over this list and assigns "z" to the 
first value of the tuple (the index-values) and "when" to the second 
(the values from "height"). You later never use "when" but just use "z". 
If you really want that, the "enumerate" is completly unnecessary and 
you could just use "for z in range(len(height))". But I'm not sure if 
numpy arrays work with "len()".



nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence
diffusivity m**2/s
nu.append(num + nuh[z])

The story is like this:
I should define layers and thickness and see how the diffusion profile
changes over the z.
height (or depth) of the total thickness or 'z'.
I basically, define 'z' in 10 layers and each layer is called  ' N' .
Difference between each layer is 'h', which is equal 10 micrometer.
Now, what I like to do is the modification of nu based on each zvalue
In fact, for each 'zvalue' o'z' step, I need to calculate a different
value for 'nu' based on the available equation in the program.

BUT, I am not sure, exactly, how to add the new do loop of z inside
another loop of nu.


For me your explanations are still too confusing. Could it be that you 
are thinking way too complicated?


My guess is you want to have a range of material thicknesses (from 1 to 
200 micrometers in 10 micrometer-steps) and then you want from each 
thickness 10 different layers, right?


import math # you should always tell us which modules you import
num = 0.05 # some constant
nu = [] # list of resulting values
h = 10.0 # height of one layer
thickness = range(0, 210, 10) # a list from 0 to 200 with step 10 (0, 
10, 20, ..., 190, 200)

layers = range(1,11) # a list from 1 to 10
for t in thickness:
  for l in layers:
z = t + h * l # I'm not sure if you want to add or subtract the 
layer thickness

nu = num + (0.01 * math.exp(-0.05 * (z + 200.0)))

This will result in a big one-dimensional list where you calculate for 
each thickness the nu-value for 10 layers. Am I close?
I'm still not sure about the steps and the height of the layers. I also 
wonder if it wouldn't be better to use a two-dimensional list.



I have done this way as well (the other way around):

height = arange((z)*dz,0,dz)
for z,when in enumerate(height):
 for N in increments:
h = hvalues[-1] - N
hvalues.append(h)
z = zvalues[-1] + h
zvalues.append(z)
nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence
diffusivity m**2/s
nu.append(num + nuh[z])

but still no sign of 'nu changes' over 'z'!


As Charles has already mentioned, the values for "nu" are very similar 
(they start beginning to differ just at the seventh digit after the 
comma). How do you further process this values? If you plot them what's 
your scale?


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


Re: [Tutor] how to delete some quasi-duplicated keys

2011-11-27 Thread Andreas Perstinger

On 2011-11-26 03:49, lina wrote:


 for k, v in occurence.items():
 print(v,k)

292 frozenset({66, 69})
222 frozenset({24, 27})


How can I let the result like:

292 {66,69}
222 {24,27}

don't output the frozenset


If you want to use your own output format you have to provide it.

For example, you could use a combination of string formatting and 
".join()" to get what you want:


for k, v in occurence.items():
print("{0} {{{1}}}".format(v, ",".join([str(x) for x in k])))

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


Re: [Tutor] How to use try and except in this case?

2011-11-27 Thread Andreas Perstinger

On 2011-11-27 17:58, Mic wrote:

Say that I want to try and open 10 files. If none of these exists, I want an
error
message to appear. But only if NONE of these files exists.

I know how to handle this with one file. But I don't know how to do that
with more than one.
So the program should try and open all 10 files and if, and only if, none
of the files exists I want en error message to appear.


Use a counter which increments with every existing file. After opening 
all files check if the counter is bigger than 0.


Or, if you need to know which files exist, use a list, append existing 
files to it and check at the end if it's not empty.


Do you need more help?

Bye, Andreas


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


Re: [Tutor] Parsing

2011-11-27 Thread Andreas Perstinger

On 2011-11-27 21:45, Deanna Wilson wrote:

  Project 4: Parsing rhinoceros sightings


Please confirm that this is homework. At least I've found this site:
https://www.e-education.psu.edu/geog485/node/144

[snip]

sample of my code:


What are your problems?
I've skimmed your sample and found a number of errors. Since your task 
looks like homework, you should be more specific about your problems.


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


Re: [Tutor] Random order program

2011-11-27 Thread Andreas Perstinger

On 2011-11-27 23:17, myles broomes wrote:

#get the users input for the list of words, one by one
first_word = input("Please enter your first word: ")
second_word = input("Please enter your second word: ")
third_word = input("Please enter your third word: ")
fourth_word = input("Please enter your fourth word: ")
fifth_word = input("Please enter your fifth word: ")

#create a tuple containing the users words of the words
word_list = (first_word,second_word,third_word,fourth_word,fifth_word)


You could shorten the input procedure by using a for-loop and appending 
every word to a list instead using five different "word"-variables and 
building a tuple with them.



#create an empty list that the words will go into to be returned in a random 
order
random_word_list = []

print("Now your list will be displayed in a random order.")

#random order list
while len(random_word_list) != len(word_list):
 word = random.choice(word_list)
 if word not in random_word_list:
 random_word_list += word


Bob told you already that you are creating an infinite-loop. Try this:

Python 3.2 (r32:88445, Mar 25 2011, 19:28:28)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> l = []
>>> s = "test"
>>> l += s
>>> l
['t', 'e', 's', 't']

Do you see your problem? You want to "add" a string to a list but with 
the inplace operator "+=" "word" is interpreted as a sequence (a list of 
letters). You can't "add" a string to a list:


>>> l = l + s
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate list (not "str") to list

If you want to add an element to a list you should use the 
".append"-method of lists:

http://docs.python.org/py3k/tutorial/datastructures.html#more-on-lists

Bob mentioned also the problem with your algorithm. Everytime you get a 
word from "random.choice" which is already in "random_word_list" you 
have to loop again:


>>> counter = 0
>>> random_word_list = []
>>> word_list = ["a", "b", "c", "d", "e"]
>>> while len(random_word_list) != len(word_list):
...   counter += 1
...   word = random.choice(word_list)
...   if word not in random_word_list:
... random_word_list.append(word)
...
>>> print(counter)

If you are lucky, "counter" is close to the minimum 5. But in one of my 
test runs it was 25.
This is unnecessary because you don't need more iterations than the 
length of "word_list" (5 in your case)


Anyways, there is already a shuffle-method in the "random"-module:
docs.python.org/py3k/library/random.html

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


Re: [Tutor] Parsing

2011-11-27 Thread Andreas Perstinger
[Please reply to the list. Your indentation also got lost during the 
mail delivery.]


On 2011-11-27 23:21, Deanna Wilson wrote:

Yes it is homework, but not from Penn state. It is a Geog690 class. I'm
having difficulties with determining where the rhino is referenced in the
split line, determining if the dictionary has a key for the rhino and if no
key exists, creating a new array object. So pretty much writing the
dictionary. I think I got the rest of the script just not understanding the
dictionary portion. I would appreciate any help/advice.

Here is part of my script where I tried to create a dictionary

rhinoLocalDictionary = {}

def rhinoName(Rhino, Lat, Lon, dictionary):
if rhinoName in dictionary:
dictionary[rhinoName].append([Lat, Lon])
else:
dictionary[rhinoName]= ([Lat, Lon])


You define the function "rhinoName" with the parameter "Rhino" but 
inside the function you use "rhinoName" which is the function's name.


You want to build a list of lists for each dictionary-value. But then 
you need to start the list with a nested-list in the else-branch. 
Otherwise your list will start with two elements followed by 
two-elements lists:


>>> d = {}
>>> d[1] = [1, 2]
>>> d[1].append([3, 4])
>>> d[1]
[1, 2, [3, 4]] # That's not what you want
>>> d[2] = [[1, 2]]
>>> d[2].append([3, 4])
>>> d[2]
[[1, 2], [3, 4]]   # Better

But assuming that your lat/lon-values don't change I would suggest using 
tuples.


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


Re: [Tutor] Multiplater gaming

2011-11-28 Thread Andreas Perstinger

On 2011-11-28 13:22, surya k wrote:

I am building a multiplayer game (Game:Bingo) where friends(players)
connect over internet. In this particular game, users sends a
"character/ number" to all other players..

Can you please shed some light on it. I've been looking into 'Core
Python Programming' book by Chun but I couldn't understand clearly.


What are your specific problems? We can't help you if you don't give us 
more information about your program. Show us the problematic parts of 
your code.



So, If possible, please provide links to related free e-books /
tutorials.


Some tutorials (IIRC you have already programming experiences, haven't 
you?):

http://wiki.python.org/moin/BeginnersGuide/Programmers


my another question is.. do I need to setup any external hardware
infrastructure to get this done ??


I'm not a hardware expert, but if you want to create an online game 
you'll need at least some kind of server which probably has to be online 
24/7 and is able to handle the traffic.


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


Re: [Tutor] plotting in python

2011-12-01 Thread Andreas Perstinger

[Please don't top-post. Put your answers below the text you cite.]

On 2011-12-01 09:01, stm atoc wrote:

The output of the print len(Conc[0]), len(z) is 100 3600.
Now I changed Conc[0] to Conc[1], and the output is: 100 100


So, you've changed the line

print len(Conc[0]), len(z)

to

print len(Conc[1]), len(z)

and the only thing that changed in the output is the length of "z" which 
is calculated independently of "Conc" in your script?


This would be very strange.

Does your script run if you use "Conc[1]" (or some other indexes) 
instead of "Conc[0]" when you call the "plot"-function?
If yes, it's very likely that you have the "wrong" data in "Conc[0]". 
But that's impossible to tell without your data file ("ourtest_out.list").


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


Re: [Tutor] plotting in python

2011-12-01 Thread Andreas Perstinger

[Still top-posting :-( ]

On 2011-12-01 11:13, stm atoc wrote:

Well, I did also change the line in the python script to this:

plot(Conc[0],z,'r-',label='initial')
plot(Conc[1],z,'b-',label='after 20s')

to see both Conc[0] and [1].


And did it work?


I will send the output data attaches to this email  ("ourtest_out.list").

I wonder if this way is fine.


I'm not sure about the policy regarding attachements on this list but I 
think it would have been better to provide a link than attach it.


Anyways, I've reduced your original script, did a test run and it works 
as expected (at least it shows a plot):


import numpy
import matplotlib.pyplot as pyplot

with open("ourtest_out.list", "r") as f:
z = numpy.array([float(v) for v in f.readline().split()[1:]])

a = numpy.loadtxt("ourtest_out.list", skiprows=3)
N = 100
Conc = a[1:, N+1:]

print len(Conc[0]) == len(z)

pyplot.figure()
pyplot.plot(Conc[0], z)
pyplot.show()

Do you still get an error?

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


Re: [Tutor] New plot over the old graph

2011-12-01 Thread Andreas Perstinger

On 2011-12-01 14:30, stm atoc wrote:

With your help, I have a good script from the previous discussion:

**
from pylab import *


Have you used MATLAB before and are used to its syntax? In general "star 
imports" (from xxx import *) are a bad practice and IMHO should be avoided.



import numpy
import matplotlib.pyplot as pyplot
import matplotlib.mlab as mlab


These imports are unnecessary if you use the first line because "pylab" 
imports everything from "numpy" and "matplotlib" into a single 
namespace. So either use just the first line (not recommended) or the 
following line (recommended).


See also
http://matplotlib.sourceforge.net/faq/usage_faq.html#matplotlib-pylab-and-pyplot-how-are-they-related
and
http://matplotlib.sourceforge.net/faq/usage_faq.html#coding-styles

BTW: Why do you import "mlab" when you don't use it?


with open("ourtest_out.list", "r") as f:
z = numpy.array([float(v) for v in f.readline().split()[1:]])

a = numpy.loadtxt("ourtest_out.list", skiprows=3)
N = 100
Conc = a[0:, N+1:]
print len(Conc[0]) == len(z)


This line was just for testing. You can delete it without any consequences.



figure()

pyplot.plot(Conc[0],z,'r-',label='initial')
pyplot.plot(Conc[1],z,'b-',label='after 20s')

show()


Isn't that what you want? You are plotting all your data in one graph. 
There is a straight red line on the left side and a falling blue line 
from left to right.



*

I have tried to make subplot for this case as follows:

pyplot.subplot(111)
pyplot.plot(Conc[0],z,'r-',label='initial')
pyplot.plot(Conc[1],z,'b-',label='after 20s')


Here you are creating a subplot with 1 plot each row and 1 plot each 
column, in other words you do the same as above (creating just 1 plot). 
If you want to have for example 4 plots in the same window with 2 each 
row and 2 each column you have to use


pyplot.subplot(221)

After plotting all the data in this first "axes" you have to switch to 
the next one:


pyplot.subplot(222)

Have you already read the matplotlib-tutorial:
http://matplotlib.sourceforge.net/users/pyplot_tutorial.html


However, I am not sure how to add new data over this to make a graph
including both new and old data simultaneously.


As I've said before: You are already plotting all data in one graph.
Don't you get two different lines?

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


Re: [Tutor] New plot over the old graph

2011-12-01 Thread Andreas Perstinger

On 2011-12-01 19:20, stm atoc wrote:

Thanks for all information/websites and advice. Yes the graph is
exactly like the one you mentioned. Also, I would like to have them in
one not two, but I think since the dimension of the x and y are not
same, I have no choice.

  What I like to do now is comparing 2 (later 3 or more) different sets
of data, e.g. comparison among Conc[1] with sets

I have changed the script like this:

with open("ourtest_out.list", "r") as f:
z = numpy.array([float(v) for v in f.readline().split()[1:]])

a1 = numpy.loadtxt("ourtest_out1.list", skiprows=3)
a2 = numpy.loadtxt("ourtest_out2.list", skiprows=3)
a3 = numpy.loadtxt("ourtest_out3.list", skiprows=3)

N = 100

Conc1 = a1[0:, N+1:] #base case
Conc2 = a2[0:, N+1:] # Ydw=0.1
Conc3 = a3[0:, N+1:] # nuh=0.01
lw = 2.0 #linewidth


You aren't using "lw" so it doesn't make sense to define it.


dpi = 96
figure(figsize=(10,6),dpi=dpi)


I prefer to not clutter up the namespace with "star imports" (from 
pylabs import *) but it's your choice.




pyplot.subplot(111)


If you just use one graph/figure this call is unnecessary.


pyplot.plot(Conc1[1], z)
pyplot.plot(Conc2[1], z)
pyplot.plot(Conc3[1], z)
pyplot.xlim(0,1)

plt.xlabel('Conc')
plt.ylabel('z')


I assume you've got these lines from the tutorial. But there they are 
using the following import:


import matplotlib.pyplot as plt

I've used

import matplotlib.pyplot as pyplot

so you have to decide which name you want to use (You can't mix both).

In general, if you just use

import matplotlib.pyplot

you would have to use always the full name:

matplotlib.pyplot.xlabel('Conc')

But with the "as"-keyword you can choose, which name gets imported into 
the namespace.


If you have problems understanding imports and namespaces look at Alan's 
tutorial:
http://www.freenetpages.co.uk/hp/alan.gauld/tutfunc.htm (section "Using 
Modules")

http://www.freenetpages.co.uk/hp/alan.gauld/tutname.htm (about Namespaces)



pyplot.grid(True)
show()
savefig('Conc.png')


You should call "savefig" before "show" because in non-interactive mode 
(calling the script from the commandline) "show" will block all figures 
until they are closed. So after "show" there won't be any figures left 
and "savefig" will write an empty figure to the file.



close()

This can give me the comparison in one graph, I suppose.
Now, first I like to know if this is a fine/logical script. otherwise
I would like to know about probably a better way to write it with less
lines!


You could write the whole script in a more object-oriented style where 
you create a figure-instance and then set the attributes you want 
instead of calling all the functions. But for the beginning it's ok.



and second, when I do plot, each grid between x or y axis, has a
thickness of 0.2. what I like do is to change it to 0.1 grid . So, I
couldn't find it through matplotlib website (at least with my
searching. Would it be possible helping me about?


You set the scale with the "xticks"-function (or the corresponding 
"yticks"):

http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks

So in your case you could use

pyplot.xticks(numpy.arange(0, 1.1, 0.1))

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


Re: [Tutor] Need help adding a funcation

2011-12-02 Thread Andreas Perstinger

On 2011-12-02 08:22, Michael Hall wrote:

I am still not understanding what it is I am being asked to do.


Ok, forget about your working program and just concentrate on question 1a):

> # a) write a function, getDivisors(), that returns a list of all
> # of the positive divisors of a given number. for example -
> # result = getDivisors(24)
> # print(result)
> # would yield: "[ 1, 2, 3, 4, 6, 8, 12]"

I suppose you know how functions and lists works, do you?
You have to write a function named "getDivisors" which takes one 
argument (a number) and returns a list. Nothing more, nothing less.


You started right with the line

def getDivisors(num):

but in all your attempts you have never returned a value. Do you know 
how a function can return something?


In your case you have to return a list. Therefore you have to build this 
list inside the function. You don't need to print the values or 
calculate a sum, just add every divisor to the list. I'm sure you have 
learned already how lists works, haven't you?


If you have problems understanding functions and lists, you should 
re-read these parts in your learning material or in the online tutorial:

http://docs.python.org/py3k/tutorial/introduction.html#lists
http://docs.python.org/py3k/tutorial/controlflow.html#defining-functions
http://docs.python.org/py3k/tutorial/datastructures.html#more-on-lists


I am asking if you are given the following question how would you
write the program.


Sorry, we won't write the program for you. You have to do it yourself. 
We will just try to give you some hints - if you carefully read the 
links I've mentioned you'll find an example which comes close to yours :-).


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


Re: [Tutor] Generating dynamic output

2011-12-02 Thread Andreas Perstinger

On 2011-12-02 00:30, Charles Karl Becker wrote:

So the main thing I'm looking for are pointers on how I could
optimize/refactor this, and any resources on this and how to 'think'
more in the right way for this type of thing.  Also, please let me
know what's good about it :P

def build_line(part):
 ''' dynamically builds and returns the static lines for use in the board 
'''
 line = [part for x in range(board_size)]
 line = ''.join(line)
 line = line[:-1]
 return line

# defines the board size
board_size = 5

# these pieces are used in creating the two static lines
part1 = '   |'
part2 = '---|'

# this creates a list of the line #s which will be dynamic (if 0 is the first)
dynamic_list = [x for x in range(board_size)[1:board_size*board_size:4]]


I don't understand what you want to do with "dynamic_list". You are not 
using it and if you need a range from 1 to board_size with step 4 just 
use the range-function:


dynamic_list = range(1, board_size, 4)

But I've still no clue why you need this list.


# generates the array used for controlling the board spaces/taken locations
master = [[str(x+1), 0] for x in range(board_size**2)]


I guess "master" is later used to save the content of each board cell, 
right? But why do you store the cell-number as a string? And what is the 
second value (0)?

Wouldn't it be easier to have a structure like

master = ["xxo",
  " xo",
  "xoo"]

because then you can easily index every cell with

master[row][col]

?


# this section builds the two static lines
line1 = build_line(part1)
line2 = build_line(part2)


As Alan has already mentioned you can build the two lines without using 
an extra function. For example "line1" becomes


line1 = "   |" * (board_size - 1)



# these are used for loop/flow control
b = 0 # this is used to tell which line needs to be printed
c = 0 # this controls the slicing to tell the board where to start 'temp_row'
# this generates the board on the fly
for row in range(board_size*4-1):
 if(b == 0 or b == 2):
 print(line1)
 elif(b == 3):
 print(line2)
 elif(b == 1):
 # since these rows are dynamic they are called 'temp_row'
 # and are reset each time a new one is made
 temp_row = ''
 for cell in master[c:c+board_size]:
 if(int(cell[0])>= 100):
 temp_row += '{0}|'.format(cell[0])
 if(int(cell[0])>= 10):
 temp_row += '{0} |'.format(cell[0])
 else:
 temp_row += ' {0} |'.format(cell[0])
 c += board_size # this is how this variable determines where
to start next time
 temp_row = temp_row[:-1] # need to get rid of extra '|' at end of line
 print(temp_row)
 # this is just some loop/flow control
 b += 1
 if(b == 4):
 b = 0


You can easily simplify your main drawing part:

for row in board_size:
content_line = master[row] # You have to build the line here
print(line1)
print(content_line)
print(line1)
if row < (board_size - 1): print(line2)

So no need for "b" and "c" and and all the if-checks.

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


Re: [Tutor] creating a pie chart in Python

2011-12-07 Thread Andreas Perstinger

On 2011-12-07 19:31, Christopher Spears wrote:

I do need to be able to save the chart as an image file, so it can be
linked to the wiki.  My only complaint about matplotlib is that I
have not figured out a way to save a graph as an image using a python
script.


You can save a graph with "matplotlib.plot.savefig()":

Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plot
>>> fig = plot.figure(figsize=(8,8))
>>> ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
>>> pie_chart = ax.pie([10, 20, 30, 40])
>>> fig.savefig("piechart.png")

More about "savefig()" in the documentation:
http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.savefig

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


Re: [Tutor] What style do you call Python programming?

2011-12-10 Thread Andreas Perstinger

On 2011-12-09 20:46, Alan Gauld wrote:

On 09/12/11 19:24, Alan Gauld wrote:


 In February 1991, after just over a year of development, I decided to
 post to USENET. The rest is in the Misc/HISTORY file.

 =

 Hopefully that clarifies rather than condfusing! :-)
 The HISTORY file gives more detail still.


Hmm, I just went to check the HISTORY file and I can't find it.
It used to come with the source tarball, but I haven't downloaded
the source for years!...


http://hg.python.org/cpython/file/e37a7dc8944e/Misc/HISTORY


Where has the online source code repository gone?


http://hg.python.org/cpython/branches

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


Re: [Tutor] What style do you call Python programming?

2011-12-10 Thread Andreas Perstinger

On 2011-12-10 18:12, Alan Gauld wrote:

On 10/12/11 16:29, Andreas Perstinger wrote:


 Hmm, I just went to check the HISTORY file and I can't find it.
 It used to come with the source tarball, but I haven't downloaded
 the source for years!...


 http://hg.python.org/cpython/file/e37a7dc8944e/Misc/HISTORY



Thanks Andreas. Now, how was I supposed to find that? Is it linked in
any way from the main Python.org website? I couldn't find it (or the
code) anywhere.



On www.python.org there is on the left sidebar a link to the "Core 
Development". This gets you to the "Developer's Guide" where you'll find 
in the QuickStart-Section the link to the Mercurial-Repository.


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


Re: [Tutor] TypeError in class destructor

2011-12-10 Thread Andreas Perstinger

On 2011-12-10 20:22, Walter Prins wrote:

Is the example wrong, or is this something to do with how Windows
handles stdout that is causing this not to work as designed?  I am
using Python 3.2 on Windows Vista Home Premium.


It seems the example may be wrong -- the __exit__ method, as stated
by the error, is being given 4 parameters whereas the one defined in
the code only expects one.  I've looked an this is correct on Python
3.2 that I have on Windows as well.   Perhaps the implementation of
__exit__ has been changed somewhere and had the paramters added and
the book is just out of date?  In any case, changing the def
__exit__ line to:

def __exit__(self, type, value, traceback):

... will fix the problem.


Perhaps a typo in the book, because the online-version 
(http://www.diveintopython3.net/examples/stdout.py) works:


def __exit__(self, *args):
sys.stdout = self.out_old

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


Re: [Tutor] something relevant to array

2011-12-23 Thread Andreas Perstinger

On 2011-12-23 12:02, lina wrote:

 for i in range(len(result)):
 for j in range(len(result[i])):
 print(result[i][j])

still have a little problem about print out,

I wish to get like
a a
b b
c c
which will show in the same line,

not as
a
b
c
a
b
c


So you wish to print all the first elements from your sublists on the 
first line, all the second elements on the second line, and so on, right?


Python 3.2 (r32:88445, Mar 25 2011, 19:28:28)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> result = [["a1", "b1", "c1"],["a2", "b2", "c2"],["a3", "b3", "c3"]]
>>> for i in zip(*result):
...   print(" ".join(i))
...
a1 a2 a3
b1 b2 b3
c1 c2 c3

Explanation:
"zip()" takes an arbitrary number of iterables and "returns an iterator 
of tuples, where the i-th tuple contains the i-th element from each of 
the argument sequences or iterables." (see the docs on 
http://docs.python.org/py3k/library/functions.html#zip):


>>> print(list(zip([1, 2, 3], [4, 5, 6])))
[(1, 4), (2, 5), (3, 6)]

In your case, you would have to call "zip()" with

zip(result[0], result[1], result[2], ... result[x])

depending on how many files you process.

But using the *-operator you can unpack "result" (which is a list of 
sublists), so that "zip" will see all the sublists as separate 
arguments. See also 
http://docs.python.org/py3k/tutorial/controlflow.html#unpacking-argument-lists 



For printing you just join all the elements of one tuple to a string.

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


Re: [Tutor] general basic question

2012-02-09 Thread Andreas Perstinger
On Wed, 8 Feb 2012 23:54:58 -0800 (PST) ken brockman
 wrote:
> I'm back on the list again, and if not too late, here is the asked
> for trace. i've managed to replicate the original error msg, by
> removing the pickled file Genfacts.p, from the directory.
> Traceback (most recent call last):
> File "/home/bob/Ninja/ArtyNOW2.py", line 120, in  Ginfo =
> General_info() 
> File "/home/bob/Ninja/ArtyNOW2.py", line 69, in General_info file4 =
> open("Genfacts.p", "rb") 
> IOError: [Errno 2] No such file or directory: 'Genfacts.p'

Because you have deleted "Genfacts.p" you are trying to open an
non-existing file. So check if the file exists before opening it.

Bye, Andreas

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


Re: [Tutor] Same code has different result

2012-02-12 Thread Andreas Perstinger
On Sun, 12 Feb 2012 21:31:57 +0800
daedae11  wrote:

> The code is:
> from nntplib import NNTP
> s = NNTP('news.gmane.org')
> resp, count, first, last, name = s.group
> ('gmane.comp.python.committers') print 'Group', name, 'has', count,
> 'articles, range', first, 'to', last resp, subs = s.xhdr('subject',
> first + '-' + last) for id, sub in subs[-10:]:
> print id, sub
> s.quit()
> 
> When I write it into a script, it can execute normally. However, when
> I input it in interpreter line by line, I got the follow error when I
> execute the third sentence. What's the matter?

It seems that the connection is closed if you need more than about 6-7 seconds 
(on my computer) to type the third line.

>From the source of "nntplib.py":

def getline(self):
"""Internal: return one line from the server, stripping CRLF.
Raise EOFError if the connection is closed."""

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


Re: [Tutor] Same code has different result

2012-02-12 Thread Andreas Perstinger
[You've forgot to include the list in your reply]

On Mon, 13 Feb 2012 00:04:54 +0800 daedae11  wrote:

> Sorry, I'm not sure I know your viewpoint. Could you give me a
> detailed explanation about "you need more than about 6-7 seconds (on
> my computer) to type the third line."? Thank you very much.

The comment in "nntplib.py" says that if the connection is closed, an 
"EOFError" will be raised (that's the error you get).

In the interpreter you type in first the line "s = NNTP('news.gmane.org')" 
which opens the connection. Then you type in the "s.group"-line which is rather 
long and you are probably not typing fast enough. Meanwhile the connection to 
the gmane-Server is closed and that's why you get the "EOFError".

In your script there is no problem because there is no delay between those two 
lines.

Try to copy the lines of your script into your interpreter shell and you 
shouldn't get the error (don't type them manually, use copy & paste!).

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


Re: [Tutor] help writing functions

2012-02-22 Thread Andreas Perstinger

On 2012-02-23 01:59, Saad Javed wrote:

I am learning python and need guidance for writing some code. I've written
a simple program (with pointers from people) that parses an tv show xml
feed and prints their values in plain text after performing some string
operations.

[CODE]feed = urllib.urlopen(rssPage) #rssPage: address of xml feed

  ^^

[snip]


Running this code returns [B]None[/B].

^^^

This is not a web forum, so please post only in plain text.

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


Re: [Tutor] Re.findall()

2012-04-12 Thread Andreas Perstinger
On Thu, 12 Apr 2012 09:06:53 -0700 
Michael Lewis  wrote:

> Here's the "pattern" portion that I don't understand:
> 
> re.findall("[^A-Z]+[A-Z]{3}([a-z])[A-Z]{3}[^A-Z]+"
> 

You have 5 different parts here:
1) [^A-Z]+ - this matches one or more non-uppercase characters.
The brackets [] describe a set of wanted characters. A-Z would match
any uppercase character, but the caret ^ at the first position inside
the brackets means to inverse the set (i.e., match any character
not in the set). + means to match at least one of the character(s)
described before.
2) [A-Z]{3} - this matches exactly three uppercase characters.
With the braces {} you can define how many characters should match: {3}
matches exactly 3, {3,} matches at least 3, {,3} matches up to three
and {3,6} matches 3 to 6.
3) ([a-z]) - this matches exactly one lowercase character.
The parens () are used to save the character for later use. (using the
group()/groups()-methods, see the docs).
4) [A-Z]{3} - again matches exactly three uppercase characters.
5) [^A-Z]+ - again matches at least one non-uppercase character.

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


Re: [Tutor] Problem with mechanize and forms

2012-04-15 Thread Andreas Perstinger

On 2012-04-14 17:46, Karim Gorjux wrote:

But I can't get any of these forms! I need the first form so I tried

br.select_form(nr=0)

but I get None!


With "br.select_form()" you set the current form which is accessible 
through the "br.form" attribute. The method itself doesnt't return 
anything and thus you get "None" if you do "print br.select_form(nr=0)".


For further processing you have to work with "br.form" and its methods. 
See also help(br.select_form) and help(br.form).


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


Re: [Tutor] RuntimeError: maximum recursion depth exceeded

2012-04-19 Thread Andreas Perstinger

On 2012-04-19 21:51, James Stauble wrote:

I have seen in a few places where this means my program is essentially in an
endless loop, but as far as I can see it is formatted correctly. Any help would
be greatly appreciated. Thanks in advance.


[snip]


#This function gets the tip which will be added to the meal
def getTip(mealPrice):
  tipPercent = getTip(mealPrice)


As soon as you enter "getTip()" you immediately call it again and again 
and again ... without a chance to break out of this endless loop.


As far as I can tell from your code snippet you don't need the line

tipPercent = getTip(mealPrice)

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


Re: [Tutor] Datetime Integer Array

2012-05-22 Thread Andreas Perstinger
On Mon, 21 May 2012 13:04:26 -0700 
Jeremy Traurig  wrote:
> I have already tried creating a numpy array of integers using this
> code:
> 
> import time
> time_format = %m/%d/%Y %H:%M:%S
> for x in range(len(datetime_IN)):
> junk = time.strptime(datetime[x],time_format)
> junk2 = [y for y in junk]
> 
> The above code works in general

No, this code doesn't work at all because there are two errors in it
(syntax error in line 2 and name error in line 4). So in the future
please copy&paste your code and don't retype it.

> the same number of rows as datetime_IN, and I understand it doesn't
> because the previous data in junk2 is lost. I'd like to build the
> junk2 array but I'm not sure how.

Currently, as you've noticed, you overwrite junk2 with each iteration.
You need to append junk2 (which represents one row) to an array:

import time
time_format = "%m/%d/%Y %H:%M:%S"
datetime_IN = ['03/10/2010 02:00:00', 
   '03/10/2010 02:10:00',
   '03/10/2010 02:20:00', 
   '03/10/2010 02:30:00']
datetime_NEW = []
for d in datetime_IN:
junk = time.strptime(d, time_format)
junk2 = [y for y in junk]
datetime_NEW.append(junk2)

You will notice that there is more information than you want in each
row and the items are not in the order you've specified. So you
probably want to construct each row manually in the order you need:

datetime_NEW = []
for d in datetime_IN:
d = time.strptime(d, time_format)
datetime_NEW.append([d.tm_mon, d.tm_mday, d.tm_year,
 d.tm_hour, d.tm_min, d.tm_sec])

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


Re: [Tutor] Issue with classes

2012-06-12 Thread Andreas Perstinger
On Tue, 12 Jun 2012 09:07:13 +0100 
Bod Soutar  wrote:

> C:\>python cheatsheet.py --list
> done
> here?
> Traceback (most recent call last):
>   File "cheatsheet.py", line 167, in 
> main()
>   File "cheatsheet.py", line 165, in main
> ca.parseArgs()
>   File "cheatsheet.py", line 39, in parseArgs
> self.argList()
>   File "cheatsheet.py", line 96, in argList
> handle = cf.load()
> NameError: global name 'cf' is not defined

You define "cf" only inside your "main" function, so the "cliArgs"
class doesn't know about it. So either make "cf" global (bad) or change
your "cliArgs" class so that it takes a "cheatFile" object as an
argument and you would call it like:

ca = cliArgs(cf)

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


Re: [Tutor] joining selected items in list

2012-06-24 Thread Andreas Perstinger
On Sun, 24 Jun 2012 18:11:10 +0200 
David  wrote:

> I have a list that I wish to reorganise into fewer list items.
> What happens is that some of the items belong together:
> not ['keine', 'Antwort'] but ['Keine Antwort'].
> 
> I am not aware of any list methods that can help me here, and would
> thus be grateful for a hint or two.

If you know the indeces of the items which belong together, you could
do for example:

l = [['Intervall-', 'Anzahl', 'Rufzeit', 'Rufzeit', 'Rufzeit',
  'Rufzeit', '>', 'Mittlere', 'Anzahl', 'Unzul\xe4ssiger',
  '\xdcberlauf', 'Zielanschlu\xdf', 'keine', 'Antwort', 'nicht',
  'aktiv', 'Ung \xfcltiger', 'REST', '(andere']]
indices = [5, 12, 14, 17]

for index in reversed(indices):
l[0][index] = " ".join([l[0][index], l[0].pop(index + 1)])

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


Re: [Tutor] subprocess.Popen help

2012-08-22 Thread Andreas Perstinger

On 22.08.2012 03:39, Ray Jones wrote:

Does anyone know of a link to a really good tutorial that would help me
with subprocess.Popen? a tutorial that uses really small words and more
examples than explanation? After 15 years of scripting, I'm ashamed to
say that I'm still not all that familiar with input, output, pipes, etc.
much beyond a simple 'ls | ws -l' or  &2>/dev/null scenarios. The
docs for Popen have left me completely boggled, and I'm not seeing much
available on Google search. Any suggestions?


What about this tutorial:
http://jimmyg.org/blog/2009/working-with-python-subprocess.html

or Doug Hellmann's PyMOTW page about subprocess:
http://www.doughellmann.com/PyMOTW/subprocess/index.html

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


Re: [Tutor] using 'and ' and 'or' with integers

2013-01-08 Thread Andreas Perstinger

[Please don't send HTML to this list. Just use plain text]

On 09.01.2013 07:56, ken brockman wrote:

I was looking through some lab material from a computer course
offered at UC Berkeley and came across some examples in the form of
questions on a test about python. 1 and 2 and 3 answer 3 I've goggled
it till i was red in the fingers, but to no avail.. Could someone be
kind enuff to direct me to some docs that explain this??


Language Reference - 6.10 Boolean operations (for Python 3.3; it's 5.10 
for Python 2.7):

http://docs.python.org/3.3/reference/expressions.html#boolean-operations

"The expression x and y first evaluates x; if x is false, its value is 
returned; otherwise, y is evaluated and the resulting value is returned."


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


Re: [Tutor] Question regarding lists and manipulating items in lists.

2013-01-15 Thread Andreas Perstinger

On 16.01.2013 01:23, Scurvy Scott wrote:
> After playing with your example I keep being told that list has no
> attribute int_to_note. I know what the problem is, I just don't know
> how to fix it.
[SNIP]
> So right now my code is:
>
> import mingus.core.notes as notes
  ^
On this line you import your module and give it the name "notes".

> def make_notes(num_notes):
>it = fib()
>notes = []
^

Inside your function "notes" is a list.

>for i in range(num_notes):
>n = next(it) % 12
>notes.append(notes.int_to_note(n))
 ^

Since "notes" is a list inside the function, Python tries to find the 
method "int_to_note" for a list and fails. But I think you want to use 
the function which is defined in your module.


You have to either rename your module reference or your list.

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


Re: [Tutor] Python gmail script for conky

2013-01-19 Thread Andreas Perstinger

On 20.01.2013 00:27, Polo Heysquierdo wrote:

I'm getting the following error on my script for conky.

"Traceback (most recent call last):
   File "/home/troll/.gmail/gmail.py", line 1, in 
 import urllib.request
ImportError: No module named request"


What's your python version?
(Type "python -V" on the command line or "import sys; sys.version" in 
the interpreter)


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


Re: [Tutor] Please Help

2013-03-22 Thread Andreas Perstinger

Please use a meaningful subject.

On 22.03.2013 13:37, Arijit Ukil wrote:

I have the following data points.
data = [1,2,0,9,0,1,4]
I like to store in an array and print the odd-indexed points, i.e. 2, 9,1
(considering index starts at 0)


You can simply slice your list:

>>> data = [1, 2, 0, 9, 0, 1, 4]
>>> number_list = data[1::2]
>>> number_list
[2, 9, 1]

See also
http://docs.python.org/3/library/stdtypes.html#common-sequence-operations

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


Re: [Tutor] TypeError: can't multiply sequence by non-int of type 'float'

2013-04-04 Thread Andreas Perstinger
Sayan Chatterjee  wrote:

>I know this error occurs when one tries to multiply a string with a
>fraction i.e float. In my case , I can't figure out how can a numpy
>floating point array be a string.

The problem is not that the numpy array is a string but that you append
the array to a python list:

>  pv_za=[]
>  pv_za.append(-K*np.sin(K*pv_za_temp))
>  pv_za_temp = []
>  pv_za_temp.append(np.array(pv_za))

Both "pv_za" and "pv_za_temp" are python lists to which you append a
numpy array. But since you delete both lists in each iteration I assume
you want to just assign a new numpy array to both names:

pv_za = -K * np.sin(K * pv_za_temp)
pv_za_temp = pv_za # "pv_za" is already a numpy array

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


Re: [Tutor] Socket Error Handling Syntax

2013-05-28 Thread Andreas Perstinger

On 28.05.2013 19:25, sparkle Plenty wrote:

I need to catch and handle 10057 exceptions when they occur and keep
running.  I know 10057 is a WinError, which is a subset of OSError, I
just can't find the right syntax for it.  I would appreciate some
help on this one.


I have neither Windows nor Python3.3 to test but according to the docs, 
"winerror" is an attribute of the OSError exception ( 
http://docs.python.org/3/library/exceptions.html?highlight=oserror#OSError 
). Thus something like


try:
   # some code
except OSError as e:
   if e.winerror == 10057:
  # do error handling
   else:
  raise # re-raise any other error

should work.

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


Re: [Tutor] Socket Error Handling Syntax

2013-05-28 Thread Andreas Perstinger

On 28.05.2013 21:37, sparkle Plenty wrote:

If I use an if statement, I cannot use continue after I do my error
handling, so I am really trying to use the except errorname: instead of an
if statement.


I think you haven't understood the code snippet I've posted. The 
if-statement is inside the except clause to check the Windows error number.



Therefore, I have to find the correct error name to identify
the 10057 condition to the interpreter,


As Dave told you, the actual traceback will tell you the name of the 
exception.


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


Re: [Tutor] a little loop

2013-05-28 Thread Andreas Perstinger

On 29.05.2013 05:20, Jim Mooney wrote:

On 28 May 2013 19:34, Steven D'Aprano  wrote:

The standard method for assembling a string from a collection

of substrings is to do it in one go, using the join method,


Wow, that means I can do this:   print  ''.join('But this parrot is dead!')


But why do you want to do that?

"join" iterates over the string you gave as an argument and puts the 
empty string in between each character:

'B' + '' + 'u' + '' + 't' + '' + ...

Thus you end up with the same string as you started.

Or did you mean something like:

>>> print '<>'.join('But this parrot is dead!')
B<>u<>t<> <>t<>h<>i<>s<> <>p<>a<>r<>r<>o<>t<> <>i<>s<> <>d<>e<>a<>d<>!

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


Re: [Tutor] Quick Question on String Compare

2013-06-01 Thread Andreas Perstinger

On 01.06.2013 07:47, Sarma Tangirala wrote:

I had a quick question on how string compare works. If did '1001' <= '999'
I get true. I know how the string compare works but I was wondering why it
were so. Why doesn't the string length factor into the comparison?


Because usually you are interested in the lexicographical order when you 
compare strings.
You wouldn't expect "pear" listed before "apple" in an ordinary 
dictionary, would you?



For example, If I compared character-by-character but also found how
different the lengths are, I could avoid a wrong logical answer as in
the example above.


Why is it a "wrong logical answer"?
Neither '1001' nor '999' are numbers but strings.
If you want to compare them like numbers you need to convert them to 
numbers first.


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


Re: [Tutor] regex grouping/capturing

2013-06-13 Thread Andreas Perstinger

On 13.06.2013 17:09, Albert-Jan Roskam wrote:

I have a string of the form "required optional3 optional2 optional1
optional3" ('optional' may be any kind of string, so it's not simply
'optional\d+'.
I would like to use a regex so I can distinguish groups. Desired
outcome: ('required', 'optional3', 'optional2', 'optional1',
'optional3'). Below is  a fragment of the many things I have tried.

[SNIP]

How can I make this work?


If you really want to use a regex:
>>> import re
>>> s = "required optional3 optional2 optional1 optional3"
>>> s2 = "required optional1 optional2 optional3"
>>> pattern = "required|optional1|optional2|optional3"
>>> re.findall(pattern, s)
['required', 'optional3', 'optional2', 'optional1', 'optional3']
>>> re.findall(pattern, s2)
['required', 'optional1', 'optional2', 'optional3']

But why not simply:
>>> s.split()
['required', 'optional3', 'optional2', 'optional1', 'optional3']
>>> s2.split()
['required', 'optional1', 'optional2', 'optional3']

Bye, Andreas

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


Re: [Tutor] regex grouping/capturing

2013-06-14 Thread Andreas Perstinger

On 14.06.2013 10:48, Albert-Jan Roskam wrote:

I am trying to create a pygments  regex lexer.


Well, writing a lexer is a little bit more complex than your original 
example suggested.


> Here's a simplfied example of the 'set' command that I would like to 
> parse.

s = 'set workspace = 6148 header on.'


As I understand it the order of the parts following "set" is arbitrary, 
i. e.

set workspace = 6148 header on.
is equivalent to
set header on workspace = 6148.
correct?

I'm not sure if a single regex can capture this.
But looking at the pygments docs I think you need something along the 
lines of (adapt the token names to your need):


class ExampleLexer(RegexLexer):
tokens = {
'root': [
(r'\s+', Text),
(r'set', Keyword),
(r'workspace|header', Name),
(r'\S+', Text),
]
}

Does this help?

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


Re: [Tutor] Is there a programmatic use for keys() and values()

2013-06-15 Thread Andreas Perstinger
Jim Mooney  wrote:
>When I try to get the keys of a dictionary, such as d.keys(), I get
>the below instead of a plain list, and it's not very usable. How can I
>use the keys from this like it was a list, or is this basically
>useless other than to see the keys or values?

If you really need a list you can use the built-in list() constructor
since the return value of d.keys() is an iterable:

>>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> list(d.keys())
['a', 'c', 'b', 'd']

Notice that the order of the keys is arbitrary.

But usually you just iterate over the keys.

(In Python 2, d.keys() actually returns a list).

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


Re: [Tutor] The Whole Tree

2013-06-16 Thread Andreas Perstinger

On 16.06.2013 19:21, Jim Mooney wrote:

Speaking of which, I put "Python class hierarchy" in Google but just
got a bunch of specific wheeze. What I want is a
list of the whole tree. Is there such, or a way I can generate it?


I'm not sure if that's what you are looking for but the language 
reference describes the standard type hierarchy:

http://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy

Bye, Andreas

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


Re: [Tutor] No module named odbchelper

2013-10-09 Thread Andreas Perstinger

On 09.10.2013 00:37, Alan Gauld wrote:

On 08/10/13 19:33, Rabah Abdallah wrote:

Hi

I am using dive in python book to to learn python programing languege  on  mac
in one of the examples is odbchelper imported but when i start debugging I 
recieved
  ImportError: No module named odbchelper


ODBC is a Microsoft database access protocol.
It may not exist on non Windows systems. From
the path you give below that might be the
problem here.


Actually, Mark Pilgrim, the author of "Dive into Python" introduces a 
module called "odbchelper" in chapter 2:

http://www.diveintopython.net/getting_to_know_python/index.html#odbchelper.divein

Abdallah, you need to make sure that the file "odbchelper.py" is in the 
same directory as the script from which you want to import it.


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


Re: [Tutor] Geometric sequence

2013-10-31 Thread Andreas Perstinger

On 31.10.2013 04:00, bob gailer wrote:

On 10/30/2013 1:08 PM, Peter O'Doherty wrote:

Hi List,

I know a geometric sequence can be produced by:

series = [2**x for x in range(7)]

But I would like to curtail the sequence before the last element
excedes a certain value.

import itertools
series = [2**x for x in itertools.takewhile(lambda x: 2**x<60, range(7))]


If you first produce an infinite geometric series and take only the 
elements up to a certain limit you avoid calculating 2**x twice:


>>> import itertools as it
>>> [x for x in it.takewhile(lambda x: x < 60, (2**x for x in 
it.count(0)))]

>>> [1, 2, 4, 8, 16, 32]

Bye, Andreas

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


Re: [Tutor] Not sure what I'm doing wrong with these 2 python scripts

2013-11-20 Thread Andreas Perstinger
Anton Gilb  wrote:

>Not sure what I'm doing wrong, here are the problems and what I have
>for answers so far.

You should tell us what's wrong with your solutions.

Do you get an error? Then please show us the complete traceback (error
message).

Does your code something else than you expect? Then show us what you
do, what you get and how/why it differs from the expected solution.

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


Re: [Tutor] Nested for loops

2013-11-27 Thread Andreas Perstinger
Rafael Knuth  wrote:
>I am trying to figure out how exactly variables in nested loops are
>generated, and don't get it 100% right yet. Here's my code:

Maybe it's easier if you look at a simpler example like:

for i in range(4):
for j in range(4):
print("i: {}, j: {}".format(i, j))

Do you understand how that works?

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


Re: [Tutor] Prime Numbers

2013-12-16 Thread Andreas Perstinger

On 16.12.2013 09:49, Rafael Knuth wrote:

That's the tiny little detail I am confused about: What does return
exactly do? Does it return only the first value within a loop or does
it iterate through all values within a loop? (unless a given condition
is met)


The return statement has nothing to do with loops. Whenever the Python 
interpreter gets to a return statement during the program execution it 
will immediately leave the current function and return to the caller.


"return" outside of a function doesn't work:

>>> for i in range(10):
...   return i
...
  File "", line 2
SyntaxError: 'return' outside function

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


Re: [Tutor] arrangement of datafile

2013-12-27 Thread Andreas Perstinger
[Please don't top-post and trim the quoted message to the essential.
See http://www.catb.org/~esr/jargon/html/T/top-post.html ]

Amrita Kumari  wrote:
>My data file is something like this:
>
[SNIP]
>can you suggest me how to produce nested dicts like this:
[SNIP]

What's the current version of your program? Did you fix the
problem Dave told you?

Don't expect that we will write the program for you. Show us what you
have tried and where you are stuck and we will help you move on. And
always include the full traceback (error message) you get when you run
the program.

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


Re: [Tutor] for: how to skip items

2014-02-17 Thread Andreas Perstinger
Gabriele Brambilla  wrote:
>it's because my problem is not so simple:
>imagine that in a100 contains not integer sorted in a good way but a
>random float numbers.
>How could I display only one item every 10?

You can provide a step size if you slice a list:

>>> l = list(range(10))
>>> l[0:10:2]
[0, 2, 4, 6, 8]
>>> l[0:10:5]
[0, 5]

Is that what you want?

Bye, Andreas

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