[Tutor] multiply and sum two lists with list comprehension?
Hi, I am multipliying two lists so that each of list As elements get multiplied to the corresponding list Bs. Then I am summing the product. For example, A= [1, 2, 3] and B=[2, 2, 2] so that I get [2, 4, 6] after multiplication and then sum it to get 12. I can do it using map like this: sum(map(lambda i,j:i*j, A, B)) But map is being dropped out in python 3? or has it already been dropped? And I have heard Guido say that list comprehension do a better job than map so how would we do this with list comps? Thanks, Ali ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Pythonify this code!
Hi, This is my first attempt at python. I tried my hand at steganography for fun. The code includes separate, combine, encode, decode functions. The separate function takes a number and it's base and returns a list containing each digit of the number in a list, vice versa for combine. The encode function encodes each char's ascii value into each pixel's RGB values at the least significant end. The decode function does the opposite. e.g., a = 97, so if we have at a pixel r, g, b (230, 107, 155) it will become (230, 109, 157) when it's encoded. Since I am new and don't speak the python idiom yet, I would like the experts to pythonify the following code as much as possible for both python 2.6 and 3.0. Any other suggestion to improve the quality would also be highly appreciated Thanks a lot! #The code starts here: def separate(num, base): li = [] while num / base > 0: li.insert(0, num % base) num = num / base li.insert(0,num) return li def combine(tup, base): num = 0 mul = pow(base, len(tup) - 1) for i in tup: num = num + i * mul mul = mul / base return num #Will make changes to the original image and not to a copy! You have been warned! import Image def encode(img, text): x = 0 y = 0 height, width = img.size text = text + "~~" if len(text) > height * width: return false pix = img.load() for c in text: li = separate(ord(c), 10) if(len(li) == 1): li.insert(0, 0) li.insert(0, 0) elif(len(li) == 2): li.insert(0, 0) r, g, b = pix[x, y] r = r - (r % 10) + li[0] if (r > 255): r = r - 10 g = g - (g % 10) + li[1] if (g > 255): g = g - 10 b = b - (b % 10) + li[2] if (b > 255): b = b - 10 pix[x,y] = (r,g,b) if y == width - 1: y = 0 x = x + 1 else: y = y + 1 img.save(img.filename) def decode(img): x = 0 y = 0 text = "" c = "" height, width = img.size pix = img.load() while 1: r, g, b = pix[x, y] if (c == '~') and chr(combine([r % 10, g % 10, b % 10], 10)) == '~': return text[:len(text) - 1] c = chr(combineUnits([r % 10, g % 10, b % 10], 10)) text = text + c if y == width - 1: y = 0 x = x + 1 else: y = y + 1 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pythonify this code!
Hi everyone, Thanks for the comments Dave and Alan! Based on these I have updated the code... I don't know if this is more readable. @Dave: I kept the original separate and combine function with bases as I thought I would move them to a math library if I need to work in other bases, however now I have followed your advice and made them more specific to the solution. I couldn't understand the bit about how to use format. Could you check it out in the context of the new code? Also didn't get the bit about zip() either, however it got me thinking and I used map instead. I am still not very happy about the separateToList function :( and I hope I haven't been overzealous in using map(). I have also changed the text concatenation. Here's the code: import Image ENDTEXT = '~~' def separateToList(num): """ changes an integer into a list with 0's padded to the left if the number is in tens or units """ assert(num <= 255) s = str(num) li = [] if len(s) > 2: li = [s[0:1], s[1:2], s[2:3]] elif len(s) > 1: li = [0, s[0:1], s[1:2]] elif len(s) > 0: li = [0, 0, s[0:1]] return map(int, li) def getCharFromRGB(rgb): """ takes an rgb tuple and changes it to an ascii char by taking the unit digits of each color """ rgb = map(lambda x: x %10, rgb) ordChar = int(''.join(map(str, rgb))) assert(ordChar <= 255) return chr(ordChar) def hidePartOfCharInColor(color, charDigit): """ take a color as integer not exceeding 255 and replace the unit digit with one of the ascii char's digit """ assert(color <= 255) color -= (color % 10) color += charDigit if (color > 255): color -= 10 return color def incrementRowCol(imgWidth, row, col): row += 1 if row == imgWidth: row, col = 0, col+1 return row, col def encode(img, text): """ Takes PIL image and any string, encodes the text in the image, saving the changes to the image Returns False if text size is greater than pixels """ x = 0 y = 0 height, width = img.size text = text + ENDTEXT if len(text) > height * width: return False pix = img.load() for c in text: ordAsList = separateToList(ord(c)) rgb = pix[x, y] pix[x,y] = tuple(map(hidePartOfCharInColor, rgb, ordAsList)) x, y = incrementRowCol(width, x, y) img.save(img.filename) return True def decode(img): x = 0 y = 0 charList = [] c = "" height, width = img.size pix = img.load() while True: lastc = c c = getCharFromRGB(pix[x, y]) charList.append(c) if (c + lastc == ENDTEXT): return ''.join(charList[:-2]) x, y = incrementRowCol(width, x, y) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can't transform a list of tokens into a text
Try changing all instances of list[i + 1] to list[i] On Thu, Jul 16, 2009 at 8:33 AM, Eduardo Vieira wrote: > #=== > I tried this version to post in this forum but that gives me an error. > I don't know why I don't get an error with the code above which is > essentially the same: > # -*- coding: cp1252 -*- > > result = '' > lista = [ > 'No', ',', 'thank...@+', > 'He', 'said', ',', '"', 'no', ',', 'thanks', '.', '"', 'OK', '?', 'Hi'] > > punct = '!#$%)*,-.:;<=>?@/\\]^_`}~”…' > for i, item in enumerate(lista): > >if item == '"' and lista[i + 1] not in punct: >result +=item >spacer = True >elif '+...@+' in item: >donewline = item.replace('+...@+','\n ') >result += donewline >elif item not in punct and lista[i + 1] in punct: >result += item >elif item in punct and lista[i + 1] in punct: >result += item >elif item in punct and lista[i + 1] == '"' and spacer: >result += item >spacer = False >elif item not in punct and lista[i + 1] == '"' and spacer: >result += item >spacer = False >elif item in '([{“': >result += item >else: >result += (item + " ") > > print result > > #== > The error is this: > Traceback (most recent call last): > File "", line 244, in run_nodebug > File "C:\mytools\jointags-v4.py", line 17, in >elif item not in punct and lista[i + 1] in punct: > IndexError: list index out of range > > I'm using python 2.6.2 with PyScripter IDE > I have tried a so many variations that I'm not sure what I'm doing any > more > I'm just trying to avoid some post-processing with sed again. > > Thankful, > > Eduardo > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- http://alitechtips.blogspot.com/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Mapping of co-ordinates... pygame
Hi, I have some x and y co-ordinates ranging from (-100, 100) for each x and y. Something like this: 100 | | | | -100--100 | | | | -100 I would like to plot them on a pygame surface. I have found that pygame surface is (0, 0) at top right to (width, height) at the bottom right corner, like this: (0,0) (width, 0) | | | | | | | | | | | | | | (0,height)(width, height) I need a way to map any value from my range to this surface so I could do stuff like this: pygame.draw.circle(screen, color, (x, y), size Also my range could vary from -5, 5 or -500 to 500 so I need something generic... It looks like a simple problem but I can't seem to be able to figure it out. Thanks, Ali ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Mapping of co-ordinates... pygame
Thanks Wayne and Alan, Here is what I finally ended up with: def newCoord(x, y, oldWidth, oldHeight, newWidth, newHeight): return( newWidth/2 + newWidth/oldWidth * x), (newHeight/2 - newHeight/oldHeight * y) for my earlier example, the old width and height would be 200, 200 respectively. Thanks! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [pygame] why does my window not close?
Hi, I have the same problem running pygame programs from the interpreter. I now just put a shebang line on top of the script like #!/usr/bin/env python and do chmod +x on the script and then run it from the terminal by doing ./script.py or double clicking on the file. It works fine when run directly instead of from the interpreter. Regards, Ali On Sat, Aug 1, 2009 at 8:03 PM, David wrote: > Dear Tutors, > > I have written a simple pygame program: > > > import pygame, sys > pygame.init() > screen = pygame.display.set_mode([640, 480]) > screen.fill([255,255,255,255]) > pygame.draw.circle(screen, [0,255,0], [150,200,], 30, 0) > my_rect = (250, 150, 300, 200) > pygame.draw.rect(screen, [0,0,255], my_rect, 0) > pygame.display.flip() > while True: >for event in pygame.event.get(): >if event.type == pygame.QUIT: >sys.exit() > > > I am using Ubuntu Jaunty, Python 2.6.2: > > When I try to quit the program (clicking on the windows' [X] button), > nothing happens. > When I press CTRL-C on the Python interpreter, triggering a > KeyboardInterrupt, the windows' content vanishes (turns black), but the > window itself remains and can't be killed except by killing the Python > interpreter from which I started my program. > What is going on? I obviously want the window to disappear once I hit > the [X] button! > > Cheers for a hint, > > David > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- http://alitechtips.blogspot.com/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] nonlinear fittinig
Don't know about nlinfit but you can check numpy, scipy and matplotlib that provide matlab like functionality. Ali On Mon, Aug 3, 2009 at 11:20 PM, Alireza Alemi wrote: > Dear All > > I am not sure if here is the right place to ask this question. > Anyway, the question is: Is there a pythonic counterpart for Matlab > nonlinear fitting ( which is " nlinfit() " function )? > > Thanks, > Alireza > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- http://alitechtips.blogspot.com/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Scope of exceptions
Instead of putting it in every function, you could probably do it once in your "main" function that does all the work... On Wed, Aug 5, 2009 at 4:34 PM, Craig McDonald wrote: > Howdy, > > I am in the process of moving all my perl scripts to python and also > trying to learn to program rather than just know enough to automate > sections of my job. I am trying exit cleanly if I force the script to > exit early. I am working my way through core python but not yet read > properly about exceptions so this is how I guessed exceptions to work. > > try: >statements >extractData() >more_statements >even_more_statements > except KeyboardInterrupt: >exit('Exiting') > > Once it enters/runs the extractData func and if I choose to exit > (control c) it throws an exception rather than exiting cleanly. Do I > need to put a 'KeyboardInterrupt' exception for every function? > > Thanks in advance, > > Craig > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- http://alitechtips.blogspot.com/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor