[Tutor] Re: Printing two elements in a list

2004-12-19 Thread C Smith
Jacob S. wrote:
Would this work for you?
a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA']
for index,thing in enumerate(a):
if "Name=" in thing:
del a[index]
I know, that it might be slow, but I thought that maybe it would hold 
its
own because it doesn't have to import the re module, everything's 
builtin,
etc.

Be careful here, the above code will miss deleting an element 
containing "Name=" if there are two in a row.  Look at this simple 
example where we attempt to delete elements equal to 2:

###
>>> a=[1,2,1,2]
>>> for i,x in enumerate(a):
..  if x==2:del a[i]
..
>>> a
[1, 1]
>>> #
>>> # ok that looks right, but watch this
>>> #
>>> b=[2,2,1,1]
>>> for i,x in enumerate(b):
..   if x==2: del b[i]
..
>>> b
[2, 1, 1]
###
After deleting element 0 in b, all the elements "slid down" one place 
and the 2nd 2 that was in b is now in position 0...but you are moving 
on to index 1 with the enumerate loop:

[2, 2, 1, 1]
 ^
 enumerate is at index 0
we delete element 0
[2, 1, 1]
^
enumerate is at index 1 and the 2 that was at position 1 is now at 
position 0

An alternative is to use a list comprehension, keeping only the 
elements that are not 2. As is shown, you can replace the list you are 
filtering with the filtered result:

###
>>> b=[2,2,1,1]
>>> b=[x for x in b if not(x==2)]
>>> b
[1, 1]
###
/c
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] working with new classes

2005-03-08 Thread C Smith
Hello,
After learning about the new class behavior, I am trying to implement a 
circular type list where, for example, you can compare the nth value to 
the "(n+1)th" value without worrying about going past the end of the 
list. (An old approach might be to create a function that converts a 
given index to the real index (e.g. maps the "(n+1)th" value back to 
the 1st value), but I thought I would try subclassing the list 
behavior.)

Seeing an ASPN entry on circular lists 
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52246), I 
first tried to define a "turn" method for the list.  The following works

###
class ring(list):
def turn(self, incr=1):
tail=self[incr:]
head = self[:incr]
self[:] = tail+head
l=ring(range(10))
l.turn(5) #the list now has a turn method
print l   #--> [5, 6, 7, 8, 9, 0, 1, 2, 3, 4]
###
Then I tried to redefine how the list is initialized, desiring to give 
it a "zero" attribute which will be used whenever an item from the list 
is requested. I'm hoping not to have work with slices of the list--I 
just change how it is accessed.  BUT...it doesn't work. Apparently 
__getitem__ is not accessed in order to print the list; and Python 
crashes when I try to print a single element.

Am I trying to subclass the wrong aspects of the list?
###
class Ring(list):
def __init__(self, l):
self[:] = l
self._zero = 0

def turn(self, incr=1):
self._zero+=incr
def __getitem__(self, i):
return self[(i-self._zero)%len(self)]
l=Ring(range(10))
print l
l.turn(5)
print l#same as original
print l[0] #crashes python
###
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with new classes

2005-03-09 Thread C Smith
Thanks to Sean and Kent for replies.  I found a site that provided some  
good examples, too, at  
http://www.cafepy.com/articles/python_attributes_and_methods/ 
ch03s02.html

Here's a blurb from the title page:
 wep page excerpt
Shalabh Chaturvedi
Copyright © 2004 Shalabh Chaturvedi
This book is part of a series:
Python Types and Objects
Python Attributes and Methods [you are here]

After playing with this for a while I get the feeling that trying to  
create an alternate access for the list is not the way to go.  I was  
able to define the following methods with success...

###
class Ring(list):
def __init__(self,l):
list.__init__(self,l)
self._zero=0
def turn(self,incr=1):
self._zero+=incr
	def __getitem__(self,i):
		if type(i)==int:
			return list.__getitem__(self,(i-self._zero)%len(self))
		else:
			return [list.__getitem__(self,(k-self._zero)%len(self)) for k in  
range(i.start,i.stop,i.step)]
			
	def __setitem__(self,i,v):
		list.__setitem__(self,(i-self._zero)%len(self),v)
	
	def __getslice__(self,i,j):
		return  
list.__getslice__(self,(i-self._zero)%len(self),(j- 
self._zero)%len(self))

	def __setslice__(self,i,j,v):
		list.__setslice__(self,(i-self._zero)%len(self),(j- 
self._zero)%len(self),v)

	def __repr__(self):
		return repr([self[i] for i in range(len(self))])
###
..but then something like pop(3) pops the original element not the  
element in the 3rd position of the turned list:

###
>>> l=Ring(range(10))
>>> l.turn(5)
>>> print l
[5, 6, 7, 8, 9, 0, 1, 2, 3, 4]
>>> l.pop(3); print l
[5, 6, 7, 8, 9, 0, 1, 2, 4] #I wanted the 8 to go
###
So in the absence of being able to redefine in the class the way that  
indices should be computed (like the way that your own cmp function can  
be supplied for the sort method) it seems best to use the existing  
structure and either access the list by passing it indices which have  
been remapped:

###
>>> def ring_index(i):
return (i-ring_zero)%ring_length
>>> l = range(10)
>>> ring_length = len(l)
>>> ring_zero = 3 #does a virtual shift to the right 3 elements
>>> print l[ring_index(0)]
7
###
But this will only help you look at individual entries and slices that  
don't go across the boundaries of the list.

Alternatively, the list class can be appended with helpers like 'turn'  
and 'segment' which can actually turn the "ring" and remove a piece  
from it without worrying about the endpoint:

###
>>> class ring(list):
def turn(self, incr=1):
incr%=len(self)
self[:] = self[incr:]+self[:incr]
def segment(self, i, length, incr=1):
length=min(len(self),length)
if i+length>len(self):
return 
self[i::incr]+self[(length-i)%incr:i+length-len(self):incr]
>>> l=ring(range(20)); l.turn(3); print l
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2]
>>> >>> l.segment(17,5,3) #start at 17, length of 5, stride 3
[0, 3]
###
This is my first intoduction to the new class modifications...initially  
it seems nice to be able to wrap your methods up into a class like this  
rather than creating dangling functions in one's program.

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


Re: [Tutor] help

2005-03-13 Thread C Smith
On Sunday, Mar 13, 2005, at 05:01 America/Chicago, 
[EMAIL PROTECTED] wrote:

if this is not a program please teach me what is a
program and what i need to know to write them and if this is a program 
teach me
how to write better programs i can use outside of the python shell...
OK, how about this for starters:
http://www.ibiblio.org/obp/thinkCS/python/english/
This is an introductory html text that can act as a teacher for you. 
(There are some other resources at that address, too.)  It is the text 
that I used in an introductory programming class that I taught. As you 
go through this you sill start to learn the answers to your questions.

As to your desire to write programs you can use outside the 
shell...well that will come after you have an idea of what you would 
like to do and learn how to "say it" with a language.  But at this 
point I think your main task will be to learn how to "say things" in 
general.  Python is a nice language to work with in this regard.

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


Re: [Tutor] creating a tab delimited filename

2005-03-15 Thread C Smith
On Tuesday, Mar 15, 2005, at 05:01 America/Chicago, 
[EMAIL PROTECTED] wrote:

how am i going to change the filename automaticaly?
for example:
#every 5 minutes, i am going to create a file based on the 
data above
 for i in range(100)
output_file = file('c:/output' +.join(i) +'.txt', 'w')
#guess this won't work
output_file.writelines(lines)
output_file.close()

When faced with this problem, one of the tings that I liked to do was 
use a date stamp for the files. The time module has a function called 
strftime which allows you to use a template to create a string from the 
current time. (See the documentation of python module 'time' for more 
details.)  e.g.

###
>>> import time
>>> time.strftime('%Y%m%d%H%M')
'200503150934'
###
This string can be added to your 'c:/output' rather than a generic 
number like i. Just to be safe you might want to check that the file 
doesn't already exist. The nice thing is that there should be few files 
that have this number added to them so the loop to get a valid name is 
going to succeed quickly.

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


Re: [Tutor] creating a tab delimited filename

2005-03-16 Thread C Smith
Hi Jacob,
Watch out with your code,
###
if i==1000:
i=0
else:
i=i+1
###
Since this test is done after you have stored your data you are 
actually going to store 1001 pieces of data.
	i starts at 0
	you store 0
	you do your test and i is incremented
	{that's set 1}
	i is 1
	you store 1
	you do your test and i is incremented
	{that's set 2}
	...
	i is 1000
	you store 1000
	you do your test and i is set to 0
	{that's set 10001}

Also, it looks like you have that i-incrementing happening at the same 
level as the if-test. If so, it is possible that the i's that are used 
to store the data will not increase by 1 each time since they are being 
incremented for every k and not only when the data is being stored. If 
you only want it incremented when something is stored, put it inside 
the if-block.  Also, consider using the modulo operator to keep track 
of i: replace your test with

###
i = (i+1)%1000
###
i starts and 0 and will be incremented until it is 999 and then when 
this calculation is then performed you will calculate (999+1)%1000 
which is 1000%1000 which is 0--just what you wanted.  Here's an example 
that cycles through 3 number, 0, 1, and 2:

###
>>> j=0
>>> for i in range(10):
..   print j
..   j = (j+1)%3
..
0
1
2
0
1
2
0
1
2
0
###
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] primes

2005-03-17 Thread C Smith
On Thursday, Mar 17, 2005, at 17:49 America/Chicago, 
[EMAIL PROTECTED] wrote:

On my system, it took 415 seconds to generate a list of primes < 50,000
using range, but only 386 seconds if I use the same code, but with 
xrange instead.


If you only calculate y up to sqrt(x) you will see a dramatic time 
reduction:

###
import math
big=5
[x for x in xrange(2,big) if not [y for y in 
range(2,int(math.sqrt(x)+1)) if x%y==0]]
###

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


Re: [Tutor] Looking for a Pythonic way to pass variable

2005-03-22 Thread C Smith
On Tuesday, Mar 22, 2005, at 05:01 America/Chicago, 
[EMAIL PROTECTED] wrote:

I met a similar question.
what if one has L = [[1,2],[3,4]], K = [100, 200]
How to 'zip' a List like [[1,2,100], [3,4,200]]?
I would do something like:
###
for i in range(len(L)):
  L[i].append(K[i])
###
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] primes - sieve of odds

2005-03-22 Thread C Smith
Hi Gregor,
I had done the same thing.  I also noted that assigning (or inserting) 
an element into a list is faster than creating a new list: 
l.insert(0,2) is faster than l = [2]+l.

###
def sieve (maximum):
 if maximum < 2: return []
 limit = int(maximum**0.5)
 nums = range(1,maximum+1,2)
 nums[0] = None
 for p in nums:
 if p:
 if p > limit: break
 nums[(p*p)//2::p] = [False]*(1+(maximum//p- p)//2)
 nums[0] = 2
 return filter(None, nums)
###
/c
Hi Sean!
Thanks for your measurements.
In the meantime I did another amendment,
leaving out the even numbers from the sieve.
It goes like this:
def sieve(maximum):
 nums = range(3, maximum+1, 2)
 for p in nums:
 if p:
 if p*p > maximum: break
 start = (p*p-2)//2
 nums[start::p] = [False]*(1+((maximum-3)//2-start)//p)
 return [2] + filter(None, nums)
Perhaps not very elegant. But approximately twice as fast as
the former version.

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


Re: [Tutor] primes - sieve of odds

2005-03-23 Thread C Smith
On Wednesday, Mar 23, 2005, at 04:00 America/Chicago, 
[EMAIL PROTECTED] wrote:

Now it would be fine to have an *equally fast*
infinite prime number generator.
Has anybody any suggestions?
I think when you add the condition of it being an infinite generator, 
you are changing the rules and can't end up with something as fast.  
What makes the sieve so fast is that we are generating all the primes 
in a given range using a very simple "strike out" method.  In the 
infinite generator scenario, you will get all the primes up to n with 
the sieve and can yield those back, but at some point you will have to 
stop and get "the next one." To get the next one you will have to pick 
a range in which a next prime is likely to be found. The previous 
primes can be used to clear out this range.

What follows is an attempt based on the previous tutor-evolved sieve 
that extends the range in which to find the next prime by a factor of 2 
over the last known prime. A similar algorithm is on ASPN (I bellieve), 
under

Space-efficient version of sieve of Eratosthenes.
D. Eppstein, May 2004
It's slower than the sieve but about twice as fast as Eppstein's up to 
1,000,000.  I'll leave it to someone else to see when it finally blows 
up :-) The output of primes was checked through 1,000,000 against 
Eppstein's generator without error.

/c
###
def esieve():
'''extended sieve generator that returns primes on each call. When the 
end of the
existing list is reached, more primes are sought in the range that 
extends to
twice the last known prime. The known primes are used to clear out this 
extended
range using the Sieve of Eratosthenes.'''

# get started with primes less than 100; you need at least [2, 3]
primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
i=0
while 1:
yield primes[i]
i+=1
if i==len(primes): #extend range
minn=primes[-1]+2 #this is an odd number
maxx=2*minn+1 #there should be a prime in this range; +1 
makes it odd
sqrt=int(maxx**.5) #don't use primes bigger than this
length = (maxx-minn)//2 #this is used for computing the 
crossing out None values
nums=range(minn,maxx+1,2) #here is the range in which a 
primes will be found
for p in primes:
if p>sqrt:break
j=minn%p #find out where the striking out should start
if j<>0:
j=(p-j) #if evens were present, this is where to 
start, but...
if (minn+j)%2==0:j+=p #if it lands on an even, go 
to the next one
j//=2 #and now account for the fact that evens 
aren't present
nums[j::p]=[None]*(1+(length-j)//p) #cross out 
multiples of p
x=filter(None,nums) #clean up the range
assert len(x)>0 #there should be a prime in here, but check 
anyway
primes.extend(x) #add these to the existing primes and 
continue yielding
###

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


Re: [Tutor] primes - sieve of odds

2005-03-23 Thread C Smith
Now it would be fine to have an *equally fast*
infinite prime number generator.
Has anybody any suggestions?

[cut]
What follows is an attempt based on the previous tutor-evolved sieve 
that extends the range in which to find the next prime by a factor of 
2 over the last known prime. A similar algorithm is on ASPN (I 
bellieve), under

Space-efficient version of sieve of Eratosthenes.
D. Eppstein, May 2004
Oh, please...ignore what I suggested and look at Eppstein's code. It's 
a thing of beauty and just keeps chugging out primes well past what the 
inefficient version that I suggested could do with the same memory. 
It's a "tortoise and hare" race as the memory gets chewed up by the 
esieve approach.

The ASPN version of Eppstein's program is an older one than the one at 
the following site:
http://www.ics.uci.edu/~eppstein/PADS/Eratosthenes.py

Take a look!
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Float precision untrustworthy~~~

2005-03-29 Thread C Smith
On Monday, Mar 28, 2005, at 22:11 America/Chicago, 
[EMAIL PROTECTED] wrote:
[cut]
the mere fact that floats are difficult to check with equality has
bitten me more than anything I've met yet in python.
[cut]
I understand what you are talking about, but I tend toward just making 
it one of the things to remember when working with floats.  (I've been 
bitten a lot when I forget to use '==' instead of '=', too!)

As you say, the problems arise when you try to make comparisons. To get 
around the difficulties with comparisons, I wrote a helper function:

###
Python 2.3 (#2, Jul 30 2003, 11:45:28)
[GCC 3.1 20020420 (prerelease)]
Type "copyright", "credits" or "license" for more information.
MacPython IDE 1.0.1
>>> from math import floor, log10
>>> def Round(x, n=0, sigfigs=False):
	'''An enhanced rounder which rounds to the nth significant digit
	(the nth digit from the first non-zero digit, not the nth decimal 
place)
if the parameter sigfigs is not zero.
This uses "round-up" decisions when the digit following the one of
interest is a 5, i.e. 1.35 and 1.45 Round to 1.4 and 1.5 when 
sigfigs = 2.
	'''
	if x==0: return 0
	if not sigfigs:
		return round(x,n)
	else:
		return round(x,n-1-int(floor(log10(abs(x)
###

And here's a helper that uses it to check for equality of two numbers 
(floats, or otherwise)
to whatever number of digits you desire --starting from the first 
non-zero digit, The default is for high precision.

###
>>> def same(x,y,prec=9):
	"""Return True if x and y are the same after being rounded to the same 
degree of precision."""
	return Round(x,prec,1)==Round(y,prec,1)
..
>>> print same(1.3,1.31,3) #at the 3rd digit these are different
False
>>> print same(1.3,1.31,2) #at the second digit they are (rounded to) 
the same digit number
True
>>> same(64.0**(1/3.0) ,4) #here's your example
True
###

You can be bitten by any comparison, not only tests for equality, too.
###
>>> while 1:
..  i+=.1
..  if i>2.1:break
..
>>> print i
2.1
###
It doesn't look like the last value of i was really greater than 
2.1--it's actually 2.1005 so the result is correct (though 
not what we expected). We don't have the problem with a step size of 
0.7 in this case, though, because the value before 2.8 was 
2.0996--just a little smaller than 2.1.

Here, we specify the precision and get the desired result.
###
>>> i=0
>>> while 1:
..  i+=.1
..  if round(i,9)>round(2.1,9):break
..
>>> print i
2.2
###
[cut]
The last three checks also show that you need to define the places 
argument
to get a good answer. Why not just implement decimal or some 
equivalent and
get rid of hidden, hard to debug headaches?I understand uses of 
floats
where the precision isn't exact anyway -- i.e. sqrt(2)
Wish granted in version 2.4 ;-) I don't have it on the mac, but there 
is a write-up at

http://www.python.org/doc/2.4/whatsnew/node9.html
The starting blurb says:
"Python has always supported floating-point (FP) numbers, based on the 
underlying C double type, as a data type.  However, while most 
programming languages provide a floating-point type, many people (even 
programmers) are unaware that floating-point numbers don't represent 
certain decimal fractions accurately.  The new Decimal type can 
represent these fractions accurately, up to a user-specified precision 
limit.  "

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


[Tutor] Re: If elif not working in comparison

2005-03-29 Thread C Smith
> gerardo arnaez wrote:
>
>> On Mon, 28 Mar 2005 09:27:11 -0500, orbitz 
>> wrote:
>>
>>> Floats are inherintly inprecise.  So if thigns arn't working like 
you
>>> expect don't be surprised if 0.15, 0.12, and 0.1 are closer to the 
same
>>> number than you think.
>>
>>
>>
>> Are you telling me that I cant expect 2 digit preceision?
>
>
> Not without using round. Have *NO* faith in floating points. This is
> especially true when you are creating the decimals via division and 
the
> like.

What makes one nervous when looking at your tests with floating point 
numbers is that calcuations that might lead up to one of the numbers in 
your test might actually be a tiny bit higher or a tiny bit lower than 
you expect.  *However*, I think the thing to keep in mind is that if 
you are only a billionth or less away from the boundary, it really 
doesn't matter which way you go in terms of dosage--you are at the 
border.

Here is an example of two calculations that you think should get you to 
2.1. One is actually just shy of it and the other just a bit past:

###
>>> 3*.7
2.0996
>>> 7*.3
2.1001
###
So if you have the following test to determine if it is time to 
increase someone's dose of medication and the results are based on some 
measurement being greater than 2.1, then...

###
>>> def test(x):
 if x>2.1:
  print 'increase dose'
 else:
  print 'decrease dose'
>>>
###
if you test the above computed values, you will get different results:
###
>>> dose1, dose2 = 3*.7, 7*.3
>>> test(dose1)
decrease dose
>>> test(dose2)
decrease dose
###
OR NOT! Why do they both come out to be the same even though one number 
is bigger than 2.1 and the other not? Because 2.1 is not actually '2.1':

###
>>> 2.1
2.1001
###
The 7*.3 is actually "equal" to 2.1: they both are 2.1001.
On the one hand, we want the boundaries so we can say, "if you are past 
this boundary you take the next sized dose"...but if you are so close 
to the boundary that you can just as well say that you are right on it, 
does it really matter which way you go? Other than bothering the 
deterministic nature, are there other reasons to be concerned? As far 
as economics, the '2,1' case will have people staying at a lower dose 
longer (as would 2.2, 2.6 and 2.7 which all are a tiny bit bigger than 
their mathematical values, just like 2.1).  Just the opposite will 
happen at the 2.3, 2.4, 2.8, and 2.9 since these values are represented 
as numbers smaller than their mathematical counterparts:

###
>>> 2.9
2.8999
###
If you have Python 2.4 you might want to check out the decimal type 
that is now part of the language.  There is a description at

http://www.python.org/doc/2.4/whatsnew/node9.html
which starts with:
"Python has always supported floating-point (FP) numbers, based on the 
underlying C double type, as a data type.  However, while most 
programming languages provide a floating-point type, many people (even 
programmers) are unaware that floating-point numbers don't represent 
certain decimal fractions accurately.  The new Decimal type can 
represent these fractions accurately, up to a user-specified precision 
limit.  "

And it gives the following example:
Once you have Decimal instances, you can perform the usual mathematical 
operations on them.  One limitation: exponentiation requires an integer 
exponent:

>>> import decimal
>>> a = decimal.Decimal('35.72')
>>> b = decimal.Decimal('1.73')
>>> a+b
Decimal("37.45")
>>> a-b
Decimal("33.99")
>>> a*b
Decimal("61.7956")
>>> a/b
Decimal("20.64739884393063583815028902")
Another suggestion is to use the Round replacement that I wrote about 
in response to the "Float precision untrustworthy~~~" thread. With it, 
you don't have to worry about how large or small your numbers are when 
you Round them (unlike with round()). You just decide on how many 
"parts per x" you are interested in with your numbers.  e.g. if your 
calculations are only precise to about 1 part per hundred then you 
would round them to the 2nd (or maybe 3rd) digit and compare them.  
With the separation of code and data as already suggested this would 
look something like this:

###
def Round(x, n=0, sigfigs=False):
if x==0: return 0
if not sigfigs:
return round(x,n)
else:
#round to nth digit counting from first non-zero digit
# e.g. if n=3 and x = 0.002356 the result is 0.00236
return round(x,n-1-int(floor(log10(abs(x)
 ...
 for cutoff, value in cutoffs:
 if Round(x,3) < Round(cutoff,3):
 return value
..
###
IMHO, I don't think that decimal is the way to go with such 
calculations since calculations performed with limited precision 
numbers shouldn't be treated as though they had infinite precision. 
From basic error analysis of the calculated values above, one shouldn't 
probably keep more than 3 digits in a/b result of 
Decimal("20.64739884393063583815028902").  On the 

Re: [Tutor] Math Question

2005-03-29 Thread C Smith
On Tuesday, Mar 22, 2005, at 15:34 America/Chicago, 
[EMAIL PROTECTED] wrote:

When I adjust coumadin doses I normal have to use whole or half pills
of the medicien the patient already has.
Fer Instance, if a pt takes 5mg of coumadin a day, that's 35mg of 
coumadin week
and suppose I do a test that says thye are not taking enough coumadin
and to increase the dose by 10%, ie add another 3.5mg but have it
split evenly over the week or at least every other day.
normall, I would say ok
Take 5mg coumadine everty but on mon and thurs day take 7.5mg
(Note the patient only has 5mg tabs, which they can split to make dose
adjust my 2.5)

My question is,
How would I solve this using math instead of geustimating it.
What kind of math am I talking about here?
I don't know that much about this medication (and I know you just said 
that the patient only has 5 mg pills) but on this page,

http://www.heartpoint.com/coumadin.html
I see that doses come in amounts like 1, 2, 2.5, 5, 7.5, and 10.
With the ability to split pills, you can add 0.5, 1.25 and 3.75 to the 
list of possibilities.

And then I wonder if the "math topic" expands from integer math, as has 
been suggested, to combinatorics which can tell you what combinations 
of pills and half pills that are at your disposal for making dosages.  
There are other factors, however, like keeping the prescription simple 
for patients.  For example, let's say that the patient is not going to 
want to buy more than 2 pill sizes. This will give 4 different dosage 
amounts that one could play with.

Let's say that the patient should never have to take more than 2 pills 
(or pill pieces) each day.  The possible dosages that can be prescribed 
for a given day would be all the pair-wise combinations of the dosages. 
These could be obtained with 2 FOR loops:

###
>>> dosages = [1, 2, 3] #just an example; different from above notes
>>> possible = []
>>> for i,x in enumerate(dosages):
..   for y in dosages[i:]:
.. possible.append((x+y,[x,y]))
..
>>> for pi in possible:
..   print pi
..
(2, [1, 1])
(3, [1, 2])
(4, [1, 3])
(4, [2, 2])
(5, [2, 3])
(6, [3, 3])
>>>
###
Just a thought,
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I am puzzled - help needed

2005-03-31 Thread C Smith
I need to rewrite the high_low.py program (see below) to use the last 
two digits of time at that moment to be the "random number".
Be sure you understand what format the time number has and that you 
understand the problem statement.  Here are two time values:

1112306463.0
1112306463.01
Do you see what is going to happen if you blindly take the last two 
characters of the time in the first case and try to convert it to an 
integer? Are you suppose to take the last two digits of the integer 
portion?

Also, a neat way to get the last 2 digits of a number is to use the 
"remainder/modulus" operator:

###
>>> from time import *
>>> t=int(time())
>>> t
1112306749
>>> t%10 #last 1
9
>>> t%100 #last 2
49
>>> t%1000 #last 3
749
###
Also, note that when you "import *" you no longer need (or can) use the 
"time." prefix for times functions; when you import them that way it is 
as if they are part of your own function set:

###
>>> from time import *
>>> time.time()
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'builtin_function_or_method' object has no attribute 
'time'
###

..you get this error because time's function "time()" is part of your 
programs functions; there is not module "time" for you to interact 
with, only time's functions. So go ahead and just use the function:

###
>>> time()
1112306900.8461709
###
If you import the whole module, though, and try the same thing...
###
>>> import time
>>> time()
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: 'module' object is not callable
###
python knows about the *module* time but you are now treating the 
module like a function. Instead, you should access the function through 
the module's name:

###
>>> time.time()
1112306919.518116
###
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] one line code

2005-04-04 Thread C Smith
From: "Alan Gauld" <[EMAIL PROTECTED]>
With other words I'd like to tell Python: Convert into a float if
possible, otherwise append anyway.
[ (type(x) == type(5) and float(x) or x) for x in mylist ]
This is a perfect opportunity to give the reminder that the conversion 
functions are also types that can be used more transparently for such 
type tests:

###
>>> type(int)

>>> type(1)==int
True
>>> type(1)==float
False
###
If you really want a float and not an int then you should use the 
following 1-liner as suggested by the programming FAQ 1.2.11 ( 
http://www.python.org/doc/faq/programming.html ):

[ (type(x) == int and [float(x)] or [x])[0] for x in mylist]
###
>>> l=['foo', 0]
>>> [(type(x)==int and float(x) or x) for x in l]
['foo', 0]
>>> # notice that 0 is still an int, not a float
>>> [(type(x)==int and [float(x)] or [x])[0] for x in l]
['foo', 0.0]
>>> # ok, that's better
###
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] str.split and quotes

2005-04-06 Thread C Smith

I wish it would leave the stuff in quotes in tact:
If you first split on your delimiter (which must have a matching one) 
you will obtain a list in which every odd position contains a string 
that was quoted. Step through the result and split the ones that are 
not quoted ones but don't do anything to the quoted ones.

###
s='"Hi" there "Python Tutors" please help me'
delim='"'
# check for matching quotes
if s.count(delim)%2<>0:
print 'Unmatched delimiters in string'
assert s.count(delim)%2==0
# split it
s=s.split(delim)
# remove elements 1 at a time, putting result to end of list;
# when you're done, the original list has been destroyed and
# the correct list is in its place
for i in range(len(s)):
si=s.pop(0) #pop off the next one from the list
if i%2==0:
s.extend(si.split())
else:
s.append(si)
print s
###
OUTPUT: ['Hi', 'there', 'Python Tutors', 'please', 'help', 'me']
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] flatten

2005-04-07 Thread C Smith
After posting the suggestion about splitting a string that contained a  
quoted string, I looked back at my (at least I think it’s mine) flatten  
routine and didn’t see anything like it at ASPN. Before I would post it  
there, does anyone see any problems with this non-recursive approach?

I know that there are iterator approaches, but since the list already  
exists is there any problem with flattening the whole thing? Or is part  
of the problem that there may be iterable things that don’t need to be  
completely “iterated to completion” before being able to yield the next  
element? (Does that make sense?)

After searching for "Tim Peters flatten" I was able to find a similar  
routine at

http://sourceforge.net/project/ 
showfiles.php?group_id=87034&package_id=90541&release_id=288585

(It is in the basictypes folder in the latebind.py script by  Mike C.  
Fletcher.) It's so short, I post it for comparison. I'm not really sure  
why there is a run through all possible indices rather than the ones  
that exist in the given "inlist", though.

### Fletcher's
import sys
def flatten(inlist, type=type, ltype=(list,tuple), maxint= sys.maxint):
	"""Flatten out a list, code developed by myself and modified by Tim  
Peters, then by me again :)"""
	try:
		# for every possible index
		for ind in xrange( maxint):
			# while that index currently holds a list
			while isinstance( inlist[ind], ltype):
# expand that list into the index (and subsequent indicies)
inlist[ind:ind+1] = list(inlist[ind])
			#ind = ind+1
	except IndexError:
		pass
	return inlist
###

### mine
def flatten(l):
	’’’Flattens a list in place.’’’
	i=0
	while i
		while hasattr(l[i],“__iter__”): #used by some ASPN flatteners to  
avoid strings
			l[i:i]=l.pop(i)
		i+=1

###
input: [1, 2, [3, 4, 5, [[6, 7], 8]], ’abc’, 9, [10, 11]]
output:[1, 2, 3, 4, 5, 6, 7, 8, ’abc’, 9, 10, 11]
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] str.split and quotes

2005-04-08 Thread C Smith
Tony wrote:

With Python 2.4 I get these results (all imports are factored out,
all givethe same result except for CSV which strips the "s) with
timeit.py:
Just a note here in terms of results.  Although the
results are all the same and they work for the case where there is
single quoted phrase with more than one word in it, the
split_and_rejoin has problems for the case where there is only a single
word in quotes (since the trailing quote that you are assuming is in
another word occurs in the same word and thus is never found). e.g. 'I
said "wow" when I saw the result' will give it problems.
 
The re _expression_ has a problem if there is more than one
quoted string in the string (e.g. 'if "this" and "that" are quoted').
The reason is that the _expression_ is "greedy" and matches the longest
string of characters between quote marks: in '"this" and "that"' the
entire string will be matched rather than the first "this". The fix is
to use the non-greedy pattern:
 
re.compile(r'\".*?\"|[^ ]+')
 
Note the ? after the *
 
/c
 
 

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


Re: [Tutor] Flatten

2005-04-11 Thread C Smith
Sorry for the delay in answering.
Bill Mill wrote:
[cut]
1) you should special-case dictionaries: > >> x = [1, 2, [3, 4, 5, 
[[6, 7], 8]], 'abc', 9, [10, 11], {'test': 12}] > >> flatten(x) > >> x 
[1, 2, 3, 4, 5, 6, 7, 8, 'abc', 9, 10, 11, 'test']

OK, now it only handles lists and tuples
2) What's different about your flatten than those ASPN entries? Just
that it flattens in-place? I see a general-purpose flattener and a
flattening generator.
The flatten procedure by Ganel does excessive work, it appears, by 
doing one level of flattening per pass through the entire list. Initial 
non-iterable items are rechecked as long as any iterables remain in the 
list. It is also not an "in-place" routine.

The one by Rodrigues and the one by Rol is recursive (and the one by 
Yoo is admittedly complicated).

The one I presented is essentially the same as Fletcher's.  Fletcher's 
does not actually run through all indices as I thought: as soon as it 
steps on an out-of-range index it exits. Fletcher's routine is a 
non-recursive version that runs in place that can be recommended if 
recursion is a problem.

I'll add a note to the ASPN pages.
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sorting of files based on filesize

2005-04-11 Thread C Smith
--request for a method of sorting disk files based on size so as to 
fill backup disks--

You may want to check out the karp.py routine posted at
http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/749797
Right now it is coded to split N numbers into 2 groups that have sums 
as nearly identical as possible. The set of numbers it is coded to test 
are are the first 50 square roots of integers; you would replace these 
with a list of N file sizes that are close to 2X a single disk capacity 
and it would tell you how to split up the group into two 
nearly-identically sized groups.  It's "very, very, very clever, and 
runs in an eyeblink" says Tim Peters. You might even want to use Tim's 
greedy "knapsack filler" approach that he initially proposed as part of 
the thread above which will try random selections from a list of values 
and keep track of the one that came closest to a target value. Your 
target value would be 2X the storage limit and then you could use the 
karp routine to split it nicely. Tim's greedy approach is at
http://mail.python.org/pipermail/tutor/2001-August/008075.html

An alternative to breaking your list of file sizes into sublists that 
are close to 2X your disk capacity would be to generalize the algorithm 
to break the numbers into M groups rather than 2 groups...but I'm not 
sure how easy that will be.

You're going to love using the karp for this problem :-)
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] how obsolete is 2.2?

2011-09-07 Thread c smith
I found a book at the local library that covers python but it's 2.2.
I already have been using 2.7 for basic stuff and would like to know if it's
worth my time to read this book.
Are there any glaring differences that would be easy to point out, or is it
too convoluted?
Also, am I correct in thinking that 3.0 will always be called 3.0 but will
change over time and will always include experimental features, while 2.x
will gradually increase the 'x' and the highest 'x' will indicate the most
current, stable release?

oh, and a question on 'pickle':
can pickle deserialize things that were not serialized by python?
can it convert data into a python data type regardless of it was originally
a 'c array' or something else that python doesn't support?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] how obsolete is 2.2, and a pickle question

2011-09-07 Thread c smith
I found a book at the local library that covers python but it's 2.2.
I already have been using 2.7 for basic stuff and would like to know if it's
worth my time to read this book.
Are there any glaring differences that would be easy to point out, or is it
too convoluted?
Also, am I correct in thinking that 3.0 will always be called 3.0 but will
change over time and will always include experimental features, while 2.x
will gradually increase the 'x' and the highest 'x' will indicate the most
current, stable release?

oh, and a question on 'pickle':
can pickle deserialize things that were not serialized by python?
can it convert data into a python data type regardless of it was originally
a 'c array' or something else that python doesn't support?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] making lists of prime numbers

2011-09-14 Thread c smith
hi list, i am trying the MIT opencourseware assignments.
one was to find the 1000th prime.
since this isn't actually my homework, I modified the solution as I would
like to collect lists of primes and non-primes up to N, also some log()
ratio to one comparison.
here is what I came up with on paper:
#!/usr/bin/env python
import sys, os, math

def main(a):
notprime = []
primelist = [2,3]
nprime = sys.argv[1]
numcheck = 4
while len(primelist) < nprime:
for i in range(2,numcheck-1):
if numcheck % i == 0:
print numcheck,'is not prime'
notprime.append(numcheck)
numcheck += 1
break
if i == numcheck and numcheck % i !=0:
print numcheck, 'is prime'
primelist.append(numcheck)
numcheck += 1
break
TwotoN = 0
for j in primelist:
TwotoN += log(j)
print 'sum of logs of primes from 2 to', nprime,'is',TwotoN
print 'the ratio of this sum to 1 is' %f % (float(TwotoN)/nprime)
if __name__=='__main__':
main(sys.argv[1])

my questions would be:
am I passing arguments from the command line correctly?
this seems to count by twos (going through both 'if statements' maybe?)
I thought the 'break' would send control back to the 'while'
basically, is there an obvious problem here or is it just completely wrong?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] help with a recursive function

2011-09-27 Thread c smith
hi list,
i understand the general idea of recursion and if I am following well
written code I can understand how it works, but when I try to write it for
myself I get a bit confused with the flow.
I was trying to turn an ackerman function into python code for practice and
I tried writing it like this:
#!/usr/bin/env python

import sys, os
def ack(m,n):

if m == 0:
return n+1
elif m > 0 and n == 0:
ack(m-1,1)
elif m > 0 and n > 0:
ack(m-1,ack(m,n-1))

if __name__=='__main__':
sys.argv[1] = int(sys.argv[1])
sys.argv[2] = int(sys.argv[2])

print ack(sys.argv[1], sys.argv[2])

The major problem, I think, is that I cant figure out where to turn the args
into ints.
When run in this form I get the 'typeError' error on 'n+1' I guess because
the args are still strings.
Also, does the second 'elif' make sense?
I am not sure if the function can take itself as an argument.
thanks for any suggestions, this list has been a big help.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running a script in the background

2012-09-01 Thread c smith
You are thinking of &&
& is what you want
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] html checker

2012-10-01 Thread c smith
You will not find much help in getting a program to 'just work' regardless
of your own experience. My advice would be to try and run small parts at a
time to pinpoint where the problem is. Are you opening and reading the file
properly? Are you iterating over the read file properly? Does your html
check work on a local, properly formatted html file? Create a small text
file to run it on. Also keep track of file position and when you are
assigning variables new values. I am still learning myself, so this isnt
very specific, but you will have to ask more specifically so more
experienced people will be willing to help without doing your work for you.
Good luck
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] html checker

2012-10-01 Thread c smith
yourlisthere.pop() will return the last element in the list and change the
list so it no longer contains the element. yourlisthere.push(x) will add x
to the end of the list. Works on more than just lists
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] HELP!

2012-10-01 Thread c smith
Is the only problem that your code is giving unexpected results, or that it
doesnt run or what?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python help?

2012-10-01 Thread c smith
It is hard to see things like images and attachments. I think purely html
is preferred, but i would have to look over 'the list rules' again.
You should look into dictionaries as the structure to hold your info.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Filename match on file extensions

2012-10-02 Thread c smith
Would this be a time when regex is necessary? Maybe:
\b[^.]*quarantine[^.]*\.[a-zA-Z]*\b
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What can I do if I'm banned from a website??

2012-10-10 Thread c smith
how could someone know enough to write their own web-scraping program and
NOT know that this is not about python or how to get around this problem?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python type confusion?

2015-09-28 Thread C Smith
On Mon, Sep 28, 2015 at 1:27 PM, Ken Hammer  wrote:
> A simple "type" problem?
>
> The following code works as a py file with the XX'd lines replacing the two 
> later "raw_input" lines.
> Why do the "raw_input" lines yield a TypeError: 'str' object is not callable? 
>  Same result if I use/omit
> the parens around the poly tuple.
>
>  evaluate a polynomial as formula for a defined function
> ##poly = (0.0, 0.0, 5.0, 9.3, 7.0)# f(x) = 7x^4 + 9.3x^3 + 5x^2
> ##x = -13
> poly = raw_input("Type, 0.0-n ,")## these do not work in place of 
> above
> x = raw_input("Type your val of x, ")## 'str' object is not callable?
y = int(x) #see below

>
> total = 0.0
> for i in range(len(poly)):
> totalTerm = poly[i]* (x ** i)
Here you would get "unsupported operand type" since you are getting
the ith power of a string.


> total += totalTerm
> print "totalTerm ", i , totalTerm
> print "Equation Value", total
>
>  Good answer follows:
> totalTerm  0 0.0
> totalTerm  1 0.0
> totalTerm  2 845.0
> totalTerm  3 -20432.1
> totalTerm  4 199927.0
> Equation Value 180339.9

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


Re: [Tutor] Python type confusion?

2015-09-28 Thread C Smith
On Mon, Sep 28, 2015 at 4:13 PM, C Smith  wrote:
> On Mon, Sep 28, 2015 at 1:27 PM, Ken Hammer  wrote:
>> A simple "type" problem?
>>
>> The following code works as a py file with the XX'd lines replacing the two 
>> later "raw_input" lines.
>> Why do the "raw_input" lines yield a TypeError: 'str' object is not 
>> callable?  Same result if I use/omit
>> the parens around the poly tuple.
>>
>>  evaluate a polynomial as formula for a defined function
>> ##poly = (0.0, 0.0, 5.0, 9.3, 7.0)# f(x) = 7x^4 + 9.3x^3 + 5x^2
>> ##x = -13
>> poly = raw_input("Type, 0.0-n ,")## these do not work in place of 
>> above
>> x = raw_input("Type your val of x, ")## 'str' object is not callable?
> y = int(x) #see below
>
>>
>> total = 0.0
>> for i in range(len(poly)):
>> totalTerm = poly[i]* (x ** i)
> Here you would get "unsupported operand type" since you are getting
> the ith power of a string.
EDIT: change "x" to "y"
>
>
>> total += totalTerm
>> print "totalTerm ", i , totalTerm
>> print "Equation Value", total
>>
>>  Good answer follows:
>> totalTerm  0 0.0
>> totalTerm  1 0.0
>> totalTerm  2 845.0
>> totalTerm  3 -20432.1
>> totalTerm  4 199927.0
>> Equation Value 180339.9
>>>>>
>> thanks,  Ken Hammer
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Mutable data type in python

2015-10-03 Thread C Smith
> Here is my modified version which I think works as you want:
>
> def findMinDepthPath(n):
> if n <= 0: raise ValueError
> elif n==1:
> return 0
> elif n==2 or n==3:
> return 1
> else:
> d1 = findMinDepthPath(n-1)+1
> d2 = d3 = (d1+1) # initialize to higher than d1
>
> if n%3 == 0:
> d3 = findMinDepthPath(n/3)+1
> if n%2 == 0:
> d2 = findMinDepthPath(n/2)+1
>
> return min(d1,d2,d3)
>
>
> n = int(raw_input('N? '))
> print "Minimum depth = ", findMinDepthPath(n),'\n'

Doesn't this only look one level deep? Is the poster asking for
something that would traverse all possible paths and then check for
the shortest?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Mutable data type in python

2015-10-03 Thread C Smith
On Sat, Oct 3, 2015 at 11:55 AM, Alan Gauld  wrote:
> On 03/10/15 19:10, C Smith wrote:
>>>
>>> Here is my modified version which I think works as you want:
>>>
>>> def findMinDepthPath(n):
>>>  if n <= 0: raise ValueError
>>>  elif n==1:
>>>  return 0
>>>  elif n==2 or n==3:
>>>  return 1
>>>  else:
>>>  d1 = findMinDepthPath(n-1)+1
>>>  d2 = d3 = (d1+1) # initialize to higher than d1
>>>
>>>  if n%3 == 0:
>>>  d3 = findMinDepthPath(n/3)+1
>>>  if n%2 == 0:
>>>  d2 = findMinDepthPath(n/2)+1
>>>
>>>  return min(d1,d2,d3)
>>>
>>>
What I meant was that the algorithm assumes that the lowest value from
one "action" (minus one, divide by 2, divide by 3) is the best
possible branch in the tree. That seems intuitively correct, but is it
necessarily so?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Difficulty in getting logged on to python.org; want to resubscribe at the beginner level; finding "While" Loops in Python 3.4.0 to be extremely picky

2014-04-25 Thread C Smith
You can get python 3.4 to work on your mac, but it has 2.5 or 2.4 which the
OS uses and things can get very messed up if you don't know what you are
doing. You should use virtualbox to run virtual OS's on your mac without
messing up your main computer.

You should probably describe what kind of error you are getting when trying
to log in to the website.


On Fri, Apr 25, 2014 at 4:34 PM, Stephen Mik <
mik.step...@yahoo.com.dmarc.invalid> wrote:

> Dear Sir(s):
> My name is Stephen W. Mik,my email address is "mik.step...@yahoo.com";
> and I am having trouble logging on to the "Python Tutor Site". I
> desperately need HELP with a Python 3.4.0 "Guess A Number" Homework
> Assignment 4 which is due VERY SOON.. I recognize,and acknowledge,that I am
> a Python Programming amateur and some of my questions may seem trivial or
> naive;but a guy has to start somewhere.I was briefly on the mailing list
> for a few days;unsubscribed Apr. 24,2014,and now I want to get back in,but
> am having trouble doing so. I have to do my programming in a shared
> computer lab(on Windows machines) Mondays,Tuesdays,Thursdays and limited
> hours on Friday because my home computer is a 2007 MacIntosh which I  can't
> configure to run Python 3.4.0. Anyway,people,I need help with Python as
> soon as I can get it.Thanks.
> SINCERELY,Stephen W. Mik
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help needed

2014-04-26 Thread C Smith
Just glancing at your work, I see you have curly braces around what looks
like it should be a list. If you are concerned with the order of your
output, dictionaries do not have a concept of order.


On Sat, Apr 26, 2014 at 3:16 PM, Suhana Vidyarthi  wrote:

> Hi Danny,
>
> Let me give you a high level brief of what I am doing:
> I am working on doing "disaster aware routing" considering the 24-node US
> network where I will be setting up connection between two any two nodes (I
> will select the source and destination nodes randomly). Also I have some
> links whose "probability of failure" is mentioned in the attached file.
> Other links, which are not mentioned in the file - we suppose their
> "probability of failure" is zero. So between the source-destination nodes,
> there will be multiple paths and I will select the one which has "least
> probability of failure".
>
> Now to setup the connection between two nodes, I have to select a path
> whose "probability of failure" is least. To do that first I will calculate
> the risk of each path from the attached file and then select the path with
> least risk value. Did you get this part? I know it can be a bit confusing.
>
> Now I break the problem into parts:
>
> 1. I have to topology of the 24-node map
> 2. I have the link values of each link - where risk values are the
> "probability of failure"
> 3. I calculate the total "probability of failure" of each path (a path may
> have multiple links): Suppose my source node is "a" and destination node is
> "b". I can setup a path between a to b via c or via d (a-c-b or a-d-c):
> Here I will check the risk values of a-c and c-b; also risk values of a-d
> and d-c. If the total risk valure of a-c-b is lower that risk value of
> a-d-c, then I select the path a-c-d to setup the connection. (again risk
> value = probability of failure)
>
> Now, I will first calculate the "total probability of failure" of each
> link (using the file.txt) and since some links are repeated their values
> will be added. The probabilities get added if a link is mentioned twice
> or thrice. For example:  link 3—5 is repeated 3 times: in line one, it
> has a probability of failure as 0.03, in line two it is 0.11 and in line
> three it is 0.04. So the probability of failure for link 3—5 is
> 0.03+0.11+0.04 = 0.18
>
> The length of each array will be same. You see the code I wrote: here is
> the output for it:
>
> Links ->
>
> [('10', '13'), ('14', '18'), ('7', '8'), ('15', '20'), ('5', '8'), ('5',
> '4'), ('11', '9'), ('21', '22'), ('12', '13'), ('21', '20'), ('17', '13'),
> ('20', '21'), ('21', '16'), ('14', '10'), ('11', '12'), ('11', '19'),
> ('14', '13'), ('3', '5'), ('11', '6'), ('19', '20')]
>
>
> Probability ->
>
> [0.04, 0.06, 0.04, 0.24, 0.08, 0.15, 0.08, 0.27, 0.04, 0.29, 0.08, 0.27,
> 0.27, 0.04, 0.08, 0.08, 0.08, 0.18002, 0.08, 0.24]
>
>
> It means that link [10,13] has a "probability of failure" as [0.04] and
> since the link [3-5] is repeated thrice with probability of 0.03, 0.11 and
> 0.04, its "probability of failure" is [0.18] (third last element in the
> Probability array). For some reason instead of 0.18 it is showing
> 0.1802, which I cannot figure to why.
>
>
> Please see the attached code. If you see the file.txt and my output: the
> output is not displayed in sequence and that is what I need help with. I
> want this to display :
>
>
> Links = { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13]
> [14,13] [17,13] [12,13] [11,6] [11,9] [11,12] [11,19] [19,20] [15,20]
> [21,20] [20,21] [21,16] [21,22] }
>
>
> Prob = {[0.18] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08]
> [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]}
>
>
> If you can figure why the output is not generated in same sequence as in
> the file.txt for me, it will be very helpful.
>
>
> let me know if I explained correctly, and if you have any questions or
> doubts?
>
>
> On Sat, Apr 26, 2014 at 11:41 AM, Danny Yoo wrote:
>
>> >>> I want to create two arrays using the above file (Links array and Prob
>> >>> array) that should give following output:
>> >>>
>> >>> *Links *= { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18]
>> >>> [10,13] [14,13] [17,13] [12,13] [11,6] [11,9][11,12] [11,19] [19,20]
>> >>> [15,20] [21,20] [20,21] [21,16] [21,22] }
>> >>>
>> >>> *Prob *= {[0.28] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04]
>> [0.08]
>> >>> [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]}
>> >>
>> >>
>> >> I don't understand how you develop this? The first list has 22 items
>> the
>> >> second 17. I would have expected them to be the same?
>> >
>> >
>> > In the "Prob" array the elements are less because if you read the note
>> > below: I said the links that are repeating for example [3,5] their
>> > probabilities  get added and stored as a single value in the "Prob"
>> array.
>>
>>
>> But what will you plan to do with these values afterwards?  I think
>> Alan's point here is that if there's no direc

Re: [Tutor] Help needed

2014-04-26 Thread C Smith
err, set also is unordered. I can see you are using set for a reason, but
has no concept of order.


On Sat, Apr 26, 2014 at 3:20 PM, C Smith wrote:

> Just glancing at your work, I see you have curly braces around what looks
> like it should be a list. If you are concerned with the order of your
> output, dictionaries do not have a concept of order.
>
>
> On Sat, Apr 26, 2014 at 3:16 PM, Suhana Vidyarthi <
> suhanavidyar...@gmail.com> wrote:
>
>> Hi Danny,
>>
>> Let me give you a high level brief of what I am doing:
>> I am working on doing "disaster aware routing" considering the 24-node US
>> network where I will be setting up connection between two any two nodes (I
>> will select the source and destination nodes randomly). Also I have some
>> links whose "probability of failure" is mentioned in the attached file.
>> Other links, which are not mentioned in the file - we suppose their
>> "probability of failure" is zero. So between the source-destination nodes,
>> there will be multiple paths and I will select the one which has "least
>> probability of failure".
>>
>> Now to setup the connection between two nodes, I have to select a path
>> whose "probability of failure" is least. To do that first I will calculate
>> the risk of each path from the attached file and then select the path with
>> least risk value. Did you get this part? I know it can be a bit confusing.
>>
>> Now I break the problem into parts:
>>
>> 1. I have to topology of the 24-node map
>> 2. I have the link values of each link - where risk values are the
>> "probability of failure"
>> 3. I calculate the total "probability of failure" of each path (a path
>> may have multiple links): Suppose my source node is "a" and destination
>> node is "b". I can setup a path between a to b via c or via d (a-c-b or
>> a-d-c): Here I will check the risk values of a-c and c-b; also risk values
>> of a-d and d-c. If the total risk valure of a-c-b is lower that risk value
>> of a-d-c, then I select the path a-c-d to setup the connection. (again risk
>> value = probability of failure)
>>
>> Now, I will first calculate the "total probability of failure" of each
>> link (using the file.txt) and since some links are repeated their values
>> will be added. The probabilities get added if a link is mentioned twice
>> or thrice. For example:  link 3—5 is repeated 3 times: in line one, it
>> has a probability of failure as 0.03, in line two it is 0.11 and in line
>> three it is 0.04. So the probability of failure for link 3—5 is
>> 0.03+0.11+0.04 = 0.18
>>
>> The length of each array will be same. You see the code I wrote: here is
>> the output for it:
>>
>> Links ->
>>
>> [('10', '13'), ('14', '18'), ('7', '8'), ('15', '20'), ('5', '8'), ('5',
>> '4'), ('11', '9'), ('21', '22'), ('12', '13'), ('21', '20'), ('17', '13'),
>> ('20', '21'), ('21', '16'), ('14', '10'), ('11', '12'), ('11', '19'),
>> ('14', '13'), ('3', '5'), ('11', '6'), ('19', '20')]
>>
>>
>> Probability ->
>>
>> [0.04, 0.06, 0.04, 0.24, 0.08, 0.15, 0.08, 0.27, 0.04, 0.29, 0.08, 0.27,
>> 0.27, 0.04, 0.08, 0.08, 0.08, 0.18002, 0.08, 0.24]
>>
>>
>> It means that link [10,13] has a "probability of failure" as [0.04] and
>> since the link [3-5] is repeated thrice with probability of 0.03, 0.11 and
>> 0.04, its "probability of failure" is [0.18] (third last element in the
>> Probability array). For some reason instead of 0.18 it is showing
>> 0.1802, which I cannot figure to why.
>>
>>
>> Please see the attached code. If you see the file.txt and my output: the
>> output is not displayed in sequence and that is what I need help with. I
>> want this to display :
>>
>>
>> Links = { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13]
>> [14,13] [17,13] [12,13] [11,6] [11,9] [11,12] [11,19] [19,20] [15,20]
>> [21,20] [20,21] [21,16] [21,22] }
>>
>>
>> Prob = {[0.18] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08]
>> [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]}
>>
>

Re: [Tutor] Help needed

2014-04-26 Thread C Smith
As others have pointed out, a mapping/dictionary or just a list of lists
seems like how you would want to organize the data for input. I think your
problem is insistence on using sets. I am no Python guru, but I think this
list is more for exploratory learning of Python. I think people are trying
to get you to answer your own questions or coax more information from you
rather than simply provide their own version of your code.


On Sat, Apr 26, 2014 at 3:48 PM, Suhana Vidyarthi  wrote:

> Thanks for the response Smith, I was thinking make be I have done
> something incorrect and if there is some other function that can be used to
> display the output in desired order but don't see it possible thats why was
> wondering if any of you Python gurus have any inputs for me :-)
>
>
>
> On Sat, Apr 26, 2014 at 12:36 PM, C Smith wrote:
>
>> err, set also is unordered. I can see you are using set for a reason, but
>> has no concept of order.
>>
>>
>> On Sat, Apr 26, 2014 at 3:20 PM, C Smith wrote:
>>
>>> Just glancing at your work, I see you have curly braces around what
>>> looks like it should be a list. If you are concerned with the order of your
>>> output, dictionaries do not have a concept of order.
>>>
>>>
>>> On Sat, Apr 26, 2014 at 3:16 PM, Suhana Vidyarthi <
>>> suhanavidyar...@gmail.com> wrote:
>>>
>>>> Hi Danny,
>>>>
>>>> Let me give you a high level brief of what I am doing:
>>>> I am working on doing "disaster aware routing" considering the 24-node
>>>> US network where I will be setting up connection between two any two nodes
>>>> (I will select the source and destination nodes randomly). Also I have some
>>>> links whose "probability of failure" is mentioned in the attached file.
>>>> Other links, which are not mentioned in the file - we suppose their
>>>> "probability of failure" is zero. So between the source-destination nodes,
>>>> there will be multiple paths and I will select the one which has "least
>>>> probability of failure".
>>>>
>>>> Now to setup the connection between two nodes, I have to select a path
>>>> whose "probability of failure" is least. To do that first I will calculate
>>>> the risk of each path from the attached file and then select the path with
>>>> least risk value. Did you get this part? I know it can be a bit confusing.
>>>>
>>>> Now I break the problem into parts:
>>>>
>>>> 1. I have to topology of the 24-node map
>>>> 2. I have the link values of each link - where risk values are the
>>>> "probability of failure"
>>>> 3. I calculate the total "probability of failure" of each path (a path
>>>> may have multiple links): Suppose my source node is "a" and destination
>>>> node is "b". I can setup a path between a to b via c or via d (a-c-b or
>>>> a-d-c): Here I will check the risk values of a-c and c-b; also risk values
>>>> of a-d and d-c. If the total risk valure of a-c-b is lower that risk value
>>>> of a-d-c, then I select the path a-c-d to setup the connection. (again risk
>>>> value = probability of failure)
>>>>
>>>> Now, I will first calculate the "total probability of failure" of each
>>>> link (using the file.txt) and since some links are repeated their values
>>>> will be added. The probabilities get added if a link is mentioned
>>>> twice or thrice. For example:  link 3—5 is repeated 3 times: in line
>>>> one, it has a probability of failure as 0.03, in line two it is 0.11 and in
>>>> line three it is 0.04. So the probability of failure for link 3—5 is
>>>> 0.03+0.11+0.04 = 0.18
>>>>
>>>> The length of each array will be same. You see the code I wrote: here
>>>> is the output for it:
>>>>
>>>> Links ->
>>>>
>>>> [('10', '13'), ('14', '18'), ('7', '8'), ('15', '20'), ('5', '8'),
>>>> ('5', '4'), ('11', '9'), ('21', '22'), ('12', '13'), ('21', '20'), ('17',
>>>> '13'), ('20', '21'), ('21', '16'), ('14', '10'), ('11', '12'), ('11',
>>>> '19'), (&

Re: [Tutor] converting strings to float: strange case

2014-04-28 Thread C Smith
.split() will split things based on whitespace or newlines. Do you know
that your file is only going to contain things that should convert to
floats? If you post your entire code, the error you have included will be
more helpful as it points to a certain line. The last line in your code has
(stri) should be (str).


On Mon, Apr 28, 2014 at 11:13 AM, Gabriele Brambilla <
gb.gabrielebrambi...@gmail.com> wrote:

> Hi,
>
> I'm trying to convert a string to a float. It seems a basic thing but I
> don't know why I'm getting this erroris
>
> Traceback (most recent call last):
>   File "phresREADER.py", line 27, in 
> tra = float(stri)
> ValueError: could not convert string to float:
>
> My file has this line
>
> 5.5e+000 5.5e+001 5.5e+002 5.5e+003
>
> my code is:
>
> my_line = f.readline()
> avg_energySTR = [str(i) for i in my_line.split(' ')]
> for stri in avg_energySTR:
> tra = float(stri)
>
> do you have any idea?
>
> thanks
>
> Gabriele
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stephen Mik-Almost Brand New to Python 3.4.0-"Guess My Number" program is syntactically correct but will not run as expected

2014-04-28 Thread C Smith
That is definitely more useful information in answering your questions.
Whenever you see the error you are getting:

NameError: name 'smv_guessNumber' is not defined

That means you are using a variable, in this case 'smv_guessNumber', that
has not been created yet.

The reason this is happening here is you need to import sys.


On Mon, Apr 28, 2014 at 1:32 PM, Stephen Mik <
mik.step...@yahoo.com.dmarc.invalid> wrote:

> Dear Python Tutor:
> Well,I am Stephen Mik,and I'm a beginning,rookie programmer who is
> just trying to get a class Assignment going. The instructor of my class
> does not accept email and she is not on Campus on Monday. So,my only
> recourse is to turn to Python Tutor for assistance.
>
> My program, Assignment4,does run partially. You can see the results of
> the Python Shell attached to this email. I also have included part of my
> code for your perusal.
>
> I must be doing something very wrong. The program is supposed to run a
> main loop ,for control of the program. The program DOES print out the
> prompts before the While Loop, but when it comes to a variable
> named"smv_guessNumber" the program DOES NOT prompt for the input for
> "smv_guessNumber" as it should. It is a mystery to me as to why the program
> will not get to the "smv_guessNumber=int(input("Think out a first
> guess:")". I am mystified why it doesn't reach that point in the program!
> Can anyone please help? I have attached the Python Traceback Error
> Output,which shows that at least part of the program IS working. I also
> have attached part of the code for the Assignment 4 which should help in
> the debugging.I need help ASAP,another program is due very soon and I have
> not even worked out the pseudocode for it yet!
> CONCERNED,Stephen W. Mik
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stephen Mik-Almost Brand New to Python 3.4.0-"Guess My Number" program is syntactically correct but will not run as expected

2014-04-28 Thread C Smith
I should probably clarify that this list is mainly for python2.7, correct
me if I am wrong.


On Mon, Apr 28, 2014 at 1:49 PM, C Smith wrote:

> That is definitely more useful information in answering your questions.
> Whenever you see the error you are getting:
>
> NameError: name 'smv_guessNumber' is not defined
>
> That means you are using a variable, in this case 'smv_guessNumber', that
> has not been created yet.
>
> The reason this is happening here is you need to import sys.
>
>
> On Mon, Apr 28, 2014 at 1:32 PM, Stephen Mik <
> mik.step...@yahoo.com.dmarc.invalid> wrote:
>
>> Dear Python Tutor:
>> Well,I am Stephen Mik,and I'm a beginning,rookie programmer who is
>> just trying to get a class Assignment going. The instructor of my class
>> does not accept email and she is not on Campus on Monday. So,my only
>> recourse is to turn to Python Tutor for assistance.
>>
>> My program, Assignment4,does run partially. You can see the results
>> of the Python Shell attached to this email. I also have included part of my
>> code for your perusal.
>>
>> I must be doing something very wrong. The program is supposed to run
>> a main loop ,for control of the program. The program DOES print out the
>> prompts before the While Loop, but when it comes to a variable
>> named"smv_guessNumber" the program DOES NOT prompt for the input for
>> "smv_guessNumber" as it should. It is a mystery to me as to why the program
>> will not get to the "smv_guessNumber=int(input("Think out a first
>> guess:")". I am mystified why it doesn't reach that point in the program!
>> Can anyone please help? I have attached the Python Traceback Error
>> Output,which shows that at least part of the program IS working. I also
>> have attached part of the code for the Assignment 4 which should help in
>> the debugging.I need help ASAP,another program is due very soon and I have
>> not even worked out the pseudocode for it yet!
>> CONCERNED,Stephen W. Mik
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stephen Mik-Almost Brand New to Python 3.4.0-"Guess My Number" program is syntactically correct but will not run as expected

2014-04-28 Thread C Smith
 The reason this is happening here is you need to import sys.
>

 I don't know why you would think importing sys would fix this.

docs say it accepts from sys.stdin


On Mon, Apr 28, 2014 at 1:55 PM, Philip Dexter wrote:

>
>
> On Mon, 28 Apr 2014, C Smith wrote:
>
>  I should probably clarify that this list is mainly for python2.7, correct
>> me if I am wrong.
>>
>
> I don't think that is true.
>
>
>  On Mon, Apr 28, 2014 at 1:49 PM, C Smith 
>> wrote:
>>
> 
>
>
>  The reason this is happening here is you need to import sys.
>>
>
> I don't know why you would think importing sys would fix this.
>
>  On Mon, Apr 28, 2014 at 1:32 PM, Stephen Mik 
> 
>> wrote:
>> I must be doing something very wrong. The program is supposed to run
>> a main loop ,for control of the program. The program DOES print out the
>> prompts
>> before the While Loop, but when it comes to a variable
>> named"smv_guessNumber" the program DOES NOT prompt for the input for
>> "smv_guessNumber" as it should. It
>> is a mystery to me as to why the program will not get to the
>> "smv_guessNumber=int(input("Think out a first guess:")". I am mystified
>> why it doesn't reach that
>> point in the program! Can anyone please help? I have attached the Python
>> Traceback Error Output,which shows that at least part of the program IS
>> working. I
>> also have attached part of the code for the Assignment 4 which should
>> help in the debugging.I need help ASAP,another program is due very soon and
>> I have not
>> even worked out the pseudocode for it yet!
>> CONCERNED,Stephen W. Mik
>>
>
> Your first while loop is not running. You convert smv_grandCounter to
> an int but compare it with a string.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stephen Mik-Almost Brand New to Python 3.4.0-"Guess My Number" program is syntactically correct but will not run as expected

2014-04-28 Thread C Smith
>
>  The reason this is happening here is you need to import sys.
>

 I don't know why you would think importing sys would fix this.

docs say it accepts from sys.stdin

I now see that it is not necessary to import sys, although I am not sure
why.


On Mon, Apr 28, 2014 at 1:59 PM, C Smith wrote:

>
>
>  The reason this is happening here is you need to import sys.
>>
>
>  I don't know why you would think importing sys would fix this.
>
> docs say it accepts from sys.stdin
>
>
> On Mon, Apr 28, 2014 at 1:55 PM, Philip Dexter wrote:
>
>>
>>
>> On Mon, 28 Apr 2014, C Smith wrote:
>>
>>  I should probably clarify that this list is mainly for python2.7,
>>> correct me if I am wrong.
>>>
>>
>> I don't think that is true.
>>
>>
>>  On Mon, Apr 28, 2014 at 1:49 PM, C Smith 
>>> wrote:
>>>
>> 
>>
>>
>>  The reason this is happening here is you need to import sys.
>>>
>>
>> I don't know why you would think importing sys would fix this.
>>
>>  On Mon, Apr 28, 2014 at 1:32 PM, Stephen Mik
>>>  wrote:
>>> I must be doing something very wrong. The program is supposed to run
>>> a main loop ,for control of the program. The program DOES print out the
>>> prompts
>>> before the While Loop, but when it comes to a variable
>>> named"smv_guessNumber" the program DOES NOT prompt for the input for
>>> "smv_guessNumber" as it should. It
>>> is a mystery to me as to why the program will not get to the
>>> "smv_guessNumber=int(input("Think out a first guess:")". I am mystified
>>> why it doesn't reach that
>>> point in the program! Can anyone please help? I have attached the Python
>>> Traceback Error Output,which shows that at least part of the program IS
>>> working. I
>>> also have attached part of the code for the Assignment 4 which should
>>> help in the debugging.I need help ASAP,another program is due very soon and
>>> I have not
>>> even worked out the pseudocode for it yet!
>>> CONCERNED,Stephen W. Mik
>>>
>>
>> Your first while loop is not running. You convert smv_grandCounter to
>> an int but compare it with a string.
>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Logical error?

2014-05-02 Thread C Smith
The first loop tests for the last element of fullPath to have today's date.
The second loop tests the first element in fullPath, if it is not today,
you will end up running sys.exit() when you hit the else clause in second
loop.


On Fri, May 2, 2014 at 6:38 PM, C Smith wrote:

> The first loop tests for the last element of fullPath to have today's
> date. The second loop tests the first element in fullPath, if it is not
> today, you will end up running sys.exit() when you hit the else clause in
> second loop.
>
>
> On Fri, May 2, 2014 at 6:19 PM, Bob Williams 
> wrote:
>
>> -BEGIN PGP SIGNED MESSAGE-
>> Hash: SHA1
>>
>> Hi,
>>
>> I'm fairly new to coding and python. My system is linux (openSUSE
>> 13.1). I've written the following code to examine a log file, and
>> extract strings from certain lines if two conditions are met, namely
>> that the file has been modified today, and the line contains the
>> string 'recv'.
>>
>> - ---Code---
>> #!/usr/bin/python
>>
>> import sys
>> import datetime
>> import codecs
>> import subprocess
>>
>> # Format date as /MM/DD
>> today = (datetime.datetime.now()).strftime('%Y/%m/%d')
>>
>> fullPath = []   # declare (initially empty) lists
>> truncPath = []
>>
>> with codecs.open('/var/log/rsyncd.log', 'r') as rsyncd_log:
>> for line in rsyncd_log.readlines():
>> fullPath += [line.decode('utf-8', 'ignore').strip()]
>> if fullPath[-1][0:10] == today:
>> print("\n   Rsyncd.log has been modified in the last 24 hours...")
>> else:
>> print("\n   No recent rsync activity. Nothing to do.\n")
>> sys.exit()
>>
>> # Search for lines starting with today's date and containing 'recv'
>> # Strip everything up to and including 'recv' and following last '/'
>> path separator
>> for i in range(0, len(fullPath)):
>> if fullPath[i][0:10] == today and 'recv' in fullPath[i]:
>> print("got there")
>> begin = fullPath[i].find('recv ')
>> end = fullPath[i].rfind('/')
>> fullPath[i] = fullPath[i][begin+5:end]
>> truncPath.append(fullPath[i])
>> print("   ...and the following new albums have been added:\n")
>> else:
>> print("   ...but no new music has been downloaded.\n")
>> sys.exit()
>>
>> - ---Code---
>>
>> The file rsyncd.log typically contains lines such as (sorry about the
>> wrapping):
>>
>> 2014/05/02 19:43:14 [20282]
>> host109-145-nnn-xxx.range109-145.btcentralplus.com recv Logical
>> Progression Level 3 (1998) Intense/17 Words 2 B Heard Collective -
>> Sonic Weapon.flac 72912051 72946196
>>
>> I would expect the script to output a list of artist and album names,
>> eg Logical Progression Level 3 (1998) Intense. IOW what is between the
>> string 'recv' and the trailing '/'. What it actually produces is:
>>
>> :~> python ~/bin/newstuff.py
>>
>>Rsyncd.log has been modified in the last 24 hours...
>>...but no new music has been downloaded.
>>
>> This suggests that the first 'if' clause (matching the first 10
>> characters of the last line) is satisfied, but the second one isn't,
>> as the flow jumps to the second 'else' clause.
>>
>> As the script runs without complaint, this is presumably a logical
>> error rather than a syntax error, but I cannot see where I've gone wrong.
>>
>> Bob
>> - --
>> Bob Williams
>> System:  Linux 3.11.10-7-desktop
>> Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.13.0
>> Uptime:  06:00am up 11:26, 4 users, load average: 0.00, 0.02, 0.05
>> -BEGIN PGP SIGNATURE-
>> Version: GnuPG v2.0.22 (GNU/Linux)
>> Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/
>>
>> iEYEARECAAYFAlNkGewACgkQ0Sr7eZJrmU57YwCgg91pxyQbFMSe+TqHkEjMuzQ6
>> 03MAnRQ50up6v+kYE+Hf/jK6yOqQw4Ma
>> =+w0s
>> -END PGP SIGNATURE-
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] append vs list addition

2014-05-04 Thread C Smith
I had always assumed that append() was more efficient, but some recent
discussions seem to point at that it is the same as append(). Which is
preferable and why?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] append vs list addition

2014-05-04 Thread C Smith
Sorry.

I meant for example:
list1 = [1,2,3]
list2 = [3,4,5]

newList = list1 + list2

versus

for x in list2:
list1.append(x)

Which is the preferred way to add elements from one list to another?

On Sun, May 4, 2014 at 7:36 AM, Dave Angel  wrote:
> C Smith  Wrote in message:
>>
>>
> I had always assumed that append() was more efficient, but some recent 
> discussions seem to point at that it is the same as append(). Which is 
> preferable and why?
>
> Please be more explicit,  preferably with example code.
>  list.append and list.__add__ don't even do the same thing.
>  Perhaps you mean list.extend
>
> I would also encourage you to properly use text mail to post,  as
>  there are a number of problems triggered by html mails as you're
>  doing now. Most of them don't matter with your current message,
>  however.
>
> --
> DaveA
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stephen Mik-Novice Python Programmer(Version 3.4.0)Can't get help using Dictionaries, Lists to 'Hangman Game Problem"

2014-05-04 Thread C Smith
Hey, you will want to include some code to show your progress so far.
Can you write a basic program and then work the requirements into it?
Do you have some idea of where to start? Are you supposed to modify a
completed version of "hangman" that is in your text, or come up with
an original 'hangman' program? Does the hangman game need a graphical
interface, or is just printing words to the screen fine?

On Sun, May 4, 2014 at 7:17 PM, Stephen Mik
 wrote:
> Dear Python World:
> I am almost brand new to Python 3.4.0 and am taking a beginning Python
> Programming class at the nearby Community College. One major problem I have
> is time management with beginning pseudo code and coding for my Class
> Assignments. The instructor prefers Office Hour help,and does not respond to
> email.
> One of my Class Assignments due on May 9,2014 deals with making a
> version of the "Hangman Game" which I'm sure somebody out there is familiar
> with. The program problem says to use 1.Dictionaries 2. Lists 3.Embedded
> While lists 4.for loops and more. I can refer to the Textbook for the class
> to get a basic idea of what some of the code will look like,but I cannot
> fathom how to use a Dictionary or List  in order to enhance the Basic
> Hangman Game Problem in the text  (written by Michael Dawson). The Text does
> cover "Dictionaries","Lists","While Loops","For Loops" but doesn't "amplify"
> and show with examples how some of these Data Structures can be used. And my
> instructor's Assignment directions are very terse and "you do it by
> yourself".
> If I can't get some ideas and hints from the Python Community by
> Monday,May 5,2014, I will have to hold off this difficult  programming
> assignment until Tuesday,May 6,2014 when the instructor will be available to
> help. That leaves me just 3 days to pseudocode,code in Python,fix syntax and
> run-time and Logical errors before I can turn it in by Friday,May 16,2014.
> The instructor will only probably give me a suggestion and not some tangible
> ideas.Any thoughts out there about how to implement the Loops and Data
> Structures into a "Hangman Game" programming problem?
> SINCERELY,Stephen W. Mik
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Alice_in_wonderland Question

2014-05-04 Thread C Smith
>ordered_keys = word_count.keys()
>sorted(ordered_keys)

sorted() does not modify the list, but returns a sorted version of the
list for me on Python 2.7
my_sorted_list = sorted(ordered_keys)
This will alphabetize all of the words, regardless of frequency.

>print ("All the words and their frequency in", 'alice in wonderland')
>for k in ordered_keys:

for k in my_sorted_keys:

>print (k, word_count[k])

This will still print out all the words alphabetically, regardless of frequency.
Maybe you could have a different dictionary for each value, for
example, a dictionary of all the words that appear once, twice, three
times.

By 'asking the user for input information' do you mean so they could
pass any txt file into the program to be sorted?

On Sun, May 4, 2014 at 5:04 PM, Jake Blank  wrote:
> Hi,
> So I'm doing a problem on the Alice_in_wonderland.txt where I have to write
> a program that reads a piece of text from a file specified by the user,
> counts the number of occurrences of each word, and writes a sorted list of
> words and their counts to an output file. The list of words should be sorted
> based on the counts, so that the most popular words appear at the top. Words
> with the same counts should be sorted alphabetically.
>
> My code right now is
>
> word_count = {}
> file = open ('alice_in_wonderland.txt', 'r')
> full_text = file.read().replace('--',' ')
> full_text_words = full_text.split()
>
> for words in full_text_words:
> stripped_words = words.strip(".,!?'`\"- ();:")
> try:
> word_count[stripped_words] += 1
> except KeyError:
> word_count[stripped_words] = 1
>
> ordered_keys = word_count.keys()
> sorted(ordered_keys)
> print ("All the words and their frequency in", 'alice in wonderland')
> for k in ordered_keys:
> print (k, word_count[k])
>
> The Output here is just all of the words in the document NOT SORTED by
> amount of occurrence.
> I need help sorting this output of words in the Alice_in_wonderland.txt, as
> well as help asking the user for the input information about the files.
>
> If anyone could give me some guidance you will really be helping me out.
>
> Please and Thank you
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stephen Mik-Novice Python Programmer(Version 3.4.0)Can't get help using Dictionaries, Lists to 'Hangman Game Problem"

2014-05-05 Thread C Smith
Stephen, respond to the list so someone with more experience can help
you. I am still learning a lot about Python, but when over-generalized
questions are asked, I can tell that more experienced tutor-members
will not be able to help you much unless you can learn to frame the
questions correctly. You will notice this trend on many forums or
mailing lists not even related to Python. Sites like stackoverflow.com
(another great resource) will follow similar trends.

One thing you could do is post the code from hangman.py. Some people
will be averse to downloading even a .py file for various reasons, so
you are more likely to get a response by posting the entire code in
PLAIN TEXT. Right now your text is not plain text and will make it
hard to copy/paste or indent code properly.

If the instructor said you can use the code, use it. Changing variable
names should take about 5 seconds, as long as you have at least
feigned interest in the class. If changing variable names sounds
daunting, don't feel hopeless, you have just not been exposed to it
before. Adding a dictionary does not have to change the program
dramatically. You could even just add a minor functionality like
keeping track of score for players and not change the major parts of
the program.

Earlier you said: 'embedded while lists'.
Did you mean 'embedded while loop'?
If you can have a flash drive for the final, could you load it up with
Python reference material? If you can, make sure it is in a format
that you are comfortable searching and understanding. If you try to
cheat in programming, it will be easy to tell if the instructor
decides to ask you about your code.

On Mon, May 5, 2014 at 12:19 PM, Stephen Mik  wrote:
> Stephen Mik-"hung-up" on Hangman Python code, pseudo code,worries about
> using Dictionaries,Lists.embedded while lists,for loops:
> Thank you,. C. Smith for responding to my help plea on Python-Tutor.org. One
> version of the "Hang Man" problem is listed in the textbook,but it doesn't
> use Dictionaries,Lists,embedded while lists;so I am fairly flummoxed as to
> what is needed in the pseudo code,or Python code. If I just copy the code
> from the Textbook,I am afraid that I will not learn very much about the
> Algorithm used to guess the scrambled word in Hang Man.The program
> assignment does not require a GUI to the screen,just printing words and some
> primitive ASCII Graphics of a man being hung if the word is not guessed in
> time. The instructor says we can use the code for the Hangman.py at the back
> of the chapter,but must of course change the variable names and add
> Dictionaries,Lists,etc. Another program is due by May 13,2014(A Tic-Tac-Toe
> program,which has MANY functions. And to top it off,the Final Exam is
> scheduled for Thursday,May 15,2014. In the Final we are NOT allowed textbook
> or class notes,just a Flash Drive and a Python interpreter. Anything else
> ,including looking up help on the Internet,is strictly forbidden.You talk
> about pressure,I sure feel it now! SWM
> On Sunday, May 4, 2014 4:45 PM, C Smith 
> wrote:
> Hey, you will want to include some code to show your progress so far.
> Can you write a basic program and then work the requirements into it?
> Do you have some idea of where to start? Are you supposed to modify a
> completed version of "hangman" that is in your text, or come up with
> an original 'hangman' program? Does the hangman game need a graphical
> interface, or is just printing words to the screen fine?
>
> On Sun, May 4, 2014 at 7:17 PM, Stephen Mik
>  wrote:
>> Dear Python World:
>>I am almost brand new to Python 3.4.0 and am taking a beginning Python
>> Programming class at the nearby Community College. One major problem I
>> have
>> is time management with beginning pseudo code and coding for my Class
>> Assignments. The instructor prefers Office Hour help,and does not respond
>> to
>> email.
>>One of my Class Assignments due on May 9,2014 deals with making a
>> version of the "Hangman Game" which I'm sure somebody out there is
>> familiar
>> with. The program problem says to use 1.Dictionaries 2. Lists 3.Embedded
>> While lists 4.for loops and more. I can refer to the Textbook for the
>> class
>> to get a basic idea of what some of the code will look like,but I cannot
>> fathom how to use a Dictionary or List  in order to enhance the Basic
>> Hangman Game Problem in the text  (written by Michael Dawson). The Text
>> does
>> cover "Dictionaries","Lists","While Loops","For Loops" but doesn't
>> "amplify"
>> and show with examples how some of these Data Structures can be used. And
>> my
>> instructor's Assignmen

[Tutor] How inefficient is this code?

2014-05-07 Thread C Smith
A topic came up on slashdot concerning "intermediate" programming,
where the poster expressed the feeling that the easy stuff is too easy
and the hard stuff is too hard.

Someone did point out that 'intermediate' programming would still
involve actually selling code or at least some professional
experience, so this would probably fall into the category of 'novice'.

I feel similarly right now and the cs 101 classes from udacity or
coursera or the opencourseware stuff are very easy and boring. I tried
the class "design of computer programs" on udacity and made it about
halfway before being overwhelmed. The class involved making an api for
a regex-like function to parse text (if I am communicating that
correctly, it was sort of rewriting regex functionality in Python
terms), and it seemed to go over a very definite cliff in terms of
difficulty. Could someone provide a concise example of decorator use?

Someone suggested projecteuler.net and I started blazing through
things I had done before, when I realized this would be a good time to
start more efficient practices instead of code that just happens to
work and may be very inefficient.

#sum all even fib seq integers under 4 million
fibs = [1,2]
sum = 0
while fibs[-1] < 400:
nexty = fibs[-1] + fibs[-2]
fibs.append(nexty)

for xer in fibs:
if xer%2 == 0:
sum += xer
print sum

This gets the correct solution, but what would be ways to improve
speed or use more complicated parts of Python to do the same thing.
Thanks in advance
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How inefficient is this code?

2014-05-07 Thread C Smith
I see. Thanks that is exactly what I was looking for. Would your
example be an instance of an object-oriented approach,
compartmentalizing things into functions?

On Wed, May 7, 2014 at 7:55 PM, Joe Cortes  wrote:
> Welcome to the wonderful world of generators!
>
> Looking at your code, you'll notice two things. First, you're
> iterating over all the numbers twice: once to calculate them, and then
> another time to actually do the sum. What's worse, at any given point
> in time, you're only really using fibs[-1] and fibs[-2], and yet
> you're still building this huge list with all the numbers. This is bad
> in terms of memory efficiency. Luckily, it's such a common problem
> that Python offers a really nice, really Pythonic solution. You can
> define the following function:
>
> def fib(top):
> first = 1 # As an aside, consider starting the sequence from 0, 1.
> next = 2
> yield first
> while next < top:
>  yield next
>  # For kicks, try rewriting the following three lines as a
> tuple assignment.
>  new_next = next + first
>  first = next
>  next = new_next
>
> Now, how do you use this? This being Python, there is a super simple
> way to do this:
>
> sum = 0
> for num in fib(400):
>  if num % 2 == 0:
> sum += num
> print sum
>
>
> So, what's going on here? fib is mostly straightforward, but that
> yield keyword might look new.
> Here's the deal: when you have a function that uses the yield keyword,
> that function becomes usable in the context of a for loop. Every time
> it hits a yield it will, well, yield that value out to the for loop.
> At the end of an iteration, control will be handed back to the
> function, which will do its magic, and yield another value. Again, the
> value will be sent out to the for loop, in this case as the "num"
> variable, for use in that iteration.
> When the function hits a return (or reaches the end of its body), the
> for loop ends.
>
> This is called a generator function, and is a really nice way to
> simplify and optimize your loops.
>
> You can read more about generators here: 
> https://wiki.python.org/moin/Generators
>
>
> On Wed, May 7, 2014 at 7:27 PM, C Smith  wrote:
>> A topic came up on slashdot concerning "intermediate" programming,
>> where the poster expressed the feeling that the easy stuff is too easy
>> and the hard stuff is too hard.
>>
>> Someone did point out that 'intermediate' programming would still
>> involve actually selling code or at least some professional
>> experience, so this would probably fall into the category of 'novice'.
>>
>> I feel similarly right now and the cs 101 classes from udacity or
>> coursera or the opencourseware stuff are very easy and boring. I tried
>> the class "design of computer programs" on udacity and made it about
>> halfway before being overwhelmed. The class involved making an api for
>> a regex-like function to parse text (if I am communicating that
>> correctly, it was sort of rewriting regex functionality in Python
>> terms), and it seemed to go over a very definite cliff in terms of
>> difficulty. Could someone provide a concise example of decorator use?
>>
>> Someone suggested projecteuler.net and I started blazing through
>> things I had done before, when I realized this would be a good time to
>> start more efficient practices instead of code that just happens to
>> work and may be very inefficient.
>>
>> #sum all even fib seq integers under 4 million
>> fibs = [1,2]
>> sum = 0
>> while fibs[-1] < 400:
>> nexty = fibs[-1] + fibs[-2]
>> fibs.append(nexty)
>>
>> for xer in fibs:
>> if xer%2 == 0:
>> sum += xer
>> print sum
>>
>> This gets the correct solution, but what would be ways to improve
>> speed or use more complicated parts of Python to do the same thing.
>> Thanks in advance
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How inefficient is this code?

2014-05-07 Thread C Smith
I guess intuiting efficiency doesn't work in Python because it is such
high-level? Or is there much more going on there?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Python

2014-05-11 Thread C Smith
Hey Glen, include the error you are getting. It will make answering
your question easier. How are you running this program, in an IDE?

On Sat, May 10, 2014 at 11:16 PM, Glen Chan  wrote:
> Hello, I am a student trying to figure out Python. I am getting errors that
> I don't know how to fix. What do you do after you get the error message and
> something is highlighted? Does that have to be deleted? Anyway, here is what
> I mean...
>
>
> #>>> The Dice Game
> #add libraries needed
> import random
> #the main function
> def main():
> print
> #initialize variables
> playerOne = 'No Name'
> playerTwo = 'No Name'
>
> #call to inputNames
> playerOne, playerTwo = inputNames(playerOne, playerTwo)
> #while loop to run program again
> while endProgram == 'no':
> #initialize variables
>  winnersName = 'NO NAME'
>  p1number = 0
>  p2number = 0
> #call to rollDice
>  winnerName = rollDice(p1number, p2number, playerOne, playerTwo,
> winnerName)
>
> #call to displayInfo
>  winnerName
> endProgram = raw_input('Do you want to end program? (Enter yes or
> no): ')
>
>
>
> #this function gets the players names
> def inputNames(playerOne, playerTwo):
> playerOne = raw_input("Enter Name")
> playerTwo = raw_input("Enter Name")
>
> return playerOne, playerTwo
> #this function will get the random values
> def rollDice(p1numer, p2numer, playerOne, playerTwo, winnerName):
>  p1number = random.randint(1, 6)
>  p1number = random.randint(1, 6)
>
> #this function displays the winner
>
> if p1number == p2number:
> winnerName = "TIE"
> elif p1number > p2number:
> winnerName = playerOne
> else:
> winnerName = playerTwo
> return winnerName
>
> # calls main
> main()
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Real world experience

2014-05-11 Thread C Smith
I have never known anyone that works in this industry. I got one job
transforming xml (should have used xslt, ended up using sed and python
regex scripts) where the guy asked me how much I wanted and I threw
200 bucks out there because I could get a room for two weeks at that
cost. He just laughed and handed me the money. That is the only
professional experience I have and no formal education whatsoever
(some high school). I have been doing online stuff and hit a wall in a
'design of computer programs' class on udacity. I made it about
halfway through but started back at square one to sharpen my skills
before trying to come at it again from a different angle. I started to
feel overwhelmed when trying to basically recode regex (functions for
'*' and '.' for instance) in python and make an api to interact easily
with the text parser.

I am still completely in the dark about what level of difficulty I
would be facing in the professional world.
If this is difficult at all for me, is there hope to think about
making money in this field?
I am pretty persistent and can keep up a level of work if I am not
even close yet, but I don't know if I am a year off or 10 years off.
Are basic scripting skills employable at even a very low rate (10
bucks an hour)?
What level of experience are the people at who make 100k a year?
Sorry if this is off-topic for the list, but I am trying to get past a
psychological hurdle or two before reapplying myself and hopefully it
would be valuable to others as well.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Real world experience

2014-05-11 Thread C Smith
What is a difficult problem that if I could solve it would indicate I
am ready to begin looking for a job? I realize that solving just ONE
problem isn't too meaningful, but I am looking for a level of
difficulty or some sort of gauge as to what a good programmer would
consider difficult. What would a junior programmer for a company be
expected to be able to do? This way I could have an idea of the range
between a beginner (still a paid employee) and someone with many years
of experience. I am in the south, USA.
thanks

On Sun, May 11, 2014 at 9:43 PM, Tim Krupinski  wrote:
> Probably off-topic for the list but i'll let some of the others weigh in on
> that.  This is more for help with the python language itself.
>
> But i'll weigh in.  Programming is difficult work.  It's definitely a
> profitable career.  Its hard to say how much you'll make since it varies
> depending on location, but in general a combination of experience and your
> ability to solve difficult problems and provide solutions consistently
> command higher salaries.  However, many companies wont even consider you
> without a degree, or a significant contribution to the industry.
>
> If you want to pursue a career in IT, you need to finish high school.  You
> would be wise to get a degree.
>
> My $0.02.
>
> Tim
>
>
> On Sun, May 11, 2014 at 7:12 PM, C Smith 
> wrote:
>>
>> I have never known anyone that works in this industry. I got one job
>> transforming xml (should have used xslt, ended up using sed and python
>> regex scripts) where the guy asked me how much I wanted and I threw
>> 200 bucks out there because I could get a room for two weeks at that
>> cost. He just laughed and handed me the money. That is the only
>> professional experience I have and no formal education whatsoever
>> (some high school). I have been doing online stuff and hit a wall in a
>> 'design of computer programs' class on udacity. I made it about
>> halfway through but started back at square one to sharpen my skills
>> before trying to come at it again from a different angle. I started to
>> feel overwhelmed when trying to basically recode regex (functions for
>> '*' and '.' for instance) in python and make an api to interact easily
>> with the text parser.
>>
>> I am still completely in the dark about what level of difficulty I
>> would be facing in the professional world.
>> If this is difficult at all for me, is there hope to think about
>> making money in this field?
>> I am pretty persistent and can keep up a level of work if I am not
>> even close yet, but I don't know if I am a year off or 10 years off.
>> Are basic scripting skills employable at even a very low rate (10
>> bucks an hour)?
>> What level of experience are the people at who make 100k a year?
>> Sorry if this is off-topic for the list, but I am trying to get past a
>> psychological hurdle or two before reapplying myself and hopefully it
>> would be valuable to others as well.
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Real world experience

2014-05-12 Thread C Smith
Thanks to everyone.

>> practice.  That programming doesn't have to be a solitary thing needs
>> to be strongly emphasized, because the media likes to exaggerate,
>Yes, This can't be stressed too much. Industrial coding is a team activity not 
>a solo process.

This is particularly good advice for me. Although I realized that a
big project would involve many people, I was thinking of myself as
"coding alone in dark room " without being able to go over ideas with
a team. I would probably get less frustrated that way.

>One big step is "program for someone else"

This is something I need to practice.

>Just as a side comment: there are probably several folks on this
>mailing list whose job description would match "working in industry".

I was thinking IRL. Thanks for the sense of community though.

>I don't know where you're geographically located, but if you are close
>to Hacker Dojo, they're good people.

That looks pretty amazing. I am in Atlanta, but I may take a bus out
there just to check it out. I lived in LA for a little while and
venice beach, santa monica, and the desert-y hills around mulholland
drive were beautiful.

>or a significant contribution to the industry.

I will keep this in mind.

>involve following standardized practices, using standard notations and naming 
>conventions and so on.

This is another very relevant thing for me to keep in mind. My
variables are usually interesting animals or spells from final fantasy
1.

Thanks

On Mon, May 12, 2014 at 4:55 PM, Alan Gauld  wrote:
> On 12/05/14 18:47, Danny Yoo wrote:
>
>> practice.  That programming doesn't have to be a solitary thing needs
>> to be strongly emphasized, because the media likes to exaggerate,
>
>
> Yes, This can't be stressed too much. Industrial coding is a team activity
> not a solo process.
>
> In fact one well known and respected management book(*) had as a maxiom -
> "Beware of the man in a darkened room". What it meant was be suspicious of
> the lone wolf coder who doesn't tell you what he'sd doing, where he's at
> etc.
> His code will likely not work with any one else's (and he'll blame
> them of course!) and it will be late because its always 95%
> complete...
>
> There are a few lone shark geniuses out there, I've met maybe 2 in
> my 40 years in IT. But 99.9% of coders work best in a team.
>
>
> (*)Software Project Survival Guide by Steve McConnell
> (also author of Code Complete etc)
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.flickr.com/photos/alangauldphotos
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Real world experience

2014-05-12 Thread C Smith
Freeside is more makers. I haven't gone but have known people that
have. You might find some arduino supposedly, but not much coding
otherwise and you have to pay membership fees. It is more social than
technical, I think. And your car will probably be broken into. I will
check out the python-atlanta group though, thanks.

On Mon, May 12, 2014 at 7:42 PM, Danny Yoo  wrote:
>>>I don't know where you're geographically located, but if you are close
>>>to Hacker Dojo, they're good people.
>>
>> That looks pretty amazing. I am in Atlanta, but I may take a bus out
>> there just to check it out. I lived in LA for a little while and
>> venice beach, santa monica, and the desert-y hills around mulholland
>> drive were beautiful.
>
> Scanning Atlanta
>
> ...
> ...
>
> I do not know what the status of this is in real life, since I don't
> live in Atlanta, but you might want to check on:
>
> https://wiki.freesideatlanta.org/fs/Info
>
>
> Alternatively, check your local meetups in the area.  For example:
>
> http://www.meetup.com/Geekspace-Gwinnett/
>
> http://www.meetup.com/python-atlanta/
>
>
> There are probably many others out there in your local area.  Start
> searching.  :P
>
>
> Good luck to you!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Real world experience

2014-05-12 Thread C Smith
I think that is going to be my new wallpaper.

On Mon, May 12, 2014 at 8:25 PM, Martin A. Brown  wrote:
>
> Hello,
>
>   10 Pick one favorite specific topic, any topic (XML parsing; Unix
>  process handling; databases).  The topic matters for you.
>  Learn it deeply.  Keep learning it.  The topic matters less for
>  others (unless it is specifically within the computer science
>  discipline).  You have just begun. [0]
>
>   20 Pick a toolkit (minidom, etree; os, multiprocessing, threading,
>  subprocess; sqlite, psycopg, sqlalchemy, mysql).  Learn why
>  people solved the problem differently each time.  Ask.
>
>   30 Write a program that does something interesting with this.
>  Try a different toolkit.  What was hard?  What was easy?
>  What could you simply not accomplish?  Look at the source code
>  for the tool you used?  Why couldn't you accomplish what you
>  wanted?
>
>   40 Read all of the documentation.  Read it again.  Read papers and
>  books listed in the documentation footnotes.  Read the
>  documentation again.  Realize that all of this is a (fallible)
>  human endeavor.
>
>   45 Find other, related mailing lists.  Subscribe.  Listen.  Post.
>
>   46 Talk to somebody who has solved the problem.  How?  What tools
>  did that person use [1]?
>
>   48 If reference to something that was new or you did not
>  understand, GOTO 40.
>
>   50 Write a brand new program to solve the same problem.  Examine
>  what you did differently.  Ask somebody to review your code.
>
>   52 Read your old code.
>
>   53 Talk to somebody who has solved the problem in his/her own
>  way, potentially with different tools. [2]
>
>   59 If MASTERY and BORED, GOTO 10.
>
>   60 GOTO 20 [3]
>
> This discipline can be approached in depth-first or breadth-first
> traversal pattern.  Most people on more technical mailing lists
> appreciate the depth-first traversal.
>
> Time waits for nobody (Oh! I need to go eat!),
>
> -Martin
>
>  [0] For these purposes, mine was IP networking.
>  [1] What!?!  Not Python?!  Why?  There are reasons to choose
>  something else.  Do not be blind to those resaons.
>  [2] Find people who are motivated as you are and are working on
>  similar problems.  Work for them.  Keep reading.  Hire them.
>  Keep writing.  Keep reading.
>  [3] Oops.  I learned on BASIC.  I hope I do not get banned from
>  the list.
>
> --
> Martin A. Brown
> http://linux-ip.net/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] for the error about 'import site' failed; use -v for traceback

2014-05-14 Thread C Smith
That looks pretty normal. I don't see any errors.

On Wed, May 14, 2014 at 5:42 AM, Tao Zhu  wrote:
> Hi everyone,
> when I use python, the problem occured. when I used the command "python -v",
> the results are listed as follows. could you tell me what wrong?
>
> $ python -v
> # installing zipimport hook
> import zipimport # builtin
> # installed zipimport hook
> # /usr/local/lib/python2.4/site.pyc matches /usr/local/lib/python2.4/site.py
> import site # precompiled from /usr/local/lib/python2.4/site.pyc
> # /usr/local/lib/python2.4/os.pyc matches /usr/local/lib/python2.4/os.py
> import os # precompiled from /usr/local/lib/python2.4/os.pyc
> import posix # builtin
> # /usr/local/lib/python2.4/posixpath.pyc matches
> /usr/local/lib/python2.4/posixpath.py
> import posixpath # precompiled from /usr/local/lib/python2.4/posixpath.pyc
> # /usr/local/lib/python2.4/stat.pyc matches /usr/local/lib/python2.4/stat.py
> import stat # precompiled from /usr/local/lib/python2.4/stat.pyc
> # /usr/local/lib/python2.4/UserDict.pyc matches
> /usr/local/lib/python2.4/UserDict.py
> import UserDict # precompiled from /usr/local/lib/python2.4/UserDict.pyc
> # /usr/local/lib/python2.4/copy_reg.pyc matches
> /usr/local/lib/python2.4/copy_reg.py
> import copy_reg # precompiled from /usr/local/lib/python2.4/copy_reg.pyc
> # /usr/local/lib/python2.4/types.pyc matches
> /usr/local/lib/python2.4/types.py
> import types # precompiled from /usr/local/lib/python2.4/types.pyc
> # /usr/local/lib/python2.4/warnings.pyc matches
> /usr/local/lib/python2.4/warnings.py
> import warnings # precompiled from /usr/local/lib/python2.4/warnings.pyc
> # /usr/local/lib/python2.4/linecache.pyc matches
> /usr/local/lib/python2.4/linecache.py
> import linecache # precompiled from /usr/local/lib/python2.4/linecache.pyc
> import encodings # directory /usr/local/lib/python2.4/encodings
> # /usr/local/lib/python2.4/encodings/__init__.pyc matches
> /usr/local/lib/python2.4/encodings/__init__.py
> import encodings # precompiled from
> /usr/local/lib/python2.4/encodings/__init__.pyc
> # /usr/local/lib/python2.4/codecs.pyc matches
> /usr/local/lib/python2.4/codecs.py
> import codecs # precompiled from /usr/local/lib/python2.4/codecs.pyc
> import _codecs # builtin
> # /usr/local/lib/python2.4/encodings/aliases.pyc matches
> /usr/local/lib/python2.4/encodings/aliases.py
> import encodings.aliases # precompiled from
> /usr/local/lib/python2.4/encodings/aliases.pyc
> # /usr/local/lib/python2.4/encodings/utf_8.pyc matches
> /usr/local/lib/python2.4/encodings/utf_8.py
> import encodings.utf_8 # precompiled from
> /usr/local/lib/python2.4/encodings/utf_8.pyc
> Python 2.4.4 (#3, May 15 2014, 00:22:35)
> [GCC 3.4.4 20050721 (Red Hat 3.4.4-2)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> dlopen("/usr/local/lib/python2.4/lib-dynload/readline.so", 2);
> import readline # dynamically loaded from
> /usr/local/lib/python2.4/lib-dynload/readline.so

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


Re: [Tutor] for the error about 'import site' failed; use -v for traceback

2014-05-14 Thread C Smith
What are you trying to do?

On Wed, May 14, 2014 at 12:24 PM, C Smith  wrote:
> That looks pretty normal. I don't see any errors.
>
> On Wed, May 14, 2014 at 5:42 AM, Tao Zhu  wrote:
>> Hi everyone,
>> when I use python, the problem occured. when I used the command "python -v",
>> the results are listed as follows. could you tell me what wrong?
>>
>> $ python -v
>> # installing zipimport hook
>> import zipimport # builtin
>> # installed zipimport hook
>> # /usr/local/lib/python2.4/site.pyc matches /usr/local/lib/python2.4/site.py
>> import site # precompiled from /usr/local/lib/python2.4/site.pyc
>> # /usr/local/lib/python2.4/os.pyc matches /usr/local/lib/python2.4/os.py
>> import os # precompiled from /usr/local/lib/python2.4/os.pyc
>> import posix # builtin
>> # /usr/local/lib/python2.4/posixpath.pyc matches
>> /usr/local/lib/python2.4/posixpath.py
>> import posixpath # precompiled from /usr/local/lib/python2.4/posixpath.pyc
>> # /usr/local/lib/python2.4/stat.pyc matches /usr/local/lib/python2.4/stat.py
>> import stat # precompiled from /usr/local/lib/python2.4/stat.pyc
>> # /usr/local/lib/python2.4/UserDict.pyc matches
>> /usr/local/lib/python2.4/UserDict.py
>> import UserDict # precompiled from /usr/local/lib/python2.4/UserDict.pyc
>> # /usr/local/lib/python2.4/copy_reg.pyc matches
>> /usr/local/lib/python2.4/copy_reg.py
>> import copy_reg # precompiled from /usr/local/lib/python2.4/copy_reg.pyc
>> # /usr/local/lib/python2.4/types.pyc matches
>> /usr/local/lib/python2.4/types.py
>> import types # precompiled from /usr/local/lib/python2.4/types.pyc
>> # /usr/local/lib/python2.4/warnings.pyc matches
>> /usr/local/lib/python2.4/warnings.py
>> import warnings # precompiled from /usr/local/lib/python2.4/warnings.pyc
>> # /usr/local/lib/python2.4/linecache.pyc matches
>> /usr/local/lib/python2.4/linecache.py
>> import linecache # precompiled from /usr/local/lib/python2.4/linecache.pyc
>> import encodings # directory /usr/local/lib/python2.4/encodings
>> # /usr/local/lib/python2.4/encodings/__init__.pyc matches
>> /usr/local/lib/python2.4/encodings/__init__.py
>> import encodings # precompiled from
>> /usr/local/lib/python2.4/encodings/__init__.pyc
>> # /usr/local/lib/python2.4/codecs.pyc matches
>> /usr/local/lib/python2.4/codecs.py
>> import codecs # precompiled from /usr/local/lib/python2.4/codecs.pyc
>> import _codecs # builtin
>> # /usr/local/lib/python2.4/encodings/aliases.pyc matches
>> /usr/local/lib/python2.4/encodings/aliases.py
>> import encodings.aliases # precompiled from
>> /usr/local/lib/python2.4/encodings/aliases.pyc
>> # /usr/local/lib/python2.4/encodings/utf_8.pyc matches
>> /usr/local/lib/python2.4/encodings/utf_8.py
>> import encodings.utf_8 # precompiled from
>> /usr/local/lib/python2.4/encodings/utf_8.pyc
>> Python 2.4.4 (#3, May 15 2014, 00:22:35)
>> [GCC 3.4.4 20050721 (Red Hat 3.4.4-2)] on linux2
>> Type "help", "copyright", "credits" or "license" for more information.
>> dlopen("/usr/local/lib/python2.4/lib-dynload/readline.so", 2);
>> import readline # dynamically loaded from
>> /usr/local/lib/python2.4/lib-dynload/readline.so
>>>>>
>> Tao
>>
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Translator - multiple choice answer

2014-05-14 Thread C Smith
This might be useful for reading values from a text value into a dictionary:
https://stackoverflow.com/questions/17775273/how-to-read-and-store-values-from-a-text-file-into-a-dictionary-python

On Wed, May 14, 2014 at 7:00 PM, Danny Yoo  wrote:
>> Program read TXT file (c:\\slo3.txt)
>> In this file there are two words per line separated by tab.
>> First word is foreign language and second word is proper translation, like
>> this:
>>
>> pivobeer
>> kruhbread
>> rdeca   red
>> krompir potatoe
>> hisahouse
>> cesta   road
>> autocar
>>
>> (not even trying to mess with special characters for now, lol)
>
> Do look at:
>
> http://www.joelonsoftware.com/articles/Unicode.html
>
> because the fact that you're dealing with foreign language means you
> want to get it right.
>
>
> If it were me, I'd just say that the input is UTF-8 encoded text, and
> always open up the file in utf-8 mode.
>
> myfile = open("slo3.txt", "r", encoding="utf8")
>
> and just know that we're working with Unicode from that point forward.
>
>
>
>> I was going to read content into dictionary, each pair as tuple but I gave
>> up, couldn't figure it out. Looks like it is working with the list so no
>> problem.
>>
>> Question 1: would be better to use dictionary, than list?
>
> It depends.
>
> If you're picking out a random entry, then having a dictionary in hand
> is not going to need the key lookup support that dictionaries give
> you.
>
> For the application you're describing right now, it doesn't sound like
> you need this yet.
>
>
>
>> Question 2: slo3.txt is just small sample for now and before I type in all
>> words, I would like to know is it better to use some other separator such as
>> coma or empty space instead of TAB? I found on the internet example for TAB
>> only, so this is what I'm using for now.
>
> TAB is a reasonable separator.  You might also consider comma, as in
> Comma-Separated Values (CSV).
>
> If your data starts having more structure, then check back with folks
> on the tutor mailing list.  There are richer formats you can use, but
> your program's description suggests that you probably don't need the
> complexity yet.
>
>
>
>
>>
>> I need help with two things. First one is simple, basic, but I couldn't
>> figure it out. If I want to print out 'Wrong' part in the same line next
>> to wrong answer, how do I do it?
>
> The print function puts a newline at the end.  You can change this
> default behavior by providing an "end" keyword to it.  The
> documentation mentions it here:
>
> https://docs.python.org/3/library/functions.html#print
>
> Small test program to demonstrate:
>
> 
> print("Hello ", end="")
> print("world ")
> 
>
>
>
>> Now, big, huge help request.
>> I would like to make it easy on my wife :-) instead of her needing to type
>> in answer I would like that she could choose (click on) multiple choice. Say
>> she get 4 or 5 possible answers and one of them is correct. Then she need to
>> click on correct answer...
>>
>> What do I need to do? I understand there will be some graphic/windows things
>> involved. I don't have any additional packages or libraries installed, nor
>> do I know what/how do do it. Complete noob
>
> How about printing them with numbers, so that entry is just a number
> rather than the typed word?
>
>
> You can put a graphical user interface on the program, though it does
> take a bit more effort to get it to work.
>
> Look into "Tkinter", which is a library for producing graphical user 
> interfaces:
>
> https://wiki.python.org/moin/TkInter
>
>
>
> Another option might be to turn your program into a web site, so that
> the interface is the web browser, which everyone is getting used to
> these days.  But this, too, is also... involved.  :P
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While truth

2014-05-20 Thread C Smith
You can test out a condition like this in IDLE like so:
while 6:
print "yes its true"
break


while 0:
print "yes its true"
break


while -1:
print "yes its true"
break


emptyList = []
while emtpyList:
print "yes its true"
break

This way you don't have to deal with an infinite loop.
It will print "yes its true" once, if it IS true and then "break" will
break you out of the loop.

On Tue, May 20, 2014 at 2:00 PM, Danny Yoo  wrote:
> On Tue, May 20, 2014 at 1:25 AM, Ian D  wrote:
>> I was reading a tutorial that had these examples in it:
>>
>>
> while False:
>>   print("False is the new True.")
>>
>>
> while 6:
>>   print("Which numbers are True?")
>>
>>
>> while -1:
>>   print("Which numbers are True?")
>>
>>
>> while 0:
>>   print("Which numbers are True?")
>>
>> Unfortunately the author never explained these statements.
>
>
> The statements above are trying to talk about what Python considers to
> be "true".  In some languages, there is a single distinguished true
> value.  Python chooses a broader definition that allows everything to
> be considered true, with the exception of the following values:
>
> False
> None
> Numeric zero
> Empty collection
> Empty string
>
> Reference: https://docs.python.org/3/reference/expressions.html#booleans
>
> We care about what values are true, because they are the switch that
> controls which way we're flowing through a conditional statement like
> "if" or "while".
>
> As people are pointing out, the examples above are a bit
> disappointing.  They are demonstrating this with infinite while loops,
> and that's probably not a great idea because the output will be so
> overwhelming to be actively distracting.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While truth

2014-05-20 Thread C Smith
Of course that isn't very useful code. I thought it might be a useful
quick test for someone learning how while loops treat different
values.

On Tue, May 20, 2014 at 2:46 PM, Danny Yoo  wrote:
> On Tue, May 20, 2014 at 11:44 AM, C Smith  
> wrote:
>> You can test out a condition like this in IDLE like so:
>> while 6:
>> print "yes its true"
>> break
>>
>>
>> while 0:
>> print "yes its true"
>> break
>>
>>
>> while -1:
>> print "yes its true"
>> break
>>
>>
>> emptyList = []
>> while emtpyList:
>> print "yes its true"
>> break
>>
>> This way you don't have to deal with an infinite loop.
>> It will print "yes its true" once, if it IS true and then "break" will
>> break you out of the loop.
>
>
> That being said, if we're going to go through these contortions, we
> might as well use "if", right?  :P
>
>
> The infinite loops in the examples above are a complete distraction
> from the main point, I think.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Doubts about installing python3.1 in squeeze

2014-05-22 Thread C Smith
Sorry, typing is hard.
*You will need to use virtualenv

On Thu, May 22, 2014 at 2:40 PM, C Smith  wrote:
> You can't use apt-get or similar to install 3.1.
> You will need to virtualenv.
>
> On Thu, May 22, 2014 at 12:22 PM, Alex Kleider  wrote:
>> On 2014-05-22 06:17, Markos wrote:
>>>
>>> Hi,
>>>
>>> I'm learning Python and I'm using Debian 6.0 (squeeze)
>>>
>>> The installed version is 2.6.6. (python -V)
>>>
>>> I have seen some recommendations for beginners to invest in version 3.
>>>
>>> I found package of Python 3.1 in repository for squeeze.
>>>
>>> I am considering installing Python 3.1 with
>>>
>>> apt-get install python3.1
>>>
>>> But I found the site
>>> http://www.circuidipity.com/python2-and-python3.html information on
>>> how to keep the two versions using virtualenv.
>>>
>>> Also I found in the /usr/bin python2.5 and python2.6
>>>
>>> And in /usr/lib python2.4, python2.5 and python2.6
>>>
>>> Can I just run apt-get install python3.1 or should I do any other
>>> configuration?
>>>
>>> I'm confused.
>>>
>>>
>>> Are there any risk to install python3.1 and some programs stop working
>>> on my debian squeeze?
>>>
>>> Thanks for any tips?
>>> Markos
>>
>>
>> On Ubuntu both v2 and v3 are installed by default.
>> Have you tried typing
>> python3
>> on the command line?
>> If you get the interpreter, it's installed.
>> Then you just have to use a different shebang line in your code files:
>> #!/usr/bin/env python3
>>
>> I don't have a debian system close at hand to test this myself.
>>
>> alex
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Doubts about installing python3.1 in squeeze

2014-05-22 Thread C Smith
You can't use apt-get or similar to install 3.1.
You will need to virtualenv.

On Thu, May 22, 2014 at 12:22 PM, Alex Kleider  wrote:
> On 2014-05-22 06:17, Markos wrote:
>>
>> Hi,
>>
>> I'm learning Python and I'm using Debian 6.0 (squeeze)
>>
>> The installed version is 2.6.6. (python -V)
>>
>> I have seen some recommendations for beginners to invest in version 3.
>>
>> I found package of Python 3.1 in repository for squeeze.
>>
>> I am considering installing Python 3.1 with
>>
>> apt-get install python3.1
>>
>> But I found the site
>> http://www.circuidipity.com/python2-and-python3.html information on
>> how to keep the two versions using virtualenv.
>>
>> Also I found in the /usr/bin python2.5 and python2.6
>>
>> And in /usr/lib python2.4, python2.5 and python2.6
>>
>> Can I just run apt-get install python3.1 or should I do any other
>> configuration?
>>
>> I'm confused.
>>
>>
>> Are there any risk to install python3.1 and some programs stop working
>> on my debian squeeze?
>>
>> Thanks for any tips?
>> Markos
>
>
> On Ubuntu both v2 and v3 are installed by default.
> Have you tried typing
> python3
> on the command line?
> If you get the interpreter, it's installed.
> Then you just have to use a different shebang line in your code files:
> #!/usr/bin/env python3
>
> I don't have a debian system close at hand to test this myself.
>
> alex
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What are your favourite unofficial resources

2014-06-30 Thread C Smith
Learning Python Design Patterns, by Gennadiy Zlobin
Let us know when your book is done!

On Mon, Jun 30, 2014 at 7:05 AM, Bob Williams
 wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> On 29/06/14 23:41, Alan Gauld wrote:
>> I'm looking for tips for an appendix to a book that I'm working
>> on.
>>
>> What are the best unofficial (ie not python.org) resources for
>> people who have learned the basics but are not experts yet? ie
>> Typical tutor list "graduates"...
>>
>> I'm thinking about web sites, blogs, books, videos etc. Anything
>> that might be worth knowing about.
>>
>> I've got a few of my own - Activestate, O'Reilly, ByteOfPython,
>> PythonChallenge, ShowMeDo etc.
>>
>> But I thought the tutor list readers might be an interesting source
>> of alternatives that I hadn't thought of, or even heard of.
>>
>> All contributions considered :-)
>>
>
> Python Module of the Week 
>
> Bob
> - --
> Bob Williams
> System:  Linux 3.11.10-17-desktop
> Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.13.2
> Uptime:  06:00am up 1 day 20:14, 0 users, load average: 0.04, 0.05, 0.05
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v2.0.22 (GNU/Linux)
> Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/
>
> iEYEARECAAYFAlOxRIsACgkQ0Sr7eZJrmU5kfQCgkE0dRzO1G+o/GX78s4U7oe3U
> mNQAoJ+ayTo+79Xj+9JaHoMrflxDHCzW
> =uWQJ
> -END PGP SIGNATURE-
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why is Quick Search at docs.Python.org so useless?

2014-07-05 Thread C Smith
I agree very much. I feel like I might have a learning disability when
I try to reference the official Python docs for something that seems
like it should be a very common task.

On Sat, Jul 5, 2014 at 1:31 PM, Deb Wyatt  wrote:
> I am betting that a big reason newbies don't go straight to documentation for 
> answers is because of the useless quick search.  You should be able to type 
> 'dictionary' and get links to the dictionary info.  You get a bunch of links 
> that are meaningless to someone who wants to learn about how to use 
> dictionaries.  It frustrates me to death when I want to look up a detail 
> about how a particular function works and I can't find it because quick 
> search doesn't provide the link to the BASIC information.
>
> Another example of what I am talking about, I just did a search of max(), a 
> BUILT-IN function.  This is what quick search gives me:
>
> Your search did not match any documents. Please make sure that all words are 
> spelled correctly and that you've selected enough categories.
>
> What is up with that???
>
> I realize that this list doesn't have control over python.org, but there are 
> enough of you who are experts about all this stuff that maybe some changes 
> can be made.  If I ever learn enough, I hope to be part of the solution 
> myself.  A working search engine would be most helpful.
>
> Yes, I use Google all that time. But quick search should be useful. Thanks in 
> advance for any insights and help.
>
>
> Deb in WA, USA
>
> 
> Receive Notifications of Incoming Messages
> Easily monitor multiple email accounts & access them with a click.
> Visit http://www.inbox.com/notifier and check it out!
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
I am on OSX, which needs to escape spaces in filenames with a backslash.
There are multiple files within one directory that all have the same
structure, one or more characters with zero or more spaces in the
filename, like this:
3 Song Title XYZ.flac.
I want to use Python to call ffmpeg to convert each file to an .mp3.
So far this is what I was trying to use:
import os, subprocess
track = 1
for filename in os.listdir('myDir'):
subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
track += 1


I am about to use re.sub to just replace all the '/s' with '\\/s', but
is there a simpler/more pythonic way to do this?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
>Change:


>subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

>to:

>subprocess.call(['ffmpeg', '-i', '"%s"' % filename, str(track)+'.mp3'])

I still get the same errors, the filenames are passed to the shell
without escaping the spaces.

>Why not using ffmpeg without jumping into Python. It's well documented, check 
>Google.

I guess you mean that the ability to change multiple files with ffmpeg
is possible. I hadn't considered that but I would rather do it with
Python, just for the practice.

On Thu, Jul 31, 2014 at 4:36 PM, Emile  wrote:
> On 7/31/2014 1:19 PM, C Smith wrote:
>>
>> I get
>> TypeError: unsupported operand type(s) for %: 'int' and 'str
>> I am not understanding the use of the list inside the subprocess.call().
>> I tried all of the following
>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3']) % filename
>> --gives type error stated above
>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3'] % filename)
>> --same
>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3' % filename])
>> -- TypeError: not all arguments converted during string formatting
>> and tried all three with the triple quotes, just to be sure.
>>
>> On Thu, Jul 31, 2014 at 4:04 PM, Emile van Sebille  wrote:
>>>
>>> You might try using '"%s"' % filename so that the name is within quotes
>>> for the shell environment.
>
>
> Change:
>
>
> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>
> to:
>
> subprocess.call(['ffmpeg', '-i', '"%s"' % filename, str(track)+'.mp3'])
>
> Emile
>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
Even when I am using:
re.sub('/s', '\\/s', filename)
I am still getting the same output, even trying to assign the above to
a new variable doesn't work (as I wasn't sure if re.sub returned a new
value or changed filename in place, I tried both with)
Does the Python interpreter strip off backslashes or something with strings?

On Thu, Jul 31, 2014 at 5:53 PM, C Smith  wrote:
>>Change:
>
>
>>subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>
>>to:
>
>>subprocess.call(['ffmpeg', '-i', '"%s"' % filename, str(track)+'.mp3'])
>
> I still get the same errors, the filenames are passed to the shell
> without escaping the spaces.
>
>>Why not using ffmpeg without jumping into Python. It's well documented, check 
>>Google.
>
> I guess you mean that the ability to change multiple files with ffmpeg
> is possible. I hadn't considered that but I would rather do it with
> Python, just for the practice.
>
> On Thu, Jul 31, 2014 at 4:36 PM, Emile  wrote:
>> On 7/31/2014 1:19 PM, C Smith wrote:
>>>
>>> I get
>>> TypeError: unsupported operand type(s) for %: 'int' and 'str
>>> I am not understanding the use of the list inside the subprocess.call().
>>> I tried all of the following
>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3']) % filename
>>> --gives type error stated above
>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3'] % filename)
>>> --same
>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3' % filename])
>>> -- TypeError: not all arguments converted during string formatting
>>> and tried all three with the triple quotes, just to be sure.
>>>
>>> On Thu, Jul 31, 2014 at 4:04 PM, Emile van Sebille  wrote:
>>>>
>>>> You might try using '"%s"' % filename so that the name is within quotes
>>>> for the shell environment.
>>
>>
>> Change:
>>
>>
>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>
>> to:
>>
>> subprocess.call(['ffmpeg', '-i', '"%s"' % filename, str(track)+'.mp3'])
>>
>> Emile
>>
>>
>>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
Okay I messed up with slash instead of backslash, so the re.sub()
works, but I am still curious about the previous question.

On Thu, Jul 31, 2014 at 6:14 PM, C Smith  wrote:
> Even when I am using:
> re.sub('/s', '\\/s', filename)
> I am still getting the same output, even trying to assign the above to
> a new variable doesn't work (as I wasn't sure if re.sub returned a new
> value or changed filename in place, I tried both with)
> Does the Python interpreter strip off backslashes or something with strings?
>
> On Thu, Jul 31, 2014 at 5:53 PM, C Smith  wrote:
>>>Change:
>>
>>
>>>subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>
>>>to:
>>
>>>subprocess.call(['ffmpeg', '-i', '"%s"' % filename, str(track)+'.mp3'])
>>
>> I still get the same errors, the filenames are passed to the shell
>> without escaping the spaces.
>>
>>>Why not using ffmpeg without jumping into Python. It's well documented, 
>>>check Google.
>>
>> I guess you mean that the ability to change multiple files with ffmpeg
>> is possible. I hadn't considered that but I would rather do it with
>> Python, just for the practice.
>>
>> On Thu, Jul 31, 2014 at 4:36 PM, Emile  wrote:
>>> On 7/31/2014 1:19 PM, C Smith wrote:
>>>>
>>>> I get
>>>> TypeError: unsupported operand type(s) for %: 'int' and 'str
>>>> I am not understanding the use of the list inside the subprocess.call().
>>>> I tried all of the following
>>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3']) % filename
>>>> --gives type error stated above
>>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3'] % filename)
>>>> --same
>>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3' % filename])
>>>> -- TypeError: not all arguments converted during string formatting
>>>> and tried all three with the triple quotes, just to be sure.
>>>>
>>>> On Thu, Jul 31, 2014 at 4:04 PM, Emile van Sebille  wrote:
>>>>>
>>>>> You might try using '"%s"' % filename so that the name is within quotes
>>>>> for the shell environment.
>>>
>>>
>>> Change:
>>>
>>>
>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>>
>>> to:
>>>
>>> subprocess.call(['ffmpeg', '-i', '"%s"' % filename, str(track)+'.mp3'])
>>>
>>> Emile
>>>
>>>
>>>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
Actually, I can get re.sub() to print the filenames where they look
like they would be in the correct format for the shell, like this:
10\ track \number \ten.flac
but the shell still says that no such file exists, and I am sure I am
operating on them in the right place because I can modify them. So, I
am still wondering about that too.

On Thu, Jul 31, 2014 at 6:20 PM, C Smith  wrote:
> Okay I messed up with slash instead of backslash, so the re.sub()
> works, but I am still curious about the previous question.
>
> On Thu, Jul 31, 2014 at 6:14 PM, C Smith  wrote:
>> Even when I am using:
>> re.sub('/s', '\\/s', filename)
>> I am still getting the same output, even trying to assign the above to
>> a new variable doesn't work (as I wasn't sure if re.sub returned a new
>> value or changed filename in place, I tried both with)
>> Does the Python interpreter strip off backslashes or something with strings?
>>
>> On Thu, Jul 31, 2014 at 5:53 PM, C Smith  
>> wrote:
>>>>Change:
>>>
>>>
>>>>subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>>
>>>>to:
>>>
>>>>subprocess.call(['ffmpeg', '-i', '"%s"' % filename, str(track)+'.mp3'])
>>>
>>> I still get the same errors, the filenames are passed to the shell
>>> without escaping the spaces.
>>>
>>>>Why not using ffmpeg without jumping into Python. It's well documented, 
>>>>check Google.
>>>
>>> I guess you mean that the ability to change multiple files with ffmpeg
>>> is possible. I hadn't considered that but I would rather do it with
>>> Python, just for the practice.
>>>
>>> On Thu, Jul 31, 2014 at 4:36 PM, Emile  wrote:
>>>> On 7/31/2014 1:19 PM, C Smith wrote:
>>>>>
>>>>> I get
>>>>> TypeError: unsupported operand type(s) for %: 'int' and 'str
>>>>> I am not understanding the use of the list inside the subprocess.call().
>>>>> I tried all of the following
>>>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3']) % filename
>>>>> --gives type error stated above
>>>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3'] % filename)
>>>>> --same
>>>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3' % filename])
>>>>> -- TypeError: not all arguments converted during string formatting
>>>>> and tried all three with the triple quotes, just to be sure.
>>>>>
>>>>> On Thu, Jul 31, 2014 at 4:04 PM, Emile van Sebille  wrote:
>>>>>>
>>>>>> You might try using '"%s"' % filename so that the name is within quotes
>>>>>> for the shell environment.
>>>>
>>>>
>>>> Change:
>>>>
>>>>
>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>>>
>>>> to:
>>>>
>>>> subprocess.call(['ffmpeg', '-i', '"%s"' % filename, str(track)+'.mp3'])
>>>>
>>>> Emile
>>>>
>>>>
>>>>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
>for track, filename in enumerate(os.listdir(directory), 1):
It seems kinda counter-intuitive to have track then filename as
variables, but enumerate looks like it gets passed the filename then
track number. Is that correct and just the way enumerate works, a
typo, or am I missing something else here?

It is an ffmpeg error I am getting.
ffmpeg just gives its usual build information and the error is (for
each song title in the directory):
songTitleIsHere.flac: no such file or directory

So it looks like it is close to working because it finds the correct
file names, but doesn't recognize it for some reason.
Here is how I put in your code
import os, subprocess
directory = '/absolute/path/goes/here'
for track, filename in enumerate(os.listdir(directory), 1):
pathname = os.path.join(directory, filename)
subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])

So it goes to the right place, because every song title is listed out,
ffmpeg or the shell just don't recognize them correctly.

On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano  wrote:
> You may have already have solved your problem, unfortunately my
> emails are coming in slowly and out of order, but I have a suggestion:
>
> On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
>> I am on OSX, which needs to escape spaces in filenames with a backslash.
>
> Same as any other Unix, or Linux, or, indeed, Windows.
>
>> There are multiple files within one directory that all have the same
>> structure, one or more characters with zero or more spaces in the
>> filename, like this:
>> 3 Song Title XYZ.flac.
>> I want to use Python to call ffmpeg to convert each file to an .mp3.
>> So far this is what I was trying to use:
>> import os, subprocess
>> track = 1
>> for filename in os.listdir('myDir'):
>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>> track += 1
>
> I believe that your problem is *not* the spaces, but that you're passing
> just the filename and not the directory. subprocess will escape the
> spaces for you. Also, let Python count the track number for you. Try
> this:
>
>
> directory = '/path/to/the/directory'
> for track, filename in enumerate(os.listdir(directory), 1):
> pathname = os.path.join(directory, filename)
> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>
>
> I expect something like that will work. You should be able to pass
> either an absolute path (beginning with /) or a relative path starting
> from the current working directory.
>
> If this doesn't work, please show the full error that you receive. If it
> is a Python traceback, copy and paste the whole thing, if it's an ffmpeg
> error, give as much information as you can.
>
>
>
> --
> Steven
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
woops, I see it pathname != filename

On Thu, Jul 31, 2014 at 6:55 PM, C Smith  wrote:
>>for track, filename in enumerate(os.listdir(directory), 1):
> It seems kinda counter-intuitive to have track then filename as
> variables, but enumerate looks like it gets passed the filename then
> track number. Is that correct and just the way enumerate works, a
> typo, or am I missing something else here?
>
> It is an ffmpeg error I am getting.
> ffmpeg just gives its usual build information and the error is (for
> each song title in the directory):
> songTitleIsHere.flac: no such file or directory
>
> So it looks like it is close to working because it finds the correct
> file names, but doesn't recognize it for some reason.
> Here is how I put in your code
> import os, subprocess
> directory = '/absolute/path/goes/here'
> for track, filename in enumerate(os.listdir(directory), 1):
> pathname = os.path.join(directory, filename)
> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>
> So it goes to the right place, because every song title is listed out,
> ffmpeg or the shell just don't recognize them correctly.
>
> On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano  wrote:
>> You may have already have solved your problem, unfortunately my
>> emails are coming in slowly and out of order, but I have a suggestion:
>>
>> On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
>>> I am on OSX, which needs to escape spaces in filenames with a backslash.
>>
>> Same as any other Unix, or Linux, or, indeed, Windows.
>>
>>> There are multiple files within one directory that all have the same
>>> structure, one or more characters with zero or more spaces in the
>>> filename, like this:
>>> 3 Song Title XYZ.flac.
>>> I want to use Python to call ffmpeg to convert each file to an .mp3.
>>> So far this is what I was trying to use:
>>> import os, subprocess
>>> track = 1
>>> for filename in os.listdir('myDir'):
>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>> track += 1
>>
>> I believe that your problem is *not* the spaces, but that you're passing
>> just the filename and not the directory. subprocess will escape the
>> spaces for you. Also, let Python count the track number for you. Try
>> this:
>>
>>
>> directory = '/path/to/the/directory'
>> for track, filename in enumerate(os.listdir(directory), 1):
>> pathname = os.path.join(directory, filename)
>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>
>>
>> I expect something like that will work. You should be able to pass
>> either an absolute path (beginning with /) or a relative path starting
>> from the current working directory.
>>
>> If this doesn't work, please show the full error that you receive. If it
>> is a Python traceback, copy and paste the whole thing, if it's an ffmpeg
>> error, give as much information as you can.
>>
>>
>>
>> --
>> Steven
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
Works now, thanks!

On Thu, Jul 31, 2014 at 6:57 PM, C Smith  wrote:
> woops, I see it pathname != filename
>
> On Thu, Jul 31, 2014 at 6:55 PM, C Smith  wrote:
>>>for track, filename in enumerate(os.listdir(directory), 1):
>> It seems kinda counter-intuitive to have track then filename as
>> variables, but enumerate looks like it gets passed the filename then
>> track number. Is that correct and just the way enumerate works, a
>> typo, or am I missing something else here?
>>
>> It is an ffmpeg error I am getting.
>> ffmpeg just gives its usual build information and the error is (for
>> each song title in the directory):
>> songTitleIsHere.flac: no such file or directory
>>
>> So it looks like it is close to working because it finds the correct
>> file names, but doesn't recognize it for some reason.
>> Here is how I put in your code
>> import os, subprocess
>> directory = '/absolute/path/goes/here'
>> for track, filename in enumerate(os.listdir(directory), 1):
>> pathname = os.path.join(directory, filename)
>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>
>> So it goes to the right place, because every song title is listed out,
>> ffmpeg or the shell just don't recognize them correctly.
>>
>> On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano  wrote:
>>> You may have already have solved your problem, unfortunately my
>>> emails are coming in slowly and out of order, but I have a suggestion:
>>>
>>> On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
>>>> I am on OSX, which needs to escape spaces in filenames with a backslash.
>>>
>>> Same as any other Unix, or Linux, or, indeed, Windows.
>>>
>>>> There are multiple files within one directory that all have the same
>>>> structure, one or more characters with zero or more spaces in the
>>>> filename, like this:
>>>> 3 Song Title XYZ.flac.
>>>> I want to use Python to call ffmpeg to convert each file to an .mp3.
>>>> So far this is what I was trying to use:
>>>> import os, subprocess
>>>> track = 1
>>>> for filename in os.listdir('myDir'):
>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>>> track += 1
>>>
>>> I believe that your problem is *not* the spaces, but that you're passing
>>> just the filename and not the directory. subprocess will escape the
>>> spaces for you. Also, let Python count the track number for you. Try
>>> this:
>>>
>>>
>>> directory = '/path/to/the/directory'
>>> for track, filename in enumerate(os.listdir(directory), 1):
>>> pathname = os.path.join(directory, filename)
>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>>
>>>
>>> I expect something like that will work. You should be able to pass
>>> either an absolute path (beginning with /) or a relative path starting
>>> from the current working directory.
>>>
>>> If this doesn't work, please show the full error that you receive. If it
>>> is a Python traceback, copy and paste the whole thing, if it's an ffmpeg
>>> error, give as much information as you can.
>>>
>>>
>>>
>>> --
>>> Steven
>>> ___
>>> Tutor maillist  -  Tutor@python.org
>>> To unsubscribe or change subscription options:
>>> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
Huh, that is quite an annoyance about changing the order though. Any
ideas about that? I will look into it further in the meantime...

On Thu, Jul 31, 2014 at 6:57 PM, C Smith  wrote:
> Works now, thanks!
>
> On Thu, Jul 31, 2014 at 6:57 PM, C Smith  wrote:
>> woops, I see it pathname != filename
>>
>> On Thu, Jul 31, 2014 at 6:55 PM, C Smith  
>> wrote:
>>>>for track, filename in enumerate(os.listdir(directory), 1):
>>> It seems kinda counter-intuitive to have track then filename as
>>> variables, but enumerate looks like it gets passed the filename then
>>> track number. Is that correct and just the way enumerate works, a
>>> typo, or am I missing something else here?
>>>
>>> It is an ffmpeg error I am getting.
>>> ffmpeg just gives its usual build information and the error is (for
>>> each song title in the directory):
>>> songTitleIsHere.flac: no such file or directory
>>>
>>> So it looks like it is close to working because it finds the correct
>>> file names, but doesn't recognize it for some reason.
>>> Here is how I put in your code
>>> import os, subprocess
>>> directory = '/absolute/path/goes/here'
>>> for track, filename in enumerate(os.listdir(directory), 1):
>>> pathname = os.path.join(directory, filename)
>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>>
>>> So it goes to the right place, because every song title is listed out,
>>> ffmpeg or the shell just don't recognize them correctly.
>>>
>>> On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano  
>>> wrote:
>>>> You may have already have solved your problem, unfortunately my
>>>> emails are coming in slowly and out of order, but I have a suggestion:
>>>>
>>>> On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
>>>>> I am on OSX, which needs to escape spaces in filenames with a backslash.
>>>>
>>>> Same as any other Unix, or Linux, or, indeed, Windows.
>>>>
>>>>> There are multiple files within one directory that all have the same
>>>>> structure, one or more characters with zero or more spaces in the
>>>>> filename, like this:
>>>>> 3 Song Title XYZ.flac.
>>>>> I want to use Python to call ffmpeg to convert each file to an .mp3.
>>>>> So far this is what I was trying to use:
>>>>> import os, subprocess
>>>>> track = 1
>>>>> for filename in os.listdir('myDir'):
>>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>>>> track += 1
>>>>
>>>> I believe that your problem is *not* the spaces, but that you're passing
>>>> just the filename and not the directory. subprocess will escape the
>>>> spaces for you. Also, let Python count the track number for you. Try
>>>> this:
>>>>
>>>>
>>>> directory = '/path/to/the/directory'
>>>> for track, filename in enumerate(os.listdir(directory), 1):
>>>> pathname = os.path.join(directory, filename)
>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>>>
>>>>
>>>> I expect something like that will work. You should be able to pass
>>>> either an absolute path (beginning with /) or a relative path starting
>>>> from the current working directory.
>>>>
>>>> If this doesn't work, please show the full error that you receive. If it
>>>> is a Python traceback, copy and paste the whole thing, if it's an ffmpeg
>>>> error, give as much information as you can.
>>>>
>>>>
>>>>
>>>> --
>>>> Steven
>>>> ___
>>>> Tutor maillist  -  Tutor@python.org
>>>> To unsubscribe or change subscription options:
>>>> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
thanks, got it
import os, subprocess, re
directory = 'abs/path'
for track, filename in enumerate(os.listdir(directory), 1):
pathname = os.path.join(directory, filename)
subprocess.call(['ffmpeg', '-i', pathname, filename+str(track)+'.mp3'])

On Thu, Jul 31, 2014 at 7:02 PM, C Smith  wrote:
> Huh, that is quite an annoyance about changing the order though. Any
> ideas about that? I will look into it further in the meantime...
>
> On Thu, Jul 31, 2014 at 6:57 PM, C Smith  wrote:
>> Works now, thanks!
>>
>> On Thu, Jul 31, 2014 at 6:57 PM, C Smith  
>> wrote:
>>> woops, I see it pathname != filename
>>>
>>> On Thu, Jul 31, 2014 at 6:55 PM, C Smith  
>>> wrote:
>>>>>for track, filename in enumerate(os.listdir(directory), 1):
>>>> It seems kinda counter-intuitive to have track then filename as
>>>> variables, but enumerate looks like it gets passed the filename then
>>>> track number. Is that correct and just the way enumerate works, a
>>>> typo, or am I missing something else here?
>>>>
>>>> It is an ffmpeg error I am getting.
>>>> ffmpeg just gives its usual build information and the error is (for
>>>> each song title in the directory):
>>>> songTitleIsHere.flac: no such file or directory
>>>>
>>>> So it looks like it is close to working because it finds the correct
>>>> file names, but doesn't recognize it for some reason.
>>>> Here is how I put in your code
>>>> import os, subprocess
>>>> directory = '/absolute/path/goes/here'
>>>> for track, filename in enumerate(os.listdir(directory), 1):
>>>> pathname = os.path.join(directory, filename)
>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>>>
>>>> So it goes to the right place, because every song title is listed out,
>>>> ffmpeg or the shell just don't recognize them correctly.
>>>>
>>>> On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano  
>>>> wrote:
>>>>> You may have already have solved your problem, unfortunately my
>>>>> emails are coming in slowly and out of order, but I have a suggestion:
>>>>>
>>>>> On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
>>>>>> I am on OSX, which needs to escape spaces in filenames with a backslash.
>>>>>
>>>>> Same as any other Unix, or Linux, or, indeed, Windows.
>>>>>
>>>>>> There are multiple files within one directory that all have the same
>>>>>> structure, one or more characters with zero or more spaces in the
>>>>>> filename, like this:
>>>>>> 3 Song Title XYZ.flac.
>>>>>> I want to use Python to call ffmpeg to convert each file to an .mp3.
>>>>>> So far this is what I was trying to use:
>>>>>> import os, subprocess
>>>>>> track = 1
>>>>>> for filename in os.listdir('myDir'):
>>>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>>>>> track += 1
>>>>>
>>>>> I believe that your problem is *not* the spaces, but that you're passing
>>>>> just the filename and not the directory. subprocess will escape the
>>>>> spaces for you. Also, let Python count the track number for you. Try
>>>>> this:
>>>>>
>>>>>
>>>>> directory = '/path/to/the/directory'
>>>>> for track, filename in enumerate(os.listdir(directory), 1):
>>>>> pathname = os.path.join(directory, filename)
>>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>>>>
>>>>>
>>>>> I expect something like that will work. You should be able to pass
>>>>> either an absolute path (beginning with /) or a relative path starting
>>>>> from the current working directory.
>>>>>
>>>>> If this doesn't work, please show the full error that you receive. If it
>>>>> is a Python traceback, copy and paste the whole thing, if it's an ffmpeg
>>>>> error, give as much information as you can.
>>>>>
>>>>>
>>>>>
>>>>> --
>>>>> Steven
>>>>> ___
>>>>> Tutor maillist  -  Tutor@python.org
>>>>> To unsubscribe or change subscription options:
>>>>> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
or more accurately
import os, subprocess, re
directory = '/abs/path'
for track, filename in enumerate(os.listdir(directory), 1):
pathname = os.path.join(directory, filename)
subprocess.call(['ffmpeg', '-i', pathname, filename[:-5]+'.mp3'])

On Thu, Jul 31, 2014 at 7:13 PM, C Smith  wrote:
> thanks, got it
> import os, subprocess, re
> directory = 'abs/path'
> for track, filename in enumerate(os.listdir(directory), 1):
> pathname = os.path.join(directory, filename)
> subprocess.call(['ffmpeg', '-i', pathname, filename+str(track)+'.mp3'])
>
> On Thu, Jul 31, 2014 at 7:02 PM, C Smith  wrote:
>> Huh, that is quite an annoyance about changing the order though. Any
>> ideas about that? I will look into it further in the meantime...
>>
>> On Thu, Jul 31, 2014 at 6:57 PM, C Smith  
>> wrote:
>>> Works now, thanks!
>>>
>>> On Thu, Jul 31, 2014 at 6:57 PM, C Smith  
>>> wrote:
>>>> woops, I see it pathname != filename
>>>>
>>>> On Thu, Jul 31, 2014 at 6:55 PM, C Smith  
>>>> wrote:
>>>>>>for track, filename in enumerate(os.listdir(directory), 1):
>>>>> It seems kinda counter-intuitive to have track then filename as
>>>>> variables, but enumerate looks like it gets passed the filename then
>>>>> track number. Is that correct and just the way enumerate works, a
>>>>> typo, or am I missing something else here?
>>>>>
>>>>> It is an ffmpeg error I am getting.
>>>>> ffmpeg just gives its usual build information and the error is (for
>>>>> each song title in the directory):
>>>>> songTitleIsHere.flac: no such file or directory
>>>>>
>>>>> So it looks like it is close to working because it finds the correct
>>>>> file names, but doesn't recognize it for some reason.
>>>>> Here is how I put in your code
>>>>> import os, subprocess
>>>>> directory = '/absolute/path/goes/here'
>>>>> for track, filename in enumerate(os.listdir(directory), 1):
>>>>> pathname = os.path.join(directory, filename)
>>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>>>>
>>>>> So it goes to the right place, because every song title is listed out,
>>>>> ffmpeg or the shell just don't recognize them correctly.
>>>>>
>>>>> On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano  
>>>>> wrote:
>>>>>> You may have already have solved your problem, unfortunately my
>>>>>> emails are coming in slowly and out of order, but I have a suggestion:
>>>>>>
>>>>>> On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
>>>>>>> I am on OSX, which needs to escape spaces in filenames with a backslash.
>>>>>>
>>>>>> Same as any other Unix, or Linux, or, indeed, Windows.
>>>>>>
>>>>>>> There are multiple files within one directory that all have the same
>>>>>>> structure, one or more characters with zero or more spaces in the
>>>>>>> filename, like this:
>>>>>>> 3 Song Title XYZ.flac.
>>>>>>> I want to use Python to call ffmpeg to convert each file to an .mp3.
>>>>>>> So far this is what I was trying to use:
>>>>>>> import os, subprocess
>>>>>>> track = 1
>>>>>>> for filename in os.listdir('myDir'):
>>>>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>>>>>> track += 1
>>>>>>
>>>>>> I believe that your problem is *not* the spaces, but that you're passing
>>>>>> just the filename and not the directory. subprocess will escape the
>>>>>> spaces for you. Also, let Python count the track number for you. Try
>>>>>> this:
>>>>>>
>>>>>>
>>>>>> directory = '/path/to/the/directory'
>>>>>> for track, filename in enumerate(os.listdir(directory), 1):
>>>>>> pathname = os.path.join(directory, filename)
>>>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>>>>>
>>>>>>
>>>>>> I expect something like that will work. You should be able to pass
>>>>>> either an absolute path (beginning with /) or a relative path starting
>>>>>> from the current working directory.
>>>>>>
>>>>>> If this doesn't work, please show the full error that you receive. If it
>>>>>> is a Python traceback, copy and paste the whole thing, if it's an ffmpeg
>>>>>> error, give as much information as you can.
>>>>>>
>>>>>>
>>>>>>
>>>>>> --
>>>>>> Steven
>>>>>> ___
>>>>>> Tutor maillist  -  Tutor@python.org
>>>>>> To unsubscribe or change subscription options:
>>>>>> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-07-31 Thread C Smith
Nice, these are useful tools. I have been building something with just
basic stuff and avoiding learning any libraries. If I wanted to get
some insight on a larger program that is about 1000 lines, would that
be doable here?

On Thu, Jul 31, 2014 at 7:37 PM, Peter Otten <__pete...@web.de> wrote:
> C Smith wrote:
>
> I'd throw in a check to verify that filename is indeed a flac:
>
>> or more accurately
>> import os, subprocess, re
>> directory = '/abs/path'
>> for track, filename in enumerate(os.listdir(directory), 1):
>> pathname = os.path.join(directory, filename)
>   if filename.endswith(".flac"):
>   subprocess.call(['ffmpeg', '-i', pathname, filename[:-5]+'.mp3'])
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-08-01 Thread C Smith
>However, the subprocess call above uses a list for the command, and that form 
>DOES NOT pass anything to the shell. The >command gets executed directly. And 
>therefore no spaces need escaping at all.

That makes more sense to me now.

In terms of the code review, I found that stackexchange has a code
review site, in case anyone else is curious:
https://codereview.stackexchange.com
It would be hard to post a sscc example since the parts I am curious
about reference other class variables that would be unclear out of
context, I think.
Much appreciated...

On Fri, Aug 1, 2014 at 4:38 AM, Ben Finney  wrote:
> Peter Otten <__pete...@web.de> writes:
>
>> C Smith wrote:
>>
>> > Nice, these are useful tools. I have been building something with
>> > just basic stuff and avoiding learning any libraries. If I wanted to
>> > get some insight on a larger program that is about 1000 lines, would
>> > that be doable here?
>>
>> In general we prefer concrete questions and smaller chunks of code.
>> With 1000 lines you get fewer people to even take a look.
>
> Right. When attrmpting to learn, keep the examples simple. This will
> make it easier to focus on the essential points, and also minimise whole
> categories of error.
>
> To get feedback on some code, make it a Short, Self-Contained,
> Compilable Example http://sscce.org/>. This means we will be able
> to read the code quickly, run it ourselves, and better see what its
> purpose is.
>
>> You might still try and post a link to the code together with a few
>> questions here...
>
> Not really advised. If the code is too long to discuss in context here,
> much of the point is lost; we prefer discussions to have the code inline
> so the public archives contain the code too. That's an important reason
> to keep it short and self-contained.
>
> --
>  \   “I bought some batteries, but they weren't included; so I had |
>   `\to buy them again.” —Steven Wright |
> _o__)  |
> Ben Finney
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using subprocess on a series of files with spaces

2014-08-01 Thread C Smith
>Won't that write the mp3 to the current working dir? (Is that the dir where 
>the .py lives? Or even the Python bin dir? Perhaps >the cwd parameter of 
>call() will be good?

Yeah, it just wrote the mp3's to my desktop, where I had the .py
script. But that was fine for my purposes. Just for curiosity's sake,
would you put cwd outside the list and inside the parens of the
subprocess.call()?

On Fri, Aug 1, 2014 at 4:23 PM, Albert-Jan Roskam
 wrote:
>
>
>
> --
> On Fri, Aug 1, 2014 12:35 AM CEST Steven D'Aprano wrote:
>
>>You may have already have solved your problem, unfortunately my
>>emails are coming in slowly and out of order, but I have a suggestion:
>>
>>On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote:
>>> I am on OSX, which needs to escape spaces in filenames with a backslash.
>>
>>Same as any other Unix, or Linux, or, indeed, Windows.
>>
>>> There are multiple files within one directory that all have the same
>>> structure, one or more characters with zero or more spaces in the
>>> filename, like this:
>>> 3 Song Title XYZ.flac.
>>> I want to use Python to call ffmpeg to convert each file to an .mp3.
>>> So far this is what I was trying to use:
>>> import os, subprocess
>>> track = 1
>>> for filename in os.listdir('myDir'):
>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>> track += 1
>>
>>I believe that your problem is *not* the spaces, but that you're passing
>>just the filename and not the directory. subprocess will escape the
>>spaces for you. Also, let Python count the track number for you. Try
>>this:
>>
>>
>>directory = '/path/to/the/directory'
>>for track, filename in enumerate(os.listdir(directory), 1):
>>pathname = os.path.join(directory, filename)
>>subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>
> Won't that write the mp3 to the current working dir? (Is that the dir where 
> the .py lives? Or even the Python bin dir? Perhaps the cwd parameter of 
> call() will be good?
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2014-09-18 Thread C Smith
Check this guy's youtube channel. He has very basic examples. His
username is thenewboston

On Wed, Sep 17, 2014 at 4:36 PM, Art Pelletier  wrote:
>
> I am a beginner with pythons programming   I would like to see if their is a 
> site that has samples programs that I can practice on.
> Sent from my iPad
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor