Gribouillis 1,391 Programming Explorer Team Colleague

I don't understand the argument. If you succeed in writing your random generator differently, it will be an alternative to shuffle. Can you explain more precisely the probabilistic argument ? I think that with shuffle, each item has the same probability to be at a given position in the generated sequence.

Gribouillis 1,391 Programming Explorer Team Colleague

Why don't you just use shuffle ?

from random import shuffle

def random_unique(sequence):
    L = list(sequence)
    shuffle(L)
    return iter(L)

for x in random_unique(range(10)):
    print(x)
Gribouillis 1,391 Programming Explorer Team Colleague

Strange how I missed that even after looking at the Python documentation for strings.

Type help(str) in a python console.

Gribouillis 1,391 Programming Explorer Team Colleague

Isnt this allready a method of string?

>>> x = 'Testing ONE TWO THREE'
>>> x.swapcase()
'tESTING one two three'
>>>

Excellent remark. It's the best method ;)

Gribouillis 1,391 Programming Explorer Team Colleague

I would use the re module and substitution

import re
pattern = re.compile(r"([a-z]+)|[A-Z]+")

def swap(match):
  return match.group(0).upper() if match.group(1) else match.group(0).lower()

def swapcase(msg):
    return pattern.sub(swap, msg)

if __name__ == "__main__":
    print (swapcase("HellO WOrlD!"))

""" my output --->
hELLo woRLd!
"""
Gribouillis 1,391 Programming Explorer Team Colleague

hint: use ord("a") .

Gribouillis 1,391 Programming Explorer Team Colleague

Also note that the line looks like an xml tag. If your file is an xml file, you could parse it with lxml for example.

Gribouillis 1,391 Programming Explorer Team Colleague

Go here and download "Beautiful Soup version 3.1.0.1". This is a compressed .tar.gz file. To uncompress it with windows, you'll need 7zip from here. Right click on the BeautifulSoup.tar.gz and uncompress once, which should give you a file with suffix .tar, uncompress a second time and you should get a folder BeautifulSoup. Then copy BeautifulSoup.py to the site-packages directory in your python lib. It should work then.

Gribouillis 1,391 Programming Explorer Team Colleague

it seems complex and hard to install...

what's your os ? For windows, all you have to do is to download the MS windows installer for your version of pyton and your processor (32 or 64 bits) from http://pypi.python.org/pypi/lxml/2.2.2 and run the installer.

Gribouillis 1,391 Programming Explorer Team Colleague

how to get lxml module?

HERE

Gribouillis 1,391 Programming Explorer Team Colleague

it doesn't work,when i run the code,it gave
Traceback (most recent call last):
File "C:/Users/ALEXIS/Desktop/extactphoto.py", line 5, in <module>
from lxml.html import soupparser
ImportError: No module named lxml.html

As I said, you need the lxml module.
@kaninelupus. there are different ways to understand the question. I don't think my solution is complex.

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a way to get the addresses of the images

# extract the addresses of the images included in a web page
# you need the modules lxml and beautifulsoup
# (for linux, packages python-lxml and python-beautifulsoup)
# tested with python 2.6 
from lxml.html import soupparser
from urllib2 import urlopen

def gen_elements(tag, root):
    if root.tag == tag:
        yield root
    for child in root:
        for elt in gen_elements(tag, child):
            yield elt

def gen_img_src(url):
    content = urlopen(url).read()
    content = soupparser.fromstring(content)
    for elt in gen_elements("img", content):
        yield elt.attrib.get("src", None)

def main():
    url = "http://www.it.usyd.edu.au/about/people/staff/tomc.shtml"
    for src in gen_img_src(url):
        print(src)

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

ah... but why the difference? why do basic data types exhibit one behavior and things like list another?
(I suppose it is more intuitive.. I just wrote my last program without any knowledge of this and it still works.. lucky me ;-))

In fact I think it's true for all datatypes as the following experiment shows

>>> myInt = 3764
>>> a = myInt
>>> id(myInt)
22352896
>>> id(a)
22352896

myInt and a have the same id, meaning that they refer to the same object.

Gribouillis 1,391 Programming Explorer Team Colleague

What does "variables containing objects" mean?

I think he means everything but basic datatypes like int, floats and strings. However, you can do as if it was always true.

Gribouillis 1,391 Programming Explorer Team Colleague

Hi, I want to sort a tuple consisting of two floats and one array by the absolute value of the first float in reverse order. What I did is the following:

from numpy import *

test = [(-0.02, 100.2, array([1, 0, 0])), 
            (-4.02, 300.4, array([1, 1, 0])), 
            (3.57, 503.7, array([1, 0, 1])), 
            (0.01, 700.0, array([0, 0, 0]))]

for f in range(len(test)):
sorted(test[f], key=lambda item: abs(item[0]), reverse=True)

TypeError: 'float' object is unsubscriptable

Any ideas?
awa

Try

from numpy import *

test = [(-0.02, 100.2, array([1, 0, 0])), 
            (-4.02, 300.4, array([1, 1, 0])), 
            (3.57, 503.7, array([1, 0, 1])), 
            (0.01, 700.0, array([0, 0, 0]))]

print sorted(test, key=lambda item: abs(item[0]), reverse=True)
Gribouillis 1,391 Programming Explorer Team Colleague

So what are objects all about anyway? It looks to me like a long complicated way of walling a function or method.

Objects are the result of years of programming practice by thousands of programmers. You need some time to see the benefit. The idea is that an object holds a certain quantity of data. The object's methods are functions which purpose is to manipulate the object's data.

Gribouillis 1,391 Programming Explorer Team Colleague

The best way to do it is to read your file and write a new file with the negated digits. Could you be more specific about the content of your file (attach your file to a post ?).

Gribouillis 1,391 Programming Explorer Team Colleague

Another way

lucky = raw_input("Enter an integer: ")
x = "" if lucky.count("7") else "not "
print("%s is %slucky" %(lucky, x))
Gribouillis 1,391 Programming Explorer Team Colleague

You could use HTMLParser like this

import sys
if sys.version_info[0] < 3:
    from HTMLParser import HTMLParser
    from urllib2 import urlopen
else:
    from html.parser import HTMLParser
    from urllib.request import urlopen

class MyParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.day = None

    def handle_starttag(self, tag, attrs):
        if tag == 'tr':
            for key, value in attrs:
                if key == 'colData0':
                    self.day = value

def get_day(url):
    parser = MyParser()
    html = urlopen(url).read().decode('utf8')
    parser.feed(html)
    parser.close()
    return parser.day

if __name__ == '__main__':
    print(get_day("http://www.mywebsite.com/py"))
Gribouillis 1,391 Programming Explorer Team Colleague

mylist[i] will raise IndexError unless i is in the interval [-n, n[ where n is the length of mylist. When the list is empty, this interval is empty. You could use

mylist.append("hello")
mylist.insert(0, "hello")
Gribouillis 1,391 Programming Explorer Team Colleague

You could write

if "7" in lucky:
    print lucky + " " + "is lucky!"
else:
    print lucky + " " + "is not lucky."

Also you could add some code to check if the input was an integer

try:
    int(lucky.strip())
except ValueError:
    print("Error: an integer is required.")
Gribouillis 1,391 Programming Explorer Team Colleague

I'm using an online dictionary. This is what I get for potato :)

Gribouillis 1,391 Programming Explorer Team Colleague

Can anyone explain the

x = (math.sqrt(8 * n + 1) - 1) / 2

triangular numbers have sums of consecutive ints like 1+2 = 3, 1+2+3=6 1+2+3+4 = 10 and ect.

A number n is triangular if it has the form n = k(k+1)/2. For example 1+2 = 2*3/2, 1+2+3=3*4/2, 1+2+3+4=4*5/2. If you compute 8n+1, you have 8n+1 = 4k(k+1)+1 = 4 k^2 + 4k + 1 = (2k+1)^2 , so this gives k = (sqrt(8n+1) -1)/2 .

Gribouillis 1,391 Programming Explorer Team Colleague

Your program should be

#Program to count number of specific vowels

msg = input("Enter a message:")
msg_lower = msg.lower()
VOWELS = list("aeiou")
msg_list = list(msg_lower)
x = dict()
for letter in VOWELS:
    x[letter] = msg_list.count(letter)
for letter in x:
    print(letter, x[letter])

When there is an error, please put the traceback in your posts. The traceback was

Traceback (most recent call last):
  File "vow.py", line 5, in <module>
    VOWELS = list(aeiou)
NameError: name 'aeiou' is not defined
Gribouillis 1,391 Programming Explorer Team Colleague

I don't know exactly what you want to compare, but here is a code which measures the time necessary to execute 1,000,000 times a dictionary lookup (the statement '7498' in D )

from timeit import Timer

D = dict()

for i in range(10000):
  D[str(i)] = i

print(Timer("'7498' in D", "from __main__ import D").timeit())

For your problem, I would choose a dictionary lookup over other methods.

Gribouillis 1,391 Programming Explorer Team Colleague

from __main__ import * must not be written if you want to write maintainable code. What you should do is first see if some parts of your program can be implemented as separate modules, at functional level (for example a module could be devoted to communicate with a database, etc). The variables that you have in __main__ could become members of a single object which could be passed to functions and classes in other modules.

Gribouillis 1,391 Programming Explorer Team Colleague

gribilus, overclock's code:

from multiprocessing import Process
 
def f(name):
    print 'hello', name
 
if __name__ == '__main__':
    p = Process(target=f, args=('bob',)) #inits thread
    p.start() #starts thread
    p.join() #waits untill thread is done

On my machine it works well with python 2.6.

Gribouillis 1,391 Programming Explorer Team Colleague

i downloaded pyprocess. installed an=d got error:
'module' object has no attribute 'f'

post your code

Gribouillis 1,391 Programming Explorer Team Colleague

multiprossessing is a standard module for python >= 2.6. For older versions, you must download pyprocessing.

Gribouillis 1,391 Programming Explorer Team Colleague

One way to do it is to use the subprocess module

import subprocess as SP
child_process = SP.Popen(["python", "t.py"])
Dixtosa commented: thx +0
Gribouillis 1,391 Programming Explorer Team Colleague

I suggest this

from turtle import *

def snowflake(lengthSide, levels):
    if levels == 0:
        forward(lengthSide)
        return
    lengthSide /= 3.0
    snowflake(lengthSide, levels-1)
    left(60)
    snowflake(lengthSide, levels-1)
    right(120)
    snowflake(lengthSide, levels-1)
    left(60)
    snowflake(lengthSide, levels-1)


if __name__ == "__main__":
    speed(0)
    length = 300.0
    penup()
    backward(length/2.0)
    pendown()
    snowflake(length, 4)
Gribouillis 1,391 Programming Explorer Team Colleague

If you've learned about lists, a good way to store the numbers would be to append them to a list. But as gerard4143 said, you don't really need to store them.

Gribouillis 1,391 Programming Explorer Team Colleague

It could be useful to visit the pycrypto page.

Gribouillis 1,391 Programming Explorer Team Colleague

A nice LR(1) parser is wisent. Simple to use and efficient. Also it generates parsers independant of wisent, so that a user of your program wouldn't need wisent to run your wisent-generated parser.

Gribouillis 1,391 Programming Explorer Team Colleague

is that where the command / statement "staticmethod" in python comes from?

Yes. It came from older OO languages like C++.

Gribouillis 1,391 Programming Explorer Team Colleague

Is it good programming practice to refer to class variables by using their instances?
like mycow.numcows?

Yes it's good programming practice. The purpose of classes is to hold data shared by all the instances of the class. This includes class variables, also called static fields in other languages.

Gribouillis 1,391 Programming Explorer Team Colleague

1. Does c1 inherit the global trait, or remain local
2. Does the global trait remained assigned to a variable named c, or would deleting the variable also delete the global statement.

There is nothing special with a global variable. The statement global c in testfunc only means that the name 'c' used in the function's body is the same as the name 'c' defined at module level, and not a new name local to this function. When testfunc returns, nothing remains of this 'global trait' that could be inherited by c1.
As JugglerDrummer said above, not using global variables is a programming paradigm. It's a matter of code design. Module level variables are OK when they have constant value, and usually written in uppercase letters, like

HOST = '127.0.0.1'
PORT = 9000

It shouldn't be a religion, use global variables if you need them, but with some experience with python, you might end up avoiding global variables too.

Gribouillis 1,391 Programming Explorer Team Colleague

I took my ping.py from ftp://ftp.visi.com/users/mdc/ping.py. It seems that doOne accepts a timeout argument. Why don't you use it ?

Gribouillis 1,391 Programming Explorer Team Colleague

2 ways at least: you can type

>>> from xandy import xandy

and then use your function. The file must be in a place where python will find it (in a folder listed in your PYTHONPATH environment variable.
Second (and best) way, run python's built-in gui IDLE (look in the subfolder idlelib of your python library). When idle has started, choose to open your program in the file menu, then select RUN MODULE in the Run menu and your program will run in the shell.

Gribouillis 1,391 Programming Explorer Team Colleague

yes,download matplotlib.

Gribouillis 1,391 Programming Explorer Team Colleague

Have a look for the "grep" tool that is available for your OS.
Ignore case searching is done with the -i option

There is an interesting python alternative to grep, called grin . Have a look here http://pypi.python.org/pypi/grin.

Gribouillis 1,391 Programming Explorer Team Colleague

If I'm not mistaken, the function range() in python 3.x is equivalent with the function xrange() in python 2.x?

exactly.

Gribouillis 1,391 Programming Explorer Team Colleague

You could use (bool(example) and example in "hello there") . This is true only if example is a non empty substring of "hello there".

Gribouillis 1,391 Programming Explorer Team Colleague

When you're working with strings, s in t means that s is a substring of t. The question is what is a substring ? We could give 2 defintitions, first s is a substring of t if there are strings x and y such that t == x + s + y. When s is empty, this is always true, because you can write t == "" + "" + t. Another possible definition is that s is a substring of t if s == t[a:b] for 2 numbers a and b. Again, one has "" == t[0:0]. So it'scoherent to define the empty string as a substring of any string. In the same way, mathematicians define the empty set as a subset of any set. In python: set().issubset(set("hello")) ---> True .

Gribouillis 1,391 Programming Explorer Team Colleague

Here is another method, using numbers, bases and generators

import sys
if sys.version_info[0] > 2:
    xrange = range # python 3 compatibility

def digits(n, base, how_many):
  """generate a given number of digits of n in base
  starting from the lower order digit"""
  for i in xrange(how_many):
    n, r = divmod(n, base)
    yield r

def genmaps(seq, size):
  """generate all the tupes of length size
  taking their elements in the sequence seq.
  There are len(seq) ** size tuples"""
  seq  = list(seq)
  base = len(seq)
  for n in xrange(base ** size):
    yield tuple(seq[d] for d in digits(n, base, size))

if __name__ == "__main__":
    source = genmaps("abc", 10)
    # we print only the first tuples
    # to get a list, use 'list(source)'
    for i in xrange(20):
        print(next(source))

""" my output -->
('a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a')
('b', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a')
('c', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a')
('a', 'b', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a')
('b', 'b', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a')
('c', 'b', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a')
('a', 'c', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a')
('b', 'c', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a')
('c', 'c', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a')
('a', 'a', 'b', 'a', 'a', 'a', 'a', 'a', 'a', 'a')
('b', 'a', 'b', 'a', 'a', 'a', 'a', 'a', 'a', 'a')
('c', 'a', 'b', 'a', 'a', 'a', 'a', 'a', 'a', 'a')
('a', 'b', …
Gribouillis 1,391 Programming Explorer Team Colleague

More exotic

from itertools import takewhile, count
c = sum(1 for b in takewhile(lambda x: x != a, (int(random.triangular(1, 100)) for x in count())))
Gribouillis 1,391 Programming Explorer Team Colleague

In python, x = y is a statement. It can't be used as an expression. You should write

import random
a =int(random.triangular(1,100))
c = 0
while True:
    b = int(random.triangular(1, 100))
    if b == a:
        break
    else:
        c += 1
print(c)
Gribouillis 1,391 Programming Explorer Team Colleague

It's best to use a set and also generator expressions like this

exclude_set = set(exclude_list)
print [f for f in main_list if not (f.order_id in exclude_set)]
Gribouillis 1,391 Programming Explorer Team Colleague

This works for me

from progress import PB
from time import sleep

def main():
    bar = PB(300, 50)
    bar.open()
    for i in range(10):
        bar.update((10.0 * i) / 100)
        sleep(1)
    bar.close()

main()

Also, you could replace self.__root = Tkinter.Toplevel() by self.__root = Tkinter.Tk() (or add an argument to __init__ to chose between the 2 classes)

Gribouillis 1,391 Programming Explorer Team Colleague

I'm putting some comments in your code, in dive into python's way

def next_block(x):  # [1]
    ...
    return p1, p2, p3, p4, p5, print (x) # [2]

 next_block("testing") # [3]
 p1, p2, p3, p4, p5 = next_block() # [4]

"""
[1]  This function declares the argument x. It must be called with exactly 1 argument. Correct.
[2]  The function returns a tuple with 6 elements. The last element is the return value of the expression print(x), which is always None. No error.
[3]  Here you call next_block, but you don't do anything with the returned tuple which is lost. It's OK.
[4]  2 errors here: you call next_block without arguments, which contraditcs the function's signature (how it must be called), and you try to assign 5 values from the returned tuple, which won't work because the returned value has length 6.
"""
vegaseat commented: great explanation +14