Gribouillis 1,391 Programming Explorer Team Colleague

Here is a much faster version using numpy

from numpy.fft import fft, ifft
import numpy as np

def func(f, d):
    a = np.zeros((d*f,))
    a[:f] = np.ones((f,))
    x = ifft(fft(a) ** d)
    return [int(z) for z in x  + .49][:d*(f-1) + 1]

def test_it(f, d):
    sums = find_sums(d, f)
    table = [v for k, v in sorted(sums.items())]
    assert func(f, d) == table
TrustyTony commented: You show that sometimes it is usefull to know some maths +13
Gribouillis 1,391 Programming Explorer Team Colleague

If you would multiply all values by constant, say 1000000, and divide solution accordingly, maybe it could work out to transform the problem to integer realm.

This is not a good idea. LP problems are much easier to solve with real numbers than with integers, so yes I think pulp can work with real numbers, but since I don't use pulp, I can't make the required changes to your code. The solution is in the pulp documentation https://www.coin-or.org/PuLP/ .

Gribouillis 1,391 Programming Explorer Team Colleague

i think it is the problem with data types. am not sure :( how can i convert a result of pysnmp get into an unsigned char??

unsigned char, signed, unsigned int, unsigned char array... do all these things differ and cause the code to go astray....

there is no way to predefine data type of any variable right?

You don't really need to worry about this: python is not C. In an array.array() defined with type 'B', you can only store integers in the range [0, 256[. Python will complain if you try to give another value to an array element

>>> import array
>>> a = array.array('B', [0]*10)
>>> a[3] = 300
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: unsigned byte integer is greater than maximum
>>> a[3] = -23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: unsigned byte integer is less than minimum
>>> a[3] = 45 # ok
>>>

All you have to do is to convert your pysnmp results into ordinary python integers.

In any case, these datatype issues cannot lead to 'List index out of range'.

Ene Uran commented: agree +13
Gribouillis 1,391 Programming Explorer Team Colleague

I just started a new small python project on google code which goal is to easily create clickable graphs on a GKT+ goocanvas. The initial idea comes from this code snippet http://www.daniweb.com/software-development/python/code/323792 . I want to do about the same, but instead of simply drawing the graph, I want to display it on a goocanvas to make it interactive.

The project's page is here http://code.google.com/p/clickonpy/ , there is no code yet, but if some members of the python forum are ready to contribute, please let me know :)

Gribouillis 1,391 Programming Explorer Team Colleague

This snippet defines a context autofilename() to create an existing temporary file with a new name in python. Unlike the methods in the tempfile module, it only gives a filename which exists within a 'with' block, instead of an open file. This is useful for example when a program needs to pass a new filename to a function which does not accept a file object argument. As with the tempfile module, there should be no race condition between processes on the temporary file creation.

Gribouillis 1,391 Programming Explorer Team Colleague

You can also do it with PIL instead of ImageMagick

cv.postscript(file="circles.eps")
    from PIL import Image
    img = Image.open("circles.eps")
    img.save("circles.png", "png")
vegaseat commented: I like that soluion +14
TrustyTony commented: You are maestro! +13
Gribouillis 1,391 Programming Explorer Team Colleague

There are different ways to do it. Here is one

>>> for score, name in nameScore:
...  print "{0}, {1}".format(score, name)
... 
13, Matthew
6, Luke
3, John
3, john

Also, use code tags when you post python code. See here http://www.daniweb.com/forums/announcement.php?f=8&announcementid=3

Gribouillis 1,391 Programming Explorer Team Colleague

In Linux all terminals use commands that I'm very comfortable with, that is how I chose Cygwins terminals. With CMD I have to be in the python directory to run python, with xrvt I can be any where.

The issue really is running a script with colorama using xrvt $ python script.py, works and running from Idle or ipython I get error that module colorama is not found.

1/ Normally in windows, you don't need to be in the python directory to run python.
2/ I think you should have 2 installations of python: one in cygwin and the other one in windows, installed with a windows installer found here http://python.org/download/
3/ Therefore, you should have 2 installations of colorama, one for your cygwin python and one for the windows native python.

vegaseat commented: agree +14
Gribouillis 1,391 Programming Explorer Team Colleague

See itertools.product("daniweb", repeat=3) .

Gribouillis 1,391 Programming Explorer Team Colleague

sys.argv is the list of command line arguments that were passed to your python program. QApplication() may use command line arguments, as described here for example http://doc.trolltech.com/latest/qapplication.html#QApplication (this is not the python version, but the same principle applies).
Here is a example program

# myprog.py
import sys
print(sys.argv)

And its execution in a shell

$ python myprog.py --geometry=200x324 1 2 3
['myprog.py', '--geometry=200x324', '1', '2', '3']
Gribouillis 1,391 Programming Explorer Team Colleague

Thanks for the excellent description.

Perfect. Is ther anyway to use lognormal in the same way as randn? to choose sample from log normal distribution.

I suppose so. Write numpy.random.lognormal(mean, sigma, (100,20)) . But can you explain what your matrix is and why you want to add random samples, and also why should the result be in [-1,1] ?

Gribouillis 1,391 Programming Explorer Team Colleague

If you only want to add some random noise to your data, you could add a normal random sample with a small standard deviation and clip the result in the interval [-1.0, 1.0] like this

sigma = 0.1
a = numpy.clip(X + sigma * randn(100, 20), -1.0, 1.0)

However, due to the clipping, your array won't exactly be a normal perturbation of the initial array, and this distorsion increases with the value of sigma. Mathematically speaking, it is impossible to require both a normal distribution and bounds on the possible values, but if sigma is small enough, the amount of clipped values will be small and the distorsion can be neglected.

vegaseat commented: goog explanation +14
pythonbegin commented: short and sweet +2
Gribouillis 1,391 Programming Explorer Team Colleague

This works with Python 2.7

class B:
    def __init__(self, arg):
        print(arg)

class C(B):
    def __init___(self, arg):
        super(C, self).__init__(arg)

c = C('abc')  # abc

Here super() gives a TypeError: must be type, not classobj

from math import pi

class Circle:
    """with Python3 object is inherited automagically"""
    def __init__(self, r):
        self.r = r

    def area(self):
        """a method of class Circle, first arg is self"""
        area = pi * self.r**2
        return area


class Cone(Circle):
    """class Cone inherits class Circle"""
    def __init__(self, r, h):
        super(Cone, self).__init__(r)
        # Python27 gives TypeError: must be type, not classobj
        self.r = r
        self.h = h

    def volume(self):
        """a method of class Cone, first arg is self"""
        # notice how to call the method of class Circle
        vol = 1.0/3 * self.h * Circle.area(self)
        sf = "Cone of height = %s and radius = %s has volume = %0.2f"
        print(sf % (self.h, self.r, vol))


cone = Cone(r=4, h=10)
# methods of class Box are dot connected to the instance box
cone.volume()

In the "working" example, you wrote __init__ with 3 underscores on the right. It was probably not called. To me, super is useless. It's a purist's detail in the python language which only adds noise in your code. Better call Circle.__init__(self, r) :)

HiHe commented: thank you +4
Ene Uran commented: I agree +13
Gribouillis 1,391 Programming Explorer Team Colleague
for((word  = wordlist[-2]) in ['ar','er',ir']):
    print word

Riechieking, you should test your code before posting. This can't work in python because word = wordlist[2] is not an expression but a statement. This is a C idiom, not a python one.

bumsfeld commented: thanks +7
Gribouillis 1,391 Programming Explorer Team Colleague
a = [[1,2,3],
     [4,5,6],
     [7,8,9]]
a = [[1,4,7],
     [2,5,8],
     [3,6,9]]

Okay, now which way should I organize the list? The first way or the second way? PRobably the first way if I'm changing to col and row.

There is no rule, think about your list as a table, it all depends on the semantics of your rows and colums. For example if your table contains students marks, the logical way to organize the table would be that each item of the list contains all the marks for a given student, so there would be a row for each student with the list of his/her marks. That's the way tables are designed in relational databases.

Gribouillis 1,391 Programming Explorer Team Colleague
from sys import argv
file = open(argv[1],'r')
setlist = []
rec = file.readlines()
nestedlist = []
for line in rec :
        field = line.split('\t')
        #print field
        header = field[0]
        nestedlist = field[1].strip()
        #print a
        print header + "\t",
        print nestedlist + "\t",
        print sorted(set.intersection(*(set(x) for x in nestedlist)))
        #print set.intersection(*(set(x) for x in nestedlist))
        nestedlist = []

when i am implying this program to find out

the_list = [['CUB', 'CUB', 'CUB'], ['CUB', 'Zona_pellucida'], ['CUB', 'CUB', 'CUB', 'CUB', 'CUB'], ['Kringle', 'WSC', 'CUB'], ['CUB', 'CUB', 'F5_F8_type_C', 'F5_F8_type_C', 'MAM', 'DUF3481'], ['Astacin', 'CUB', 'CUB', 'CUB', 'CUB'], ['CUB', 'PDGF'], ['CUB', 'CUB', 'Zona_pellucida'], ['CUB', 'CUB'], ['CUB', 'Laminin_EGF']]

instead of giving

['CUB']

it gives

[]

This code is very different from the one you posted before. I suspect that nestedlist is now a string instead of a list of lists. This seems confirmed by the line print nestedlist + "\t", because you can't add a list and a string, so there must be an error in your program. The expression that I wrote applies only to a list of lists having the form that you described before. Try to print repr(nestedlist) to see what it really is.

The program doesn't complain if you pass a string because a string is iterable, its items being characters, and in python, characters are also strings which are also iterable, so, if I write [set(x) for x in "hello"] , the interpreter computes [set(['h']), set(['e']), set(['l']), set(['l']), set(['o'])] . The intersection of these sets is empty, so be careful that set("CUB CUB …

Gribouillis 1,391 Programming Explorer Team Colleague

Thanks for answer. So I understood that Tkinter cant use combobox.

When you work with Tkinter, don't hesitate to use Pmw. It's only a small appendix to Tkinter, but very useful. A bible for Tkinter programming is the book by John Grayson (Python and Tkinter programming): he uses Pmw all the time.

Gribouillis 1,391 Programming Explorer Team Colleague

You may consider using a Pmw.OptionMenu, which has a setitems() method. See here http://pmw.sourceforge.net/doc/OptionMenu.html

Gribouillis 1,391 Programming Explorer Team Colleague

Module ctypes is new in python 2.5. I suggest that you uninstall python 2.4 and upgrade to python 2.7, then reinstall serial.

Gribouillis 1,391 Programming Explorer Team Colleague

Since radians is only self.rotations converted to radians, it would be easier to make it a property

class Player(pygame.sprite.Sprite):
    
    def rotateShip(self, rotAmt):
        # here use self.radians

    @property
    def radians(self):
        return self.rotation * math.pi / 180

In other classes, use player.radians . In this case, you may consider renaming player.rotation to player.degrees.

Gribouillis 1,391 Programming Explorer Team Colleague

Ok, then replace the first line of your post with

( options, args ) = parser.parse_args()
import glob
args = list(f for arg in args for f in glob.glob(arg)) # expand regex in args

You can add a print(args) afterwards to see what it did to args.

weblover commented: it solved my problem +3
Gribouillis 1,391 Programming Explorer Team Colleague

Hi Tonijv

thanks for the reply. It works perfect, faster than the usual for,for for loops
sorry for the bad way of posting code and variables.

cheers

Also try

from itertools import product

for triple in product(listofitems, listofitems2, listofitems3):
    print triple
Gribouillis 1,391 Programming Explorer Team Colleague

Here are 2 expressions that you could try

subprocess.call("Rscript script.R --args arg1 arg2", shell=True)
subprocess.call(["Rscript", "script.R", "--args", "arg1", "arg2"])
Gribouillis 1,391 Programming Explorer Team Colleague

It seems that the only place where U_data is modified are lines 48 and 51, which are only executed once when the program is loaded, so U_data can't be affected by the code at the end of the file.

You could make your code more robust: 1) don't use global variables except for some constants N = 1001; M = 75; Dx = 1.5/M ; Dt = 0.0005; a = 1.0 ('a' should be given a more explicit name), 2) don't write code at module level, (lines 11, 16, 17, 48, 50, 51 could go in the if __name__ == "__main__" section), 3) instead, write code in functions (most part of the if __name__ = "__main__" section should go in one or more functions), 4) configure your editor to indent python code with 4 space characters instead of a tab.

vegaseat commented: agree +15
Gribouillis 1,391 Programming Explorer Team Colleague

Silly me, I forgot to paste the main function in (was buried under uncommented code) :$ - here is the missing code:

currentNode = startNode

if __name__ == "__main__":
    populateNodeTable()
    network()
    nearestNeighbour(currentNode, theNetwork)
    #tentativeDistance(currentNode,populateNodeTable())

Well progress has been made, though it's now complaining that 'theNetwork has not been defined' even though I have defined it in my network function:

nearestNeighbour(currentNode, theNetwork)
NameError: name 'theNetwork' is not defined

Names defined in a function don't exist outside the function. They are called local variables. Use the value returned by the function

if __name__ == "__main__":
    populateNodeTable()
    theNetwork = network() # here we define a variable (it's not the same theNetwork)
    nearestNeighbour(currentNode, theNetwork)
    #tentativeDistance(currentNode,populateNodeTable())
Gribouillis 1,391 Programming Explorer Team Colleague

Hi, I have changed the variable 'network' to 'theNetwork' though I am now getting this error:

for node in theNetwork[currentNode]:
TypeError: 'function' object is not subscriptable

I'm probably overseeing something simple, I will include all of my code, though I don't think it has any bearing:

infinity = 1000000
invalid_node = -1
startNode = 0

#Values to assign to each node
class Node:
     distFromSource = infinity
     previous = invalid_node
     visited = False

#read in all network nodes
def network():
    f = open ('network.txt', 'r')
    theNetwork = [[int(node) for node in line.split(',')] for line in f.readlines()]
    print theNetwork

    return theNetwork

#for each node assign default values    
def populateNodeTable(): 
    nodeTable = []
    index = 0
    f = open('network.txt', 'r')
    for line in f: 
      node = map(int, line.split(',')) 
      nodeTable.append(Node())
      
      print "The previous node is " ,nodeTable[index].previous 
      print "The distance from source is " ,nodeTable[index].distFromSource 
      index +=1
    nodeTable[startNode].distFromSource = 0 

    return nodeTable

It seems that the line causing the error appears nowhere in your code !

Gribouillis 1,391 Programming Explorer Team Colleague

network ---> network()
Also it's not a very good idea to give variables the same name as your function. A good name for the function would be load_network()

Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague

With the fastgraph snippet above, I replaced your call to main() by

from fastgraph import graph
import webbrowser as web

def links(tree):
    for n in (tree.left, tree.right):
        if n is not None:
            yield tree, n
            for link in links(n):
                yield link

def label(tree):
    return repr(tree.key)

def show(tree, filename="tree.png"):
    g = graph(links(tree), label, directed=True)
    g.draw(filename, prog = 'dot')
    web.open(filename)


if __name__ == "__main__":
    t = buildParseTree("( 3 * 5 + 7 ) - 4")
    show(t)

This pops up a window showing the tree. This tree is probably not what you are expecting, so there are still errors in your program. Remark that fastgraph cannot distinguish left from right.

Gribouillis 1,391 Programming Explorer Team Colleague

Keep getting Attribute Errors with my code any suggestions?
There are two files attatched

from string12 import *
from root import *

def main():
    tree1 = raw_input("enter numbers: ")
    print buildParseTree(tree1)
    

def buildParseTree(fpexp):
    fplist = fpexp.split()
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree
    for i in fplist:
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif i not in '+-*/)':
            currentTree.setRootVal(eval(i))
            parent = pStack.pop()
            currentTree = parent
        elif i in '+-*/':
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()      
        elif i == ')':
            currentTree = pStack.pop()
        else:
            print "error:  I don't recognize " + i
    return eTree
main()

I got something by replacing root.py with

class BinaryTree:
    def __init__(self,rootObj):
        self.key = rootObj
        self.left = None
        self.right = None

    def insertLeft(self,newNode):
        if self.left == None:
            self.left = BinaryTree(newNode)
        else:
            t = BinaryTree(newNode)
            t.left = self.left
            self.left = t

    def insertRight(self,newNode):
        if self.right == None:
            self.right = BinaryTree(newNode)
        else:
            t = BinaryTree(newNode)
            t.right = self.right
            self.right = t

    def getRootVal(root): # accessor functions are java-ic and not very pythonic.
        return root.key
    
    def setRootVal(root,newVal):
        root.key = newVal
    
    def getLeftChild(root):
        return root.left
    
    def getRightChild(root):
        return root.right

""" Result of main -->
enter numbers: ( 3 * 5 + 7 ) - 4
<root.BinaryTree instance at 0x7f08309c2170>
"""

Note that specialized modules exist to parse arithmetic expressions, and languages in general. Also this snippet could draw your binary tree http://www.daniweb.com/code/snippet323792.html .

Gribouillis 1,391 Programming Explorer Team Colleague

An improvement in the previous code is to replace self.R[0].select() by self.R[0].invoke() which invokes the button's action. You can even remove the call to deselect() .

Behseini commented: Perfect +1
Gribouillis 1,391 Programming Explorer Team Colleague

It works with

def call_back(self, event):
     self.zones = self.Lb1.curselection()
     assert len(self.zones) == 1
     z = self.zones[0]
     if z == '0':
        self.make_Red()
     elif z == '1':
        self.make_Green()
     elif z == '2':
        self.make_Blue()

Also, configure your editor to indent with 4 spaces, it will be easier to help.

Behseini commented: Perfect answer +1
Gribouillis 1,391 Programming Explorer Team Colleague

i apologize this is my first time posting code into a forum, wasn't sure how to format it... my bad.

Read about code tags here http://www.daniweb.com/forums/announcement.php?f=8&announcementid=3

Gribouillis 1,391 Programming Explorer Team Colleague

Why do you need to locate the hyphen since the date has a fixed format ?

>>> date = "2011-03-03"
>>> date[4]
'-'
>>> date[7]
'-'

You could also split the date on hyphens to get a list

>>> items = date.split("-")
>>> items
['2011', '03', '03']
xxhellothere commented: thank you ! +0
Gribouillis 1,391 Programming Explorer Team Colleague

Here is a solution

from Tkinter import *

class App:
   def __init__(self, parent):
    self.myParent = parent
    self.fm = Frame(parent, width=400, height=300)
    self.fm.pack_propagate(0) # to keep the frame size
    self.fm.pack()

    self.btnBlue = Button(self.fm, text = "Blue", command=self.make_blue)
    self.btnBlue.pack()

   def make_blue(self):
    # Don't create new widgets, configure existing ones
    self.fm.configure(bg="blue")

root = Tk()
root.title ("Color Option")
app = App(root)
root.mainloop()
Behseini commented: Good help +1
Gribouillis 1,391 Programming Explorer Team Colleague

Tony is going too fast. Let's decompose a little

the_list = the_string.split("\n")
the_list = the_list[22:]
the_string = "\n".join(the_list)
yeleek commented: great solution - and explained well. +1
Gribouillis 1,391 Programming Explorer Team Colleague

Wit this:

import math

print(math.cos((2*math.pi)/3))         # -0.5
print(0.5 + math.cos((2*math.pi)/3))   # 2.22044604925e-16
print(-0.5 + math.cos((2*math.pi)/3))  # -1.0

x = math.cos((2*math.pi)/3)
print(x)        # -0.5
print([x])      # [-0.4999999999999998]
print([-0.5 + x])   # [-0.9999999999999998]

Strange?

It is not strange, because printing a float x prints str(x) in fact, while printing a list invokes the repr() of the list items. The method float.__str__() yields less decimals than float.__repr__, so the floating number is rounded

>>> x = 1.0/3
>>> str(x)
'0.333333333333'
>>> repr(x)
'0.33333333333333331'
>>>
>>> x = -0.49999999999999
>>> str(x)
'-0.5'
>>> repr(x)
'-0.49999999999999001'

About the actual bits used by C python, the PyFloatObject structure from floatobject.h uses a C double to store the number, so the bits are the same as the bits of the C type double. I wrote a small functions to extract the actual bits using module ctypes

from ctypes import *
from binascii import hexlify

def double_to_bits(f):
    cf = c_double(f)
    n = sizeof(cf)
    assert not n % 2
    pc = cast(pointer(cf), POINTER(c_char))
    h = ''.join(pc[i] for i in xrange(n))
    return bin(int(b"1" + hexlify(h), 16))[3:]

print double_to_bits(-0.5)

""" my output (this should be machine dependent) -->
0000000000000000000000000000000000000000000000001110000010111111
"""

Interestingly, this yields the same result as using struct.pack() :

>>> from binascii import hexlify
>>> import struct
>>> p = struct.pack("d", -0.5)
>>> print bin(int(b"1" + hexlify(p), 16))[3:]
0000000000000000000000000000000000000000000000001110000010111111

Also notice that on my machine, this representation differs from the IEEE 754 representation referred to above. How is it coded ? It would be worth having a python …

vegaseat commented: Thank you, that explains a lot +13
Gribouillis 1,391 Programming Explorer Team Colleague

OS win 7 ... python 0.61 ... in a console

Then you should perhaps start by reading this http://www.burgaud.com/bring-colors-to-the-windows-console-with-python/ . There is also a small module for download.

I also know that it's not the only method to print in colors with the cmd console, but I don't usually use windows, so I can't say more.

Edit: what is this python 0.61 ?

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a much faster version using binascii.hexlify:

from binascii import hexlify

def a2bits(bytes):
    """Convert a sequence of bytes to its bits representation as a string of 0's and 1's
    This function needs python >= 2.6"""
    return bin(int(b"1" + hexlify(bytes), 16))[3:]
Gribouillis 1,391 Programming Explorer Team Colleague

Use zip

for i, a in zip(var1, var2):
    print i
    print a

Items are printed until the shortest list is consumed.

Gribouillis 1,391 Programming Explorer Team Colleague

Start with a script which prints the lines one by one

SOURCE_FILE = "myfile.srt"

def main():
    with open(SOURCE_FILE) as src_file:
        for line in src_file:
            print(repr(line))

if __name__ == "__main__":
    main()
Gribouillis 1,391 Programming Explorer Team Colleague

Use the format() method

# python >= 2.6

numbers = [ 123456.78, 3434.2 ]

for x in numbers:
    print( "The number is {num:0>9.2f}".format(num=x) )
    
""" my output -->
The number is 123456.78
The number is 003434.20
"""

See this code snippet for more http://www.daniweb.com/code/snippet232375.html :)

Gribouillis 1,391 Programming Explorer Team Colleague

I suggest to call the following function to ensure the target directories exist

def make_target_dirs(target_paths):
    for dirname in set(os.path.dirname(p) for p in target_paths):
        if not os.path.isdir(dirname):
            os.makedirs(dirname)

Edit: to attach a .py file, zip it first, then attach the zipped file.

yeticannotski commented: Great and fast help. Thanks +1
Gribouillis 1,391 Programming Explorer Team Colleague

I suggest a shell script

#!/bin/sh
python f4761sk3.py
python f4761sk2.py
python f4761sk1.py
python f4761se3.py
python f4761se2.py
python f4761se1.py
python f4761pl3.py
python f4761pl2.py
python f4761pl1.py
python f4761no3.py
python f4761no2.py
python f4761no1.py
python f4761nl3.py
python f4761nl2.py
python f4761nl1.py
python f4761ie3.py
python f4761ie2.py
python f4761ie1.py
python f4761hu3.py
python f4761hu2.py
python f4761hu1.py
python f4761gb3.py
python f4761gb2.py
python f4761gb1.py
python f4761fi3.py

and make this file executable.

Karthik_4 commented: How to make it executable ? +0
Gribouillis 1,391 Programming Explorer Team Colleague

You can use itertools.permutations to rotate over all the numbers

import itertools
for p in itertools.permutations(range(1, 5)):
    print(p)
(1, 2, 3, 4)
(1, 2, 4, 3)
(1, 3, 2, 4)
(1, 3, 4, 2)
(1, 4, 2, 3)
(1, 4, 3, 2)
(2, 1, 3, 4)
(2, 1, 4, 3)
(2, 3, 1, 4)
(2, 3, 4, 1)
(2, 4, 1, 3)
(2, 4, 3, 1)
(3, 1, 2, 4)
(3, 1, 4, 2)
(3, 2, 1, 4)
(3, 2, 4, 1)
(3, 4, 1, 2)
(3, 4, 2, 1)
(4, 1, 2, 3)
(4, 1, 3, 2)
(4, 2, 1, 3)
(4, 2, 3, 1)
(4, 3, 1, 2)
(4, 3, 2, 1)
Gribouillis 1,391 Programming Explorer Team Colleague

After the first l.pop(0) , the list is ["asd'das",'qw','213'] , so the second item is 'qw'.

vegaseat commented: nice point +13
Gribouillis 1,391 Programming Explorer Team Colleague

You can use time.time()

import time
before = time.time()
somme = raw_input('1 + 1 = ')
diff = time.time() - before # time difference in seconds as a floating point number
Gribouillis 1,391 Programming Explorer Team Colleague

Strings are indexable. text[0] is the first symbol.

Gribouillis 1,391 Programming Explorer Team Colleague

A list of old recipes.

# linux, mac
os.kill(pid, signal.SIGKILL)
killedpid, stat = os.waitpid(pid, os.WNOHANG)
if killedpid == 0:
print >> sys.stderr, "ACK! PROCESS NOT KILLED?"

# windows
handle = subprocess.Popen("someprocess here", shell=False)
subprocess.Popen("taskkill /F /T /PID %i"%handle.pid , shell=True)

#also
# Create a process that won't end on its own
import subprocess
process = subprocess.Popen(['python.exe', '-c', 'while 1: pass'])


# Kill the process using pywin32
import win32api
win32api.TerminateProcess(int(process._handle), -1)


# Kill the process using ctypes
import ctypes
ctypes.windll.kernel32.TerminateProcess(int(process._handle), -1)


# Kill the proces using pywin32 and pid
import win32api
PROCESS_TERMINATE = 1
handle = win32api.OpenProcess(PROCESS_TERMINATE, False, process.pid)
win32api.TerminateProcess(handle, -1)
win32api.CloseHandle(handle)


# Kill the proces using ctypes and pid
import ctypes
PROCESS_TERMINATE = 1
handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, process.pid)
ctypes.windll.kernel32.TerminateProcess(handle, -1)
ctypes.windll.kernel32.CloseHandle(handle)
richieking commented: Santa python.... Keep it up buddy +2
vegaseat commented: thanks +13
Gribouillis 1,391 Programming Explorer Team Colleague

Here is a version with regex. It should work even if the data string contains newlines

# python 2 and 3
import re
regex = re.compile(r"\\.|[\"',]", re.DOTALL)

def parts(data):
    delimiter = ''
    compos = [-1]
    for match in regex.finditer(data):
        g = match.group(0)
        if delimiter == '':
            if g == ',':
                compos.append(match.start())
            elif g in "\"'":
                delimiter = g
        elif g == delimiter:
            delimiter = ''
    # you may uncomment the next line to catch errors
    #if delimiter: raise ValueError("Unterminated string in data")
    compos.append(len(data))
    return [ data[compos[i]+1:compos[i+1]] for i in range(len(compos)-1)]

if __name__ == "__main__":
    a = 'par1=val1,par2=val2,par3="some text1, again some text2, again some text3",par4="some text",par5=val5'
    print(parts(a))

""" my output -->
['par1=val1', 'par2=val2', 'par3="some text1, again some text2, again some text3"', 'par4="some text"', 'par5=val5']
"""
_neo_ commented: Great, thank you for your snippet. +1