Re: Append to python List

2013-05-09 Thread Gary Herron

On 05/08/2013 11:36 PM, RAHUL RAJ wrote:

Checkout the following code:

sample2 = [x+y for x in range(1,10) for y in range(1,10) if x!=y]
output=[]



output=[x for x in sample2 if x not in output]
This statement is not doing what you expect.  It is not building a list 
in the variable named output, it is building a list (anonymously) then 
binding it to the variable output once it's built.  Therefore output is 
[] for the whole list building operation.


The later operation works, because your *are* building the list in place 
as you go.




the output I get is
3 4 5 6 7 8 9 10 3 5 6 7 8 9 10 11 4 5 7 8 9 10 11 12 5 6 7 9 10 11 12 13 6 7 8 
9 11 12 13 14 7 8 9 10 11 13 14 15 8 9 10 11 12 13 15 16 9 10 11 12 13 14 15 17 
10 11 12 13 14 15 16 17

which contains duplicate values.




But if I do like this:

sample2 = [x+y for x in range(1,10) for y in range(1,10) if x!=y]
output=[]
for x in sample2:
   if x not in output:
  output.append(x)


the value of 'output' I get like this:
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

I know that both the programs have the same functionality, but why do I have 
different outputs?

Please help!


--
http://mail.python.org/mailman/listinfo/python-list


Re: create new python file

2013-06-04 Thread Gary Herron

On 06/04/2013 09:07 AM, kakararunachalserv...@gmail.com wrote:

Hi,
Can anyone please tell me how to dynamically create a new python file within a 
program???


What do you mean by a "python file"?   If you mean a text file 
containing python code, then create it like any other text file. For 
instance:


with open("Hello.py", "w") as f:
print("print('Hello world')\n", file=f)

will create a file containing a simple one-line Python program.

If you meant something else, then please take the time to provide more 
detail.


Gary Herron


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: Default Value

2013-06-19 Thread Gary Herron

On 06/19/2013 12:17 PM, Ahmed Abdulshafy wrote:

I'm reading the Python.org tutorial right now, and I found this part rather 
strange and incomprehensible to me>

Important warning: The default value is evaluated only once. This makes a 
difference when the default is a mutable object such as a list, dictionary, or 
instances of most classes


This code:

def f(a, L=[]):
 L.append(a)
 return L


does the same as this code:

M=[]
def f(a, L=M):
L.append(a)
return L

where it's slightly more obvious that the list is created once, and 
modified with each call to the function (or rather with each call to the 
function that does not supply its own value for L).


Gary Herron




print(f(1))
print(f(2))
print(f(3))

This will print
[1]
[1, 2]
[1, 2, 3]

How the list is retained between successive calls? And why?



--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: n00b question on spacing

2013-06-21 Thread Gary Herron

On 06/21/2013 02:17 PM, Yves S. Garret wrote:
Hi, I have a question about breaking up really long lines of code in 
Python.


I have the following line of code:
log.msg("Item wrote to MongoDB database %s/%s" 
%(settings['MONGODB_DB'], settings['MONGODB_COLLECTION']), 
level=log.DEBUG, spider=spider)


Given the fact that it goes off very far to the right on my screen is 
not terribly

pleasing to my eyes (and can be rude for other developers).

I was thinking of splitting it up like so:
log.msg("Item wrote to MongoDB database %s/%s"
  %(settings['MONGODB_DB'], settings['MONGODB_COLLECTION']),
  level=log.DEBUG, spider=spider)

Is this ok?  Are there any rules in Python when it comes to breaking 
up long lines of

code?


This is how I'd do it:  (And it's *FAR* clearer -- You win no points for 
clarity by having it all in one statement.)


fmt  = "Item wrote to MongoDB database %s/%s"
msg = fmt % (settings['MONGODB_DB'],
     settings['MONGODB_COLLECTION'])
log.msg(msg, level=log.DEBUG, spider=spider)

Gary Herron

--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: analyzing time

2013-07-05 Thread Gary Herron

On 07/05/2013 12:18 PM, noydb wrote:

Hello All,

I have a table with a column of type date, with dates and time combined (like 
'1/6/2013 3:52:69PM'), that spans many months.  How would I pull out records 
that are the first and last entries per day?

Also, if I wanted to find time clusters per day (or per week) -- like if an 
entry is made every day around 11am -- is there a way to get at that temporal 
statistical cluster?

Python 2.7, Windows 7.

Any guidance would be greatly appreciated!  Time seems tricky...

Thanks,

N


Are you asking a Python question, like how to turn a string "1/6/2013 
3:52:69PM" into an internal representation of time, or are you asking a 
data analysis and statistical question?


If the former, then look at datetime.strptime from the datetime module.

If the later, then you may get an answer here, but I'd suggest trying 
somewhere that discusses statistics and analysis.


Gary Herron

--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: RAM slots problem

2013-07-09 Thread Gary Herron

On 07/08/2013 10:06 PM, saadharana wrote:

I've got some annoying problem with RAM. I was depth cleaning my case,
everything regular, it wasn't my first time. And when I put it all together
and powered it on, it wasn't working, just beeps fast. But how that happend
when I put all back in like it was before?? Later I realised that problem
was in position of RAM sticks. I still can't understand what happend, but
now computer won't work on every RAM position, and especially not like it
was before.



-
used computers in chennai
--
View this message in context: 
http://python.6.x6.nabble.com/RAM-slots-problem-tp5024183.html
Sent from the Python - python-list mailing list archive at Nabble.com.


This is a PYTHON list -- for discussing issues concerning Python. You'd 
best ask for HARDWARE help elsewhere.



Good luck.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Storing a very large number

2013-07-17 Thread Gary Herron

On 07/17/2013 12:21 PM, Hasit Mistry wrote:
I came across a problem that requires me to store a very large number 
(say >10^100). How do I do it efficiently?
And also, how do I select a particular number (say 209th) from that 
very large number?

I am relatively new to Python.

Thank you in advance.



Python already has long numbers (integers) built in.:

>>> 10**100
1L

The 'L' on the end notifies you it's a *long* int.  I can't speak about 
its efficiency, but I assume it's OK.


By 209th number, do you mean 209th *digit*?I'd say just get a string 
representation and index the 209th character:


>>> str(12**345)
'2077446682327378559843444695582704973572786912705232236931705903179519704325276892191015329301807037794598378537132233994613616420526484930777273718077112370160566492728059713895917217042738578562985773221381211423961068296308572143393854703167926779929682604844469621152130457090778409728703018428147734622401526422774317612081074841839507864189781700150115308454681772032'
>>> str(12**345)[209]
'1'

Gary Herron


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a Program to Decompose a Number and Run a Function on that Decomposition

2013-07-18 Thread Gary Herron

On 07/18/2013 02:57 PM, CTSB01 wrote:

On Thursday, July 18, 2013 5:12:08 AM UTC-4, Joshua Landau wrote:

On 18 July 2013 00:58, CTSB01  wrote:


Please let me know if this is unclear.  I will certainly continue revising 
until it makes sense to those reading.



Can you summarize what your question is? Leave aside the details of

the function, just explain what thing in particular you aren't able

to do.

Hi Joshua,

I actually managed to find a certain block like this:

  def phi_m(x, m):
...   rtn = []
...   for n2 in range(0, len(x) * m - 2:

That 'for' line has miss-matched parentheses.

... n = n2 / m
... r = n2 - n * m
... rtn.append(m * x[n] + r * (x[n + 1] - x[n]))
... print 'n2 =', n2, ': n =', n, ' r =' , r, ' rtn =', rtn
...   rtn

However, I am getting the error "expected an indented block" on line two.  Any 
idea why?



--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: Has anyone gotten Pyglet to work

2013-07-29 Thread Gary Herron

On 07/29/2013 01:56 PM, Devyn Collier Johnson wrote:
I tried Pyglet in a Python3 and a Python2 script, but both fail. The 
error code is below and the script is attached. The 'boot.ogg' file is 
Ubuntu's default bootup sound. I got my code from this link 
(http://guzalexander.com/2012/08/17/playing-a-sound-with-python.html).


collier@Nacho-Laptop:~$ ./pyglet.py
Traceback (most recent call last):
  File "./pyglet.py", line 2, in 
import pyglet
  File "/home/collier/pyglet.py", line 3, in 
song = pyglet.media.load('./boot.ogg')
AttributeError: 'module' object has no attribute 'media'


Mahalo,

DCJ




You appear to have confused Python by having a module named pyglet AND a 
local file named pyglet.py.


This when you say import pyglet, you are not getting the pyglet module, 
but instead your own file pyglet.py, which of course, has nothing named 
media in it.


Rename your file and try again.

P.S.  It is a common newbie error to hide a system file like this and 
suffer the consequence.  We've all done it -- at least once. :^) )


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: binary key in dictionary

2013-07-30 Thread Gary Herron

On 07/30/2013 01:29 PM, cerr wrote:

Hi,

In my application I have followingf lines:
 print curr_mac
 print hexlify(buf)
 binmac = unhexlify(curr_mac)
 tmpgndict[binmac] += buf
curr_mac being a 3Byte MAVC address in ASCII and I want to populate a 
dictionary where the value(buf) is indexed by binary mac.

I get this in my code:

Traceback (most recent call last):
   File "gateway.py", line 2485, in 
 main()
   File "gateway.py", line 2459, in main
 cloud_check()
   File "gateway.py", line 770, in cloud_check
 gnstr_dict[src] = gn_from_cloud(curr_mac)
   File "gateway.py", line 2103, in gn_from_cloud
 tmpgndict[binmac] += "HELLO"
KeyError: '\x04\xeeu'

but then again, the following works fine in the python interpreter:

mac = '04ee75'
dat = '2a0001016d03c400040001000a'
mydict = {}
mydict[unhexlify(mac)]=dat
print mydict

{'\x04\xeeu': '2a0001016d03c400040001000a'}

I really seem to do something wrong and can't see what it is. Can anyone help 
me further here?

Thank you very much!
Ron



You are confusing the problem with excess code.  Examine the following 
simpler example which illustrates the problem:

>>> d = {}
>>> d[1] = 99
>>> d[2] += 98
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 2
>>>

The  line
  d[1] = 99
creates a key-value pair in the dictionary, but the line
  d[2] += 98
tries to add 98 to an already existing value at d[2],   But there is no 
value at d[2] until you set it:

  d[2] = 0 # for instance

You may want to look at defaultdict from the collections module.

Gary Herron





--
http://mail.python.org/mailman/listinfo/python-list


Re: What’s the differences between these two pieces of code ?

2012-07-06 Thread Gary Herron

On 07/06/2012 09:56 PM, iMath wrote:

What’s the differences between these two  pieces of code ?
(1)
for i in range(1, 7):
print(2 * i, end='   ')


(2)
for i in range(1, 7):
 print(2 * i, end='   ')
print()


when executed both  respectively in Python shell ,I  get  the same effect . Who 
can tell me why  ?


What "effect" are you referring to?   What did you expect?  What did you 
get?   What version of Python?  (3 I'd guess).


As for me, the first one fails because of a syntax (indentation) error 
and the second prints the even numbers 2 through 12.  What are we 
supposed to be comparing?


Gary Herron




--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
http://mail.python.org/mailman/listinfo/python-list


Re: python CAD libraries?

2012-09-10 Thread Gary Herron

On 09/10/2012 02:10 PM, Jayden wrote:

Are there any python CAD libraries that can

(1) build simple 3D primitives solids such as spheres, cylinders and so on
(2) perform bool operations on 3D solids
(3) better if it has some transformations such has scaling, sweeping, and 
lofting

Please recommend some good ones for me? Thanks a lot!!


Try PythonCAD:  http://sourceforge.net/projects/pythoncad/

(Google would have been faster. :-) )

Gary Herron

--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: how to insert random error in a programming

2012-10-15 Thread Gary Herron

On 10/15/2012 06:55 AM, Debashish Saha wrote:

how to insert random error in a programming?


Drink several beers before you start programming. :-)



--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: date and time comparison how to

2012-10-29 Thread Gary Herron

On 10/29/2012 04:13 PM, noydb wrote:

All,

I need help with a date and time comparison.

Say a user enters a date-n-time and a file on disk.  I want to compare the date 
and time of the file to the entered date-n-time; if the file is newer than the 
entered date-n-time, add the file to a list to process.

How best to do?  I have looked at the datetime module, tried a few things, no 
luck.

Is os.stat a part of it?  Tried, not sure of the output, the st_mtime/st_ctime 
doesnt jive with the file's correct date and time.  ??

Any help would be appreciated!


Use the datetime module (distributed with Python) to compare date/times.

You can turn a filesystem time into a datetime with something like the 
following:

import datetime, os, stat
mtime = os.lstat(filename)[stat.ST_MTIME]   // the 
files modification time

dt = datetime.datetime.fromtimestamp(mtime)


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: Conversion of List of Tuples

2012-12-04 Thread Gary Herron

On 12/03/2012 11:58 AM, subhabangal...@gmail.com wrote:

[(1,2), (3,4)]

>>> L=[(1,2), (3,4)]
>>>
>>> [b   for a in L   for b in a]
[1, 2, 3, 4]


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: Python, email temperature

2012-12-22 Thread Gary Herron

On 12/22/2012 12:36 PM, Alexander Ranstam wrote:

Hi!

Im totally new to Python, and im using it on my Raspberry pi. I found a program 
that sends an email, and one that checks the temperature of my CPU, but i cant 
seem to combine the to into the funktion that i want, sending me the CPU temp 
via Email.

The two programs work very well on their own, but this doesnt work.

this works: server.sendmail(fromaddr, toaddrs, msg)
but this doesnt: server.sendmail(fromaddr, toaddrs, cpu_temperature)

despite the command "print cputemp" working in the same program.

When i run the program i get the error:

Traceback (most recent call last):
   File "sendcpu.py", line 36, in 
 msg = cpu_temperature
NameError: name 'cpu_temperature' is not defined

Does anyone know why the program claims that cpu_temperature isnt defined, when 
it is?

Thanx!

//Alexander



Could it be this easy?  In one spot you refer to it as "cpu_temperature" 
and in another as "cputemp".


If that's not it, you'd probably better show us your *real* code, 
otherwise we're just guessing.


Gary Herron


--
http://mail.python.org/mailman/listinfo/python-list


Re: Python, email temperature

2012-12-22 Thread Gary Herron

On 12/22/2012 12:54 PM, KarlE wrote:

On Saturday, December 22, 2012 9:44:39 PM UTC+1, Joel Goldstick wrote:

On Sat, Dec 22, 2012 at 3:36 PM, Alexander Ranstam  wrote:

Hi!



Im totally new to Python, and im using it on my Raspberry pi. I found a program 
that sends an email, and one that checks the temperature of my CPU, but i cant 
seem to combine the to into the funktion that i want, sending me the CPU temp 
via Email.




The two programs work very well on their own, but this doesnt work.



this works: server.sendmail(fromaddr, toaddrs, msg)

but this doesnt: server.sendmail(fromaddr, toaddrs, cpu_temperature)



despite the command "print cputemp" working in the same program.



When i run the program i get the error:



Traceback (most recent call last):

   File "sendcpu.py", line 36, in 

 msg = cpu_temperature

NameError: name 'cpu_temperature' is not defined



Does anyone know why the program claims that cpu_temperature isnt defined, when 
it is?



You should copy and paste the code here including the context around the error. 
 You say print cputemp works, but cpu_temperature is not defined.  They are 
spelled differently.  Start there




Thanx!



//Alexander



--

http://mail.python.org/mailman/listinfo/python-list




--
Joel Goldstick

Hi!

I made a typing error, and couldnt edit the post :( this is the code:


#!/usr/bin/env python
from __future__ import division
from subprocess import PIPE, Popen
import psutil
import smtplib

def get_cpu_temperature():
 process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
 output, _error = process.communicate()
 return float(output[output.index('=') + 1:output.rindex("'")])


def main():
 cpu_temperature = get_cpu_temperature()
 cpu_usage = psutil.cpu_percent()

 ram = psutil.phymem_usage()
 ram_total = ram.total / 2**20   # MiB.
 ram_used = ram.used / 2**20
 ram_free = ram.free / 2**20
 ram_percent_used = ram.percent

 disk = psutil.disk_usage('/')
 disk_total = disk.total / 2**30 # GiB.
 disk_used = disk.used / 2**30
 disk_free = disk.free / 2**30
 disk_percent_used = disk.percent
 #
 # Print top five processes in terms of virtual memory usage.
 #
 print 'CPU temperature is: ',  cpu_temperature

fromaddr = 'myemailadress'
toaddrs  = 'myemailadress'
#msg = 'There was a terrible error that occured and I wanted you to know!'
msg = cpu_temperature

# Credentials (if needed)
username = 'myusername'
password = 'mypassword'

# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, cpu_temperature)
server.quit()




if __name__ == '__main__':
 main()

running it gives the following error:

pi@raspberrypi /home/python $ python sendcpu.py
Traceback (most recent call last):
   File "sendcpu.py", line 36, in 
 msg = cpu_temperature
NameError: name 'cpu_temperature' is not defined
pi@raspberrypi /home/python $


isnt cpu_temperature defined?




First:  Learn about Python SCOPES.  You are defining variables inside 
(as local variables) the procedure main, but they are lost as soon as 
main returns.  If you want values computed inside main but available 
outside main, you should return them.


Second:  Some confusion over what order things are executed in.  The 
code in main is run when you call main -- ans that's at the very end of 
the file.   The lines before the call to main expect to use the value 
cpu_temperature when you have not yet called main to compute the value 
(and which doesn't even return the value as noted above).


The confusion is partly caused by having some of your code inside main 
and some of it outside main and expecting the two parts to 
communicate.I'd suggest putting everything up through the 
server.quit() into procedure main.

--
http://mail.python.org/mailman/listinfo/python-list


Re: how to solve complex equation?

2013-01-01 Thread Gary Herron

On 01/01/2013 11:02 AM, Usama Khan wrote:

how to solve complex equation in pyhton? and then use it to make a program. . i 
have created new post as my last post is i guessed ranked as a cheater. .:(

i know very litle about python as well as programing. .

which equation am taliking u will be thinking. . i am giving u the link kindly 
c that equation. . n kindly let me know the way. .

https://groups.google.com/forum/?fromgroups=#!topic/comp.lang.python/cxG7DLxXgmo


Please STOP asking this question, and try to understand the answers you 
have already been given.


Short answer:  This is NOT a python question, and you can't solve it in 
Python.


Longer answer:  This is a math question.  Some equations can be solved 
with algebra, and some can't, in which case perhaps you need some sort 
of a technique for numerical approximation.Other's have indicated 
that your problem probably falls into the later category.What YOU 
need to do is investigate iterative techniques for numerical solutions 
and pick one.  (And this Python list is CERTAINLY the wrong place for 
such math questions.)  Once you know what solution technique you want to 
use, you could then come back to this group and ask for help 
implementing it.


P.S.  I have implemented several such techniques, and I have taught 
college courses involving such techniques, and I'll say this:  What you 
ask is the subject of AT LEAST several hours of lectures and possibly 
several semesters worth of study.  No one is going to put that kind of 
time into answering your question here.


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: Using an object inside a class

2012-01-23 Thread Gary Herron

On 01/23/2012 11:44 AM, Jonno wrote:
I have a pretty complicated bit of code that I'm trying to convert to 
more clean OOP.


Without getting too heavy into the details I have an object which I am 
trying to make available inside another class. The reference to the 
object is rather long and convoluted but what I find is that within my 
class definition this works:


class Class1:
def __init__(self):

def method1(self):
 foo.bar.object

But this tells me "global name foo is not defined":

class Class1:
 def __init__(self):
   foo.bar.object

Obviously I want the object to be available throughout the class (I 
left out the self.object = etc for simplicity).


Any ideas why I can reference foo inside the method but not in __init__?




You're not telling us everything.  In fact, with the code you gave us, 
neither method1 nor __init__ will work correctly, because you have not 
defined foo *anywhere*.


Without knowledge of what you are *really* doing, I'll say this:  Both 
method1 and __init__ are methods of Class1, and both have the same rules 
for looking up variables.   If either method binds a value to foo, then 
your code may access it:


class Class1:
 def __init__(self):
   foo = whatever # Local to this method
   foo.bar.object

If the method does not bind it, then Python will look in the class for 
foo.  This could work


class Class1:
 foo = whatever # Available to all instances
 def __init__(self):
   foo.bar.object

If that fails, Python will look in the globals, so this could work:

foo = whatever # Available across the full module
class Class1:
 def __init__(self):
   foo.bar.object

Python goes on one further level when searching for a variable -- that 
being the builtins.








--
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: sorting 1172026 entries

2012-05-06 Thread Gary Herron

On 05/06/2012 09:29 AM, J. Mwebaze wrote:

sorry see, corrected code


for filename in txtfiles:
   temp=[]
   f=open(filename)
   for line in f.readlines():
 line = line.strip()
 line=line.split()
 temp.append((parser.parse(line[0]), float(line[1])))
   temp=sorted(temp)
   with open(filename.strip('.txt')+ '.sorted', 'wb') as p:
for i, j in temp:
   p.write('%s %s\n' %(str(i),j))


Don't do
temp = sorted(temp)
That will create a *new* copy of the list to sort, and the assignment 
will free up the original list for deletion and garbage collection.


Instead do the in-place sort:
 temp.sort()
Same result, less thrashing.

This will make your program slightly more efficient, HOWEVER, it is not 
the solution of your week-long sort problem.



Gary Herron






On Sun, May 6, 2012 at 6:26 PM, J. Mwebaze <mailto:jmweb...@gmail.com>> wrote:


I have attached one of the files, try to sort and let me know the
results.  Kindly sort by date. ooops - am told the file exceed 25M.

below is the code

import glob
txtfiles =glob.glob('*.txt')
import dateutil.parser as parser


for filename in txtfiles:
   temp=[]
   f=open(filename)
   for line in f.readlines():
 line = line.strip()
 line=line.split()
 temp.append((parser.parse(line[0]), float(line[1])))
   temp=sorted(temp)
   with open(filename.strip('.txt')+ '.sorted', 'wb') as p:
for i, j in temp:
   p.write('%s %s\n' %(str(i),j))


On Sun, May 6, 2012 at 6:21 PM, Devin Jeanpierre
mailto:jeanpierr...@gmail.com>> wrote:

On Sun, May 6, 2012 at 12:11 PM, J. Mwebaze
mailto:jmweb...@gmail.com>> wrote:
> [ (datatime, int) ] * 1172026

I can't duplicate slowness. It finishes fairly quickly here.
Maybe you
could try posting specific code? It might be something else
that is
making your program take forever.

>>> x = [(datetime.datetime.now() +
datetime.timedelta(random.getrandbits(10)),
random.getrandbits(32)) for _ in xrange(1172026)]
>>> random.shuffle(x)
>>> x.sort()
>>>

-- Devin




-- 
*Mob UG: +256 (0) 70 1735800 

| NL +31 (0) 6 852 841 38
 | Gtalk: jmwebaze | 
skype: mwebazej | URL: www.astro.rug.nl/~jmwebaze

<http://www.astro.rug.nl/%7Ejmwebaze>

/* Life runs on code */*




--
*Mob UG: +256 (0) 70 1735800 | NL +31 (0) 6 852 841 38 | Gtalk: 
jmwebaze |  skype: mwebazej | URL: www.astro.rug.nl/~jmwebaze 
<http://www.astro.rug.nl/%7Ejmwebaze>


/* Life runs on code */*





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to customise math.sqrt(x) for some x?

2011-07-16 Thread Gary Herron

On 07/16/2011 01:35 AM, Steven D'Aprano wrote:

I have a custom object that customises the usual maths functions and
operators, such as addition, multiplication, math.ceil etc.

Is there a way to also customise math.sqrt? I don't think there is, but I
may have missed something.



Create a file named myMath.py containing:
--
from math import *

def sqrt(x):
...whatever you want...
---

Then you can:
  import math #to get normal stuff and
  import myMath # to get your customized stuff
or
  import myMath as math # to get your stuff but named math.



Gary Herron
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can someone help please

2011-07-21 Thread Gary Herron

On 07/21/2011 10:02 AM, Gary wrote:

Hi
Can someone help me with this code below please,
For some reason it will not send me the first text file in the directory.
I made up an empty file a.txt file with nothing on it and it sends the 
files i need but would like to fix the code.

Thanks




total = ' '
os.chdir('/home/woodygar/Desktop/Docs')
for i in os.listdir('.'):
  if '.txt' in i:
f = open(i, 'r')
total += f.read()
f.close()
message = """\
Subject: %s
%s

"""% (SUBJECT,total)



Huh?  Confused I am.  If your first file is empty and you concatenate 
the contents of each file (that's what total+=f.read() does), then what 
do you expect to see?   If you concatenate nothing (that is, the empty 
file), then you should see nothing.   I see no problem with the code, 
but perhaps a problem with your expectations.


If I've misunderstood your question, the please reword and resend it, 
but this time include more information:  The files in '.', their 
content, the output you do get, and the output you expected.


Gary Herron


--
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: Can someone help please

2011-07-21 Thread Gary Herron

On 07/21/2011 10:23 AM, Billy Mays wrote:

On 07/21/2011 01:02 PM, Gary wrote:

Hi
Can someone help me with this code below please,
For some reason it will not send me the first text file in the 
directory.

I made up an empty file a.txt file with nothing on it and it sends the
files i need but would like to fix the code.
Thanks




total = ' '
os.chdir('/home/woodygar/Desktop/Docs')
for i in os.listdir('.'):
if '.txt' in i:
f = open(i, 'r')
total += f.read()
f.close()
message = """\
Subject: %s
%s

"""% (SUBJECT,total)



Does the file end with '.TXT' ? This might help:

total = ' '
os.chdir('/home/woodygar/Desktop/Docs')
txts = (nm for nm in os.listdir('.') if nm.lower().endswith('.txt') )
for nm in txts:
f = open(nm, 'r')
total += f.readlines()
f.close()
message = """\
Subject: %s
%s

"""% (SUBJECT,total)




I also changed read to readlines().
That won't work (You must not have even tried to run this.)  The call 
f.readlines() returns a list which causes an error when added to a string:


TypeError: cannot concatenate 'str' and 'list' objects


Gary Herron



--
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: how to separate a list into two lists?

2011-08-06 Thread Gary Herron

On 08/06/2011 10:07 AM, smith jack wrote:

if a list L is composed with tuple consists of two elements, that is
L = [(a1, b1), (a2, b2) ... (an, bn)]

is there any simple way to divide this list into two separate lists , such that
L1 = [a1, a2... an]
L2=[b1,b2 ... bn]

i do not want to use loop, any methods to make this done?


List comprehension:

   L1 = [item[0] for item in L]
   L2 = [item[1] for item in L]

which *is* still a loop.  (You are going to have to write *really* 
arcane code to have no loop.)


Gary Herron


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pairwise combination of two lists

2011-08-17 Thread Gary Herron

On 08/17/2011 01:22 PM, Yingjie Lin wrote:

Hi Python users,

I have two lists:

li1 = ['a', 'b']
li2 = ['1', '2']

and I wish to obtain a list like this

li3 = ['a1', 'a2', 'b1', 'b2']

Is there a handy and efficient function to do this, especially when li1 and li2 
are long lists.
I found zip() but it only gives [('a', '1'), ('b', '2')],  not exactly what I 
am looking for.

Thank you.


- Yingjie

>>> li1 = ['a', 'b']
>>> li2 = ['1', '2']
>>> print [a+b   for a in li1   for b in li2]
['a1', 'a2', 'b1', 'b2']


Gary Herron
--
http://mail.python.org/mailman/listinfo/python-list


Re: Floating point multiplication in python

2011-09-06 Thread Gary Herron

On 09/05/2011 10:57 PM, xyz wrote:

hi all:

As we know ,  1.1 * 1.1 is 1.21 .
But in python ,I got following :


1.1 * 1.1

1.2102

why python get wrong result? Who can tell me  where's the 0.0002 
from?


It's not a python errorIt's the nature of floating point arithmetic 
to be inaccurate on *ANY* computer.Python just allows you to see the 
inaccuracies.


(But try:
  print 1.1*1.1
and see that the print statement does hide the roundoff error from you.)

Read this for more info:

http://pyfaq.infogami.com/why-are-floating-point-calculations-so-inaccurate


--
http://mail.python.org/mailman/listinfo/python-list


Re: I am confused by

2011-09-07 Thread Gary Herron

On 09/07/2011 03:57 PM, Martin Rixham wrote:

Hi all
I would appreciate some help understanding something. Basically I am 
confused by the following:


>>> a = [[0, 0], [0, 0]]
>>> b = list(a)
>>> b[0][0] = 1
>>> a
[[1, 0], [0, 0]]

I expected the last line to be

[[0, 0], [0, 0]]

I hope that's clear enough.

Martin


You were expecting the assignment to "b" to create a copy of the 
original list, and it does, but the copy is only one level deep.


So a and b are different lists, but a[i] and b[i] are the same objects 
for each i.


There is a "deepcopy" in the library which may do what you expect.

Gary Herron


--
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question

2011-04-01 Thread Gary Herron

On 04/01/2011 12:52 PM, Karl wrote:


Hello,


one beginner question:


aList = [0, 1, 2, 3, 4]

bList = [2*i for i in aList]

sum = 0

for j in bList:

sum = sum + bList[j]



Your j is already an element of bList.  You don't need to index bList 
again.  Instead do

for b in bList:
sum = sum+b


print j


0

2

4

*IndexError:* 'list index out of range'

Why is j in the second run 2 and not 1 in the for-loop?? I think j is 
a control variable with 0, 1, 2, 3, ...



No, it's not a control variable, it's the actual elements of the list.


If you want a control variable as an index you can do
  for j in range(len(bList)):
sum = sum + bList[j]

But that is less efficient




Thanks!


Karl



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fibonacci series recursion error

2011-04-29 Thread Gary Herron

On 04/29/2011 08:22 PM, lalit wrote:

import os
def fib(n):
if n == 1:
   return(n)
else:
   return (fib(n-1)+fib(n-2))

list=fib(20)
print(list)

The above function return the
return (fib(n-1)+fib(n-2))


RuntimeError: maximum recursion depth exceeded in comparison
[36355 refs]

can any one help


You correctly test for n==1, but what about when n==2?When the 
recursion works its way down to fib(2), you call both fib(1) and fib(0), 
but the latter starts an infinite sequence of calls to fib(-1), fib(-2) 
and so on without end.


Gary Herron

--
http://mail.python.org/mailman/listinfo/python-list


Re: None is None but not working

2017-09-27 Thread Gary Herron

On 09/27/2017 01:05 PM, Sayth Renshaw wrote:

Hi

I have got a successful script setup to rotate through dates and download json 
data from the url.

As the api returns 200 whether successful I want to check if the file returned 
is not successful.

when a file doesn't exist the api returns
{'RaceDay': None, 'ErrorInfo': {'SystemId': 200, 'ErrorNo': 55013, 
'DisplayMessage': 'File Not Found.', 'ContactSupport': False, 
'SupportErrorReference': '200-55013'}, 'Success': False}

When I call data = r.json() it says its type is None if it is not successful so 
I thought it easier to check that.

However checking for None does not work the flow in my if else falls straight 
to else.

for dates in fullUrl:
 r = requests.get(dates)
 data = r.json()
 if data is None:
 print("Nothing here")
 else:
 print(data["RaceDay"])


Your data is not None, it's a full dictionary.

However, data["RaceDay"] *is* None as shown in your output.  Thus your 
test should be:

    if data["RaceDay"] is None: ...
rather than
    if data is None: ...






and I get output of

None
None
{'MeetingDate': '2017-01- ... and so on.

How can I actually get this to check?

If i use type(data) I also get None.

Cheers

Sayth



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
https://mail.python.org/mailman/listinfo/python-list


Re: Please Help

2018-01-26 Thread Gary Herron



On 01/26/2018 08:33 PM, mohammedfaraz...@gmail.com wrote:

import numpy as np
x=np.unit8([250)
print(x)
y=np.unit8([10])
print(y)
z=x+y
print(z)


output

[250]
[10]
[4]

My question how is z [4]


Despite all the typos in your post, you appear to be doing 8 bit 
unsigned arithmetic.  Do you know what that means?  The answer you might 
have expected (i.e. 260) does not fit in the 0 ... 255 range of 8 bits, 
and so the result has overflowed and "wrapped around" to produce 4.


Try this for a simpler example of the same:
>>> np.uint8(260)
4


Gary Herron


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: =- and -= snag

2023-03-13 Thread Gary Herron



On 3/13/23 2:26 PM, morp...@gmail.com wrote:

Hi.

I was working in Python today, and sat there scratching my head as the
numbers for calculations didn't add up.  It went into negative numbers,
when that shouldn't have been possible.

Turns out I had a very small typo, I had =- instead of -=.

Isn't it unpythonic to be able to make a mistake like that?

Regards,

Morten



These all mean the same thing, but I don't see a good way to designate 
the second or third as an error.



x = -5
x=-5
x =- 5


Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology

--
https://mail.python.org/mailman/listinfo/python-list


Re: Standard class for time *period*?

2023-03-27 Thread Gary Herron
The Python standard library module datetime seems to be what you want.  
It has objects representing date/times, and deltatimes (i.e., 
durations).  These can be timezone aware or not as you wish.


Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology

On 3/27/23 6:00 AM, loris.benn...@fu-berlin.de wrote:

Hi,

I have been around long enough to know that, due to time-zones, daylight
saving and whatnot, time-related stuff is complicated.  So even if I
think something connected with time should exist, there may well be a
very good reason why it does not.

My problem:

   I need to deal with what I call a 'period', which is a span of time
   limited by two dates, start and end.  The period has a 'duration',
   which is the elapsed time between start and end.  The duration is
   essentially a number of seconds, but in my context, because the
   durations are usually hours or days, I would generally want to display
   the duration in a format such as "dd-hh:mm:ss"

My (possibly ill-founded) expectation:

   There is a standard class which encapsulates this sort of functionality.

My (possibly insufficiently researched) conclusion:

   Such a standard class does not exist.

What is at fault here?  My expectation or my conclusion?

Cheers,

Loris


--
https://mail.python.org/mailman/listinfo/python-list


Re: Change first occurrence of character x in a string - how?

2021-02-14 Thread Gary Herron

The string type has a replace function that does what you want.
Except you can't change a string -- they are immutable -- so this 
creates a new string.



>>> s = 'linux-raid.vger.kernel.org'
>>> new_s = s.replace('.', '@', 1)
>>> new_s
'linux-r...@vger.kernel.org'



On 2/14/21 1:14 PM, c...@isbd.net wrote:

What's the easiest way to change the first occurrence of a specified
character in a string?

E.g. I want to change linux-raid.vger.kernel.org to
linux-r...@vger.kernel.org, it's a fairly general requirement of
needing to change '.' to '@'.

Alternatively is there an RE 'match' function that would test if
linux-r...@vger.kernel.org matches linux-raid.vger.kernel.org? I don't
really care if the '.' are all regarded as wild cards, the match will
be accurate enough.


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: A strange list concatenation result

2016-08-11 Thread Gary Herron

On 08/11/2016 03:06 PM, Mok-Kong Shen wrote:


def test(list1,list2):
  list1+=[4,5,6]
  list2=list2+[4,5,6]
  print("inside ",list1,list2)
  return

# With

list1=list2=[1,2,3]
test(list1,list2)
print("outside",list1,list2)

# I got the following:
# inside  [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6, 4, 5, 6]
# outside [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]

# With

list1=[1,2,3]
list2=[1,2,3]
test(list1,list2)
print("outside",list1,list2)

# I got the following:
# inside  [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
# outside [1, 2, 3, 4, 5, 6] [1, 2, 3]



I think the following shows the same issue in a much simpler fashion:

In this (and your first) example, there is only one list, although it 
has two names to reference it.


>>> list1 = list2 = [1,2,3]
>>> list1 += [4,5,6]
>>> print(list1, list2)
[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]


In this next example, there are two separate lists:

>>> list1 = [1,2,3]
>>> list2 = [1,2,3]
>>> list1 += [4,5,6]
>>> print(list1, list2)
[1, 2, 3, 4, 5, 6] [1, 2, 3]


Does that help?


Gary Herron


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: degrees and radians.

2016-08-23 Thread Gary Herron

On 08/23/2016 09:08 PM, murdocksgra...@gmail.com wrote:

On Saturday, May 4, 2002 at 3:37:07 AM UTC-4, Jim Richardson wrote:

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1


I am trying to get the math module to deal with degrees rather than
radians. (that it deals with radians for the angular functions like
sin() isn't mentioned in the docs, which was sort of an eyeopener :)  I
can't find any info on doing this. I can convert from-to degrees in the
code calling the function, but that's a bit clunky. Any pointers to an
FM to R? :)

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE804+jd90bcYOAWPYRAt9KAKCuqeC4ozuXSaKZ5xY27Wv+k04QuQCcCrCZ
WyichPnKgXo+GaDdAebsaeU=
=h+vc
-END PGP SIGNATURE-

--
Jim Richardson
Anarchist, pagan and proud of it
http://www.eskimo.com/~warlock
Linux, from watches to supercomputers, for grandmas and geeks.

For what is is worth.. Electrical Engineers for the most part work in degrees 
NOT Radians for example try doing polar to rectangular or vice versa in polar.
I have never seen it done.

Also Borland C and C++ used Degrees and NOT Radians.. go look at the libraries

Just for what its worth.



Do you really need anything more complex than this?

>>> toRadians = math.pi/180.0

>>> math.sin(90*toRadians)
1.0

Perhaps I'm not understanding what you mean by "clunky",  but this seems 
pretty clean and simple to me.



Gary Herron


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: why this code loop forever after a draw a rectangle

2016-09-16 Thread Gary Herron

On 09/16/2016 04:24 AM, meInvent bbird wrote:

im = img.copy()
cntcounter = 0
for cnt in contours:
 epsilon = 0.1*cv2.arcLength(cnt,True)
 approx = cv2.approxPolyDP(cnt,epsilon,True)
 #peri = cv2.arcLength(cnt, True)
 #approx = cv2.approxPolyDP(c, 0.5 * peri, True)
 #print("len(approx)="+str(len(approx)))
 if len(approx) == 4:
 print("approx=" + str(approx))
 cntcounter = cntcounter + 1
 print("here1")
 x,y,w,h = cv2.boundingRect(cnt)
 print("here2")
 while im is None:
 time.sleep(1)
 if im is not None:
 print("here3")
 im = cv2.rectangle(im.copy(), (x,y), (x+w, y+h), (0,255,0), 2)
 #im = cv2.line(im,(x,y),(x+w,y),(0,255,0),2)
 #im = cv2.line(im,(x+w,y),(x+w,y+h),(0,255,0),2)
 #im = cv2.line(im,(x,y+h),(x+w,y+h),(0,255,0),2)
 #im = cv2.line(im,(x,y),(x,y+h),(0,255,0),2)


cv2.imwrite(r'C:\Users\tester\Documents\masda.png',im)



These two lines:

  while im is None:
time.sleep(1)

are an infinite loop if im is None;


Since you haven't told us what im (or img, contours, cv2) are, I can't 
tell how im might become None, but it does look like you (confusingly) 
use im for two different things:  an img.copy() and a cv2.rectangle, 
whatever those may be.


Pure guesswork:  if cv2.rectangle draws a rectangle, what does it 
return?  If it doesn't return anything, the line

im = cv2.rectangle(...)
is how im gets the value of None.

--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: why this code loop forever after a draw a rectangle

2016-09-16 Thread Gary Herron

On 09/16/2016 05:18 AM, meInvent bbird wrote:

i follow this post to give some time it to operate,
wait a long time still looping

http://answers.opencv.org/question/60094/libpng-warning-image-width-is-zero-in-ihdr/


i can not stand this Ninja coding life any more,
i have to open my code for ask this error


import cv2
import numpy as np
#from matplotlib import pyplot as plt
import time

#print("1=" + str(int(sys.argv[1])))
#print("2=" + str(int(sys.argv[2])))
#print("3=" + str(int(sys.argv[3])))

img_rgb = cv2.imread(r'C:\Users\martin\Documents\scree2.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread(r'C:\Users\martin\Documents\dragob.png',0)
w, h = template.shape[::-1]

res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.64
 
loc = np.where( res >= threshold)

pt = [(0,0)]
 
while not zip(*loc[::-1]):

 threshold = threshold - 0.02
 loc = np.where( res >= threshold)

counter = 1
print("threshold="+str(threshold))
for pt2 in zip(*loc[::-1]):
 cv2.rectangle(img_rgb, pt2, (pt2[0] + w, pt2[1] + h), (0,0,255), 2)
 pt = pt2
 crop_img = img_rgb[pt[1]:(pt[1]+h), pt[0]:(pt[0]+w)]
 counter = counter + 1

cv2.imwrite("C:\\Users\\tester\\Documents\\res.png",crop_img)


#import cv2
#winName = "Movement Indicator"
#cv2.namedWindow(winName, cv2.WINDOW_NORMAL)
img = cv2.imread(r'C:\Users\tester\Documents\res.png',1)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
height, width = gray.shape
edges = cv2.Canny(gray,height,width,apertureSize = 3)
#edges = cv2.Canny(gray,30,200)

#gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
#ret,thresh = 
cv2.threshold(edges.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE,0)
ret,thresh = cv2.threshold(edges,250,150,0)
contours,hierarchy = cv2.findContours(thresh, 1, 2)
#contours = sorted(contours, key = cv2.contourArea, reverse = True)[:10]

im = img.copy()
cntcounter = 0
for cnt in contours:
 epsilon = 0.1*cv2.arcLength(cnt,True)
 approx = cv2.approxPolyDP(cnt,epsilon,True)
 #peri = cv2.arcLength(cnt, True)
 #approx = cv2.approxPolyDP(c, 0.5 * peri, True)
 #print("len(approx)="+str(len(approx)))
 if len(approx) == 4:
 print("approx=" + str(approx))
 cntcounter = cntcounter + 1
 print("here1")
 x,y,w,h = cv2.boundingRect(cnt)
 print("here2")
 #im = img.copy()
 while im is None:
 time.sleep(1)
 if im is not None:
 print("here3")
 im = cv2.rectangle(im.copy(), (x,y), (x+w, y+h), (0,255,0), 2)
 
#cv2.imwrite("C:\\Users\\martin\\Documents\\masda"+str(cntcounter)+".png",imi)
 #im = cv2.line(im,(x,y),(x+w,y),(0,255,0),2)
 #im = cv2.line(im,(x+w,y),(x+w,y+h),(0,255,0),2)
 #im = cv2.line(im,(x,y+h),(x+w,y+h),(0,255,0),2)
 #im = cv2.line(im,(x,y),(x,y+h),(0,255,0),2)








On Friday, September 16, 2016 at 7:34:04 PM UTC+8, Waffle wrote:

On 16 September 2016 at 14:24, meInvent bbird  wrote:

im = img.copy()
cntcounter = 0
for cnt in contours:
 epsilon = 0.1*cv2.arcLength(cnt,True)
 approx = cv2.approxPolyDP(cnt,epsilon,True)
 #peri = cv2.arcLength(cnt, True)
 #approx = cv2.approxPolyDP(c, 0.5 * peri, True)
 #print("len(approx)="+str(len(approx)))
 if len(approx) == 4:
 print("approx=" + str(approx))
 cntcounter = cntcounter + 1
 print("here1")
 x,y,w,h = cv2.boundingRect(cnt)
 print("here2")
 while im is None:
 time.sleep(1)
 if im is not None:
 print("here3")
 im = cv2.rectangle(im.copy(), (x,y), (x+w, y+h), (0,255,0), 2)
 #im = cv2.line(im,(x,y),(x+w,y),(0,255,0),2)
 #im = cv2.line(im,(x+w,y),(x+w,y+h),(0,255,0),2)
 #im = cv2.line(im,(x,y+h),(x+w,y+h),(0,255,0),2)
 #im = cv2.line(im,(x,y),(x,y+h),(0,255,0),2)


cv2.imwrite(r'C:\Users\tester\Documents\masda.png',im)
--
https://mail.python.org/mailman/listinfo/python-list

not sure but..  this bit reads really suspicious:

 while im is None:
 time.sleep(1)

if im is ever None then how will it ever become not None? unless there
is some other thread at work i can't really see this happening.
and if there is some other thread at work then there is probably some
better solution than sleep()


Reading the manual for opencv, we see that cv2.rectangle does indeed 
return None:
  Python: cv.Rectangle(img, pt1, pt2, color, thickness=1, 
lineType=8, shift=0) → None


So the first pass through your loop 

Re: specifying the same argument multiple times with argparse

2018-04-16 Thread Gary Herron

On 04/16/2018 02:31 PM, larry.mart...@gmail.com wrote:

Is there a way using argparse to be able to specify the same argument
multiple times and have them all go into the same list?

For example, I'd like to do this:

script.py -foo bar -foo baz -foo blah

and have the dest for foo have ['bar', 'baz', 'blah']



From the argparse web page 
(https://docs.python.org/3/library/argparse.html):


'append' - This stores a list, and appends each argument value to the 
list. This is useful to allow an option to be specified multiple times. 
Example usage:


>>>
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append')
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['1', '2'])


I hope that helps.


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Weird side effect of default parameter

2018-05-03 Thread Gary Herron
This is a well known feature of Python.   It's a very common "gotcha" to 
new Python programmers.


Google "Mutable default parameters in Python" for long list of 
explanations and fixes.


In short, don't use a mutable object as a default parameter.


Gary Herron



On 05/03/2018 12:47 PM, python-list@python.org wrote:

Hello,

I don't understand the behavior of the code below. Why does the dict property
"a" of both objects contain the same keys? This is only if "a=dict" is in
the initializer. If I put self.a = dict() into the init function, I get two
separate dicts



class Foo(object):
 def __init__(self, x, a=dict()):
 self.x = x
 self.a = a
 self.a[x] = x


c = Foo(1)
d = Foo(2)

print(c.__dict__)
print(d.__dict__)


robert


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Numpy array

2018-05-20 Thread Gary Herron

The "indexing" page of the documentation might help you with this:

https://docs.scipy.org/doc/numpy-1.14.0/reference/arrays.indexing.html


On 05/18/2018 09:50 PM, sharan.basa...@gmail.com wrote:

This is regarding numpy array. I am a bit confused how parts of the array are 
being accessed in the example below.

1 import scipy as sp
2 data = sp.genfromtxt("web_traffic.tsv", delimiter="\t")
3 print(data[:10])
4 x = data[:,0]
5 y = data[:,1]

Apparently, line 3 prints the first 10 entries in the array
line 4 & 5 is to extract all rows but only 1st and second columns alone for x 
and y respectively.

I am confused as to how data[:10] gives the first 10 rows while data[:,0] gives 
all rows



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: How can an int be '+' with a tuple?

2018-06-02 Thread Gary Herron
In fact, the value of *any* is *not* an integer.  The *any notation 
causes Python to pack all the arguments into a tuple. This feature is 
usually used when there are multiple (and an unknown number) of 
parameters, but it works perfectly well with a single parameter.


Here's an example:

>>> def progress(*any):
    print(any)

>>> progress(1)
(1,)
>>> progress(1,2,3)
(1, 2, 3)
>>>


On 06/02/2018 07:55 PM, jf...@ms4.hinet.net wrote:

The attached is a script which can run under Python 3.4/Windows Vista
correctly. One thing make me puzzled is that the "any + context" at line
18. The "any" was passed as an integer from line 43 and the "context"
was defined as a tuple at line 35. This concatenation works! how?

Best Regards,
Jach Fong





---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus




--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: curve_fit in scipy

2018-06-19 Thread Gary Herron
This is a Python forum, but what you are asking is not a Python 
question.  You might find a better source of answers on a scipy specific 
forum.


But here's my attempt at answers:



On 06/19/2018 08:26 AM, sharan.basa...@gmail.com wrote:

Hi All,

I am working out an exercise on curve_fit function available scipy package.

While I understand in general about curve_fit, I am unable to understand the 
following:

params, params_covariance = optimize.curve_fit(test_func, x_data, y_data,
p0=[2, 2])

Firstly, I don't understand why test_func is passed as an argument to cur_fit


You are trying to fit a curve to some data, right.  The curve_fit 
procedure needs to know what curve you are trying to fit.  Is it a 
linear curve, exponential, polynomial or ...?  In this example it's a 
sine function with parameters for regulating amplitude and frequency.  
But it could be any function with any parameters.  To be more precise, 
test_function is not a single function y=f(x), but a whole family of 
functions y=f(x; a,b) where a and b define a particular function.



Secondly, I don't understand how curve_fit knows the number of arguments that 
test_func takes.


Part of the dynamic nature of Python is that a function carries with it 
the number of parameters (as just one among many such properties).  We 
call it "introspection" when we examine such properties of objects.  The 
curve_fit function usees such an introspection to find that 
test_function has two parameters (a and b) defining the family of curves.




Full code is available below for reference:

import numpy as np

# Seed the random number generator for reproducibility
np.random.seed(0)

x_data = np.linspace(-5, 5, num=50)
y_data = 2.9 * np.sin(1.5 * x_data) + np.random.normal(size=50)

# And plot it
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data)

from scipy import optimize

def test_func(x, a, b):
 return a * np.sin(b * x)

params, params_covariance = optimize.curve_fit(test_func, x_data, y_data,
p0=[2, 2])

print(params)

plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data, label='Data')
plt.plot(x_data, test_func(x_data, params[0], params[1]),
  label='Fitted function')

plt.legend(loc='best')

plt.show()


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Probability

2018-09-11 Thread Gary Herron

On 09/11/2018 11:54 AM, end...@freemail.hu wrote:

Hello,

I am new to Python and I have an exercise which I struggle with.

The question is:
In the strategic board game called Risk, one player can attack up to three 
soldiers simultaneously, while the defending player can defend up to two. In 
the case of exactly three attackers and two defenders, the collision is as 
follows. An attacking player rolls three red dice while the defending player 
rolls two blue dice. Then they compare the bigest throws of the attacker and 
the defender. The lesser value loses a soldier, in the case of equal values the 
attacker loses one soldier. Then the second largest numbers are also compared 
in the same way. Thus, the battle has three outcomes: the attacker loses two 
soldiers, each side loses 1-1 soldiers, the defender loses two soldiers.
Simulate 1000 times the experiment and determine the relative frequency 
of the three events.Simulate 100 times the experiment and determine the 
relative frequency of the three events.Calculate the exact probability of the 
three outcomes by examining all possible cases. The probability is the ratio of 
the favorable cases and the total number of cases. Write these results with 5 
decimal places leaving 3 spaces between them! The output of the program looks 
like this (of course with other numbers)


 Attacker  Draw  Defender
1000 experiment 0.35222   0.4   0.20334
100 experiment  0.33988   0.43011   0.23001
Probability 0.34000   0.43000   0.23000



The aim of this task is to get acquainted with the classical probability field, 
the relative frequency and the relation of it to the probability.Programming 
goal: recalling the basic elements of Python programming and generating random 
numbers.Help: by loading the random package (import random) and calling 
random.random() one may get a random number between 0 and 1 (by uniform 
distribution). The code int(random.random()*6)+1 gives back an integer number 
between 1 and 6.

So I did like:
import random

def dice():
     attacker_dice=[random.randint(1,6) for _ in range(3)]
     defender_dice=[random.randint(1,6) for _ in range(2)]
     a=max(attacker_dice)
     b=max(defender_dice)
     for i in range(1000):
         F=0
         S=0
         T=0
         if a>b:
             F+=1
         if a==b:
             S+=1
         else:
             T+=1


Every time through this loop, you set F, S and T to zero.  If you want 
those variables to accumulate values, move the three initialization 
lines to before the loop:

F = 0
S = 0
T = 0
for ...
   if a>b:
 F += 1
   ... and so on ...

But you have another problem.  You simulate rolling the dice only once.  
For your 1000 trials, you need to roll the dice 1000 times. The first 
few lines that simulate the dice roll must be inside the loop so that 
each pass through the loop rolls the dice.




and I wanted to divide the F,T,S with 6^5 and make a table. But its giving me zeros or 
333. And to get 5digits after the zero i wanted to use "%.5f " %First.

Could you help me to finish this, and tell me what am I doing wrong?

Thank you



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Probability

2018-09-11 Thread Gary Herron

On 09/11/2018 11:54 AM, end...@freemail.hu wrote:

Hello,

I am new to Python and I have an exercise which I struggle with.

The question is:
In the strategic board game called Risk, one player can attack up to three 
soldiers simultaneously, while the defending player can defend up to two. In 
the case of exactly three attackers and two defenders, the collision is as 
follows. An attacking player rolls three red dice while the defending player 
rolls two blue dice. Then they compare the bigest throws of the attacker and 
the defender. The lesser value loses a soldier, in the case of equal values the 
attacker loses one soldier. Then the second largest numbers are also compared 
in the same way. Thus, the battle has three outcomes: the attacker loses two 
soldiers, each side loses 1-1 soldiers, the defender loses two soldiers.
Simulate 1000 times the experiment and determine the relative frequency 
of the three events.Simulate 100 times the experiment and determine the 
relative frequency of the three events.Calculate the exact probability of the 
three outcomes by examining all possible cases. The probability is the ratio of 
the favorable cases and the total number of cases. Write these results with 5 
decimal places leaving 3 spaces between them! The output of the program looks 
like this (of course with other numbers)


 Attacker  Draw  Defender
1000 experiment 0.35222   0.4   0.20334
100 experiment  0.33988   0.43011   0.23001
Probability 0.34000   0.43000   0.23000



The aim of this task is to get acquainted with the classical probability field, 
the relative frequency and the relation of it to the probability.Programming 
goal: recalling the basic elements of Python programming and generating random 
numbers.Help: by loading the random package (import random) and calling 
random.random() one may get a random number between 0 and 1 (by uniform 
distribution). The code int(random.random()*6)+1 gives back an integer number 
between 1 and 6.

So I did like:
import random

def dice():
     attacker_dice=[random.randint(1,6) for _ in range(3)]
     defender_dice=[random.randint(1,6) for _ in range(2)]
     a=max(attacker_dice)
     b=max(defender_dice)
     for i in range(1000):
         F=0
         S=0
         T=0
         if a>b:
             F+=1
         if a==b:
             S+=1
         else:
             T+=1


Every time through this loop, you set F, S and T to zero.  If you want 
those variables to accumulate values, move the three initialization 
lines to before the loop:

F = 0
S = 0
T = 0
for ...
   if a>b:
 F += 1
   ... and so on ...

But you have another problem.  You simulate rolling the dice only once.  
For your 1000 trials, you need to roll the dice 1000 times. The first 
few lines that simulate the dice roll must be inside the loop so that 
each pass through the loop rolls the dice.






and I wanted to divide the F,T,S with 6^5 and make a table. But its giving me zeros or 
333. And to get 5digits after the zero i wanted to use "%.5f " %First.

Could you help me to finish this, and tell me what am I doing wrong?

Thank you



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
https://mail.python.org/mailman/listinfo/python-list


Re: trying to connect the setarrange and blendshape input target weight while running the script am getting error in the 8th line. (for each in lip_val_list: )

2018-09-13 Thread Gary Herron

Your indentation of that line is incorrect.

You also have indentation errors on lines 14 and 21.  (Possibly more, 
that's all the further I checked.)  Do you understand Python's 
indentation rules?



In the future, you can do a lot better to help us help you. First, tell 
us the error you got instead of just saying you got an error.  (Copy and 
paste the full error message.)  Also tell us what version of Python (2 
or 3), and what platform, in case any of that matters.   Your subject 
line contains lots of meaningless distractions:  What's a setarrange, 
what's a blendshape, what's an input target weight,  what does it mean 
to connect them?  Either none of that is important (as is the case in 
this simple indentation error), so don't include such distractions, or 
it does matter, so take the time to define those terms.



Gary Herron



On 09/13/2018 12:11 AM, christyso...@gmail.com wrote:

lf_main_attr = "head_icon.Lf_Sticky_Lips"
rt_main_attr = "head_icon.Rt_Sticky_Lips"
lip_val_list = [18, 14]
lip_name_list = ['upperLip', 'lowerLip']

name_counter = 0
  for each in lip_val_list:
  half_val = (each / 2) + 1
  total_val = each + 1
  div_val = 10.0 / half_val
  counter = 0
  while(counter   

   


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: import inspect error

2018-09-17 Thread Gary Herron
You appear to have a local file named keyword.py which is hiding a 
python installation file of the same name.



Gary Herron





On 09/17/2018 01:06 AM, jupiter@gmail.com wrote:

I have following errors running on Ubuntu 18, any insight how to fix it? Thank 
you.

Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import inspect

Traceback (most recent call last):
   File "", line 1, in 
   File "/usr/lib/python2.7/inspect.py", line 42, in 
 from collections import namedtuple
   File "/usr/lib/python2.7/collections.py", line 22, in 
 from keyword import iskeyword as _iskeyword
   File "keyword.py", line 3, in 
 from inspect import currentframe, getframeinfo
ImportError: cannot import name currentframe


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Program to find Primes of the form prime(n+2) * prime(n+1) - prime(n) +- 1.

2018-10-02 Thread Gary Herron

On 10/02/2018 01:23 PM, tomusa...@gmail.com wrote:

  Primes of the form prime(n+2) * prime(n+1) - prime(n) +- 1.
DATA

31, 71, 73, 137, 211, 311, 419, 421, 647, 877, 1117, 1487, 1979, 2447, 3079, 
3547, 4027, 7307, 7309, 12211, 14243, 18911, 18913, 23557, 25439, 28729, 36683, 
37831, 46853, 50411, 53129, 55457, 57367, 60251, 67339, 70489, 74797, 89669, 
98909, 98911

EXAMPLE 

7*5 - 3 - 1 = 31

11*7 - 5 - 1 = 71

11*7 - 5 + 1 = 73

13*11 - 7 + 1 = 137

Can someone put this in a Python program and post?



No, sorry, but that's not how this works.  We're not here to do your 
homework for you, and you won't learn anything if we do.  You make an 
attempt at solving this, asking any specific Python related questions 
you need help with, and you'll find this to be prompt, friendly, and 
helpful group.



Gary Herron


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
https://mail.python.org/mailman/listinfo/python-list


Re: My python code has suddenly started to give me error. Please see code below**

2018-10-08 Thread Gary Herron
So, tell us the error and we'll see what we can do.  Give us something 
to work with:   Cut and past the full error message, trace back, 
whatever you can.


Also tell us what version of Python, what system you are running on, how 
you run this code, ...




On 10/08/2018 10:17 PM, upadhyay.kamay...@gmail.com wrote:

## Calculating the Lower Limits(LLi) and Upper Limit(ULi) for each Band, where 
i is 1,2,.10
LL1=0
print(LL1)

print(P2)
print(D2)

if(P2>25):
 UL1=D1
 print(UL1)

elif(UL1==D2):
 print(UL1)
 
LL2=UL1
 
if(P3>25):

 UL2=D2
 print(UL2)

elif(UL2==D3):
 print(UL2)
 
LL3=UL2


if(P4>25):
 UL3=D3
 print(UL3)

elif(UL3==D4):
 print(UL3)
  


LL4=UL3

if(P5>25):
 UL4=D4
 print(UL4)

elif(UL4==D5):
 print(UL4)
 
LL5=UL4


if(P6>25):
 UL5=D5
 print(UL5)

elif(UL5==D6):
 print(UL5)
 
LL6=UL5


if(P7>25):
 UL6=D6
 print(UL6)

elif(UL6==D7):
 print(UL6)
 
LL7=UL6


if(P8>25):
 UL7=D7
 print(UL7)

elif(UL7==D8):
 print(UL7)
 
LL8=UL7


if(P9>25):
 UL8=D8
 print(UL8)

elif(UL8==D9):
 print(UL8)
 
LL9=UL8


if(P10>25):
 UL9=D9
 print(UL9)

elif(UL9==D10):
 print(UL9)
 
LL10=UL9

UL10=("& Above")

print(UL10)



**
n1=int(UL1)
count=0
while (n1>0):
 count=count+1
 n1=n1//10
 
print(count)


B11=LL1
If((count)/2)==0:
B12=int((UL1)/(10**(count-2)))
B12
 elif(B12=int((UL1)/(10**(count-1:
B12
B1=(B11,"-",B12,"M")
B1


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Advice on law firm

2018-10-18 Thread Gary Herron
This is a Python related forum, but your question has nothing to do with 
Python.  While you might get an answer here, I'm sure you could find a 
better place to post your question.



On 10/17/2018 07:36 PM, rj.amdphr...@gmail.com wrote:

Correction: specializing in warranty of merchantability, software licenses, and 
possibly class action suits.

Sent from Mail for Windows 10

From: Ryan Johnson
Sent: Wednesday, October 17, 2018 9:26 PM
To: python-list@python.org
Subject: Advice on law firm

Anyone know a good US based law firm that specializes in software licenses and 
class action suits?

Sent from Mail for Windows 10




--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: namedtuples anamoly

2018-10-18 Thread Gary Herron



On 10/17/2018 11:13 PM, me.vi...@gmail.com wrote:

Hi,

I tried using namedtuples and just found a behaviour which I am not able to
conclude as correct behaviour.

from collections import namedtuple

(n, categories) = (int(input()), input().split())
Grade = namedtuple('Grade', categories)
Grade.ID = 1
#print(Grade.ID)
ob = Grade(10, 50)
print(ob.ID)
print(ob.MARKS)
ob1 = Grade(20, 100)
print(ob1.ID)

2
ID MARKS
1
50
1
100


If we set GRADE.ID =1 ,


Whoa!  Don't do that.  The Grade object created with the namedtuple call 
is a class, and part of it's internal implementation is stored in 
Grade.ID.  Try these lines:


>>> print(Grade)

>>> print(Grade.ID)

>>>

By reassigning Grade.ID, you are sabotaging the internals of the class.  
Without looking at those internals, it's not really a surprise that 
things stop working after you destroy the   it so 
carefully stored in Grade.ID.



So now the real question is:  What were you trying to accomplish with 
the assignment?  Tell us, and let's see if we can find a way to 
accomplish yor goal without wrecking the internals of the Grade class.



Gary Herron



it has impact on all variables. Is this behaviour
just like class variable and it has global scope.
I expected ob.ID and ob1.ID to be 10.

Correct me if Iam wrong.
Appreciate any quick response.

Kind Rgds,
Vinu


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: what is the difference between one-line-operation and 2-line-operation

2016-04-25 Thread Gary Herron

On 04/25/2016 07:13 AM, oyster wrote:

for a simple code
[code]
vexList = [1, 2, 3]
print('vexList', list(vexList))

vexList=map(lambda e: e+1, vexList)
print('vexList', list(vexList))

vexList = list(vexList)
print('vexList', list(vexList))

vexList=map(lambda e: e*2,vexList)
print('vexList', list(vexList))
[/code]


py27 says
[quote]
('vexList', [1, 2, 3])
('vexList', [2, 3, 4])
('vexList', [2, 3, 4])
('vexList', [4, 6, 8])
[/quote]

but py34 says
[quote]
vexList [1, 2, 3]
vexList [2, 3, 4]
vexList []
vexList []
[/quote]


The difference in behaviour between Python2 and Python3 is the map 
function.  In P2 it returned a list, while in P3 it returns an 
iterator.  Your code runs through that iterator twice with the list() 
function.  The first time it gets the elements of the list as expected, 
but the second time, the iterator is exhausted and returns no objects.


A simpler example: "b" is a map object (iterator), then list(b) is run 
twice.


>>> a = [1,2,3]
>>> b = map(lambda e: e+1, a)
>>> b

>>> list(b)
[2, 3, 4]
>>> list(b)
[]


I hope that helps.

Gary Herron

--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: def __init__(self):

2016-04-26 Thread Gary Herron

On 04/25/2016 11:21 PM, San wrote:

Hi All,

Pls let me why
"
def __init__(self):

"
declaration required, what's the use of this one.Pls explain  me in details.

Thanks in advance.


If you understand object-oriented-programming, then this will make sense:

   The __init__ method is the constructor for instances of a class.  It
   is not required, but the situations in which a constructor is not
   needed are few and unusual.

If you don't know object-oriented-programming, then I'd suggest you put 
that high on your list of things to learn.  It's a valuable tool.


Gary Herron


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: def __init__(self):

2016-04-26 Thread Gary Herron

On 04/26/2016 06:49 AM, Random832 wrote:

On Tue, Apr 26, 2016, at 03:34, Ben Finney wrote:

That's needlessly confusing: ‘__init__’ is not a constructor because it
does not construct the instance. The ‘__new__’ method is the constructor
for a class (and returns the new instance).

the __new__ method is the *allocator*. "constructor" is used in many
languages to name a method that initializes an object once it already
"exists". Saying you can't call it that in Python is needlessly
confusing.


Agreed.  For a newbie asking about __init__, I'll stick with my original 
answer (that it's the constructor),  and suggest ignoring the overly 
pedantic (and confusing) response to the contrary.


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
https://mail.python.org/mailman/listinfo/python-list


Re: Image loading problem

2016-05-21 Thread Gary Herron

On 05/21/2016 08:22 AM, sweating_...@yahoo.com wrote:

Hi All,


I am working on an image project, and I can display my image in main(). I mean, 
I can load my image in my main(). Needless, it is awkward. I am trying to load 
my image with a function, but got an empty image window popped up, no image 
content loaded. Please take a look at code:



rom Tkinter import *

def load_img(win):  
img = PhotoImage(file="xxx.gif")
Label(win, image=img).pack()

win = Tk()
load_img(win)
win.mainloop()

Somebody can help me out? Thanks!



I believe this the problem (However It's been long since I used Tkinter, 
so be warned ... ):


The function load_img creates a local variable named img which goes out 
of scope and is deleted immediately when the function returns. However, 
Tkinter needs you to keep that image around as long as the Label uses 
it.   So, some solutions are:


keep_me = [] #  Global for keeping references to images
def load_img(win):
img = PhotoImage(file="xxx.gif")
keep_me.append(img)
Label(win, image=img).pack()

or


def load_img(win):
img = PhotoImage(file="xxx.gif")
Label(win, image=img).pack()
return img

saved_img = load_img(win)
...


Gary Herron



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Spreading a class over multiple files

2016-06-05 Thread Gary Herron

On 06/04/2016 11:55 PM, Mark Summerfield wrote:

Sometimes I want to spread a class over multiple files.


There’s and easy way to do this in Python using what's called a Mixin 
class and (multiple) inheritance:

  (See https://en.wikipedia.org/wiki/Mixin for more information.)

In one file, say extras.py

   class ExtraMethodsMixin:

  def extra_1(...):
  ...

  def extra_2(...):
  ...



In the main class file:

   from extras import ExtraMethodsMixin

   class MainClass(ExtraMethodsMixin):

  def __init__(...):
  ...
   # and so on


The result will be essentially the same as if all three methods were 
defined in MainCLass.



Gary Herron


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418





My primary use case is when I create a "Model" class to reflect an entire SQL 
database. I want a model instance to provide a single point of access to
  the database, but the database has many tables each requiring its own methods 
since they differ in their structure, purpose, validation needs, etc.

A secondary use case is when I create "MainWindow" classes in GUI programming 
and have lots of methods to reflect all the actions (e.g., menu options
and toolbar actions, plus interaction with the main widget(s)).

To meet these needs I've devised an approach that I think is easy to use and 
understand and which doesn't use any tricky or hard to maintain code.

My question is -- are there nicer/better ways to achieve this?

Here's a summary of my approach. A fuller discussion is on my website:
https://www.qtrac.eu/pyclassmulti.html

# Lib.py
# This provides the two functions (both decorators) used to support my approach
def add_methods_from(*modules):
 def decorator(Class):
 for module in modules:
 for method in getattr(module, "__methods__"):
 setattr(Class, method.__name__, method)
 return Class
 return decorator

def register_method(methods): # A decorator used purely for its side-effect
 def register_method(method):
 methods.append(method)
 return method # Unchanged and not strictly necessary
 return register_method

# Model.py
# This provides my model but some methods are in separate files
import Lib
import _ModelConfig
import _ModelOutput

@Lib.add_methods_from(_ModelConfig, _ModelOutput)
class Model:
 ...
 def small_method(self):
 ...

# _ModelConfig.py # _ModelOutput has the same structure so not shown
import Lib

__methods__ = [] # self is a Model
register_method = Lib.register_method(__methods__)

@register_method
def config(self):
 ...
So, that's the overall pattern of my solution.

Is there a nicer/better way? Could I cleanly avoid the explicit imports (e.g., 
import _ModelConfig), without resorting to stack frame hacks or similar?


--
https://mail.python.org/mailman/listinfo/python-list


Re: Operator precedence problem

2016-06-06 Thread Gary Herron

On 06/04/2016 11:53 PM, ICT Ezy wrote:

2 ** 3 ** 2

Answer is 512
Why not 64?
Order is right-left or left-right?


Evidently right to left, but you already figured that out.

Python 3.5.1+ (default, Mar 30 2016, 22:46:26)
[GCC 5.3.1 20160330] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 2 ** 3 ** 2
512
>>> 2 ** (3 ** 2)
512
>>> (2 ** 3) ** 2
64
>>>


Here's the relevant documentation page:
https://docs.python.org/3/reference/expressions.html
Look for "... except for exponentiation, which groups from right to left"

Gary Herron

--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: CAD Application

2019-05-06 Thread Gary Herron



On 5/5/19 10:23 PM, britt...@gmail.com wrote:

Hello All,

What are the frameworks available for developing a CAD application with
Python?


Regards
Britto


Well, there's PythonCadhttps://sourceforge.net/projects/pythoncad/

It seems to have stopped development about 5 years ago, but it's still 
available for download.



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Multiprocessing and memory management

2019-07-03 Thread Gary Herron


On 7/3/19 9:37 AM, ijbrews...@alaska.edu wrote:

I have a script that benefits greatly from multiprocessing (it’s generating a 
bunch of images from data). Of course, as expected each process uses a chunk of 
memory, and the more processes there are, the more memory used. The amount used 
per process can vary from around 3 GB (yes, gigabytes) to over 40 or 50 GB, 
depending on the amount of data being processed (usually closer to 10GB, the 
40/50 is fairly rare). This puts me in a position of needing to balance the 
number of processes with memory usage, such that I maximize resource 
utilization (running one process at a time would simply take WAY to long) while 
not overloading RAM (which at best would slow things down due to swap).

Obviously this process will be run on a machine with lots of RAM, but as I 
don’t know how large the datasets that will be fed to it are, I wanted to see 
if I could build some intelligence into the program such that it doesn’t 
overload the memory. A couple of approaches I thought of:

1) Determine the total amount of RAM in the machine (how?), assume an average 
of 10GB per process, and only launch as many processes as calculated to fit. 
Easy, but would run the risk of under-utilizing the processing capabilities and 
taking longer to run if most of the processes were using significantly less 
than 10GB



Try psutil to get information about memory (and cpu usage and lots 
more).  For example:


>>> import psutil
>>> psutil.virtual_memory()
svmem(total=16769519616, available=9151971328, percent=45.4, 
used=7031549952, free=4486520832, active=9026158592, 
inactive=2238566400, buffers=312815616, cached=4938633216, 
shared=234295296, slab=593375232)


Home page: https://github.com/giampaolo/psutil




2) Somehow monitor the memory usage of the various processes, and if one 
process needs a lot, pause the others until that one is complete. Of course, 
I’m not sure if this is even possible.

3) Other approaches?


---
Israel Brewster
Software Engineer
Alaska Volcano Observatory
Geophysical Institute - UAF
2156 Koyukuk Drive
Fairbanks AK 99775-7320
Work: 907-474-5172
cell:  907-328-9145


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Calculations and Variables

2019-10-31 Thread Gary Herron


On 10/31/19 11:46 AM, ferzan...@gmail.com wrote:

The code below which I have written should print the result of 43.6 with the 
given values I have included at the end of this question, but for some odd 
reason I get the result of 44.44.


bill = (input("Enter the total cost of the meal: \n"))  
  
tip = (input("Enter how much the tip is: \n"))  
  
split = (input("Enter how many people there are: \n"))  
  
total = bill + (bill / tip) 


Don't you mean
 total = bill + (bill * tip) ?



eachPay = total / split 
print("Each person will have to pay %.2f" % eachPay)



I am aiming for the result of 43.6, but somehow get the result of 44.44.
(meal cost: 200) (Tip: 9) (people: 5)

I seem to do the calculation below, but get different results each time.
Total * Percentage Amount / 100


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Source Code for a HTTP Proxy

2005-09-23 Thread Gary Herron
llothar wrote:

>Hello,
>
>i'm looking for a simple http proxy in python.
>Does anybody know about something like this ?
>
>  
>

Here's a list, maintained by Alan Kennedy,  of about 20 proxys written 
in Python:
http://xhaus.com/alan/python/proxies.html

Enjoy,
Gary Herron
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What do you use as symbols for Python ?

2005-11-10 Thread Gary Herron
Erik Max Francis wrote:

>Pierre Barbier de Reuille wrote:
>
>  
>
>>When you need some symbols in your program, what do you use in Python ?
>>
>>For example, an object get a state. This state is more readable if
>>expressed as a symbols, for example "opened", "closed", "error".
>>Typically, in C or C++, I would use an enum for that:
>>enum OBJECT_STATE
>>{
>>  opened, closed, error
>>}
>>
>>
>
>   OPENED, CLOSED, ERROR = range(3)
>
>   object.state = OPENED
>  
>
Another similar approach that keeps those values together in a single 
namespace is this (my favorite):

  class State:
  OPENED, CLOSED, ERROR = range(3)

Then you can refer to the values as
State.OPENED
State.CLOSED
State.ERROR

The extra clarity (and slight wordiness) of the dotted notation seems, 
somehow, quite Pythonic to me.

Gary Herron



-- 
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: weird problem with os.chmod

2005-11-11 Thread Gary Herron
James Colannino wrote:

>James Colannino wrote:
>
>  
>
>>So then I entered the command print 0600, and saw that the 
>>actual number being output was 384 (why would it output 384?!)
>> 
>>
>>
>>
>
>Ok, so further research revealed that 0600 is actually the octal 
>representation for 384 (which makes sense.)  So then, I guess my 
>question would have to be, is there a way for me to make Python aware 
>that the 0600 I'm passing to int() is octal and not decimal so that I 
>will get 384 instead of 600?
>  
>
int('0600',8) will do, but why would you want to do that?

Any of
x = 0600
x = 384
x = 0x180
x = int('0600',8)
will bind x to the same value (11000 in binary if you care).

But once you've got the valued defined, through whatever human readable 
representation you want, the command
chmod(filename, x)
can be issued without further thought.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to convert between type string and token

2005-11-14 Thread Gary Herron
This is not really a Python question, but a question on how to use the
nltk package.  I've never used, installed nor even seen that package, so
of course I can't answer your question, but I do have a suggestion.

A quick goggle finds a web page for nltk: http://nltk.sourceforge.net/.
Is that where your nltk package comes from?  If so, look there for an
email list where you can ask this question.  If not, they appear to have
tutorials and documentation that might help.  If not, you may be able to
get an answer here, but the other pro-active suggestions are likely to
produce better results faster.

Good luck,
Gary Herron


enas khalil wrote:

>
> hello all
> when i run the code :
> # -*- coding: cp1256 -*-
> from nltk.tagger import *
> from nltk.corpus import brown
> from nltk.tokenizer import WhitespaceTokenizer
> # Tokenize ten texts from the Brown Corpus
> train_tokens = []
> xx=Token(TEXT=open('fataha2.txt').read())
> WhitespaceTokenizer().tokenize(xx)
> for l in xx:
> train_tokens.append(l)
> #Initialise and train a unigram tagger
> mytagger = UnigramTagger(SUBTOKENS='WORDS')
> for tok in train_tokens: mytagger.train(tok)
> #Once a UnigramTagger has been trained, the tag() method can be
> used to tag new text:
> text_token = Token(TEXT="ÇáÍãÏ ááå ÑÈ ÇáÚÇáãíä")
> WhitespaceTokenizer(SUBTOKENS='WORDS').tokenize(text_token)
> mytagger.tag(text_token)
> print 'The first example : Using Unigram Tagger the reseults are :
> '*print
> acc = tagger_accuracy(mytagger, train_tokens)
> print ' With Accuracy :Accuracy = %4.1f%%,' % (100 * acc) *
> * *
> * *
> * *
> *i got the following error :*
> * *
> *Traceback (most recent call last):
>   File "F:\MSC first Chapters\unigramgtag1.py", line 14, in -toplevel-
> for tok in train_tokens: mytagger.train(tok)
>   File "C:\Python24\Lib\site-packages\nltk\tagger\__init__.py",
> line 324, in train
> assert chktype(1, tagged_token, Token)
>   File "C:\Python24\Lib\site-packages\nltk\chktype.py", line 316,
> in chktype
> raise TypeError(errstr)
> TypeError: *
> * *
> *  Argument 1 to train() must have type: Token
>   (got a str)*
> * *
> * *
> * *
> *please i want a help on how to recover this error , in other
> words how can i convert between type string and token , as im
> still new in python*
> * *
> *thanks in advance*
> * *
> * *
>
> * *
>
> --------
> * Yahoo! FareChase - Search multiple travel sites in one click. 
> <http://us.lrd.yahoo.com/_ylc=X3oDMTFqODRtdXQ4BF9TAzMyOTc1MDIEX3MDOTY2ODgxNjkEcG9zAzEEc2VjA21haWwtZm9vdGVyBHNsawNmYw--/SIG=110oav78o/**http%3a//farechase.yahoo.com/>
>  
> *





-- 
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what's wrong with "lambda x : print x/60,x%60"

2005-12-04 Thread Gary Herron
Mohammad Jeffry wrote:

> Dear All,
>
> Can't a lambda uses the input parameter more then once in the lambda 
> body?
> eg:
> lambda x : print x/60,x%60
>
> I tried with def and it works but got syntax error with lambda. Below 
> is an interactive sample:

Lambda evaluates a single *expression* and returns the result.  As print 
is a statement it does not qualify (and would provide nothing to return 
even if it did).  So just use a def.  It is constantly pointed out on 
this list that the lambda provides no extra expressive power, it is 
merely a shortcut and, as you just found out, a rather restrictive one 
at that.

See the reference manual entry: 
http://www.python.org/doc/2.4.2/ref/lambdas.html

As for your next question,
lambda x : x/60,x%60
is parsed as
(lambda x: x/60), x%60
That is, the scope of the lambda (and its x) are finished by the comma.
Perhaps being more explicit about the returned tuple would produce what 
you want.
    lambda x : (x/60,x%60)

Gary Herron

>
> [EMAIL PROTECTED] ~ $ python
> Python 2.4.2 (#1, Nov 18 2005, 19:32:15)
> [GCC 3.3.6 (Gentoo 3.3.6, ssp-3.3.6-1.0, pie-8.7.8)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> def func_hrs(x): print x/60,x%60
> ...
> >>> func_hrs(400)
> 6 40
> >>> lambda_hrs = lambda x : print x/60,x%60
>   File "", line 1
> lambda_hrs = lambda x : print x/60,x%60
> ^
> SyntaxError: invalid syntax
> >>>
>
> My main concern is how can I do this in lambda?
>
>
>
> -- 
> And whoever does an atom's weight of evil will see it. 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Slicing every element of a list

2005-07-12 Thread Gary Herron
Alex Dempsey wrote:

>Recently I tried to slice every element of a list of strings. First I tried:
>
>f = open("export.xls", "r")
>lines = f.readlines()
>
>for line in lines:
>line = line[1:-5]
>line = line.split('\"\t\"')
>  
>
This, in fact, did do the operation you expected, but after creating the 
new value and assigning it to line, you promptly threw it away. (Because 
the loop then went back to the top and (re)assigned the next thing in 
lines to line wiping out your nicely sliced computation in lines.)  You 
need to *do* something with the value in line before you end the loop -- 
but what?

>This went without returning any errors, but nothing was sliced or
>split. Next I tried:
>
>for i in range(len(lines)):
>lines[i] = lines[i][1:-5]
>lines[i] = lines[i].split('\"\t\"')
>
>This of course worked, but why didn't the first one work. Further why
>didn't the first one return an error?
>  
>
Dr. Gary Herron
Digipen Institute of Technology


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No newline using printf

2005-09-16 Thread Gary Herron
Samuel wrote:

>Hello,
>
>I have been searching for an answer for almost two hours now and have
>not found an answer. I want this code:
>
>for i in range(3):
>  print i   # or whatever
>
>To produce this output:
>012
>
>How can I print a word without appending a newline character? Appending
>a "," to the print statement only substitutes the newline for a space,
>which is not what I am looking for.
>
>Any hints?
>
>Thanks,
>-Samuel
>
>  
>
The solution is to take over full control of the output with 
sys.stdout.write.

Use '%1d' % i to convert your number into a single character string.

Use sys.stdout.write to send exactly the characters you want to sys.stdout.

Thus:  sys.stdout.write('%1d' % i) should do what you want.

Dr Gary Herron
Digipen Institute of Technology

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why this error?

2005-03-15 Thread Gary Herron
spencer wrote:
Hi,
I'm not sure why I can't concatenate dirname() with basename().
 

Of course you *can* concatenate them, but you're not getting that far.  
The piece 

   os.path.dirname(os.getcwd)
should be
   os.path.dirname(os.getcwd())
Then it will work without raising an exception, but I'm not sure the 
result makes sense.

Traceback (most recent call last):
 File "showDir.py", line 50, in ?
   print 'somthing new...', os.path.join(os.path.dirname(os.getcwd)) +
os.path.basename(os.getcwd())
 File "/usr/lib/python2.3/posixpath.py", line 119, in dirname
   return split(p)[0]
 File "/usr/lib/python2.3/posixpath.py", line 77, in split
   i = p.rfind('/') + 1
AttributeError: 'builtin_function_or_method' object has no attribute
'rfind'
Thanks,
Wayne
 

--
http://mail.python.org/mailman/listinfo/python-list


Re: Please help with this

2013-11-12 Thread Gary Herron

On 11/12/2013 08:18 PM, saad imran wrote:

Could you point out any errors in my code:





Nope.



You've got to do *some* of the work if you expect free volunteer help 
from people around here.  Take the time to tell us what you expect this 
program to do, what actually happens when you run it, what errors you 
get.  If you get Python traceback, cut and paste it into an email.
Tell us how you have tried to fix the problem, whatever that may be.  
Give some hint where in the nearly 300 lines of code the problem may be 
occurring.


You can get lots of free volunteer help from this group, but the 
question, as you've asked it, is a misuse (or even an *abuse*) of this 
group.


Gary Herron


--
https://mail.python.org/mailman/listinfo/python-list


Re: Newbie - Trying to Help a Friend

2013-11-19 Thread Gary Herron

On 11/19/2013 10:40 AM, bradleybooth12...@gmail.com wrote:

Hi,

A Friend is doing maths in University and has had some coursework to do with 
python.

The question is

"Write a program that calculates how many positive integers less than N are not 
divisible by 2,3 or 5. The user should be prompted to supply the Number N. 
Demonstrate your program output when the input N is your student id. (13006517)

"The collatz process is as follows. Take a positive integer n greater than 1. 
while n is greater than 1 repeat the following; if N is even halve it and if N is 
odd multiply it by 3 and add 1. The (Unsolved) collatz conjecture is that this 
process always terminates.

The user should be prompted to supply the number n, and your program should 
build the list of values taken by sucessive iteration of the algorithm, and 
print it out. For example, if 7 is input your program should print the list

[7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1]

Demonstrate your program output for an input value consisting of the number formed 
adding 10 to the last digit of your student id. (13006517)"

Any help would be appreciated


What sort of help are you requesting?  We're not in the habit of writing 
student assignments for them because they will learn nothing from such 
an effort.
Your friend should read the book/lecture-notes/whatever, and make an 
attempt on the assignment.  If he gets stuck, he may ask a specific 
Python question.  I'm sure lots of help will follow.


As a side note, these are extremely simple beginner problems, each 
requiring only a few lines of code.  Any programming class that assigned 
these must have included some lectures on the basics of programming.   
That's where he should start.


Gary Herron
--
https://mail.python.org/mailman/listinfo/python-list


Re: Newbie - Trying to Help a Friend

2013-11-21 Thread Gary Herron

On 11/21/2013 03:17 PM, bradleybooth12...@gmail.com wrote:

Coming back to the second question

"The collatz process is as follows. Take a positive integer n greater than 1. 
while n is greater than 1 repeat the following; if N is even halve it and if N is 
odd multiply it by 3 and add 1. The (Unsolved) collatz conjecture is that this 
process always terminates.

The user should be prompted to supply the number n, and your program should 
build the list of values taken by sucessive iteration of the algorithm, and 
print it out. For example, if 7 is input your program should print the list

[7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1]

We've managed to come up with this, but obviously it's wrong. Any Idea's?

def collatz_sequence (n) :
   seq = [ ]
   if n < 1 :
  return [ ]
   while n > 1:
if n % 2 == 0:
 n = n/2
   else:
  n = 3*n+ 1
   seq.append (n)
  return seq


Why  do you say it's wrong?   What does it do?   What was expected?

I see that your indentations don't match, but I can't tell if that's 
your error or an email problem.  Is that the 'obviously wrong' part?


I also see that you create an (apparently correct) function, which 
returns a nice result.  But you haven't called the function to actually 
run it with a specific value to be printed out.  Perhaps that's the  
'obviously wrong' part you refer to.


However, the function itself looks correct otherwise, although you may 
want to start the sequence off with [n] rather than [] so as to match 
the suggested output.


Gary Herron
--
https://mail.python.org/mailman/listinfo/python-list


Re: Newbie - Trying to Help a Friend

2013-11-21 Thread Gary Herron

On 11/21/2013 03:55 PM, bradleybooth12...@gmail.com wrote:

the problem i have is that it's just giving me the first number of the sequence 
not the actual sequence


Not when I run it.  After correcting the indentation errors, I get the 
correct sequence *except* that it's missing the first number.


You are making it very hard to help you.  Please show us the *whole* 
session: the procedure (correctly indented please), the call of the 
procedure, the print that outputs the result and the actual printed 
result.  Also provide an explanation of why the output is not what you 
wanted.


Then perhaps we can get to the bottom of this.

Gary Herron
--
https://mail.python.org/mailman/listinfo/python-list


Re: Extending the 'function' built-in class

2013-12-01 Thread Gary Herron

On 12/01/2013 11:18 AM, G. wrote:

Hi, I can't figure out how I can extend the 'function' built-in class. I tried:
   class test(function):
 def test(self):
   print("test")
but I get an error. Is it possible ?

Regards, G.


What error do you get?
What version of Python?
What OS?

And in particular: What 'function' built-in class?  I know of no such 
thing, and the error message I get with your code says exactly that:

  NameError: name 'function' is not defined
Did you not get that same error?

All of which begs the questions: What do you think the function class 
is, and why are you trying to extend it?


Gary Herron

--
https://mail.python.org/mailman/listinfo/python-list


Re: Eliminate "extra" variable

2013-12-06 Thread Gary Herron

On 12/06/2013 11:37 AM, Igor Korot wrote:

Hi, ALL,
I have following code:

def MyFunc(self, originalData):
  data = {}
  dateStrs = []
  for i in xrange(0, len(originalData)):
dateStr, freq, source = originalData[i]
data[str(dateStr)]  = {source: freq}
dateStrs.append(dateStr)
 for i in xrange(0, len(dateStrs) - 1):
   currDateStr = str(dateStrs[i])
   nextDateStrs = str(dateStrs[i + 1])


It seems very strange that I need the dateStrs list just for the
purpose of looping thru the dictionary keys.
Can I get rid of the "dateStrs" variable?

Thank you.


You want to build a list, but you don't want to give that list a name?  
Why not?  And how would you refer to that list in the second loop if it 
didn't have a name?


And concerning that second loop:  What are you trying to do there? It 
looks like a complete waste of time.  In fact, with what you've shown 
us, you can eliminate the variable dateStrs, and both loops and be no 
worse off.


Perhaps there is more to your code than you've shown to us ...

Gary Herron

--
https://mail.python.org/mailman/listinfo/python-list


Re: python programming help

2013-12-08 Thread Gary Herron

On 12/08/2013 09:59 AM, rafaella...@gmail.com wrote:

i have a dictionary with names and ages for each name. I want to write a 
function that takes in an age and returns the names of all the people who are 
that age.
please help


This looks like homework for a beginning programming class. Correct?

We like helping people use Python, and we like helping people learn 
Python, but neither of those purposes are served by us *doing* your 
homework for you.


Please, you try to solve the problem, and when you get stuck, show us 
your code, and ask a specific question.


Hint:  You will almost certainly need a loop (through the dictionary 
entries), an 'if' conditional to test for the age matching the given 
age, and a print,


Gary Herron
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Script

2013-12-12 Thread Gary Herron

On 12/12/2013 10:05 AM, Amimo Benja wrote:

I have an issue with a Python script that I will show as follows:
http://codepad.org/G8Z2ConI

Assume that you have three (well defined) classes: AirBase and VmNet, . VmNet 
has got a method that is called recursively each time an HTTP response is 
received. The variable recordTuple needs to be built independently for each 
instance of VmNet that is created. However, the mentioned variable is being 
overwritten across every instance, so if you try to get it from 
vmnet_instance_y, you would get exactly the same than retrieving it from 
vmnet_instance_x.

• What is the code issue? I need to use this script in a project and I don't 
know how to proceed.

Actually, the script aims to follow the principle don't repeat yourself (DRY). 
As you may notice, VmNet and AirBase does not have def __init__(self), so 
self.recordTupleBase does not probably exist. Additionally, many other 
subclasses, similar to VmNet, can implement the recursive method using that 
recordTupleBase.

* I will gladly appreciate any help thanks


You haven't actually asked a question here.  You say you don't know how 
to proceed with "a project", but we don't know what that project is.  In 
fact, I can't even figure out if your trouble is with the script, or 
with using the script in this unknown project.


Also, if you repost, please include the script in the email, not as a 
pointer to somewhere else.



Gary Herron

--
https://mail.python.org/mailman/listinfo/python-list


Re: Knapsack Problem Without Value

2013-12-12 Thread Gary Herron

On 12/12/2013 06:08 PM, geezl...@gmail.com wrote:

Hi,

I wanna ask about Knapsack. I do understand what Knapsack is about. But this 
one i faced is a different problem. There is no value. I mean, it's like this, 
for example.

I have 4 beams [X0, X1, X2, X3]. Each 1, 2, 2, 3 cm long. I want to make a new 
6 cm long connected-beam from these 4 beams. I can make it from some of these. 
The output will print:

1, 2, 3 #(X0, X1, X3)

You understand what my problem is? Can you help me?

Sincerely,


No, I don't understand what your problem is.

You say there are no values but then you give 4 values (1, 2, 2, and 3), 
and then you *solve* the Knapsack problem like this:

1, 2, 3 #(X0, X1, X3)

That looks like a fine solution to me.

Questions:

 * Exactly *what* is the problem.  If you tell us *carefully* what the
   problem is, we may try to solve it.

 * This is a Python list.  Does your problem have anything to do with
   Python?

 * Is this a homework problem?  We generally don't solve homework
   problems here (since you don't learn anything that way), but we are
   certainly happy to help you learn.

Gary Herron

--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Wrapping around a list in Python.

2013-12-15 Thread Gary Herron

On 12/15/2013 08:38 PM, shengjie.sheng...@live.com wrote:

Hi guys, I am trying to create a fixed list which would allow my values to be 
wrapped around it.
For example i have 10 values : 0,1,2,3,4,5,6,7,8,9
I need to create a list which contains 4 numbers and when the number exceeds 
the list, it would overwrite the first value.
[0,1,2,3]
[4,1,2,3]
[5,4,1,2]

Thanks in advance and much help appreciated.


Is the output really three lists as you show.  Or is that one list whose 
contents you have shown three snapshots of?  Then what was the point of 
putting 4 in the first spot when you are just going to move it to the 
second spot?  And why stop at 4 and 5?  What about 7, 8, and 9?


Are you really shifting elements onto the beginning of the list and off 
the end of the list?  (That's easy to do, but is that what you want?)


If I follow your example a few elements further I get [9,8,7,6], just 
the last four elements of the original list in reverse order -- so there 
is no need fill a list and "wrap-around"  -- just grab the last four 
elements and reverse them.


Or have I misunderstood the problem completely?  (I think that's 
likely.)  I'm sure Python is general enough to do what you want, but 
you'll have to do a much better job telling is what you want.  While you 
are at it, tell us what you've already done, and how it fails to do 
whatever it is you want.


Gary Herron

--
https://mail.python.org/mailman/listinfo/python-list


Re: Pygame vector handling?

2013-12-21 Thread Gary Herron

On 12/21/2013 08:24 PM, Downright Trows wrote:

I'm trying to pass a vector for the pygame function pygame.transform.rotate The 
only issue is that this doesn't work and I'm in grade 10 and haven't done the 
trig unit yet :L

Does anyone know a workaround? here is my code if it will help 
http://pastebin.com/FZQB5eux
here is a link to the pygame transform function 
http://www.pygame.org/docs/ref/transform.html
Thank you anyone who is kind enough to attempt to help me.


Welcome to programming in  Python!   Please tell us what you want to do, 
what you tried, and how it failed.  Without that information, it's 
impossible to tell what you are asking.


More specifically:

 * The rotate function does not take a vector as an argument so I don't
   know what you mean by "trying to pass a vector for the pygame
   function 
 * "It doesn't work" tells us nothing.  What error message, or what
   incorrect results?
 * I'm not likely to read your hundred+ lines of code trying to find a
   bug.  Please reduce you question to one or several lines of code,
   what you expect them to do, and what they are doing that you
   consider incorrect.

Gary Herron


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: cascading python executions only if return code is 0

2013-12-22 Thread Gary Herron

On 12/22/2013 10:37 AM, Frank Cui wrote:

hey guys,

I have a requirement where I need to sequentially execute a bunch of 
executions, each execution has a return code. the followed executions 
should only be executed if the return code is 0. is there a cleaner or 
more pythonic way to do this other than the following ?


if a() == 0:
if b() == 0:
c()

Thanks for your input.

frank


This would seem to do the same as your code and could easily be extended 
to your "bunch" of things:


exes = [a, b, c]

for e in exes:
  if e() != 0:
break
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 2nd Try: Trouble writing lines to file that include line feeds - Newbie

2013-12-23 Thread Gary Herron

On 12/22/2013 04:55 PM, Dan Healy wrote:

Overview: I'm attempting to read strings from a serial port. Each string ends 
with a carriage return and line feed. I want to write those strings to a file, 
like a log file. So, if I send P1 and the P2 on a new line, I would expect to 
open this file and find (line 1) P1 (line 2) P2.

Problem: The file only contains P2. It always overwrites the first line. I can 
send 20 strings and the file will always contain the last string received.

Code:

#Import the serial module
import serial

#Open the serial port w/ settings
ser=serial.Serial(
 port="/dev/ttyUSB0",
 baudrate=9600,
 timeout=None)

#Print data received on the serial port after removing the CR and LF characters
while True:
 rawcode=ser.readline()
 codelog=open('/home/pi/avdms/codes.log','w')
 codelog.write(rawcode)
 codelog.close()


First, that code is quite foolish:  If you want to write multiple lines 
to a file, open the file once before the loop, looped through all your 
writes, and then closed it after the loop has exited.:


codelog=open('/home/pi/avdms/codes.log','w')
while True:
rawcode=ser.readline()
codelog.write(rawcode)

codelog.close()



However, on the chance that you are writing this code for testing 
purposes, and you really do have a need to open a file, write something 
onto the end and then close the file, and that you are going to do this 
many times, I'll continue with this response:


   The default behavior of the "open" call is to *truncate* (i.e.,
   clear the  contents) and start writing at the beginning. The
   behavior you want is called *append*, and you get it with a 'wa' as
   the second parameter of the open call.


See http://docs.python.org/3/library/functions.html#open for a list of 
other modes available for the open call.


Gary Herron

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How can i return more than one value from a function to more than one variable

2013-12-23 Thread Gary Herron

On 12/22/2013 02:54 PM, dec...@msn.com wrote:

basically what I wanna do is this :

x = 4
y = 7
def switch (z,w):
***this will switch z to w and vice verca***
  c= z
  z=w
  w=c
  print 'Now x =', w, 'and y = ' , z
  return w
x = switch(x,y)

  How am I supposed to do so I can  return also a value to the variable y 
WITHOUT printing 'Now x =', w, 'and y = ' , z   a second time ?

thanks in advance


I don't' understand the question, but if you are just trying to exchange 
the values of x and y, this will do:


x,y = y,x


If you want a function to return several values to several variables, try:

def fn(...):
# calculate a and b
return a,b

p,q = fn(...)

All these comma-separated sequences are tuples, often written with 
parentheses as (x,y)=(y,x) and (p,q)=fn(...), but as here,  the 
parentheses are often not necessary.


Gary Herron


--
https://mail.python.org/mailman/listinfo/python-list


Re: Ifs and assignments

2014-01-02 Thread Gary Herron

On 01/02/2014 09:20 AM, John Allsup wrote:

Hi,

This is my debut on this list.

In many languages, such as C, one can use assignments in conditionals 
and expressions.  The most common, and useful case turns up when you 
have if/else if/else if/else constructs. Consider the following 
non-working pseudoPython.


import re
r1 = re.compile("hello (\d)")
r2 = re.compile("world([!?])")

w = "hello world!"

if m = r1.search(w):


This kind of thing in C/C+ has always been the source of much confusion 
and potential errors, because the construct is so similar to an "==" 
test.  Python does not replicate this potential for confusion.   
Instead, we use two lines of code, an assignment and then the test.   If 
you find that extra line of code inconvenient than at least you can take 
comfort in the fact that it is clearer code.  If you are still not 
convinced, ... then sorry, that's just the way Python is.


Gary Herron



handleMatch1(m)
elif m = r2.search(w):
handleMatch2(m)
else:
print("No match")

If the regular expressions are complex, running them multiple times 
(once to test, another to capture groups) isn't ideal.  On the other 
hand, at present, one has to either do:


m = r1.search(w)
if m:
handleMatch1(m)
else:
m = r2.search(w)
if m:
handleMatch2(m)
else:
print("No match")

if not running unnecessary matches, yet capturing groups in the event 
of a successful match, is what is desired.


If there are multiple tests, the indentation gets silly.  This arises 
because having removed the ability to assign in an expression, there 
is no way to save the result of a function call that is used in a 
conditional at all.


I am aware that this facility in C is a source of bugs, = being only a 
typo away from the more common ==.  With exceptions and contexts, we 
have:


with open("file") as f:
doSomethingWith(f)

try:
trySomething()
except SomethingRandomGoingWrong as e:
lookAtException(e)

What I am wondering is why not use a similar syntax with if, so that 
one could do


if r1.search(w) as m:
g = m.groups()
print(g[1])

This would remove the risk of errors by typos since the syntax for 
equality testing (if x == y:) is completely different from that for 
assigning in a conditional (which would look like 'if y as x:'


Related would be to have Nonetype work with contexts such that

with None as x:
doStuff(x)

would do nothing.  This would allow things like:

with maybeGetSomething as x:
doStuff(x)

to call doStuff(x) within a context of maybeGetSomething returns 
something, or do nothing if nothing is returned.  (Adding an else-like
keyword to with, or possibly using else in that context, would allow 
one to process a non-None object if returned, or else do something in 
response to a None object being returned by the maybeGetSomething.)


Just a thought.

Or what is the current 'Pythonic' way to do something like:

if x = func1():
do1(x)
elif x = func2():
do2(x)
elif x = func3():
do3(x)
elif x = func4():
do4(x)
else:
do5()

where each of func1,func2,func3,func4 have side effects so that func2 
is tested if and only if func1 returns a false value, func1 must be 
called only once, and what is returned from func1 must be available to 
the code inside the if block?



John



--
https://mail.python.org/mailman/listinfo/python-list


Re: Ifs and assignments

2014-01-02 Thread Gary Herron

On 01/02/2014 01:44 PM, John Allsup wrote:

The point of my original post was that, whilst C's
  if( x = 2 ) { do something }
and
  if( x == 2 ) { do something }
are easy to confuse, and a source of bugs, having a construct like 
follows:


if x == 2:
do something # what happens at present
if testFunc() as x:
do something with x

using the 'as' syntax that appears with 'with' and 'except', would allow
for the advantages of C style assignments in conditionals but without 
the easy confusion, since here the syntax is significantly different 
between assignment and equality testing (rather than a character apart 
as happens with C).


This occurs further down in my original post (past the point where you 
inserted your reply).


Another post suggested a workaround by defining a 'pocket' class, for 
which I am grateful.


John


Sorry.  I shot off my answer before reading the whole post.  That's 
never a good idea.



After reading to the end, I rather like your suggestion.  It works well 
in your example, , nicely avoids the C/C++ trap, and has some 
consistency with other parts of Python.


Gary Herron





On 02/01/2014 19:27, Gary Herron wrote:

On 01/02/2014 09:20 AM, John Allsup wrote:

Hi,

This is my debut on this list.

In many languages, such as C, one can use assignments in conditionals
and expressions.  The most common, and useful case turns up when you
have if/else if/else if/else constructs. Consider the following
non-working pseudoPython.

import re
r1 = re.compile("hello (\d)")
r2 = re.compile("world([!?])")

w = "hello world!"

if m = r1.search(w):


This kind of thing in C/C+ has always been the source of much confusion
and potential errors, because the construct is so similar to an "=="
test.  Python does not replicate this potential for confusion. Instead,
we use two lines of code, an assignment and then the test.   If you find
that extra line of code inconvenient than at least you can take comfort
in the fact that it is clearer code.  If you are still not convinced,
... then sorry, that's just the way Python is.

Gary Herron



handleMatch1(m)
elif m = r2.search(w):
handleMatch2(m)
else:
print("No match")

If the regular expressions are complex, running them multiple times
(once to test, another to capture groups) isn't ideal.  On the other
hand, at present, one has to either do:

m = r1.search(w)
if m:
handleMatch1(m)
else:
m = r2.search(w)
if m:
handleMatch2(m)
else:
print("No match")

if not running unnecessary matches, yet capturing groups in the event
of a successful match, is what is desired.

If there are multiple tests, the indentation gets silly.  This arises
because having removed the ability to assign in an expression, there
is no way to save the result of a function call that is used in a
conditional at all.

I am aware that this facility in C is a source of bugs, = being only a
typo away from the more common ==.  With exceptions and contexts, we
have:

with open("file") as f:
doSomethingWith(f)

try:
trySomething()
except SomethingRandomGoingWrong as e:
lookAtException(e)

What I am wondering is why not use a similar syntax with if, so that
one could do

if r1.search(w) as m:
g = m.groups()
print(g[1])

This would remove the risk of errors by typos since the syntax for
equality testing (if x == y:) is completely different from that for
assigning in a conditional (which would look like 'if y as x:'

Related would be to have Nonetype work with contexts such that

with None as x:
doStuff(x)

would do nothing.  This would allow things like:

with maybeGetSomething as x:
doStuff(x)

to call doStuff(x) within a context of maybeGetSomething returns
something, or do nothing if nothing is returned.  (Adding an else-like
keyword to with, or possibly using else in that context, would allow
one to process a non-None object if returned, or else do something in
response to a None object being returned by the maybeGetSomething.)

Just a thought.

Or what is the current 'Pythonic' way to do something like:

if x = func1():
do1(x)
elif x = func2():
do2(x)
elif x = func3():
do3(x)
elif x = func4():
do4(x)
else:
do5()

where each of func1,func2,func3,func4 have side effects so that func2
is tested if and only if func1 returns a false value, func1 must be
called only once, and what is returned from func1 must be available to
the code inside the if block?


John







--
https://mail.python.org/mailman/listinfo/python-list


Re: gotta love radio buttons

2014-01-05 Thread Gary Herron

On 01/05/2014 10:18 AM, eneskri...@gmail.com wrote:

So, I'm having this radio button issue in tkinter:
First I assign the IntVar:
var = []
while i < self.something:
 var.append(IntVar())
 i += 2
Later on I use them, but I get this error:
for r in var:
 helper = var[r].get()
 self.something_else[helper] += 1
Then, this happens:
Traceback (most recent call last):
   File "F:\Portable Python 3.2.5.1\App\lib\tkinter\__init__.py", line 1456, in 
__call__
 return self.func(*args)
   File "(Not giving this)", line 26, in submit_data
 helper = var[r].get()
TypeError: list indices must be integers, not IntVar
I'm willing to give additional info. Thank you in advance.



These two lines

for r in var:
helper = var[r].get()

are being redundant.

The loop returns elements from the list (one-by-one).   Also  var[r] 
attempts to return an element from the list (indexed by r -- expected to 
be an integer).


Either of these remove the redundancy (but the first is more Pythonic)

  for r in var:
  helper = r.get()

or

  for i in range(len(var)):
 helper = var[i].get()

Gary Herron

--
https://mail.python.org/mailman/listinfo/python-list


Re: gotta love radio buttons

2014-01-05 Thread Gary Herron

On 01/05/2014 10:47 AM, eneskri...@gmail.com wrote:

Now it is giving me this error, after changing to helper = var[r.get()]
line 27, in submit_data
 self.something_else[r][1] += 1
TypeError: list indices must be integers, not IntVar


In such an easy case, you really ought to be able to read the error and 
understand it rather than needing to rely on us to do that for you.


The message:
List indices must be integers, not IntVar
clearly indicates you are indexing a list with something of type IntVar 
instead of the required int.That would have to be the ...[r].  The 
value of r is *not* an integer, it's an IntVar which is container of an 
int but not an int itself.  You can access the contained int with 
r.get(), so perhaps ...[r.get()] is what you want.  (Or perhaps not...  
We really don't know what you are trying to do here.)



Reading error messages and understanding tracebacks are skills well 
worth trying to develop.  Good luck.


Gary Herron
--
https://mail.python.org/mailman/listinfo/python-list


Re: converting a string to a function parameter

2014-01-05 Thread Gary Herron

On 01/05/2014 11:39 AM, pietrod...@gmail.com wrote:

Il giorno venerdì 13 marzo 2009 08:52:39 UTC+1, koranthala ha scritto:

Hi,
 Is it possible to convert a string to a function parameter?
Ex:
str = 'True, type=rect, sizes=[3, 4]'
and I should be able to use it as:
test(convert(str)) and the behaviour should be same as calling test
with those values :
i.e. test(True, type=rect, sizes=[3, 4])

I tried eval, but it did not work. And any other mechanism I think
turns out to be creating a full fledged python parser.

Is there any mechanism with which we can do this straight away?

I need the exact opposite, what is the inverse function?
example: i pass to a function an argument

m=[654,54,65]
def function(m):
 return takethenameof(m)

and it have to return to me 'm' not [654,54,65] or '[654,54,65]'

anybody can help?
i think that when one is talking about a function he have to talk also of the 
inverse function (also because google have problems searching about this...


Absolutely not.  Objects (like [654,54,65]) do not have names, never did 
and never will!  Objects do have a type and a value (and an identity), 
but not a name.


Various namespaces will have dictionary-like associations between a name 
(like "m") and an object, and it *is* possible to get your hands on a 
(dictionary representing a) namespace and search it, but this is 
troublesome.


For instance, consider this small variation of your code:

def function(m):
   return takethenameof(m)

a=[654,54,65]
b = a
function(a)

While function is running, there will be three names associated with the list 
object.
The outer namespace will have "a" and "b" associated with the list object,
and the namespace local to function will have "m" associated with the same 
object.
That's one object associated with three names in two different namespaces.

Gary Herron


--
https://mail.python.org/mailman/listinfo/python-list


Re: buggy python interpretter or am I missing something here?

2014-01-26 Thread Gary Herron

On 01/26/2014 07:42 PM, me wrote:

I'm writing a linux daemon in python 2.x to process batches of GPS/GIS
data and I'm running into something that seems to break the expected
program flow in a REALLY BAD WAY.

Consider the attached template script and execute it with the -h option.
It is falling through to the except: clause even though try to manually
exit with sys.exit(0).  However, if I insert a "raise" into the except
clause then the sys.exit(0) executes properly.

See the attached code and output from when I run it.

Not interested in work-arounds.  I want to understand why it doesn't work
as expected.

Thanks!

TCdaemon.py 

#! /usr/bin/python

import sys


#
--

defaultparams={ \
 "basedir": "/process", \
 "inpipe": "/tmp/TCdaemonIN", \
 "maxjobs":8, \
 "outpipe": "/tmp/TCdaemonOUT", \
 "ZZZ": 0
 }

#
--

def parse_args(a,d):
 l=len(a)
 idx=1
 try:
 while (idx

Never *ever* have a bare except like that.  If it gets invoked, you have 
no idea why.   A simple typo like ixd instead of idx or a(idx) instead 
of a[idx] would raise an exception but give you no idea why.


Do
  try:
  ...
  except Exception,e:
  print e
at the absolute minimum.
(Python 3 syntax would differ slightly, but the advice is the same.)

Perhaps printing a traceback along with the exception would help. Add
traceback.print_exc()


Gary Herron




 
#

--
#
--
#
--

if (__name__=="__main__"):
 print defaultparams
 parse_args(sys.argv,defaultparams)
 print defaultparams
 





output.txt ---
[@blackbox new]$ ./TCdaemon.py -h
{'ZZZ': 0, 'basedir': '/process', 'outpipe': '/tmp/TCdaemonOUT',
'maxjobs': 8, 'inpipe': '/tmp/TCdaemonIN'}
help goes here
./TCdaemon.py: error in command line - ['-h']
[@blackbox new]$ echo $?
1
[@blackbox new]$
[@blackbox new]$
[@blackbox new]$ # editing to add "raise" at line 40
[@blackbox new]$
[@blackbox new]$
[@blackbox new]$
[@blackbox new]$ ./TCdaemon.py -h
{'ZZZ': 0, 'basedir': '/process', 'outpipe': '/tmp/TCdaemonOUT',
'maxjobs': 8, 'inpipe': '/tmp/TCdaemonIN'}
help goes here
[@blackbox new]$ echo $?
0
[@blackbox new]$




--
https://mail.python.org/mailman/listinfo/python-list


Re: buggy python interpretter or am I missing something here?

2014-01-26 Thread Gary Herron

On 01/26/2014 10:17 PM, me wrote:

On Sun, 26 Jan 2014 21:04:57 -0800, Gary Herron wrote:


Never *ever* have a bare except like that.  If it gets invoked, you have
no idea why.   A simple typo like ixd instead of idx or a(idx) instead
of a[idx] would raise an exception but give you no idea why.

Do
try:
...
except Exception,e:
print e
at the absolute minimum.
(Python 3 syntax would differ slightly, but the advice is the same.)

Perhaps printing a traceback along with the exception would help. Add
  traceback.print_exc()


So here's the clencher without debating the merits bare except: since a
bare catch(...) is totally acceptable in the c++ world.

When I have except: by itself the program fails...but simply adding the
"except Exception,e: " causes the program to work correctly.


Doubtful.   We've been doing this kind of stuff for decades without 
hitting your supposed bug.  Much more likely is that you've 
misinterpreted the results.  Ii don't know how, but I'm quite confident 
that you have.


Your contention that the raise goes back to the sys.exit() is certainly 
a mis-interpretation also.  The re-raise of the original exception is 
now an uncaught exception, and the interpreter's response to an uncaught 
exception is to kill the program.   Nearly the same result as the 
sys.exit(), but via a different pathway.




To me that signifies an undefined behavior of the python specification,
or at least bad behavior of the python interpreter I'm using.  If you can
syntactically use a bare except: without generating an invalid syntax
error then it should have a well defined and predictable outcome.


It is well defined.  Slow down a bit, rerun your two tests, show is the 
code *and* the results, and we'll get to the bottom of this.




If in fact the "except Exception, e:" is what's required then a bare
except shouldn't be considered valid syntax at all, right?


Bare excepts are perfectly legal valid syntax and have their uses, 
however it's just extremely dangerous programming to allow a simple typo 
(or any of an infinite number of possible errors) in your try section to 
masquerade as a "error in command line" (to quote your print at that 
point).Python's dynamic typing makes bare except extremely 
dangerous.  In Python, unlike C, any number of typos can be 
syntactically correct, but meaningless, exception-raising actions at run 
time.  Things like misspelling a variable/function name, substituting a 
comma for a decimal point, indexing something that is not indexable, 
applying a function to the wrong parameters or wrong number of 
parameters, ...  All these are *not* syntax errors (as they would be in 
C), but will cause a run-time exception -- and you'd never know why with 
that bare except blindly catching them all and claiming "command line 
error".


Gary Herron



kind regards


--
https://mail.python.org/mailman/listinfo/python-list


Re: buggy python interpretter or am I missing something here?

2014-01-26 Thread Gary Herron

On 01/26/2014 10:46 PM, me wrote:

In any case, thanks for the answers guys.  I'm satisfied that the except:
syntax yields undefined behavior, and in my mind it shouldn't be
syntactically allowed then.

Updating to Exception,e or Exception as e fixes the problem.



That's an irksome habit you have there,  this jumping to (incorrect) 
conclusions so quickly.   We'd like to get to the bottom of this. (And 
correct your mis-interpretations while we're at it :-)But we need to 
see your test *and* the results.


Gary Herron

--
https://mail.python.org/mailman/listinfo/python-list


Re: Calculator Problem

2014-02-02 Thread Gary Herron

On 02/02/2014 01:16 PM, Charlie Winn wrote:

Hey Guys i Need Help , When i run this program i get the 'None' Under the 
program, see what i mean by just running it , can someone help me fix this

def Addition():
 print('Addition: What are two your numbers?')
 1 = float(input('First Number:'))
 2 = float(input('Second Number:'))
 print('Your Final Result is:', 1 + 2)


def Subtraction():
 print('Subtraction: What are two your numbers?')
 3 = float(input('First Number:'))
 4 = float(input('Second Number:'))
 print('Your Final Result is:', 3 - 4)


def Multiplication():
 print('Multiplication: What are two your numbers?')
 5 = float(input('First Number:'))
 6 = float(input('Second Number:'))
 print('Your Final Result is:', 5 * 6)


def Division():
 print('Division: What are your two numbers?')
 7 = float(input('First Number:'))
 8 = float(input('Second Number:'))
 print('Your Final Result is:', 7 / 8)



print('What type of calculation would you like to do?')
Question = input('(Add, Subtract, Divide or Multiply)')
if Question.lower().startswith('a'):
 print(Addition())
elif Question.lower().startswith('s'):
 print(Subtraction())
elif Question.lower().startswith('d'):
 print(Division())
elif Question.lower().startswith('m'):
 print(Multiplication())
else:
 print('Please Enter The First Letter Of The Type Of Calculation You 
Would Like To Use')

while Question == 'test':
 Question()


Sorry, but in fact you did *not* run this program as you claim. It's 
full of syntax errors.  Any attempt to run it will display syntax errors 
immediately, and never actually run.   So please tell us what really 
happened.


But even without an accurate description of what you did, I can say this:

Lines like
1 = float(...)
don't make sense.  It's as if you are trying to change the value of the 
number one, but that's nonsense.


And lines like
print('Your Final Result is:', 5 * 6)
had better print out 30 (since that is what 5 times 6 is) but that's 
clearly not what you intended.


Gary Herron




--
https://mail.python.org/mailman/listinfo/python-list


Re: [newbie] copying identical list for a function argument

2014-02-03 Thread Gary Herron

On 02/03/2014 01:36 PM, Jean Dupont wrote:

I have a list like this:
[1,2,3]

The argument of my function should be a repeated version e.g.
[1,2,3],[1,2,3],[1,2,3],[1,2,3] (could be a different number of times repeated 
also)


That's not very clear.  You say "The" argument (singular; meaning 1) but 
then show what seems to be four arguments.  Can you show us the function 
you mention.


A number of things come to mind:

>>> 4*[[1,2,3]]
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

so fn(n*[[1,2,3]]) might do for a single parameter function
  def fn(L):
  ...

On the other hand expanding a sequence into individual parameters:
fn(*(4*[[1,2,3]]))  # note extra * preceding the arg
willl be a valid call for
  def fn(a,b,c,d):
...

I'm sure other interpretations of your question are possible.

Gary Herron






what is the prefered method to realize this in Python?

any help would be really appreciated

kind regards,
jean



--
https://mail.python.org/mailman/listinfo/python-list


Re: Calculator Problem

2014-02-03 Thread Gary Herron

On 02/03/2014 10:04 AM, Charlie Winn wrote:

On Sunday, February 2, 2014 9:46:24 PM UTC, Gary Herron wrote:



...



Sorry, but in fact you did *not* run this program as you claim. It's

full of syntax errors.  Any attempt to run it will display syntax errors

immediately, and never actually run.   So please tell us what really

happened.

...



Gary Herron

excuse me but don't be so *** rude , i did run this program and it did run 
correctly and if you want me to prove it with screenshots so be it , so don't 
make accusations ** Gary ** i only came here for some help not to be accused of 
not even running my program

Charlie :D



Sorry, it wasn't rude, it was a statement of fact pointing out an error 
on your part.  You may *think* you ran the code you posted, but in fact 
you could not have done so.The code you posted will not run.  Not in 
any version of Python, past, present or future. Assigning to a literal

1 = ...
makes no sense and produces a syntax error.   That's the only result you 
could have gotten.   If you think that's what you've done, then by all 
means post a screen-shot showing is how you came to that conclusion, and 
we'll correct you again.   But I'll guarantee with absolute certainty, 
that your posted Python program did not *run* "correctly" or incorrectly.


People on the group are willing to help with nearly anything, but it's 
all a volunteer effort.  You waste our time (either carelessly or 
maliciously) if you don't accurately post  your code and the results of 
running that code.


So please try again.  You *will* get help.  There are a number of other 
errors in your program also.  We can get to those once we know what code 
you are really running, and are sure that you know what it means to 
*run* it, and that you can correctly identify the results -- error or not.


Gary Herron



--
https://mail.python.org/mailman/listinfo/python-list


Re: kivy

2014-02-04 Thread Gary Herron

On 02/04/2014 11:55 AM, bharath wrote:

i installed python 2.7 before and installed suitable kivy.. i have also 
included the .bat file in the send to option.. but my programs are not at all 
runnning and giving me error when i run it normally or with the .bat file.. it 
says that there's no module named kivy when i import it.. please help im just 
frustrated after writing a long code and seeing that it isn't working.. if 
anyone has suggestions on how to develop android 2d games with python their 
reply would be greatly appreciated. thank you


This is a Python newsgroup.  You might find an answer here, but I think 
you'd have much better luck if you found a kivy specific newsgroup.


Good luck,

Gary Herron

--
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: 'list' object is not callable

2014-02-06 Thread Gary Herron

On 02/06/2014 12:01 AM, wilsonmo...@gmail.com wrote:

import csv

date1 = []
open = []
high = []
low = []
close = []
data = []
with open("C:/Documents and Settings/wilson/My Documents/Downloads/execution.csv", 
"rb") as csvfile:
fastreader = csv.reader(csvfile, delimiter = ",", skipinitialspace=True)
count = 0
for row in fastreader:
date1.append(row[0])
count = count + 1


TypeError: 'list' object is not callable


I'd be glad to help, but I'm not interested in guessing.  Pleas take the 
time to tell us what line produced that error?  That is: cut and paste 
the *full* traceback instead of hiding useful information when you are 
asking for help.


Gary Herron

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Dictionaries

2014-02-08 Thread Gary Herron

On 02/08/2014 11:07 PM, worthingtonclin...@gmail.com wrote:

why in a for loop can i access values for a dict that i did not address in the 
for loop.

example:

a = {blah:blah}
b = {blah:blah}

for x in a:
 
 print a[x]
 
 #here's what i don't understand
 
 print b[x]
 
 # it would print the value for dict b even though it wasn't called upon in the for loop!



Thanks in advance.


The lookup of a value in dictionary b does not care where the index 
comes from.Quite simply, x has the value of 'blah', and b has 'blah' 
as a key, so b[x] works.


If a and b had different keys, then you would get an error:

>>> a = {'a':1}
>>> b = {'b':2}
>>> for x in a:
...   print x
...   print a[x]
...   print b[x]
...
a
1
Traceback (most recent call last):
  File "", line 4, in 
KeyError: 'a'


Gary Herron

--
https://mail.python.org/mailman/listinfo/python-list


Re: Flag control variable

2014-02-11 Thread Gary Herron

On 02/11/2014 10:37 AM, luke.gee...@gmail.com wrote:

well i'm trying something else but no luck :

#!bin/bash/python
import sys
import os
a = int(sys.argv[1])
sign = (sys.argv[2])
b = int(sys.argv[3])

if sign == '+':
   sum = a + b
   print a, sign, b, "=", a + b
   command1 = "sudo mpg321  
'http://translate.google.com/translate_tts?tl=en&q=%s_plus%s_equals%s'" % (a, b, sum)
   os.system (command1)

elif sign == "*":
   sum = a * b
   print a, sign, b, "=", a * b
   command1 = "sudo mpg321  
'http://translate.google.com/translate_tts?tl=en&q=%s_times%s_equals%s'" % (a, b, 
sum)

when using * i get

Traceback (most recent call last):
   File "./math+.py", line 6, in 
 b = int(sys.argv[3])
ValueError: invalid literal for int() with base 10: 
'Adafruit-Raspberry-Pi-Python-Code'

i don't understand why b is a problem, it works fine with +


Look at the error message.  Carefully!  It says, quite clearly, the call 
to int is being passed a string "Adafruit-Raspberry-Pi-Python-Code", 
which of course can't be converted to an integer.


Now the question is how you ran the program in such a manner that 
sys.argv[3] has such an odd value.
What does your command line look like?  You didn't tell us, but that's 
where the trouble is.


Gary Herron
--
https://mail.python.org/mailman/listinfo/python-list


Re: Flag control variable

2014-02-11 Thread Gary Herron

On 02/11/2014 10:59 AM, luke.gee...@gmail.com wrote:



Look at the error message.  Carefully!  It says, quite clearly, the call

to int is being passed a string "Adafruit-Raspberry-Pi-Python-Code",

which of course can't be converted to an integer.



Now the question is how you ran the program in such a manner that

sys.argv[3] has such an odd value.

What does your command line look like?  You didn't tell us, but that's

where the trouble is.



Gary Herron
how do you meen "what does your command line look like?"


When you run this python script,  *how* do you do so?

Perhaps you type something like:
  python script.py 21 '*' 42
If not, then how do you supply values for the script's sys.argv?

If it is like that, then I see the most likely potential problem. The 
asterisk character (on Linux at least) is considered a wild-card 
character -- it is replaced by a list of local files so your command becomes

  python script.py 21 somefile1 somefile2 somefile3 <...and so on.> 42

If you put it in quotes, then it won't be expanded  (at least in the 
usual Linux shells -- you system may vary) and you'll end up with the 
asterisk in sys.argv[2] and the number in sys.argv[3].


Gary Herron

--
https://mail.python.org/mailman/listinfo/python-list


Re: Flag control variable

2014-02-11 Thread Gary Herron

On 02/11/2014 11:01 AM, luke.gee...@gmail.com wrote:
when using python script.py 2 \* 2 i get Traceback (most recent call 
last): File "math2.py", line 5, in  sign = int(sys.argv[2]) 
ValueError: invalid literal for int() with base 10: '*' 


Stop trying to guess what is going on.  Print out sys.argv, and *see* 
what values are there.  Then read the error message.


You wrote your script expecting sys.argv[2] to contain an int, but in 
fact (according to the error) it contains a '*' -- which can't be 
converted to an integer obviously.  Your error is in running the script 
incorrectly, *OR* in your understanding of how the command line 
arguments get placed in sys.argv.  In either case you best bet is to 
examine sys.argv by printing it (or examining it within a debugger) and 
*see* what values it contains.  Then adjust your script (or the running 
of it) accordingly.


These are very beginner level debugging suggestions.  If you develop the 
skill to read and understand the error messages, and the skill to print 
(or otherwise examine) the values your program is dealing with, you 
progress will by 100's of times faster then this slow wait for someone 
to respond to on this list.


Gary Herron
--
https://mail.python.org/mailman/listinfo/python-list


Re: Flag control variable

2014-02-11 Thread Gary Herron

On 02/11/2014 11:06 AM, luke.gee...@gmail.com wrote:


i found it int(sys.argv[2]) should be sys.argv[2]

is there a way i can do python ./script.py 3 * 3 instead of python ./script 3 
\* 3 ?


That's not really a Python question.  The shell (as it's called) which 
interprets your typed command and runs Python with the rest of the 
command line arguments is in control of this.  If you can find a way to 
tell your shell to not expand '*' characters, or find a shell that does 
not do so, then yes, you can dispense with the back-slash.


Gary Herron

--
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   >