You can filter the list like this
file_count = len([f for f in os.walk(".").next()[2] if f[-4:] == ".txt"])
You can filter the list like this
file_count = len([f for f in os.walk(".").next()[2] if f[-4:] == ".txt"])
it should be a unittest for python strings !
It's because your function revstr
prints the reversed string, but then returns None (because there is no return statement). Since your program contains print revstr(...
, this None value returned is printed. What you should do is replace print by return in revstr
.
Note: in the forum, use (code=python) instead of (code) :)
On windows, I was able to shutdown the system with
import os
os.system("shutdown -s")
On linux, it was
import os
os.system("sudo shutdown -h now")
Note that normaly on linux, only the superuser can shutdown the machine with 'shutdown'. Other users must be allowed to do so by the superuser. This page http://www.spencerstirling.com/computergeek/shutdown.html explains how.
I don't know the commands on osx, or other systems.
A portable program should choose the command depending on the underlying system, may be by examining the content of sys.platform
:)
I give my solution for PROBLEM 3 in obfuscated python
def alien2float(s):
from bisect import bisect
i = bisect(s, '[')
seti = lambda z: reduce(lambda x, y: 5.0*x+y,
map(dict(map(lambda(x, y): (y, x), enumerate("AEIOU"))).get, z))
try:
if i:
res = seti(s[:i])
else:
res = 0.0
x = s[i:]
if not x:
return res
elif not x.islower():
return -1
return res + seti(x.upper())/5**len(x)
except TypeError:
return -1
if you like the previous code, I'll put it in the code snippets :)
for PROBLEM 1, I suggest the following program
#!/usr/bin/env python
# printdef.py
# prints the names of all function definitions found in a program
# usage: python printdef.py myprogram.py
from tokenize import generate_tokens, NAME
def getDefSequence(programPath):
tokens = generate_tokens(open(programPath, "r").readline)
for token in tokens:
if token[0] == NAME and token[1] == "def":
func = tokens.next()
if func[0] == NAME:
yield func[1]
if __name__ == "__main__":
import sys
programPath = sys.argv[-1]
if programPath[-3:] != ".py":
print "usage: printdefs.py <path to '.py' file>"
sys.exit(-1)
for name in getDefSequence(programPath):
print name
A simple way to do this would be to write a small GUI code, using the wx.TextEntryDialog widget.
I suggest that you visit this link http://wiki.wxpython.org/AnotherTutorial#head-2e6716d7887279f22b0ffa57dc03278ea4ed8f85
and paste the code section just below, and then drop most of the methods, but the method def textentry
. In the text entry, you can edit your record.
I think it's an easy solution since the code is ready to run (you may have to install wxpython :) )
Here is a better way to handle flow of control :)
def youWantToAddAPerson():
return int(raw_input("Do you want to add a new person (0 or 1) ? "))
def getThePersonName():
return raw_input("What is the name of the person ? ")
def getThePersonNumber():
return raw_input("What is the number of that person ? ")
def youWantToSeeTheNotebook():
return int(raw_input("Do you want to see the notebook now (0 or 1) ? "))
def displayTheNotebook():
print "not yet implemented"
def addThePersonToNotebook(name, number):
# XXX not yet implemented
pass
def thankUserAndQuit():
print "Thank you for using Gribouilli's software"
while youWantToAddAPerson():
name = getThePersonName()
number = getThePersonNumber()
addThePersonToNotebook(name, number)
if youWantToSeeTheNotebook():
displayTheNotebook()
thankUserAndQuit()
found in another forum:
>>> x = "Blah"
>>> def pp():
... global x
... x = "Hello There!"
...
>>> print x
Blah
>>> pp()
>>> print x
Hello There!
Here the method is demonstration.number
(it's an attribute of the class, which you hide in the instances with self.number = number
.
The file I attached has only 68 lines. No error can occur on line 122 ! And I commented out the line sentence = ...
. So you must have done something to my file. Try to reload it :)
Strange, it works very well here. Could you post the full Exception traceback ?
I attach a slightly corrected program
#sentence generator
import random
from Tkinter import *
# Tkinter is used to make the button
class App:
def __init__(self, master):
self.frame = Frame(master)
self.frame.pack()
self.button = Button(self.frame, text="Go!", command=self.displaySentence)
self.button.pack()
def displaySentence(self):
for item in self.makeSentence(part1, part2, part3):
print item
def makeSentence(self, part1, part2, part3, n=1):
"""return n random sentences"""
#convert to lists
p1 = part1.split('\n')
p2 = part2.split('\n')
p3 = part3.split('\n')
#shuffle the lists
random.shuffle(p1)
random.shuffle(p2)
random.shuffle(p3)
#concatinate the sentences
sentence = []
for k in range(n):
try:
s = p1[k] + ' ' + p2[k] + ' ' + p3[k]
s = s.capitalize() + '.'
sentence.append(s)
except IndexError:
break
return sentence
# break a typical sentence into 3 parts
# first part of a sentence (subject)
part1 = """\
A panda
Gary Busey"""
# (action)
part2 = """\
slaps
eats
gores
"""
# (object)
part3 = """\
puppies
bananas
"""
#sentence = makeSentence(part1, part2, part3)
#for item in sentence:
# print item
root = Tk()
app = App(root)
root.mainloop()
Here is a way to swap characters
import re
swap_pat = re.compile(u"A(?:B|C|D)")
def swap(swap_match):
s = swap_match.group(0)
return s[1] + s[0]
def swap_sub(theString):
return swap_pat.sub(swap, theString)
second_pat = re.compile(u"\u1013(.*)\u102C")
def second(second_match):
middle = second_match.group(1)
return u"\u1001%s\u102B" % middle
def second_sub(theString):
return second_pat.sub(second, theString)
if __name__ == u"__main__":
s = u"ACCESS TO PADDED DATA ABORTED"
print s
print swap_sub(s)
s = u"Hello \u1013world\u102C"
print repr(s)
print repr(second_sub(s))
Since you have many substitutions to perform, you should try to group your regex in a single regex. Also make sure the regex are compiled only once with re.compile.
Hope this helps ...
I think I found it: if control imports handle_input, then handle_input must not import control so remove the
from control import *
hm, attach your module to a post may be ?
ok , you can try to remove the .pyc file (it will reappear automatically)
One thing you can try is this:
import handle_input
print handle_input.__file__
It will print you the path from where the handle_input module was imported. Make sure it's the path to your file
In fact there is another possibilty, if the handle_input module contains a statement like this
__all__ = [ "hello", "world" ]
then only the symbols "hello" and "world" can be imported
It means that there is no class nor function nor variable named 'handle_input' in the handle_input module :)
There doesn't seem to be an error. This kind of errors happen sometimes with IDE like idle when a module like 'handle_input' was previously loaded and then modified, but the modified version is not reloaded by idle.
However, since we don't know the context, I suggest for debugging that you replace from handle_input import *
by from handle_input import handle_input
. This way we can be sure that the global name handle_input
exists.
I write a lot of python code and almost never use global declarations :). In fact you must use a global declaration when you want to assign a value to a global variable in a function, like your line
Contacts_lbox = Listbox(f3,height=5)
[/codeh
however it works only if your variable is already a global name. When compiling your code, python makes a collection of your global names. Global variables refer to names in this collection.
A solution to your problem is to add lines like
[code=python]
Contacts_lbox = None
number_string = None
name_string = None
somewhere at global level (for example at the top of your file). These variables become global names.
Another (and better solution) is probably to avoid global variables and to make an object with properties Contact_lbox, etc. This would imply more changes to your code...
Python is open source and written in C, so in principle you should be able to extract pickling functions from the source code of python itself.
It's most certainly a useless task to try to write another C function for this.
Another way to hide things is to use an embedded python interpreter in your C program, and use it to call the methods of the Pickle module :)
I have some experience with speeding up python with swig. It allows you to access virtually any algorithm written in C or C++ from python. I used it for numerical analysis and also parsing. On such problems, this method is quit e efficient.
However, the most useful feature of swig is that you can wrap existing C librairies and access their functions from python. This method has been applied to many existing C librairies. Since thousands of potentially useful C libraries exist, this is a very good reason to experiment with swig, if you have a C compiler of course.
The usual warning applies: it's often difficult to predict exactly where are the botlenecks in your programs, which parts of the algorithms are going to slow down the whole program. So a good strategy can be to write a first version in python, and use profiling to determine which parts could be reimplemented in C. The golden rule is to avoid writing C code as much as possible, and speed up only key computational steps...