Re: parse a csv file into a text file
Zhen Zhang zhen.zhang.u...@gmail.com Wrote in message: I am currently running python 2.7. Yes, i thought there must be a print function in python like fprint in C++ that allows you to print into a file directly. But i google about print string into text file I got answers using f.write() instead. :) -- In python 2.x, Instead of f.write (a + + b) you can use print f, a, b -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: parse a csv file into a text file
Dave Angel da...@davea.name Wrote in message: Zhen Zhang zhen.zhang.u...@gmail.com Wrote in message: I am currently running python 2.7. Yes, i thought there must be a print function in python like fprint in C++ that allows you to print into a file directly. But i google about print string into text file I got answers using f.write() instead. :) -- Oops. Forgot the newline. In python 2.x, Instead of f.write (a + + b) f.write (a + + b + \n) you can use print f, a, b print will add in the space and newline, just as it does to sys.stdout. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:Question about `list.insert`
cool-RR ram.rac...@gmail.com Wrote in message: Hi, I'm curious. If I append an item to a list from the left using `list.insert`, will Python always move the entire list one item to the right (which can be super-slow) or will it check first to see whether it can just allocate more memory to the left of the list and put the item there, saving a lot of resources? Excellent question. list does not promise better than O (1) behavior, and CPython in particular will copy, I'm pretty sure. However that's exactly what collections.deque is for. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: kivy
Rustom Mody rustompm...@gmail.com Wrote in message: On Wednesday, February 5, 2014 1:25:43 AM UTC+5:30, bharath wrote: please help im just frustrated after writing a long code and seeing that it isn't working.. Prior to Kernighan and Ritchie people did tend to write 'a long code' and then check that its working (or not). After 'The C programming language' -- which is about 40 years -- starting any programming enterprise without writing AND CHECKING the equivalent of Hello World is just never done. IOW you underestimate how many niggling details both of the system and of your understanding are checked by that approach I recall vividly when turnaround for the cross-assembler (remotely located) was typically close to 2 days. One of the projects I did was to write an assembler that built our code locally. And once the hardware existed, I ported the assembler to run on the target directly. Cut typical module assembly time to less than 5 minutes. 1973-1975 -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Finding size of Variable
Ayushi Dalmia ayushidalmia2...@gmail.com Wrote in message: On Wednesday, February 5, 2014 12:59:46 AM UTC+5:30, Tim Chase wrote: On 2014-02-04 14:21, Dave Angel wrote: To get the total size of a list of strings, try (untested): a = sys.getsizeof (mylist ) for item in mylist: a += sys.getsizeof (item) I always find this sort of accumulation weird (well, at least in Python; it's the *only* way in many other languages) and would write it as a = getsizeof(mylist) + sum(getsizeof(item) for item in mylist) -tkc This also doesn't gives the true size. I did the following: import sys data=[] f=open('stopWords.txt','r') for line in f: line=line.split() data.extend(line) print sys.getsizeof(data) Did you actually READ either of my posts or Tim's? For a container, you can't just use getsizeof on the container. a = sys.getsizeof (data) for item in mylist: a += sys.getsizeof (data) print a -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:parse a csv file into a text file
Zhen Zhang zhen.zhang.u...@gmail.com Wrote in message: Hi, every one. I am a second year EE student. I just started learning python for my project. I intend to parse a csv file with a format like 3520005,Toronto (Ont.),C ,F,2503281,2481494,F,F,0.9,1040597,979330,630.1763,3972.4,1 2466023,Montréal (Que.),V ,F,1620693,1583590,T,F,2.3,787060,743204,365.1303,4438.7,2 5915022,Vancouver (B.C.),CY ,F,578041,545671,F,F,5.9,273804,253212,114.7133,5039.0,8 3519038,Richmond Hill (Ont.),T ,F,162704,132030,F,F,23.2,53028,51000,100.8917,1612.7,28 into a text file like the following Toronto 2503281 Montreal 1620693 Vancouver 578041 I am extracting the 1st and 5th column and save it into a text file. Looks to me like columns 1 and 6. This is what i have so far. [code] import csv file = open('raw.csv') reader = csv.reader(file) f = open('NicelyDone.text','w') for line in reader: f.write(%s %s%line[1],%line[5]) Why not use print to file f? The approach for redirection is different between python 2 and 3, and you neglected to say which you're using. My thinking is that I could add those 2 string together like c=a+' ' +b, that would give me the format i wanted. And don't forget the \n at end of line. So i can use f.write() to write into a file ;) Or use print, which defaults to adding in a newline. Sorry if my questions sounds too easy or stupid. Not in the least. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Help with TypeError: Can't convert 'list' object to str implicitly
Hello, Background. My 11 y/o son and I have taken on the task to learn python and work our way through the http://inventwithpython.com/chapters/ book. - We are currently on Chapter 9 and trying to modify the hangman program. - the first challenge was to modify the word list into a dictionary. So we changed our words variable into a dictionary -- I believe we did this correctly. - But we somehow broke the game. All of the words are only two letters and the program crashes on exit with the following error. Traceback (most recent call last): File /media/.../Python/hangman.py, line 155, in module print('You have run out of guesses! \n After ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was ' + secretWord + '') TypeError: Can't convert 'list' object to str implicitly -I can't see why this wouldn't work. By definition isn't this the cast: 1) len(correctLetters) //returns the lengths of the variable as an int 2) str(len(correctLetters)) // converts the integer into a string. Applicable code is here: # Check if player has guessed too many times and lost if len(missedLetters) == len(HANGMANPICS) - 1: displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord) print('You have run out of guesses! \n After ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was ' + secretWord + '') gameIsDone = True Any help to get us past this error message is most appreciated. Thanks in advance, Dave -- https://mail.python.org/mailman/listinfo/python-list
[Solved]Re: Help with TypeError: Can't convert 'list' object to str implicitly
On Wednesday, February 5, 2014 7:21:29 PM UTC-7, dave em wrote: Hello, Background. My 11 y/o son and I have taken on the task to learn python and work our way through the http://inventwithpython.com/chapters/ book. - We are currently on Chapter 9 and trying to modify the hangman program. - the first challenge was to modify the word list into a dictionary. So we changed our words variable into a dictionary -- I believe we did this correctly. - But we somehow broke the game. All of the words are only two letters and the program crashes on exit with the following error. Traceback (most recent call last): File /media/.../Python/hangman.py, line 155, in module print('You have run out of guesses! \n After ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was ' + secretWord + '') TypeError: Can't convert 'list' object to str implicitly -I can't see why this wouldn't work. By definition isn't this the cast: 1) len(correctLetters) //returns the lengths of the variable as an int 2) str(len(correctLetters)) // converts the integer into a string. Applicable code is here: # Check if player has guessed too many times and lost if len(missedLetters) == len(HANGMANPICS) - 1: displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord) print('You have run out of guesses! \n After ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was ' + secretWord + '') gameIsDone = True Any help to get us past this error message is most appreciated. Thanks in advance, Dave Fixed the error and am now onto the next issue. Solution was to return a list (I think) and then break out the components of the list and put in the variable. Here is how we did it: secretWord = getRandomWord(words) print('The secretWord is ' + str(secretWord[0])) print('The secretKey is ' + str(secretWord[1])) #Change secretWord from a list to a str secretWord = secretWord[1] def getRandomWord(wordDict): # This function returns a random string from the passed dictionary of lists of strings, and the key also. # First, randomly select a key from the dictionary: wordKey = random.choice(list(wordDict.keys())) print('The wordKey is ' + wordKey) # Second, randomly select a word from the key's list in the dictionary: wordIndex = random.randint(0, len(wordDict[wordKey]) - 1) print('The wordIndex is ' + str(wordIndex)) print('The word is ' + wordDict[wordKey][wordIndex]) return [wordDict[wordKey][wordIndex], wordKey] Cheers, Dave -- https://mail.python.org/mailman/listinfo/python-list
Re:[Solved]Re: Help with TypeError: Can't convert 'list' object to str implicitly
dave em daveandem2...@gmail.com Wrote in message: Fixed the error and am now onto the next issue. Solution was to return a list (I think) and then break out the components of the list and put in the variable. Here is how we did it: secretWord = getRandomWord(words) print('The secretWord is ' + str(secretWord[0])) print('The secretKey is ' + str(secretWord[1])) #Change secretWord from a list to a str secretWord = secretWord[1] def getRandomWord(wordDict): # This function returns a random string from the passed dictionary of lists of strings, and the key also. # First, randomly select a key from the dictionary: wordKey = random.choice(list(wordDict.keys())) print('The wordKey is ' + wordKey) # Second, randomly select a word from the key's list in the dictionary: wordIndex = random.randint(0, len(wordDict[wordKey]) - 1) print('The wordIndex is ' + str(wordIndex)) print('The word is ' + wordDict[wordKey][wordIndex]) return [wordDict[wordKey][wordIndex], wordKey] Much better is to change the name of the function to match what it's really doing. But I'll leave that to you. Make the return logic look like: word = [wordDict[wordKey][wordIndex] return word, wordKey Then the calling logic should be: secretWord, key = getRandomSomethings (words) print('The secretWord is ' + secretWord print('The secretKey is ' + key This way a name is not used for contradictory purposes. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Finding size of Variable
Ayushi Dalmia ayushidalmia2...@gmail.com Wrote in message: getsizeof() gives you the size of the list only; to complete the picture you have to add the sizes of the lines. However, why do you want to keep track of the actual memory used by variables in your script? You should instead concentrate on the algorithm, and as long as either the size of the dataset is manageable or you can limit the amount of data accessed at a given time you are golden. As I said, I need to merge large files and I cannot afford more I/O operations. So in order to minimise the I/O operation I am writing in chunks. Also, I need to use the merged files as indexes later which should be loaded in the memory for fast access. Hence the concern. Can you please elaborate on the point of taking lines into consideration? Please don't doublespace your quotes. If you must use googlegroups, fix its bugs before posting. There's usually no net gain in trying to 'chunk' your output to a text file. The python file system already knows how to do that for a sequential file. For list of strings just add the getsizeof for the list to the sum of the getsizeof of all the list items. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:Finding size of Variable
Ayushi Dalmia ayushidalmia2...@gmail.com Wrote in message: Where am I going wrong? What are the alternatives I can try? You've rejected all the alternatives so far without showing your code, or even properly specifying your problem. To get the total size of a list of strings, try (untested): a = sys.getsizeof (mylist ) for item in mylist: a += sys.getsizeof (item) This can be high if some of the strings are interned and get counted twice. But you're not likely to get closer without some knowledge of the data objects and where they come from. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: fseek In Compressed Files
Ayushi Dalmia ayushidalmia2...@gmail.com Wrote in message: On Thursday, January 30, 2014 4:20:26 PM UTC+5:30, Ayushi Dalmia wrote: Hello, I need to randomly access a bzip2 or gzip file. How can I set the offset for a line and later retreive the line from the file using the offset. Pointers in this direction will help. This is what I have done: import bz2 import sys from random import randint index={} data=[] f=open('temp.txt','r') for line in f: data.append(line) filename='temp1.txt.bz2' with bz2.BZ2File(filename, 'wb', compresslevel=9) as f: f.writelines(data) prevsize=0 list1=[] offset={} with bz2.BZ2File(filename, 'rb') as f: for line in f: words=line.strip().split(' ') list1.append(words[0]) offset[words[0]]= prevsize prevsize = sys.getsizeof(line)+prevsize sys.getsizeof looks at internal size of a python object, and is totally unrelated to a size on disk of a text line. len () might come closer, unless you're on Windows. You really should be using tell to define the offsets for later seek. In text mode any other calculation is not legal, ie undefined. data=[] count=0 with bz2.BZ2File(filename, 'rb') as f: while count20: y=randint(1,25) print y print offset[str(y)] count+=1 f.seek(int(offset[str(y)])) x= f.readline() data.append(x) f=open('b.txt','w') f.write(''.join(data)) f.close() where temp.txt is the posting list file which is first written in a compressed format and then read later. I thought you were starting with a compressed file. If you're being given an uncompressed file, just deal with it directly. I am trying to build the index for the entire wikipedia dump which needs to be done in a space and time optimised way. The temp.txt is as follows: 1 456 t0b3c0i0e0:784 t0b2c0i0e0:801 t0b2c0i0e0 2 221 t0b1c0i0e0:774 t0b1c0i0e0:801 t0b2c0i0e0 3 455 t0b7c0i0e0:456 t0b1c0i0e0:459 t0b2c0i0e0:669 t0b10c11i3e0:673 t0b1c0i0e0:678 t0b2c0i1e0:854 t0b1c0i0e0 4 410 t0b4c0i0e0:553 t0b1c0i0e0:609 t0b1c0i0e0 5 90 t0b1c0i0e0 So every line begins with its line number in ascii form? If true, the dict above called offsets should just be a list. Maybe you should just quote the entire assignment. You're probably adding way too much complication to it. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: __init__ is the initialiser
Chris Angelico ros...@gmail.com Wrote in message: [1] Scrub the RAM clean and return it to the computer, put the 1 bits onto the stack for subsequent reuse, and throw all the useless 0 bits out onto the heap. But don't you realize, we have to keep the zero bits around, so the one bits have someone to feel superior to. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:Python 3.3 and Pygame 19.2a install problems
edvoge...@gmail.com Wrote in message: That being said there is a base.pyd file but not a base.dll. I understand .pyd files are a type of dll. Could there be something about Win7 doesn't like about that naming convention? Please advise. I highly doubt that. Most Windows dlls have some other extension, and I can't believe Win7 breaking such a long tradition. I would instead guess that you have a path problem, either with sys.path or with Windows PATH variable. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: __init__ is the initialiser
Roy Smith r...@panix.com Wrote in message: In article mailman.6316.1391387539.18130.python-l...@python.org, Dave Angel da...@davea.name wrote: Chris Angelico ros...@gmail.com Wrote in message: [1] Scrub the RAM clean and return it to the computer, put the 1 bits onto the stack for subsequent reuse, and throw all the useless 0 bits out onto the heap. But don't you realize, we have to keep the zero bits around, so the one bits have someone to feel superior to. Just wait until the two bits start showing up. Then let's how the one bits feel, huh? And when the q-bits get entangled up, we won't know the question till after the answer has collapsed. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: __init__ is the initialiser
Skip Montanaro s...@pobox.com Wrote in message: On Sun, Feb 2, 2014 at 9:14 PM, Dave Angel da...@davea.name wrote: And when the q-bits get entangled up, we won't know the question till after the answer has collapsed. Won't looking at the answer change it? No, looking at it is what collapses it. Before that it was just another Schroedinger's cat -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: fseek In Compressed Files
Ayushi Dalmia ayushidalmia2...@gmail.com Wrote in message: The size of this file will be 10 GB. The version of Python I am using is 2.7.2. Yes, performance is an important issue. Then the only viable option is to extract the entire file and write it to a temp location. Perhaps as you extract it, you could also build a list of offsets, so the seeking by line number can be efficient. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Tkinter widgets into classes.
Lewis Wood fluttershy...@gmail.com Wrote in message: Oh and another question, say I make another window in the program itself using this: def secondwindow(): root2=Tk() root2.mainloop() Would it be possible for me to use some code which would return True if one of these windows is currently up, or return False if the window is not up? No need. Only one at a time can be running, and you won't return from this function till it's done. To put it another way, you only want one mainloop in your code. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:Python prime numbers
Panagiotis Anastasiou panas...@gmail.com Wrote in message: Hi i'm new in programming and in python and i have an assignment that i cant complete. I have to Write a Python program to compute and print the first 200 prime numbers. The output must be formatted with a title and the prime numbers must be printed in 5 properly aligned columns . I have used this code so far : numprimes = raw_input('Prime Numbers ') count = 0 potentialprime = 2 def primetest(potentialprime): divisor = 2 while divisor = potentialprime: if potentialprime == 2: return True elif potentialprime % divisor == 0: return False break while potentialprime % divisor != 0: if potentialprime - divisor 1: divisor += 1 else: return True while count int(numprimes): if primetest(potentialprime) == True: print potentialprime count += 1 potentialprime += 1 else: potentialprime += 1 but i get the result in a single column . How can i get it in 5 rows? Can someone help please -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:Python prime numbers
Panagiotis Anastasiou panas...@gmail.com Wrote in message: Hi i'm new in programming and in python and i have an assignment that i cant complete. I have to Write a Python program to compute and print the first 200 prime numbers. The output must be formatted with a title and the prime numbers must be printed in 5 properly aligned columns . I have used this code so far : numprimes = raw_input('Prime Numbers ') count = 0 potentialprime = 2 def primetest(potentialprime): divisor = 2 while divisor = potentialprime: if potentialprime == 2: return True elif potentialprime % divisor == 0: return False break while potentialprime % divisor != 0: if potentialprime - divisor 1: divisor += 1 else: return True There are several things wrong with this function, and it's redundant enough that maybe none of them matter. I'd test it carefully. while count int(numprimes): if primetest(potentialprime) == True: print potentialprime count += 1 potentialprime += 1 else: potentialprime += 1 but i get the result in a single column . How can i get it in 5 rows? Can someone help please As has been pointed out, you can use a trailing comma to suppress the implied newline for each print. Then you can add it back in every five items by checking count. But you have a bigger problem, lining up the columns. Try using the string modulus operator, or 'format'. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Tkinter widgets into classes.
Lewis Wood fluttershy...@gmail.com Wrote in message: (deleting doublespaced googlegroups trash) To put it another way, you only want one mainloop in your code. -- DaveA But I can click the button Multiple times and it will create multiple windows? Not using the function you showed. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:fseek In Compressed Files
Ayushi Dalmia ayushidalmia2...@gmail.com Wrote in message: Hello, I need to randomly access a bzip2 or gzip file. How can I set the offset for a line and later retreive the line from the file using the offset. Pointers in this direction will help. Start with the zlib module. Note that it doesn't handle all possible compression types, like compress and pack. I don't imagine that seeking to a line in a compressed text file would be any easier than a non compressed one. Try using gzip.open in a text mode to get a handle, then loop through it line by line. If you save all the offsets in a list, you should subsequently be able to seek to a remembered offset. But realize it'll be horribly slow, compared to a non compressed one. Consider using readlines and referencing the lines from there. Or building a temp file if too big for ram. If this is not enough, tell us your Python version and your os, and show what you've tried and what went wrong. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:Try-except-finally paradox
Jessica Ross deathwea...@gmail.com Wrote in message: I found something like this in a StackOverflow discussion. def paradox(): ... try: ... raise Exception(Exception raised during try) ... except: ... print Except after try ... return True ... finally: ... print Finally ... return False ... return None ... return_val = paradox() Except after try Finally return_val False I understand most of this. What I don't understand is why this returns False rather than True. Does the finally short-circuit the return in the except block? The finally has to happen before any return inside the try or the except. And once you're in the finally clause you'll finish it before resuming the except clause. Since it has a return, that will happen before the other returns. The one in the except block will never get reached. It's the only reasonable behavior., to my mind. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:1 0 == True - False
Thibault Langlois thibault.langl...@gmail.com Wrote in message: Hello, $ python Python 2.7.4 (default, Sep 26 2013, 03:20:26) [GCC 4.7.3] on linux2 Type help, copyright, credits or license for more information. 1 0 == True False (1 0) == True True 1 (0 == True) True What am I missing here ? T. You tell us. You supply only half the question, what it does, without saying what you expected or needed. I expect you're either confused about comparison chaining or about what happens when you compare objects of different types. Doing an ordered comparison between two types is undefined by default, and not guaranteed to even give the same result between builds. So the following may give different results on your 2.7.4 than on mine. 5 abc Python 3 fixes that by throwing an exception. TypeError: unorderable types This should solve it, since the first and third expression would seem to be undefined. Unfortunately there's yet another wrinkle. For hysterical reasons, True and False are instances of class bool, which is derived from int. So for comparison purposes False==0 and True==1. But in my opinion, you should never take advantage of this, except when entering obfuscation contests. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: fseek In Compressed Files
Ayushi Dalmia ayushidalmia2...@gmail.com Wrote in message: On Thursday, January 30, 2014 4:20:26 PM UTC+5:30, Ayushi Dalmia wrote: Hello, I need to randomly access a bzip2 or gzip file. How can I set the offset for a line and later retreive the line from the file using the offset. Pointers in this direction will help. We are not allowed to use databases! I need to do this without database. Why do you reply to your own message? Makes it hard for people to make sense of your post. Have you any answers to earlier questions? How big is this file, what python version, do you care about performance, code you've tried, ... -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 0 == True - False
Rotwang sg...@hotmail.co.uk Wrote in message: On 30/01/2014 12:49, Dave Angel wrote: [...] For hysterical reasons, True and False are instances of class bool, which is derived from int. So for comparison purposes False==0 and True==1. But in my opinion, you should never take advantage of this, except when entering obfuscation contests. Really? I take advantage of it quite a lot. For example, I do things like this: 'You have scored %i point%s' % (score, 's'*(score != 1)) I also did that kind of thing when computer resources were more precious the program readability. Like in 73 when my satellite navigation system had to fit in 2k code and 1.5k data. Here I'd probably do something like 'You have scored {} {}' .format (score, 'point' if score==1 else 'points') -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:Remove unwanted characters from column
matt.s.maro...@gmail.com Wrote in message: School assignment is to create a tab separated output with the original given addresses in one column and then the addresses split into other columns (ex, columns for city, postal code, street suffix). Here is my code: inHandler = open(inFile, 'r') outHandler = open(outFile, 'w') outHandler.write(FarmID\tAddress\tStreetNum\tStreetName\tSufType\tDir\tCity\tProvince\tPostalCode) for line in inHandler: str = line.replace(FarmID\tAddress, ) outHandler.write(str[0:-1]) str = str.replace( ,\t, 1) str = str.replace( Rd, ,\tRd\t\t) str = str.replace(Rd ,\tRd\t\t) str = str.replace(Ave, ,\tAve\t\t) str = str.replace(Ave ,\tAve\t\t) str = str.replace(St ,\tSt\t\t) str = str.replace(St, ,\tSt\t\t) str = str.replace(Dr, ,\tDr\t\t) str = str.replace(Lane, ,\tLane\t\t) str = str.replace(Pky, ,\tPky\t\t) str = str.replace( Sq, ,\tSq\t\t) str = str.replace( Pl, ,\tPl\t\t) str = str.replace(\tE, ,E\t) str = str.replace(\tN, ,N\t) str = str.replace(\tS, ,S\t) str = str.replace(\tW, ,W\t) str = str.replace(,\t,\t\t) str = str.replace(, ON ,\tON\t) outHandler.write(str) inHandler.close() outHandler.close() Here is some sample addresses, there are over 100: FarmIDAddress 1 1067 Niagara Stone Rd, Niagara-On-The-Lake, ON L0S 1J0 2 4260 Mountainview Rd, Lincoln, ON L0R 1B2 3 25 Hunter Rd, Grimsby, ON L3M 4A3 4 1091 Hutchinson Rd, Haldimand, ON N0A 1K0 5 5172 Green Lane Rd, Lincoln, ON L0R 1B3 6 500 Glenridge Ave, St. Catharines, ON L2S 3A1 7 471 Foss Rd, Pelham, ON L0S 1C0 8 758 Niagara Stone Rd, Niagara-On-The-Lake, ON L0S 1J0 9 3836 Main St, Lincoln, ON L0R 1S0 I have everything worked out, except that the final output places the farmID at the end of postal code as seen in the example below (notice the brackets showing where the farmID is placed): FarmIDAddress StreetNum StreetName SufType Dir City ProvincePostalCode 1 1067 Niagara Stone Rd, Niagara-On-The-Lake, ON L0S 1J0(1) 1067 Niagara Stone Rd Niagara-On-The-Lake ON L0S 1J0 Any ideas on how to fix this? Keep in mind as well that the farmID will have 2 characters at a certain point. Your specific concern is triggered by having two writes in the loop. Get rid of the first and you're marginally closer. But really, you've got much bigger troubles. All those unrestricted replace calls are not at all robust. But maybe you'll get away with it for a school assignment if the test data is very limited. Better would be to treat it like a parsing problem, figuring what delimiter rule applies to each field, and building a list Then use str.join to build the line for the outHandler. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:buggy python interpretter or am I missing something here?
me no...@all.net Wrote in message: 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. sys.exit() raises an exception, and you're deliberately eating that exception. -- def parse_args(a,d): l=len(a) idx=1 try: while (idxl): if (a[idx]==-#): idx=idx+1 d[maxjobs]=int(a[idx]) elif (a[idx]==-d): idx=idx+1 d[basedir]=a[idx] elif (a[idx]==-h): print help goes here sys.exit(0) elif (a[idx]==-i): idx=idx+1 d[inpipe]=a[idx] elif (a[idx]==-o): idx=idx+1 d[outpipe]=a[idx] idx=idx+1 except: Bare except is almost never a good idea. It's going to intercept the exit exception, plus control C, syntax errors and others. Which you'd have known if you printed the exception code. If you're going to catch an exception, be specific. Otherwise expect the unexpected. There is a hierarchy of exception classes, so you could catch a fairly generic class. But you do need to distinguish. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Class and instance related questions.
Asaf Las roeg...@gmail.com Wrote in message: On Friday, January 24, 2014 10:45:30 PM UTC+2, Chris Angelico wrote: On Sat, Jan 25, 2014 at 7:32 AM, Asaf Las r@gmail.com wrote: On Friday, January 24, 2014 6:37:29 PM UTC+2, Chris Angelico wrote: It's possible to unbind the name, but every instance retains a reference to its class, so the class itself won't disappear until there are no instances left of it. ChrisA That is interesting. Is it also reference count mechanism or something else? Yes. [1] ChrisA [1] Within the bounds of the question asked, I think a simple Yes is more useful here than a long and detailed explanation of the many Pythons and how not all of them refcount at all. Consider this footnote my apology to the experts who would otherwise feel that I'm majorly misleading the OP. Sorry. Chris, i like answers which open doors to my curiosity :-) yet i should spend my credits very carefully :-) Rather than dwelling on reference counting, which is just one mechanism for identifying and disposing of objects, it's usually more fruitful to consider what it means to be unreferenced. The usual term is reachable. If an object cannot be reached by following some chain of references, starting from a small list of kernel items, then it should be freed. The cheap way of noticing some such objects is by noticing the reference count go to zero. That's not enough, however, so you also need to periodically run a sweep type of garbage collector. See if you can guess why reference count alone is inadequate. The CPython system uses both of these, but other implementations do not. I believe that I've heard that the jython system does nothing at all, just letting the Java runtime handle it. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Need Help with Programming Science Project
kvxde...@gmail.com Wrote in message: Alright. I have the code here. Now, I just want to note that the code was not designed to work quickly or be very well-written. It was rushed, as I only had a few days to finish the work, and by the time I wrote the program, I hadn't worked with Python (which I never had TOO much experience with anyways) for a while. (About a year, maybe?) It was a bit foolish to take up the project, but here's the code anyways: . LPW_Comparisons = [avgLPW_DJ_EXAMPLE, avgLPW_SUZC_EXAMPLE, avgLPW_SUZC_EXAMPLE] avgLPW_Match = min(LPW_Comparisons) if avgLPW_Match == avgLPW_DJ_EXAMPLE: DJMachalePossibility = (DJMachalePossibility+1) if avgLPW_Match == avgLPW_SUZC_EXAMPLE: SuzanneCollinsPossibility = (SuzanneCollinsPossibility+1) if avgLPW_Match == avgLPW_RICH_EXAMPLE: RichardPeckPossibility = (RichardPeckPossibility+1) AUTHOR_SCOREBOARD = [DJMachalePossibility, SuzanneCollinsPossibility, RichardPeckPossibility] #The author with the most points on them would be considered the program's guess. Match = max(AUTHOR_SCOREBOARD) print AUTHOR_SCOREBOARD if Match == DJMachalePossibility: print The author should be D.J. Machale. if Match == SuzanneCollinsPossibility: print The author should be Suzanne Collins. if Match == RichardPeckPossibility: print The author should be Richard Peck. -- Hopefully, there won't be any copyright issues. Like someone said, this should be fair use. The problem I'm having is that it always gives Suzanne Collins, no matter what example is put in. I'm really sorry that the code isn't very clean. Like I said, it was rushed and I have little experience. I'm just desperate for help as it's a bit too late to change projects, so I have to stick with this. Also, if it's of any importance, I have to be able to remove or add any of the average letters per word/average letters per sentence/average words per sentence things to test the program at different levels of strictness. I would GREATLY appreciate any help with this. Thank you! 1. When you calculate averages, you should be using floating point divide. avg = float (a) / b 2. When you subtract two values, you need an abs, because otherwise min () will hone in on the negative values. 3. Realize that having Match agree with more than one is not that unlikely. 4. If you want to vary what you call strictness, you're really going to need to learn about functions. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:Initialise dictionary of dictionary
Ayushi Dalmia ayushidalmia2...@gmail.com Wrote in message: I need to initialise a dictionary of dictionary with float values. I do not know the size of the dictionary beforehand. How can we do that in Python Do what? There's no concept of pre-initializing a dictionary, and there's no specific limit to its eventual size. Unsure of what the floats have to do with it. Perhaps you meant float KEYS. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:generate De Bruijn sequence memory and string vs lists
Vincent Davis vinc...@vincentdavis.net Wrote in message: (something about your message seems to make it unquotable) 64gig is 4^18, so you can forget about holding a string of size 4^50 If memory size is your issue, why not make the function a generator, by replacing the append with a yield? -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: SIngleton from __defaults__
Johannes Schneider johannes.schnei...@galileo-press.de Wrote in message: On 22.01.2014 20:18, Ned Batchelder wrote: On 1/22/14 11:37 AM, Asaf Las wrote: Chris is right here, too: modules are themselves singletons, no matter how many times you import them, they are only executed once, and the same module object is provided for each import. I'm not sure, if this is the whole truth. think about this example: cat bla.py a = 10 cat foo.py from bla import a def stuff(): return a cat bar.py from foo import stuff print stuff() a = 5 print stuff() from bla import * print a python bar.py 10 10 10 here the a is coming from bla and is known in the global namespace. But the value differs in stuff() and before/after the import statement. So the instance of the module differs - it cannot be a singelton. You're using 3 different variables here, each global to its own module. If you really want to access the same object, you need to reference it as bla.a. And ditch the from deal. A from x import y. statement produces a new binding to the same object. But since the object in your example is immutable, the only way it can seem to change is by rebinding. If several names are bound to the same object, rebinding one has no effect on the others. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: generate De Bruijn sequence memory and string vs lists
Vincent Davis vinc...@vincentdavis.net Wrote in message: I didn't really study the code, and the fact that there's a nested function could mess it up. But if it were a straightforward function with exactly one append, , then replacing the append with a yield would produce the string one character at a time. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] advice and comment wanted on first tkinter program
Jean Dupont jeandupont...@gmail.com Wrote in message: Op maandag 20 januari 2014 07:24:31 UTC+1 schreef Chris Angelico: On Mon, Jan 20, 2014 at 3:04 PM, Jean Dupont jeandupont...@gmail.com wrote: I started a thread [newbie] starting geany from within idle does not work I did try to do the same on my linux desktop computer, but the problem is, it has another desktop environment (KDE4). In the rpi-environment it is possible (but it doesn't work) to change the default IDLE-editor by right-clicking the idle-icon and choosing geany in stead of leafpad, however the same can't be done in KDE4, I hoped to find a similar setting once running IDLE in Options--Configure IDLE, but nothing there neither. I also looked unsuccessfuly in the .idlerc-directory for a config-file. Hence my initial question. What does idle offer that Geary does not? Why not just run Geary from your terminal prompt? -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:No overflow in variables?
Philip Red filippo.biolc...@googlemail.com Wrote in message: Hi everyone. First of all sorry if my english is not good. I have a question about something in Python I can not explain: in every programming language I know (e.g. C#) if you exceed the max-value of a certain type (e.g. a long-integer) you get an overflow. Here is a simple example in C#: static void Main(string[] args) { Int64 x = Int64.MaxValue; Console.WriteLine(x); // output: 9223372036854775807 x = x * 2; Console.WriteLine(x); // output: -2 (overflow) Console.ReadKey(); } Now I do the same with Python: x = 9223372036854775807 print(type(x)) # class 'int' x = x * 2 # 18446744073709551614 print(x) # class 'int' print(type(x)) and I get the right output without overflow and the type is always a 'int'. How does Python manages internally the types and their values? Where are they stored? Thank you for your help :) In python, every value is an object. Some, like lists, can grow over time, and there's no specific upper limit in size. Others, like int, or string, are immutable, so the constructor can calculate just how much space is needed. In java, and I believe in C#, they make a distinction between unboxed and boxed integers. The former are NOT objects, and have a specific upper bound, generally based on some power of 2. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Self healthcheck
Asaf Las roeg...@gmail.com Wrote in message: On Wednesday, January 22, 2014 10:56:30 AM UTC+2, Frank Millman wrote: class MainObject: def __init__(self, identifier): self._del = delwatcher('MainObject', identifier) class delwatcher: def __init__(self, obj_type, identifier): self.obj_type = obj_type self.identifier = identifier log('{}: id={} created'.format(self.obj_type, self.identifier)) def __del__(self): log('{}: id={} deleted'.format(self.obj_type, self.identifier)) If you do find that an object is not being deleted, it is then trial-and-error to find the problem and fix it. It is probably a circular reference Frank Millman Thanks Frank. Good approach! One question - You could do: class MainObject: def __init__(self, identifier): self._del = delwatcher(self) then later class delwatcher: def __init__(self, tobject): self.obj_type = type(tobject) self.identifier = id(tobject) ... when creating delwatcher. Was there special reason to not to use them? is this because of memory is reused when objects are deleted and created again so same reference could be for objects created in different time slots? I couldn't make sense of most of that. But an ID only uniquely corresponds to an object while that object still exists. The system may, and will, reuse iD's constantly. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:use class in class
Robert Voigtländer r.voigtlaen...@gmail.com Wrote in message: Hi, I have a problem using a class object within another class. It is about the line: self.openlist.append(Node(self.start, None, 0, 0)) If I use it in __init__ it works. If I use it in calcRoute(self) I get the following error: local variable 'node' referenced before assignment The error occures in AMap.calcRoute() Where is my mistake? Chris has addressed your coding error. Within a function/method, you really should use a name for just one purpose, and especially if one of the purposes is global. But you have a different problem as well. You're describing an exception by retyping one of its lines, rather than using copy/paste of the whole thing. The actual error message could not have said node, as there's no such name in the method. def calcRoute(self): self.openlist.append(Node(self.start, None, 0, 0)) for Node in self.openlist: print Node.pos, Node.parent, Node.g, Node.h, Node.f -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Compiling main script into .pyc
MRAB pyt...@mrabarnett.plus.com Wrote in message: On 2014-01-17 02:56, bob gailer wrote: On 1/16/2014 8:01 PM, Sam wrote: One thing I observe about python byte-code compiling is that the main script does not gets compiled into .pyc. Only imported modules are compiled into .pyc. May I know how can I compile the main script into .pyc? Duh? Just import it! What if you want to just compile it? Importing will run it! Importing will only run the portion of the code not protected by if __name__ == __main__: -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:Question about object lifetime and access
Asaf Las roeg...@gmail.com Wrote in message: Hi community Welcome. Multithreading will be enabled in uwsgi and 'p' will be used for read only. Questions are: - what is the lifetime for global object (p in this example). The name will be visible in this module until the application shuts down or till you use del. - will the p always have value it got during module loading The (str) object that you bind to it will survive till you del or reassign p. Reassignment can happen with a simple assignment statement or via an 'as' clause. The value of such a str object will never change because it's an immutable type. Convention is to use names that are all uppercase. And long, descriptive names are preferred over one-letter names, especially for long-lived ones. Don't worry, long names do not take longer. - if new thread will be created will p be accessible to it It is accessible to all threads in the same process. It is also available to other modules via the import mechanism. But watch out for circular imports, which frequently cause bugs. - if p is accessible to new thread will new thread initialize p value again? Module level code runs only once per process. - is it guaranteed to have valid p content (set to module is loaded) whenever application() function is called. Except with circular imports. - under what condition p is cleaned by gc. Names are never garbage collected. See above for objects. The rationale behind these question is to avoid object creation within application() whose content is same and do not change between requests calling application() function and thus to reduce script response time. Highly unlikely to matter, and it might slow down a program slightly rather than speed it up slightly. Get your program readable so you have a chance of catching bugs, pick your algorithms reasonably, and if it's not fast enough, measure, don't guess. Thanks in advance! -- DaveA Android NewsGroup Reader http://www.piaohong.tk/newsgroup -- https://mail.python.org/mailman/listinfo/python-list
Re: plotting slows down
Norman Elliott norman.elli...@gmail.com Wrote in message: I cannot see how to change from html to text mode in chromium or within the group. You already did post in text mode, my error. The new newsreader I'm using apparently eats tabs. -- DaveA Android NewsGroup Reader http://www.piaohong.tk/newsgroup -- https://mail.python.org/mailman/listinfo/python-list
Re:plotting slows down
Steven D'Aprano st...@pearwood.info Wrote in message: On Mon, 13 Jan 2014 08:26:11 -0500, Dave Angel wrote: norman.elli...@gmail.com Wrote in message: [code] #!/usr/bin/python from graphics import * First things first. what operating system are you using, and where did you get the mysterious graphics. py? Thanks for telling us python 2.7.3 Next, please repost any source code with indentation preserved. He did. If you look at the original message as posted to python- l...@python.org and comp.lang.python, e.g. here: https://mail.python.org/pipermail/python-list/2014-January/664430.html you will see that the message is correctly indented with tabs. Your message shows it all flushed to the left margin, probably due to posting in html mode. Use text mode here. Looks like perhaps Gmane is stripping tabs from their mirror. You should report that as a bug to them. I just went to my Linux box and fired up thunderbird. When it reads the same message from gmane, it gets the tabs. So apparently it's this Android Newsgroups Reader that's buggy. -- DaveA Android NewsGroup Reader http://www.piaohong.tk/newsgroup -- https://mail.python.org/mailman/listinfo/python-list
Re:dictionary with tuples
Igor Korot ikoro...@gmail.com Wrote in message: Hi, ALL, C:\Documents and Settings\Igor.FORDANWORK\Desktop\winpdbpython Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. dict = {} dict[(1,2)] = ('a','b') dict[(3,4)] = ('c','d') for (key1,key2),(value1,value2) in dict: ... print key1, , key2 ... print value1, , value2 ... Traceback (most recent call last): File stdin, line 1, in module TypeError: 'int' object is not iterable What am I doing wrong? Thank you. Two things. You really shouldn't shadow a builtin with your own locals, though it hasn't hurt you this time. Next time pick a different name than dict. Your real problem is that you're trying to iterate over items, but forgot to use that method. The for loop line should end in dict.items () : You may be confused, since it's different in python 3.x -- DaveA Android NewsGroup Reader http://www.piaohong.tk/newsgroup -- https://mail.python.org/mailman/listinfo/python-list
Re:plotting slows down
norman.elli...@gmail.com Wrote in message: First let me say I have not done much python programming! I am running Python 2.7.3. I am trying to use python as a front end to a simple oscilloscope. Ultimately I intend to use it with my micropython board. At the moment I am just developing it. All it does is use a module I found called graphics.py to create a window and display randomly generated data. Each time it goes through the outer loop it gets slower and slower. I put in a small delay just so I could observe what is happening and for the first line it draws it takes about a second. If I set it to loop 20 times the final loop takes more than 6 seconds. Can anyone explain what I am doing wrong please? Here is the code: [code] #!/usr/bin/python from graphics import * First things first. what operating system are you using, and where did you get the mysterious graphics. py? Thanks for telling us python 2.7.3 Next, please repost any source code with indentation preserved. Your message shows it all flushed to the left margin, probably due to posting in html mode. Use text mode here. Finally, since you seem to be using googlegroups, please make sure you don't double space your quotes. See. wiki.python.org/moi n/GoogleGroupsPython -- DaveA Android NewsGroup Reader http://www.piaohong.tk/newsgroup -- https://mail.python.org/mailman/listinfo/python-list
Re: plotting slows down
Chris Angelico ros...@gmail.com Wrote in message: On Tue, Jan 14, 2014 at 4:39 AM, Ian Kelly ian.g.ke...@gmail.com wrote: On Mon, Jan 13, 2014 at 6:26 AM, Dave Angel da...@davea.name wrote: Next, please repost any source code with indentation preserved. Your message shows it all flushed to the left margin, probably due to posting in html mode. Use text mode here. That's odd, the message that I got includes proper indentation and is plain text, not html. Also what I saw. Dave, do you get the newsgroup or the mailing list? I get the mailing list - it's possible the HTML version got stripped by Mailman. I'm using gmane newsgroup, and recently switched to the Android Newsgroup Reader. Previously was using Groundhog, which seemed to eat the body of any message containing an html part. (Though strangely it showed the footer in the tutor newsgroup). This one was mentioned byAlan, and she far has seemed much better. -- DaveA Android NewsGroup Reader http://www.piaohong.tk/newsgroup -- https://mail.python.org/mailman/listinfo/python-list
Re:Python example source code
ngangsia akumbo ngang...@gmail.com Wrote in message: where can i find example source code by topic? Any help please http://code.activestate.com/recipes/langs/python/ http://code.activestate.com/recipes/sets/2-python-cookbook-edition-2/ http://shop.oreilly.com/product/mobile/0636920027072.do http://www.mindviewinc.com/Books/Python3Patterns/Index.php https://pypi.python.org/pypi -- DaveA Android NewsGroup Reader http://www.piaohong.tk/newsgroup -- https://mail.python.org/mailman/listinfo/python-list
Re:python first project
ngangsia akumbo ngang...@gmail.com Wrote in message: Hi everyone, I have been around this group for some time and i saw that we have very helpful people here. Welcome to the group, and to Python. i have been learning python just for about 5 months now and i have been given a task to do. This will be a leap into the programming industry for me. Is this a class assignment, a book assignment, a self assignment, or is it to be used by a real business, perhaps to replace manual methods? i am programming a system that will be giving details about finance, purchase(bills pending bills and paid bill), employees record and salary details, warehouse records. That is just all i intend to do this all on one GUI application window But your code so far is all for a terminal window. Nothing wrong with that, but if the professor is expecting GUI, that's different. A GUI might be tkinter or qt or Wxpython or ... and to make it to be able to keep records for all the transaction which has been done inputted. A key point. So you need persistence. You're going to need to write data to a file, and reread it next time the program is run. The file might be a bunch of text lines, or it might be a database. And it might belong to this program or be shared, even across multiple machines. I have started programming it , but i still feel there are a lot of things i miss out. I second the recommendation for version 3. And I suggest that if this is a business assignment, it's a lot harder than you think. For example, handling dollars and cents with floats is usually a mistake. Please i need some support from any honest person, please and also how to guide me complete this. -- DaveA nr Android NewsGroup Reader http://www.piaohong.tk/newsgroup -- https://mail.python.org/mailman/listinfo/python-list
Re: python first project
ngangsia akumbo ngang...@gmail.com Wrote in message: On Saturday, January 11, 2014 2:06:41 PM UTC+1, Dave Angel wrote: I second the recommendation for version 3. And I suggest that if this is a business assignment, it's a lot harder than you think. For example, handling dollars and cents with floats is usually a mistake. How hard is it? Please i need your support Not sure what units of measurement you'd like. How about ten thousand lines of code? -- DaveA nr Android NewsGroup Reader http://www.piaohong.tk/newsgroup -- https://mail.python.org/mailman/listinfo/python-list
Re:Open Question - I'm a complete novice in programming so please bear with me...Is python equivalent to C, C++ and java combined?
pintreo mardi bigearl...@outlook.com Wrote in message: Hi, I've just begun to learn programming, I have an open question for the group: Is the Python language an all in one computer language which could replace C, C++, Java etc.. I only ask becuase I am starting off with python and I want to learn everything in basic and advanced programming with python itself...So any advice and suggestions would be more than welcome. Thanks!! As others have said you can do nearly anything in any of those languages. But you can expect to learn and use many over time. I've used about 35 professionally, and a few more for fun. I've done substantial work in machine language and also in microcode. Sometimes I had to write the assembler, simulator, and debugger while the actual machine was being designed. Was python an appropriate language to write add and subtract in? Nope. -- DaveA nr Android NewsGroup Reader http://www.piaohong.tk/newsgroup -- https://mail.python.org/mailman/listinfo/python-list
Re: Send array back in result from urllib2.urlopen(request, postData)
On Fri, 10 Jan 2014 12:57:59 -0800 (PST), vanommen.rob...@gmail.com wrote: No idea about the php.. In python when i do para = result.read() print para the output is: [null,null,null,null,null,J] That's a string that just looks like a list. This is correct according to the data in PHP from the mysql. when I do print para[1] the output is: n the seccond character from the data. Why is this not the seccond datafield? There are no data fields in a string. And why is para[5] not J but , ? That's character 5 of the string. How can I change the data back to an array? I've tried with json, but that doesn't change anything. You have to parse it. I don't know what rules you used at the php end, but at a guess, I'd start by stripping the brackets, then splitting by comma. Then iterate through each item looking for special cases. Each item consisting of null gets replaced by None, each item starting with quotes gets them stripped, and perhaps anything else is replaced by float (item). Still questions to ask like whether quoted item can have embedded comma. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Input Error issues - Windows 7
On Fri, 10 Jan 2014 11:38:32 -0800 (PST), bryan.kardi...@gmail.com wrote: It's in the following directory on my machine C:\workspace\PyFoo\src\foo In that folder is __init__.py (created automatically) and foo.py foo.py looks like this class foo(): Ned has pointed out your path problem. But you have another, perhaps caused by overexposure to java. You have a package, a module and a class, all with the same name. Convention says at least uppercase for the class. I say make every name unique till you learn how they work. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Time zones and why they change so damned often (was: the Gravity of Python 2)
On Thu, 9 Jan 2014 15:14:55 +1100, Chris Angelico ros...@gmail.com wrote: [1] For those who aren't right up on timezone trivia, AZ has no DST. Similarly the Australian state of Queensland does not shift its clocks. And Indiana. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: python copy selected lines from one file to another using argparse or getopt
On Wed, 8 Jan 2014 13:51:40 -0800 (PST), sagarnild...@gmail.com wrote: I am trying to write a program in python which searches for user specified words in a txt file and copies the selected lines containing that word into another file. John Gordon has given you a good start on argument parsing. So let's start with some general comments. Please indent by 4 columns. Please factor your code into multiple functions so it's readable, especially by you. Please learn that complementary conditions are best handled by else not by another if. So the arguments to your main function should probably be two file objects and two lists. The function should call another one for each list, in a loop that looks something like for line in infile: if check_include (includes, line and not check_exclude (excludes, line): dosomethingwith line By the way checking the 2 filenames for equals doesn't begin to protect against trashing some file. Better to check if the output file exists, perhaps by opening in append mode and checking size. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Recover handle to shadowed builtin?
On Wed, 8 Jan 2014 14:52:10 -0500, Roy Smith r...@panix.com wrote: I'm working with ipython's pylab mode, which replaces the builtin sum() with the one from numpy: In [105]: sum Out[105]: function numpy.core.fromnumeric.sum Is there any way to recover a reference to the builtin sum()? goodsum=__builtins__.sum -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
[issue20162] Test test_hash_distribution fails on RHEL 6.5 / ppc64
Dave Malcolm added the comment: On Tue, 2014-01-07 at 16:30 +, Yury V. Zaytsev wrote: Yury V. Zaytsev added the comment: After lots of fiddling, I can tell you what's wrong with the macro: apparently it's a compiler bug, visible at -O2 and disappearing at -O1. Can you reduce the suspected compiler bug to a minimal reproducer? Please then run it through the preprocessor using gcc's -E option, and then attach it to this bug. What exact version of the compiler are you using, and with what flags? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue20162 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: function to split strings and lists on predicate
On Mon, 06 Jan 2014 06:48:11 +, Mark Lawrence breamore...@yahoo.co.uk wrote: I came across this over the weekend http://paddy3118.blogspot.co.uk/2013/10/unifying-pythons-string-and-lis t.html. I couldn't come up with a solution to the fsplit function that seemed in any way cleaner. What can our nest of avid Pythonistas come up with? Looks like that link is already broken. Try the first half of page: http://paddy3118.blogspot.co.uk/2013_10_01_archive.html I can't see any way to simplify the generator Paddy produced, but the thing that bothered me is that it won't work on iterables, such as itself. For thar reason I think I'd stick with the separate functions, or write an adaptor to convert a iterable of lists to one of strings. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: class inheritance python2.7 vs python3.3
On Mon, 6 Jan 2014 09:14:08 -0800 (PST), jwe.van.d...@gmail.com wrote: I have problems with these two classes: class LPU1() : You forgot to derive from object. That's implied on 3.x, but you say you're also running on 2.7 Without naming your base class you're asking for an old style class which has been obsolete maybe 10 years. I sure don't recall how it differs. def __init__(self, formula): formula is a string that is parsed into a SymPy function and several derived functions self.formula = formula ... ... class LPU3(LPU1): def __new__(self): the same functions as LPU1 but some added functions and some functions redefined You don't show where you call super, so we can't tell what you had in mind. And did you actually mean __new__ here or should you have defined __init__ as you did in the base class? if __name__ == '__main__: y = y = 'x_0 * x_1 + x_2' stats1 = LPU1(y) stats3 = LPU3(y) And where did you expect that y to go? Worked perfectly on Python 2.7.5+ but on Python 3.3.2+ I get on instantiatiating stat3: I don't see anything called stat3. Presumably you mean stats3, but you're not instantiating it you're instantiating LPU3. TypeError: __new__() takes 1 positional argument but 2 were given You forgot to include the rest of the stack trace. I think the real problem is you forgot to include the second parameter on the misnamed __init__ method. It should have parameters self and arg, and pass arg up through super. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Drawing shaded area depending on distance with latitude and altitude coordinate
On Mon, 6 Jan 2014 12:08:19 -0800 (PST), Isaac Won winef...@gmail.com wrote: dis1 = [[]]*1 for c in range(0,275): dis1[0].append(dis[c]) So dis1 has 1 row in it. But contourf is expecting many rows, matching the length of lat. I'm guessing you have to fill in the others. cs = plt.contourf(lon,lat,dis1) TypeError: Length of x must be number of columns in z, and length of y must be number of rows. That's only a tiny part of the error message. Please post the whole traceback. I made a guess here knowing nothing about these libraries you're using. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: need to print seconds from the epoch including the millisecond
On Thu, 2 Jan 2014 16:23:22 + (UTC), Grant Edwards invalid@invalid.invalid wrote: AFAIK, that's irrelevent. time.time() returns a float. On all the CPython implementations I know of, that is a 64-bit IEEE format, which provides 16 decimal digits of precision regardless of the granularity of the system time value. At this point in time, that means 10 digits left of the decimal point and 6 to the right. Correction: no more than about 6 to the right. You can certainly get less, from an os with a smaller resolution. Or you can lose some of what you do get by printing in a sub-optimal way. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 2.x and 3.x usage survey
On Wed, 01 Jan 2014 14:38:59 +0200, Steve Hayes hayes...@telkomsa.net wrote: python g:\work\module1.py File stdin, line 1 python g:\work\module1.py ^ Which gave a different error the previous time I did it. But, hey, it worked from the DOS prompt C:\Python32python g:\work\module1.py Hello Module World You need to understand that you are using two VERY different languages, one at the DOS prompt, the other at the python prompt and in .py files. You cannot use shell syntax at the python prompt, any more than you can do the reverse. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: unicode to human readable format
On Fri, 27 Dec 2013 02:43:58 -0800 (PST), tomasz.kaczo...@gmail.com wrote: can I ask you for help? when I try to print s[0] i vane the message: UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128). how to solve my problem, please? First, what version of what os, and what version of python? Next, what terminal are you running, or what ide, and do you have stdout redirected? Finally what does your program look like, or at least tell us the type and represents of s [0]. Bottom line is that s [0] contains a code point that's larger than 7f and print is convinced that your terminal can handle only ASCII. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Google Groups + this list
On Thu, 26 Dec 2013 12:04:22 -0800 (PST), ru...@yahoo.com wrote: On 12/26/2013 05:41 AM, Chris Angelico wrote: On Thu, Dec 26, 2013 at 4:13 PM, ru...@yahoo.com wrote: On 12/25/2013 09:17 PM, Chris Angelico wrote: [...] Or maybe I should have just filtered everything from Google Groups into the bit bucket, because responding just creates threads like this. Do you honestly think that would be better? No response at all if the post comes from GG? Do you really think that if *you* ignore Google Groups, then Google Groups posters will get no response at all? Could you please turn down your ego a little? That's not what I said, On rereading, my interpretation of your statement still seems legitimate. If you don't clarify, then my response can only be: yes, that *is* (in effect) what you said. It was and still is clear to me what Chris meant. With such a filter, clearly he would be making no response at all to such a post. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: need to print seconds from the epoch including the millisecond
On Fri, 27 Dec 2013 07:40:29 -0800 (PST), matt.doolittl...@gmail.com wrote: I am on Ubuntu 12.10. I am still working with the 2 decimal places. Sometime ago i had this issue and I forget how i solved it. maybe i used datetime? thanks! Now I'm stumped. 2.7.3 on Ubuntu 12.04 and time.time gives me 6 decimals. Of course it's a float, so you could get more or fewer. But if you're only seeing 2, something else is different. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Variables in a loop, Newby question
On Thu, 26 Dec 2013 16:41:57 +1100, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: Chris Angelico wrote: Does anyone else have the vague feeling that the OP's problem might be better served by simply importing the script (thus making those values available to another Python script) than by any of these rather more complicated theories? Damn yes! I take it then that my posts are invisible. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: need to print seconds from the epoch including the millisecond
On Thu, 26 Dec 2013 14:06:17 -0800 (PST), matt.doolittl...@gmail.com wrote: On Thursday, December 26, 2013 2:22:10 PM UTC-5, Dan Stromberg wrote: In [1]: import time In [2]: time.time() Out[2]: 1388085670.1567955 OK i did what you said but I am only getting 2 decimal places. You're probably on Windows, which does time differently. Specify your os version and python version and somebody will probably know. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: need to print seconds from the epoch including the millisecond
On Thu, 26 Dec 2013 20:03:34 -0500, Terry Reedy tjre...@udel.edu wrote: On 12/26/2013 5:48 PM, Dave Angel wrote: You're probably on Windows, which does time differently. With 3.3 and 3.4 on Windows 7, time.time() gives 6 fractional digits. import time; time.time() 1388105935.971099 With 2.7, same machine, I only get 3. The way I recall it, Windows time is a mess. To get better than 10 ms resolution you needed to use time.clock, but that isn't epoch time. Trickier solutions existed, depending on exactly what the problem was. But judging from your test, 3.3 built those gyrations into the stdlib. I dunno, I pretty much stopped using Windows 4 years ago. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Variables in a loop, Newby question
On Tue, 24 Dec 2013 09:54:48 -0800 (PST), vanommen.rob...@gmail.com wrote: You should always start by mentioning python version and o.s. import time global Sens_Raw1, Sens_Raw2, Sens_Raw3, Sens_Raw4, Sens_Raw5, Sens_Raw6, Sens_Raw7, Sens_Raw8, Sens_Raw9, Sens_Raw10 The global statement makes no sense here, as you're not inside a function. Everything you've written is global. That means global to one module or source file. If you need to access data from another module you'll use import, and if you need to share with another process you'll need to use a file, a pipe, a queue, or some other mechanism. while True: sensorids = [28-054c4932, 28-054c9454, 28-054c9fca, 28-054c4401, 28-054dab99, 28-054cf9b4, 28-054c8a03, 28-054d$ avgtemperatures = [] for sensor in range (len(sensorids)): temperatures = [] Sens_Raw = [] You're clobbering the list every time around the loop. Move this line before the loop. text = ''; while text.split(\n)[0].find(YES) == -1: tfile = open(/sys/bus/w1/devices/+ sensorids[sensor] +/w1_slave) text = tfile.read() tfile.close() time.sleep(0.1) secondline = text.split(\n)[1] temperaturedata = secondline.split( )[9] temperature = float(temperaturedata [2:]) temperatures.append(temperature / 1000) print Sensor , sensor + 1, temperatures # Sens_Raw(sensor) = temperatures Use Sens_Raw.append () to add to the end of the list. This is the program I am trying to adjust. The goal is to make Sens_Raw1 to 10 global so I can use it in other programs on the Raspberry Pi. The print Sensor wordks fine. Thanks for any help! -- DaveA -- 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
On Sun, 22 Dec 2013 15:41:06 -0800 (PST), Bob Rashkin rrash...@gmail.com wrote: On Sunday, December 22, 2013 4:54:46 PM UTC-6, dec...@msn.com wrote: 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 ? You are apparently asking 3 questions. To exchange 2 values, use the tuple-unpack approach. a, b = b, a To get the equivalent of multiple return values, return a tuple. def myfunc (a): x = a*a y = 2+a return x, y p , q = myfunc (5) To avoid executing your print twice, call the function only once. And a bonus one: to avoid my getting a blank message in this text newsgroup, post in text, not html. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Experiences/guidance on teaching Python as a first programming language
On Thu, 19 Dec 2013 19:41:00 +1300, Gregory Ewing greg.ew...@canterbury.ac.nz wrote: But it's not above inferring a dereferencing operation when you call a function via a pointer. If f is a pointer to a function, then f(a) is equivalent to (*f)(a) If the compiler can do that for function calls, there's no reason it couldn't do it for member access as well. Quite right. And I recall being confounded by the function pointer syntax; it never fit in my mental model of how the rest of C worked. Anyway I was not intending to defend C choices, merely to point out an advantage this choice gave me. On a language without garbage collection, the indirection was very important to keep in mind. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: GUI:-please answer want to learn GUI programming in python , how should i proceed.
On Thu, 19 Dec 2013 16:32:37 +0100, Wolfgang Keller felip...@gmx.net wrote: With Windows it *is* normal. An experienced software developer once even explained the reason to me. When a single process on Windows does I/O, then the system essentially falls back to single tasking. Or (non-)cooperative multitasking at best, depending on how dissocial the developer of that process is. If you were told this 20 years ago, perhaps. But Windows hasn't been running on DOS for a long time. Starting with NT 3.1, that's nonsense. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Experiences/guidance on teaching Python as a first programming language
On 18 Dec 2013 08:22:58 GMT, Steven D'Aprano st...@pearwood.info wrote: On Wed, 18 Dec 2013 13:11:58 +1100, Chris Angelico wrote: The one differentiation that I don't like is between the . and - operators. The distinction feels like syntactic salt. There's no context when both are valid, save in C++ where you can create a pointer-like object that implements the - operator (and has the . operator for its own members). Funny you should say that in the middle of a discussion about lifetime. In C, when you do the - thing, you're now in a different struct with a potentially different lifetime. If p is a local, with auto lifetime, then so is p.x So, although the two are mutually exclusive, there's valuable information hidden in the required choice. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Re: Experiences/guidance on teaching Python as a first programming language
On Thu, 19 Dec 2013 01:55:10 +1100, Chris Angelico ros...@gmail.com wrote: Sure, but you can figure out whether p is a local struct or a local pointer to some other struct by looking at its declaration. Do you also need to look at every usage of it? C is a glorified macro assembler. So the - operator is not analogous to the dot operator, it's Syntactic sugar: p- a. Is really (*p).a -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Python and MIDI
On Tue, 17 Dec 2013 08:45:28 -0800, Tobiah tshep...@rcsreg.com wrote: Is there a module out there that would let me send a predetermined list of midi messages to a MIDI device in such a way that the timing would be precise enough for music? Probably. I haven't tried it but I'd look first at pygame. Maybe first at: http://www.pygame.org/wiki/MidiScheduler -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Wrapping around a list in Python.
On Sun, 15 Dec 2013 21:26:49 -0800 (PST), shengjie.sheng...@live.com wrote: The idea is to grab the last 4 elements of the array. However i have an array that contains a few hundred elements in it. And the values continues to .append over time. How would i be able to display the last 4 elements of the array under such a condition? Your earlier example showed [5, 4, 1, 2] as one of the results, which is not the last four. But assuming your goal has now changed and you really have an array (or list) of a few hundred elements, then you can just use data [-4:] to get them. But if you're being imprecise and these values are not really in an array, then follow Peter ' advice and use a deque. Or fake it with a list, appending to the end and popping from the beginning. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] trying socket as a replacement for nc
On Mon, 16 Dec 2013 10:26:14 -0800 (PST), Jean Dubois jeandubois...@gmail.com wrote: File ./test.py, line 7 def flush() ^ SyntaxError: invalid syntax A definition line needs to end with a colon (fix the other as well) -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Eliminate extra variable
On Sun, 15 Dec 2013 18:43:53 -0800, Igor Korot ikoro...@gmail.com wrote: On Sun, Dec 15, 2013 at 4:58 PM, MRAB pyt...@mrabarnett.plus.com wrote: When writing paths on Windows, it's a good idea to use raw string literals or slashes instead of backslashes: conn = sqlite3.connect(r'c:\Documents and Settings\Igor.FORDANWORK\Desktop\mydb.db', detect_types = sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) or: conn = sqlite3.connect('c:/Documents and Settings/Igor.FORDANWORK/Desktop/mydb.db', detect_types = sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) So, how do I convert my string to one of those? I realized I can just do replace '/' to '\', but is there a better alternative? The conversion is done with a text editor. The string literals you had were just wrong. By the time they have been turned into strings it's too late to algorithmically recover your intended string values. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Movie (MPAA) ratings and Python?
On Wed, 11 Dec 2013 23:22:14 -0700, Michael Torrie torr...@gmail.com wrote: From what I can see gmail is producing a multipart message that has a plaint text part and an html part. This is what gmail normally does and as far as I know it's RFC-compliant and that's what gmail always does. Always does doesn't mean it's a good idea on a text newsgroup. Very often the pretty text in the html part is mangled in the text part. Most often this is just indentation, but for Python that's a biggie. It also means that we don't all see the same thing. Including both makes the download slower and more expensive. Some text newsreaders refuse to show anything if there's an html part. Mine (groundhog on android) apparently shows the text part if it follows the html part. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] trying socket as a replacement for nc
On Thu, 12 Dec 2013 13:27:16 -0800, Dan Stromberg drsali...@gmail.com wrote: On Thu, Dec 12, 2013 at 6:16 AM, Grant Edwards invalid@invalid.invalid wrote: I haven't done a lot of UDP, but are you pretty sure UDP can't at least fragment large packets? What's a router or switch to do if the Path MTU isn't large enough for an original packet? A router doesn't talk udp or tcp, it deals with ip packets, which it IS permitted to fragment. Conversely the udp layer in the os doesn't care about MTU. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: load_module for import entire package
On Tue, 10 Dec 2013 23:28:31 -0800 (PST), Sergey sh0...@gmail.com wrote: def get_obj(): pkg = load_package_strict(tmp, basedir) from tmp import main return main.TTT() It is working, but if package code changes on disc at runtime and I call get_obj again, it returns instance of class, loaded for the first time previously. That's how import works. Once something has been imported, the module information is cached. There are three ways to defeat that, but they're all risky. How to replace line from tmp import main by getting properties of pkg? No clue what you mean by that. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: grab dict keys/values without iterating ?!
On Wed, 11 Dec 2013 02:02:20 +0200, Tamer Higazi tamerito...@arcor.de wrote: Is there a way to get dict by search terms without iterating the entire dictionary ?! I want to grab the dict's key and values started with 'Ar'... Your wording is so ambiguous that each respondent has guessed differently. I'm guessing that you want all key/value pairs for which the key begins with the two letters 'Ar' I'm guessing further that your objection to iterating the entire dictionary is not code size but performance. If both assumptions are valid then I'll point out that a dict has no ordering to it. If you want an approach that doesn't iterate over the entire structure you'll need to store the data differently. For example if you stored all the keys in a sorted list you could use bisect. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: squeeze out some performance
On Mon, 09 Dec 2013 15:54:36 +, Robin Becker ro...@reportlab.com wrote: On 06/12/2013 22:07, Joel Goldstick wrote: end, start = start, end a similar behaviour for simple assignments for less than 4 variables the tuple method is faster. What does speed have to do with it? When you want to swap two variables, the tuple assignment reads better. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] struggling wth tkinter
On Sat, 7 Dec 2013 23:45:06 -0800 (PST), Jean Dubois jeandubois...@gmail.com wrote: This is what I get: Traceback (most recent call last): File ./feet2meters.py, line 2, in module from tkinter import * File /home/jean/tkinter.py, line 2, in module import Tkinter as tk ImportError: No module named Tkinter Regardless of your other fixes, you should rename the bogus file: /home/jean/tkinter.py You very seldom want to have files that can shadow system modules. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Fwd: Eliminate extra variable
On Sun, 8 Dec 2013 12:58:18 -0800, Igor Korot ikoro...@gmail.com wrote: It's input is the query result, so there is no looping when the function is called. It is called only once. Then why save part of the result in an instance attribute? Just return all of the results as a tuple. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] struggling wth tkinter
On Sat, 7 Dec 2013 08:52:08 -0800 (PST), Jean Dubois jeandubois...@gmail.com wrote: I'm trying to go through a tutorial on tkinter which has the code below as an example. The only thing I see when running it is a little popup with Click mouse here to quit which works as expected but always shows the following error-message. However the main window which should let you enter the numbers is not shown. This is the quit error message: Traceback (most recent call last): File ./feet2meters.py, line 3, in module from tkinter import ttk ImportError: cannot import name ttk This is the code: #!/usr/bin/env python from tkinter import * from tkinter import ttk Thanks for supplying the complete traceback. But you should also tell the python version and what OS. I'll guess python 3.3 on Linux. Finally, what version tk are you running? These widgets were introduced in tk 8.5 Since it failed on the second import, none of the rest of the code matters. However, since you're not running it from a terminal window, it's conceivable that your ide is affecting the result. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
[issue19901] tests fail due to unsupported SO_REUSEPORT when building Python 3.3.2-r2
Dave Malcolm added the comment: [FWIW, this looks similar to an issue I ran into on Fedora: https://bugzilla.redhat.com/show_bug.cgi?id=913732 which was due to a mismatch between the kernel headers on the system vs the actually running kernel. I patched around it there with a downstream-only patch (our builds are done on chroots on RHEL-5 boxes, so such mismatches tend to occur)] -- nosy: +dmalcolm ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19901 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wed, 4 Dec 2013 14:05:11 -0800 (PST), Piotr Dobrogost p...@google-groups-2013.dobrogost.net wrote: Object's attributes and dictionary's keys are quite different things. Right. So if you need arbitrary keys, use a dict. Attributes are keyed by identifiers, which are constrained. No problem. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Tue, 3 Dec 2013 09:14:49 -0800 (PST), Piotr Dobrogost p...@google-groups-2013.dobrogost.net wrote: I find global getattr() function awkward when reading code. Me too. What is the reason there's no natural syntax allowing to access attributes with names not being valid Python identifiers in a similar way to other attributes? There is. Just use a dictionary. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: The input and output is as wanted, but why error?
On Tue, 3 Dec 2013 08:35:20 -0800 (PST), geezl...@gmail.com wrote: really, i dont know why.. :( How about because you do a system exit on the first line of their input? The one that's all digits. And even if you get past that, you only process one of their words. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Unicode handling wins again -- mostly
On Fri, 29 Nov 2013 21:28:47 -0500, Roy Smith r...@panix.com wrote: In article mailman.3417.1385777557.18130.python-l...@python.org, Chris Angelico ros...@gmail.com wrote: On Sat, Nov 30, 2013 at 1:08 PM, Roy Smith r...@panix.com wrote: I would certainly expect, x.lower() == x.upper().lower(), to be True for all values of x over the set of valid unicode codepoints. Having u\uFB04.upper() == FFL breaks that. I would also expect len(x) == len(x.upper()) to be True. That's a nice theory, but the Unicode consortium disagrees with you on both points. And they were already false long before Unicode. I don’t know specifics but there are many cases where there are no uppercase equivalents for a particular lowercase character. And others where the uppercase equivalent takes multiple characters. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: error
On Wed, 27 Nov 2013 16:37:37 -0800 (PST), speen saba moonlightmadnes...@gmail.com wrote: p = [1,2] And below is the error. Evrything works fine untill class polar point, but when I try to pick point (instance) p in the list i.e x,y (1,2,3,1). It does not work. I mean p.x gets the error where it should give me the value of x. And i know this error will go all the way down to def__cmp if i dont fic it from top. p.x Traceback (most recent call last): File pyshell#46, line 1, in module p.x AttributeError: 'list' object has no attribute 'x' You have 4 different implementations, but you're mixing the first with the others. Since p is a list, you need to use list semantics, p [0] and p [1]. The .x attribute is not defined on a list. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Python project
On Wed, 27 Nov 2013 17:43:27 -0800 (PST), ngangsia akumbo ngang...@gmail.com wrote: I a beginner in python. The first project is to build an online city guide start with my own city. I will need some support on where to get started. Are you experienced in other languages, in html? Is this your first time programming on Linux? Are you using Python 3.3? Are you constrained in what extra modules you may or must use? Can you just build each page using some Web generator? -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Excute script only from another file
On Mon, 25 Nov 2013 02:52:46 -0800 (PST), Himanshu Garg hgarg.in...@gmail.com wrote: My motive is I will give scripts to somebody else and he should not run the script directly without running the parent script. Perhaps it should be a module, not a script. Have it protect itself with the usual if __name__ == __main__ And of course it gets executed by an import and a call. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
[issue19743] test_gdb failures
Dave Malcolm added the comment: FWIW, I feel that it's worth just expecting failures with an *optimized* build: with an optimizing compiler, there's likely to always be some program counter location where the debugger is going to get confused for some variables. Given umpteen different compiler variants, debugger variants etc, this is never going to be perfect. So IMHO we should run the test on a --pydebug build, but accept that there will be some failures when optimization is on. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19743 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Excute script only from another file
On Sun, 24 Nov 2013 17:55:08 -0800 (PST), Himanshu Garg hgarg.in...@gmail.com wrote: Like, I have two scripts scrip1.py and script2.py and there is a line in script1.py to call script2.py as subprocess.call([python, script2.py]). Then this is should call script2 but I should not be able to directly call script2 as $python script2.py Are you really trying to protect against yourself accidentally invoking it or someone maliciously doing it? I would probably give scrpt2 an obnoxious name like htrerttcdrrthyyh.py or put it in an obscure directory. But if you explain the rationale we might come up with something better. How about naming it dontrunme.py ? -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Help me to print to screen as well as log
On Sat, 23 Nov 2013 05:11:11 -0800 (PST), Himanshu Garg hgarg.in...@gmail.com wrote: How can I write to the same file from two different scripts opened at same time? Using what version of python and on what OS? Sone OS's will open the file exclusively by default. Others will let you stomp all over some other process' output. Why not show us what you're trying and what happens and ask a much more specific question? -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Got a Doubt ! Wanting for your Help ! Plz make it ASAP !
Try posting in text, as some of us see nothing in your message. This is a text newsgroup, not html. Also make a subject line that summarizes your issue, not the urgency. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: using getattr/setattr for local variables in a member function
On Fri, 22 Nov 2013 00:52:21 +, MRAB pyt...@mrabarnett.plus.com wrote: If I have a class that has some member functions, and all the functions define a local variable of the same name (but different type), is there some way to use getattr/setattr to access the local variables specific to a given function? If you mean to access them from within the same method, someone else has already shown it using locals(). But you cannot access locals from a method that's already terminated. They no longer exist. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Newbie - Trying to Help a Friend
On 20 Nov 2013 00:17:23 GMT, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: problem by hand. I'll get you started by solving the problem for 7. Positive integers less than 23 are 1, 2, 3, 4, 5, 6. So let's start checking them for divisors: Where did 23 come from? - 1 is not divisible by 2, 3 or 5, so we count one number. - 2 is divisible by 2, but not by 3 or 5, so we count two numbers. 2 doesn't count because it's divisible by 2. - 3 is not divisible by 2, so we count three numbers. 3 doesn't count because it's divisible by 3 - 4 is divisible by 2, but not 3 or 5, so we count four numbers And so on. - 5 is not divisible by 2, so we count five numbers. - 6 is divisible by 2 and 3, but not by 5, so we count six numbers. I count 1, not 6 And the answer is: 6. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Newbie - Trying to Help a Friend
On 20 Nov 2013 03:52:10 GMT, Steven D'Aprano st...@pearwood.info wrote: 2 does count because it isn't divisible by 3. The question states, [count] how many positive integers less than N are not divisible by 2,3 or 5. Two is not divisible by 3, so not divisible by 2,3 or 5 is true, so two gets counted. The first number which is divisible by *all* of 2, 3 and 5 (i.e. fails the test, and therefore doesn't get counted) is 30. The next few that fail the test are 60, 90, 120, 150, 180, 210, 240, 270, 300, ... Remember, these are the numbers which should not be counted. I count 1, not 6 Out of curiosity, which number did you count? 1 of course. It's the only one that's not divisible by any of the factors. Apparently we disagree about precedence and associativity in English. I believe the not applies to the result of (divisible by 2, 3, or 5), so I'd count 1, 7, 11, 13, 17, 19, 23. The first nonprime would be 49. If I were trying to get the series you describe, I'd phrase it as Not divisible by 2, and not divisible by 3, and not divisible by 5 -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Oh look, another language (ceylon)
On 18 Nov 2013 14:30:54 GMT, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: - 15 bits for a length. 15 bits give you a maximum length of 32767. There are ways around that. E.g. a length of 0 through 32766 means exactly what it says; a length of 32767 means that the next two bytes are part of the length too, giving you a maximum of 4294967295 characters per string. That's an 8GB string. Surely big enough for anyone :-) If you use nearly all of the possible 2 byte values then adding 2 more bytes won't give you anywhere near 4 bI'll ion characters. You're perhaps thinking of bringing in four more bytes when the length exceeds 32k. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list