Also, if you want to exit from a deeply nested point during the execution you can use
raise SystemExit
or
import sys
sys.exit(0) # use another value, like -1 to mean program failure
Also, if you want to exit from a deeply nested point during the execution you can use
raise SystemExit
or
import sys
sys.exit(0) # use another value, like -1 to mean program failure
The best way is to use the constructor 'int' with basis 16 to convert the hex values to integers, then use the bitwise operators &, |, ^ to perform the bitwise operations and use the 'hex' function to get the hexadecimal representation of the resulting integers. Here is an example with python 3 (but it also works with python 2)
>>> x, y = int("0x00E2", 16), int("0x0F80", 16)
>>> print(hex(x & y))
0x80
>>> print(x, y, x & y)
226 3968 128
>>> print(hex(x | y))
0xfe2
>>> print(x | y)
4066
>>> print(bin(x), bin(y), bin(x&y), bin(x|y))
0b11100010 0b111110000000 0b10000000 0b111111100010
Perhaps your file is using a BOM at the beginning. You could try open with mode 'utf-8-sig' instead of 'utf-8'.
In linux, windows shares must be mounted. For example at home, I mount the (shared) C drive of another computer with IP address 192.168.2.4 like this
$ sudo mount -t cifs 192.168.2.4:C -o password="" /mnt/othercomp
I can then access /mnt/othercomp like any other directory.
I can also unmount the shared folder with
$ sudo umount 192.168.2.4:C
Also you can obtain an IP address like this
$ nmblookup computer_name
edit: before invoking 'mount', you must create the directory /mnt/othercomp with mkdir :)
First of all, why linear search? That's like the worst algorithm to use ever.
But if you don't want to use the Python internal algorithm, a for loop can do it:
def findValue(v, li): for i in len(li): if v == len[i]: return i return -1
But that's such a bad algorithm. Internally, you have this ->
value in li
Also, you can code your own "smart" algorithm, like i did here:def average(number1, number2): return sum([number1, number2])/2 def bisectFind(li, item): midpoint = (len(li)-1)/2 minIndex = 0 maxIndex = len(li)-1 while True: if maxIndex - minIndex < 11: for i in range(minIndex,maxIndex+1): if li[i] == item: return i return None if item < li[midpoint]: maxIndex = midpoint midpoint = average(minIndex, maxIndex) continue elif item > li[midpoint]: minIndex = midpoint midpoint = average(minIndex, maxIndex) continue elif item == li[midpoint]: return midpoint
Binary search works only if the list is initially sorted.
P.S. Tabs in python files are seen as a newbie mistake. Indents are usually 2 or 3 spaces
As a newbie, use the recommended (and widely used) 4 spaces indentation. You can configure your editor to put 4 spaces when you hit the tab key.
Try print repr(text)
to see what the string 'text' actually contains.
Also if your file contains non ascii data, you should try the "rb" opening mode.
A simple > is equivalent to 1> . It redirects stdout to your file. A 2> redirects stderr. A google search with "linux redirection" should tell you all about redirection. For example, I found this http://en.wikipedia.org/wiki/Redirection_%28computing%29
A good solution is
import webbrowser
webbrowser.open("file.txt")
On my system, it opens the file with gedit.
I suggest this simpler code. Check that it works as you expect
def cfg_wlan(self, wlan_cfg):
"""
Configure a new wlan for Zone Director.
Input: a dictionary, supplied in DUT.py
Output: none
"""
defaults = [
('ssid', None), ('auth', None),
('encryption', None), ('wpa_ver', None),
('key_string', None), ('key_index', None),
('auth_server', ""), ('use_web_auth', False),
('use_guest_access', False), ('acl_name', ""),
('use_hide_ssid', False), ('vlan_id', ""),
('uplink_rate_limit', ""), ('downlink_rate_limit', ""),
('use_client_isolation', False), ('use_zero_it', False),
('use_dynamic_psk', False), ('do_tunnel', False)
]
argdict = dict([(k, wlan_cfg.get(k, v)) for (k, v) in defaults])
if not 'use_zero_it' in wlan_cfg:
argdict['use_dynamic_psk'] = False
if argdict['auth'] == "PSK":
argdict['auth'] = "open"
if argdict['auth'] == "EAP":
if wlan_cfg['use_radius']:
argdict['auth_server'] = wlan_cfg['ras_addr']
elif argdict['use_web_auth']:
argdict['auth_server'] = wlan_cfg['ras_addr'] or wlan_cfg['ad_addr'] or ""
args = [argdict[k] for (k, v) in defaults]
try:
self._create_wlan(*args)
except:
raise
If you only want to read blank cells, you could use a defaultdict
from collections import defaultdict
parsed_dictionary = defaultdict(lambda: None, book[0][1])
This would insert a value None if you try to read a non existent key (0,1) for example, instead of raising KeyError.
At first sight, you should indent def savefile():... to make it a method of the App class and use filemenu.add_command(label='Save', command=self.savefile)
in the __init__ method.
PyMouse moved to http://github.com/pepijndevos/PyMouse. I tested it on a 64 bits linux box. It seems to give a nice control of the mouse. Here is a example session with the release 1.0
>>> import pymouse
>>> dir(pymouse)
['PyMouse', 'PyMouseEvent', 'PyMouseEventMeta', 'PyMouseMeta', 'Thread', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'sys', 'unix']
>>> mouse = pymouse.PyMouse()
>>> mouse.move(100, 200)
>>> mouse.move(100, 200)
>>> mouse.move(300, 100)
>>> dir(mouse)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'click', 'move', 'position', 'press', 'release', 'screen_size']
>>> mouse.click(400, 500)
>>> mouse.click(400, 500)
>>> mouse.screen_size()
(1280, 1024)
>>> mouse.position()
(708, 894)
It's only an idea, but don't you think sys.argv
contains the path to the double-clicked file ?
See also the table of operator precedence in python http://docs.python.org/reference/expressions.html#summary.
I would use
Calculate = sum
instead of the above code ;)
Ok, last trial, can you *run* this file and *post* its output in this thread ?
# run_me.py
import os, sys, os.path
class Command(object):
"""Run a command and capture it's output string, error string and exit status"""
def __init__(self, command):
self.command = command
def run(self, shell=True):
import subprocess as sp
process = sp.Popen(self.command, shell = shell, stdout = sp.PIPE, stderr = sp.PIPE)
self.pid = process.pid
self.output, self.error = process.communicate()
self.failed = process.returncode
return self
@property
def returncode(self):
return self.failed
def main():
try:
import easy_install
except ImportError:
print("Could not import easy_install")
return
com = Command("%s %s unidecode" % (sys.executable, easy_install.__file__)).run()
if com.failed:
print com.output
print com.error
else:
try:
import unidecode
except ImportError:
print("Could not import unidecode")
else:
print("Module unidecode is installed")
main()
Unfortunately still not working
and result with word_re = re.compile("\w+") its better from Word_re = re.compile(r"[A-Za-z0-9]+")
any way i will try to resolve that, i dont want fatigue with me :)
and really thanks for your helpLast thing i want your help about unique if you have any idea
the result if contain lot of same word appear to me that
/home/cache/lang_subscriptions.php
/home/cache/lang_subscriptions.php
/home/cache/lang_subscriptions.phpI want solution to unique
I don't understand. The break statement at line 12 above ensures that each filename is printed only once. If it doesn't work, you should be able to show where it fails. Can you write an example file where it fails ?
You could try
Word_set = set(['nochex','lang','test2'])
Word_re = re.compile(r"[A-Za-z0-9]+") # better put this out of the loop
for (path, dirs, files) in os.walk("/home/cache"):
for file in files:
filename = os.path.join(path, file)
file_size = os.path.getsize(filename)
READ = open(filename).read()
for match in Word_re.finditer(READ):
word = match.group(0)
if word in Word_set:
print filename
break
You can use the re module. See http://docs.python.org/library/re.html#module-re . Here is an example
import re
word_set = set(["give", "me", "bacon", "and", "eggs", "said", "the", "other", "man"])
word_re = re.compile("\w+")
text = """
Draco chewed furiously at his toast, trying in vain to shut out the strong smell of bacon and eggs, that wafted from Crabbe's and Goyle's overfilled plates. In his view, it was a barbaric way to start the day, and not even the threat of being locked up with wild hippogriffs could make him eat a breakfast that rich and greasy. He glared across the hall, scowling as he watched Harry shovel his eggs into his mouth, his eyes fixed on his plate. """
for match in word_re.finditer(text):
word = match.group(0)
if word in word_set:
print word,
""" my output --->
the bacon and eggs and the and the and the eggs
"""
I found a funny module on the web, called unidecode http://code.zemanta.com/tsolc/unidecode/ . Here is my result
>>> from unidecode import unidecode
>>> unidecode(u'ąóęśłżźćńĄÓĘŚŁŻŹĆ')
'aoeslzzcnAOESLZZC'
nice, isn't it ?
Edit: it's also in pypi: http://pypi.python.org/pypi/Unidecode
Can't you just do this?
for a in array: number = int(a)
Yes you can, but if you want to do something with the integers, you must store them somewhere.
You can write
int_array = [ int(s) for s in array ]
You can use itertools.product(*array)
, also if your want your result in a list, you write list(itertools.product(*array))
.
The i
in range(0, i + 1, 1) should be n
.
It's strange, it works on my machine with python 3.1. A possibility is that you have a file calendar.py in your directory or in the python path which hides the standard module calendar. If this is so, you should rename this file. To see if this is the case, try this
import calendar
print(calendar)
and post the output here.
Have tried mutiple files, all with content, and still no output
content_string = open(fileName).read()
print(content_string) # <---- OUTPUT
You can go this way
>>> l = [[1, 2, 1],[1, 1, 2],[2, 1, 1]]
>>> for i, element in enumerate(l):
... l[i] = [x for x in element if x != 1]
...
>>> l
[[2], [2], [2]]
or even shorter
>>> l = [[1, 2, 1],[1, 1, 2],[2, 1, 1]]
>>> l[:] = ([x for x in e if x != 1] for e in l)
>>> l
[[2], [2], [2]]
This snippet shows how to find the complex roots of a polynomial using python (tested with python 2.6). You need the scipy or numpy module.
The \n is still there ! You should write
line = line.rstrip("\n")
# or line = line.strip() to remove all white space at both ends
line 10 should be total = sumDivisors(n)
. Also you can speed this up by adding total += counter + n/counter
when counter < n/counter
and total += counter
when counter == n/counter
.
On my computer (mandriva linux 2010), the number is not lost when I save as .ps or .pdf.
If you want a better code structure, you could write parts of the structure before the details. For example
import random
def main():
name = get_name()
while True:
show_menu()
answer = get_menu_choice()
if answer == "P":
play_game(name)
elif answer == "V":
view_high_scores()
elif answer == "Q":
break
else:
print("Please choose V, P or Q")
def show_menu():
print (''' Menu:
(V)iew High Scores
(P)lay Game
(Q)uit Game''')
def get_name():
pass # TODO
def get_menu_choice():
pass # TODO
def play_game(name):
number = random.randint(1, 42)
guessesTaken = 0
while True:
try:
guess = int(raw_input('Please enter your guess, between 1 and 42: '))
except ValueError:
print("Your guess must be an integer !")
continue
guessesTaken += 1
if guess < number:
print 'My number is higher.'
elif guess > number:
print 'My number is lower.'
else:
print 'Good job, ' + name + '! You guessed my number in ' + guessesTaken + ' guesses!'
return
def view_high_scores():
pass # TODO
if __name__ == '__main__':
main()
Here is a more compact and pythonic approach
def displayHappy():
numLimit = input("Enter a positive integer: ")
liHappy = list(i for i in range(1, numLimit+1) if isHappy(i))
print liHappy
for i in range(len(liHappy)-1):
if liHappy[i+1] - liHappy[i] == 1:
print "lovers: %d, %d" % (liHappy[i], liHappy[i+1])
def isHappy(num):
while not num in (1, 4):
num = zap(num)
return num == 1
def zap(num):
return sum(d**2 for d in digits(num))
def digits(num):
while num:
num, digit = divmod(num, 10)
yield digit
displayHappy()
Here is a version that runs. I just removed the last index in the lovers loop
def displayHappy():
numLimit = input("Enter a positive integer: ")
countHappy = 0
countUnhappy = 0
liHappy = []
for num in range(1, numLimit + 1):
inNum = num
while inNum != 1 and inNum != 4:
inNum = zap(inNum)
if inNum == 1:
liHappy.append(num)
countHappy += 1
else:
countUnhappy += 1
print liHappy
for i in range(len(liHappy)-1):
if liHappy[i+1] - liHappy[i] == 1:
print "lovers: %d, %d" % (liHappy[i], liHappy[i+1])
def zap(intNum):
total = 0
while intNum != 0:
last = intNum % 10
total += last**2
intNum = intNum / 10
return total
displayHappy()
If you have a 64 bits processor, use a linux system ! Mandriva 2010 gnome is excellent.
You can use the code module, which has classes like InteractiveConsole to evaluate python expressions.
This snippet defines a class LebsegueSet which instances represent sets of real numbers, namely finite unions of intervals. Set theoretical, topological and measure theoretical operations are implemented in pure python. Use freely and enjoy !
1) Yes, everything you manipulate in python is an object, an instance of a class.
2) You never need to declare the type of anything.
3) When a function returns more than 1 value, it returns in fact a *tuple*, one of python's FDT. There is no reason to avoid using this feature in python.
4) Python's syntax evolved *slowly* with the different versions of python. The recent change from python 2.6 to 3.0 introduced a few backwards incompatibility. The most visible syntactic changes are the print and exec statements which became functions in python 3. In previous versions, syntactic changes added new features without backwards incompatibility (for example list comprehension syntax or with statement syntax, etc).
5) You could start with an introductive text like 'dive into python' (google is your friend).
You can also make a function
def gen_args(incoming_data, lnam_fnam, db_date):
yield "'A'"
for i in list(range(5)) + [4,4]:
yield incoming_data[i]
for i in range(2):
yield lnam_fnam[i]
for i in [11, 5, 10] + list(range(12, 18)):
yield incoming_data[i]
for i in range(2):
yield ""
yield 0
yield incoming_data[4]
yield db_date
def make_request(incoming_data, lnam_fnam, db_date):
args = ",".join(str(x) for x in gen_args(incoming_data, lnam_fnam, db_date))
request = "INSERT INTO customer_synch VALUES (%s);" % args
return request
Don't you think $(CLINK) and $(CLIB) should be given to the build of _lmp_driver.so instead of lmp_driver.o ?
numarray.reshape doesn't apply to python lists. It applies to numarray.NumArray, which is a different type with a specific implementation. You can write
data2 = numarray.array(data)
data3 = numarray.reshape(data2, 5, 91)
If you want to go further, you must write functions in your program. Here is a function which splits the sentences in a text, assuming that a sentence ends with one or more ".!?".
import re
end_of_sentence = re.compile(r"([\.\!\?]+)")
def split_sentences(text):
"""split_sentences(text) --> list of pairs (sentence, punctuation)"""
L = end_of_sentence.split(text)
result = []
for i in range(0, len(L)-1, 2):
result.append((L[i].strip(), L[i+1]))
if len(L) % 2:
if L[-1].strip():
result.append((L[-1].strip(), ""))
return result
def main():
"""This program's main function"""
text = "I read the book. I read the book! I read the book? I read the book."
pairs = split_sentences(text)
print(pairs)
if __name__ == "__main__":
main()
""" my output ---->
[('I read the book', '.'), ('I read the book', '!'), ('I read the book', '?'), ('I read the book', '.')]
"""
You'd better write the datafile line by line to the output file. Here is a way to do it
#from __future__ import with_statement # <--- uncomment this line if your python is 2.5
import os
workDIR = 'C:\\work\\data'
# this is a multiline string
header = """\
ncols 1422
nrows 2044
xllcorner 409924.44886063
yllcorner 3631074.3284728
cellsize 500
NODATA_value -9999
"""
old_wd = os.getcwd() # <--- store the initial wd
os.chdir(workDIR)
try:
with open('output.txt','w') as outfile:
outfile.write(header)
with open('justdata2.txt','r') as datafile:
for line in datafile:
outfile.write(line)
finally:
os.chdir(old_wd) # <--- back to the initial wd
The use of the with statement here ensures that the files are closed afterwards, even if an error occurs (it's not very important). The try...finally ensures that we come back to the initial directory afterwards, even if an error occurred. Otherwise, a way to concatenate strings is the + operator, 'string' + 'string' + n + 'etc'
. By curiosity, which version of python are you using ?
thanks :)
I removed the underscores before 'spamify' and it works
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
static PyObject *spam_system(PyObject *self, PyObject *args)
{
const char *command;
int sts;
if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
return Py_BuildValue("i", sts);
}
static PyMethodDef SpamMethods[] = {
{"system", spam_system, METH_VARARGS,"Execute a shell command."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
PyMODINIT_FUNC initspamify(void)
{
(void) Py_InitModule("spamify", SpamMethods);
}
int main(int argc, char *argv[])
{
/* Pass argv[0] to the Python interpreter */
Py_SetProgramName(argv[0]);
/* Initialize the Python interpreter. Required. */
Py_Initialize();
/* Add a static module */
initspamify();
}
Build (linux):
$ gcc -c -fPIC -I/usr/include/python2.6/ spamify.c
$ gcc -shared -o spamify.so spamify.o -L/usr/lib64/ -lpython2.6
Test:
>>> import spamify
>>> spamify.system("date")
ven. févr. 26 08:23:18 CET 2010
0
An alternative is to replace "spamify" by "_spamify" in the call to Py_InitModule.
You need to write interface code between your C++ library and python. A good tool for this is the swig interface generator which is well documented.
If you know C++, would you be able to write a small program which uses your library and does something useful ? In that case make a list of the library functions that you are using in your program and start writing a swig interface file with these functions, then write the same program in python. This would give you a starting point, because such C++ libraries often have dozens of classes and functions.
Let the code explain how it works:
tab = " " * 2
def eds(k,L,s):
"""
starting with the k-th list in L,
adds letters to the current string s
"""
print("%sentering eds(%d, L, %s)" % (tab*k, k, repr(s)))
if k >= len(L):
print("%sfound -> %s" % (tab*k, repr(s)))
else:
for i in range(0,len(L[k])):
print("%sloop: i = %d" % (tab*k, i))
eds(k+1,L,s+L[k][i])
def main():
"""
enumerates letter combinations
"""
S = ['c','s','v']
V = ['a','e','i','o','u']
E = ['d','t','w']
L = [S,V,E]
eds(0,L,"")
main()
""" my output --->
entering eds(0, L, '')
loop: i = 0
entering eds(1, L, 'c')
loop: i = 0
entering eds(2, L, 'ca')
loop: i = 0
entering eds(3, L, 'cad')
found -> 'cad'
loop: i = 1
entering eds(3, L, 'cat')
found -> 'cat'
loop: i = 2
entering eds(3, L, 'caw')
found -> 'caw'
loop: i = 1
entering eds(2, L, 'ce')
loop: i = 0
entering eds(3, L, 'ced')
found -> 'ced'
loop: i = 1
entering eds(3, L, 'cet')
found -> 'cet'
loop: i = 2
entering eds(3, L, 'cew')
found -> 'cew'
loop: i = 2
entering eds(2, L, 'ci')
loop: i = 0
entering eds(3, L, 'cid')
found -> 'cid'
loop: i = 1
entering eds(3, L, 'cit')
found -> 'cit'
loop: i = 2
entering eds(3, L, 'ciw')
found -> 'ciw'
loop: i = 3
entering eds(2, L, 'co')
loop: i = 0
entering eds(3, L, 'cod')
found -> 'cod'
loop: i = 1
entering eds(3, L, 'cot') …
It's really strange. Could you post the output of the following code (between code tags), I just added a few print statements
#READ DATA FROM EACH ASC FILE AND CALCULATE QUANTILES FROM EACH FILE
q1=[]
q2=[]
q3=[]
print repr(runlist)
print len(runlist)
for file in runlist:
print repr(file)
gq=[]
x=open(file[0],'r')
for i in xrange(6)
x.readline()
z= x.readline()
while z != '':
z=z.strip().split()
for num in z:
num=float(num)
if num > -1:
gq.append(num)
z= x.readline()
a=quantile(gq, .25, qtype = 7, issorted = False)
#print a
b=quantile(gq, .5, qtype = 7, issorted = False)
c=quantile(gq, .75, qtype = 7, issorted = False)
q1.append(a)
q2.append(b)
q3.append(c)
print len(q1), len(q2), len(q3)
Why do you write x=open(file[0],'r')
instead of x=open(file,'r')
?
What is the content of your runlist ?
2 remarks about the style: avoid using 'file' as a variable name because this is the name of a builtin type, and also the 6 x.readline() should be written with a loop: each time that you are repeating similar statements, there is a better way to do it.
About writing a datafile with the lists q1, q2, q3 there are many ways to do it, you can simply write
outfile = open("outfile.txt", "w")
for i in xrange(len(q1)):
outfile.write("%12.3e%12.3e%12.3e\n" % (q1[i], q2[i], q3[i]))
outfile.close()
You could also output to an excel spreadsheet.