Gribouillis 1,391 Programming Explorer Team Colleague

I could not parse it with csv, but if your string looks like python code, you can use python's own tokenizer:

# python 2 and 3
import sys
if sys.version_info < (3,):
    from cStringIO import StringIO
else:
    from io import StringIO
    xrange = range
from tokenize import generate_tokens


a = 'par1=val1,par2=val2,par3="some text1, again some text2, again some text3",par4="some text",par5=val5'

def parts(a):
    """Split a python-tokenizable expression on comma operators"""
    compos = [-1] # compos stores the positions of the relevant commas in the argument string
    compos.extend(t[2][1] for t in generate_tokens(StringIO(a).readline) if t[1] == ',')
    compos.append(len(a))
    return [ a[compos[i]+1:compos[i+1]] for i in xrange(len(compos)-1)]

print(parts(a))

""" my output -->
['par1=val1', 'par2=val2', 'par3="some text1, again some text2, again some text3"', 'par4="some text"', 'par5=val5']
"""

The other alternative is to use regular expressions.

Gribouillis 1,391 Programming Explorer Team Colleague

Your method _new_ should be named __init__ (note the double underscore on each side of the word init)

superhe commented: Thank you very much! It does work! +0
Gribouillis 1,391 Programming Explorer Team Colleague

Use index = bisect.bisect(list, num) . The list must be sorted. Also, don't use 'list' as a variable name.

Gribouillis 1,391 Programming Explorer Team Colleague
from copy import deepcopy

sis = file("teedtest.01.sis", "r")
val = file("rp.val", "wt")

N, K = map(int, sis.readline().strip().split()) 

alist = []
for i in range(0, K):
  t = []
  for i in range(0, K):
    t.append(0)
  alist.append(t)
  
for i in range(K):
  a, b, c = map(int, sis.readline().strip().split())
  alist[a][b] = alist[b][a] = c

D = deepcopy(alist)
print D
for k in range(0, K): 
  for u in range(0, K): 
    for v in range(0, K): 
      #print k, u, v
      D[u][v] = min(D[u][v], (D[u][k] + D[k][v]))
      
for i in range(K):
  print D[i]
10 15
1 3 3
1 4 3
2 4 3
2 5 3
3 5 3
6 7 2
7 8 2
8 9 2
9 10 2
10 6 2
1 6 1
2 7 2
3 8 3
4 9 4
5 10 5

How to calculate all paths in every town to other?

Current output, it's not correct?

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

The undefined values must be infinite. You should take all the coefficients initially equal to sys.maxint (or sys.maxsize in python 3).

Gribouillis 1,391 Programming Explorer Team Colleague

I used a tracer module and got the following output

0. GUIcards.runGame(): # call, line 280 in blackjack.py
  1. GUIcards.game_over(): # call, line 135 in blackjack.py
    return False
  return None

So what happened is that your first call to game_over() returned False at line 135 and the body of the while was not executed.

If you want to use my (home made) tracer module (called tracepect), you must first download and install the aspects module from here http://www.cs.tut.fi/~ask/aspects/download.shtml, then unzip the attached file tracepect.py
and put it on the python path, finally, replace the 2 last lines of your program by

if __name__ == "__main__":
    from tracepect import Tracer
    t = Tracer()
    t.wrap_classes(GUIcards)
    blackjack=GUIcards(DeckOfCards().get_deck())
    blackjack.runGame()
Gribouillis 1,391 Programming Explorer Team Colleague

You could add a hierarchy of classes

class Hero:
    # contains methods common to all heroes
    ...

class Lord(Hero):
    # contains methods specific to Lords
    ...

class MainHero(Lord):
    # contains main hero specific methods
    ...

phill = MainHero(...)

Don't nest classes, it is more annoying than useful. Write all your classes at module level (unless you define functions which create new classes).

Gribouillis 1,391 Programming Explorer Team Colleague

And here is a much shorter solution using itertools

# python 2 or 3
# solve SEND + MORE = MONEY by brute force
import itertools as itt

letters = ('s', 'm', 'e','n','d','o','r','y')
coefs = (1000, 1000-10000, 100+1-10, 10-100, 1, 100-1000, 10, -1)

def solve():
    for t in itt.combinations(range(10), len(letters)):
        for v in itt.permutations(t):
            if v[0] > 0 and v[1] > 0 and sum(v[i] * coefs[i] for i in range(len(coefs))) == 0:
                print(list(zip(letters, v)))
                return

if __name__ == "__main__":     
    solve()

""" my output -->
[('s', 9), ('m', 1), ('e', 5), ('n', 6), ('d', 7), ('o', 0), ('r', 8), ('y', 2)]
"""
Gribouillis 1,391 Programming Explorer Team Colleague

Here is a working __str__ function

class NonEmptyEnv(object):
    __slots__ = ('letter','digit','rest')

    def __init__(self,letter,digit,rest):
        self.letter = letter
        self.digit = digit
        self.rest = rest
        

    def __str__(self):
        result = self.letter + "=" + str(self.digit)
        if isinstance(self.rest, NonEmptyEnv):
            result += ',' + str(self.rest)
        return result

Otherwise, your solution is overly complicated. You are using NonEmptyEnv instances as stack elements and you traverse the stack recursively for each lookup. It looks like a lisp program. Did you consider storing intermediary states in a list or a tuple or a dict or a collections.deque object ? For example you could have [('n', 6),('e',5),('s',9)] as an intermediary state.

Another interesting tool for this problem is the function itertools.combinations() . For example

>>> from itertools import combinations
>>> combi = combinations(list(range(10)), 8)
>>> for i in range(15):
...  print next(combi)
... 
(0, 1, 2, 3, 4, 5, 6, 7)
(0, 1, 2, 3, 4, 5, 6, 8)
(0, 1, 2, 3, 4, 5, 6, 9)
(0, 1, 2, 3, 4, 5, 7, 8)
(0, 1, 2, 3, 4, 5, 7, 9)
(0, 1, 2, 3, 4, 5, 8, 9)
(0, 1, 2, 3, 4, 6, 7, 8)
(0, 1, 2, 3, 4, 6, 7, 9)
(0, 1, 2, 3, 4, 6, 8, 9)
(0, 1, 2, 3, 4, 7, 8, 9)
(0, 1, 2, 3, 5, 6, 7, 8)
(0, 1, 2, 3, 5, 6, 7, 9)
(0, 1, 2, 3, 5, 6, 8, 9)
(0, 1, 2, 3, 5, 7, 8, 9)
(0, 1, 2, 3, 6, 7, 8, 9)

Finally, there are probably better approaches than brute force for this problem, so you should think a little more about the algorithm.

Gribouillis 1,391 Programming Explorer Team Colleague

Each call to a recursive function uses a new set of local variables. It means the the inner call to countSubStringMatchRecursive will use another count variable, and the count variable of the calling function is not changed.

The simplest way to understand recursion is to think about it the way mathematicians think about proof by induction: Suppose that, for any shortest target string, the function returns the number of occurrences of the key. Then the line count += countSubStringMatchRecursive(strTarget[found + len(strKey):], strKey) actually adds the remaining number of occurrences of the key. And the proof that the function works follows by induction.

vegaseat commented: nicely said +13
Gribouillis 1,391 Programming Explorer Team Colleague

People don't seem to run away from python. See this popularity comparison http://langpop.com/ for example. The only version of python which really breaks code is 3.0, but there were serious reasons for this evolution of the language. I think python only becomes better with time.

Gribouillis 1,391 Programming Explorer Team Colleague

Hi folk, I fairly new to Python 2.7 and Python 3 and like to find out how I would get a print to appear in the middle of the output screen without putting in a load of spaces into a print statement. Please keep it simple for me.

Thanks for you time.


The textwrap module can be useful too. Here is an example

>>> from textwrap import fill
>>> s = fill("""Hi folk, I fairly new to Python 2.7 and Python 3 and like to find out how I would get a print to appear in the middle of the output screen without putting in a load of spaces into a print statement. Please keep it simple for me.""", initial_indent=" "*15, subsequent_indent= " "*15, width = 70)
>>> print(s)
               Hi folk, I fairly new to Python 2.7 and Python 3 and
               like to find out how I would get a print to appear in
               the middle of the output screen without putting in a
               load of spaces into a print statement. Please keep it
               simple for me.
Gribouillis 1,391 Programming Explorer Team Colleague

It's very easy

def read_scores(score):
    try:
        with open('scores.txt', 'r') as scorefile:
            scores = scorefile.readlines()
    except IOError:
        scores = []
    return [int(s) for s in scores]

def display_scores(): # could be improved
    print("\n".join(str(s) for s in read_scores()))

def save_scores(score):
    scores = read_scores()
    scores.append(score)
    scores.sort()
    with open('scores.txt', "w") as scorefile:
        scorefile.write("\n".join(str(s) for s in scores[:5]))
vegaseat commented: great +13
Gribouillis 1,391 Programming Explorer Team Colleague

Anybodyy? really need help with this

Post you code for drawing a single rectangle, the rest will be easy.

Gribouillis 1,391 Programming Explorer Team Colleague

Hi,

I try to read line by line from a file some data. Each line in that file has the following format:

x = 78.36734693877551, z = 11.428571428571429 -> amplitude: 8.62847057093655E-6 | phase -1.5707968246742405\n

I am trying to extract those four float numbers using regular expression. I came with the following code:

import re

myteststr='x = 78.36734693877551, z = 11.428571428571429 -> amplitude: 8.62847057093655E-6 | phase -1.5707968246742405\n'

rs=re.compile(r'^x = (\S+), z = (\S+) -> amplitude: (\S+) | phase (\S+)(\s*)$')
rss=rs.search(myteststr).groups()

The problem is that only the first 3 floats are extracted. The last one and the '\n' character aren't extracted - they are set to the None object:

>>> rss
('78.36734693877551', '11.428571428571429', '8.62847057093655E-6', None, None)

Please tell me where I do wrong. I want to be able to extract the last number also.

Best regards,

PTS

The vertical bar is a special character in re. You can use

rs=re.compile(r'^x = (\S+), z = (\S+) -> amplitude: (\S+) \| phase (\S+)(?:\s*)$')

Also this looks nice http://stackoverflow.com/questions/385558/python-and-regex-question-extract-float-double-value

Gribouillis 1,391 Programming Explorer Team Colleague

after changing your code, I found that

print(*3*(y,))

gives the desired result. What does the '*' before the 3 mean? when I left it out, it returned:
print(3,'%')
('%','%','%')

In the python console

>>> def printSquare(x,y):
...  for z in range(0,x):
...   print(*(y,)*x, sep=",")
... 
>>> printSquare(3, "%")
%,%,%
%,%,%
%,%,%

The * is used when you pass a sequence of arguments to a function. print(*(y,y,y)) is the same as print(y,y,y) ,
but the argument list doesn't need to be written explicitly. For example

my_tuple = ('a', 'b', 'c')
print(*my_tuple) # prints a b c, identical to print('a','b','c')
print(my_tuple) # prints ('a', 'b', 'c'), identical to print(('a','b','c'))
Gribouillis 1,391 Programming Explorer Team Colleague

You must add a member function __str__ to the class, which returns a string representing the instance, for example

class Kort(object):
    ...
    def __str__(self):
         return "Kort({s},{f},{n},{g})".format(
             s = self.color, f = self.form, n = self.number, g = self.grade)
Gribouillis 1,391 Programming Explorer Team Colleague

Oh sorry, the code is:

containers = [0]
inp = input("Enter a weight, 20 or less, or enter 0 to quit: ")

def findContainers(containers,inp):
    
    for i in range(0,len(containers)):
        
        if inp + containers[i] <= 20:
            return i
        
        elif inp + containers[len(containers)-1] > 20:
            return -1


def Allocator(containers,inp):
    
    x = 0
    while inp != 0:
        i = findContainers(containers,inp)
        
        if i == -1:
            containers = containers + [inp]
            i = len(containers) - 1
            
        else:
            containers[i] = containers[i] + inp
            
        x = x + 1
        print "Item ", x , ", Weight ", inp ,": Container ", (i + 1)
        inp = input("Enter a weight, 20 or less, or enter 0 to quit: ")
    print "Container weights: ", containers    



Allocator(containers,inp)

Basically, this version will give the the output:
"Container weights: [17, 15, 18, 9]" with the inputs 12, 15, 5, 10, 8, 9

I want it to output:
"Container weights: [20, 20, 19]" with the same input.

Thanks again

Here is a way

>>> containers = [0]
>>> def find(w):
...  try:
...   w, i = max((x, i) for i, x in enumerate(containers) if x + w <= 20)
...   return i
...  except ValueError:
...   containers.append(0)
...   return len(containers) - 1
... 
>>> def process(seq):
...  for w in seq:
...   i = find(w)
...   containers[i] += w
... 
>>> process([12, 15, 5, 10, 8, 9])
>>> print containers
[20, 20, 19]

You should add a test to reject inputs > 20.

Gribouillis 1,391 Programming Explorer Team Colleague

I'm making a Card class and need to make sure that the suit is valid. When I call on the Card class and construct one setting the suit to 'Jordan' it actually ok's that suit and prints 'Ace of Jordan'. Instead it should become the default, of Spades. What am I doing wrong in my code that will not set it to the default suit? TIA guys

class Card:

    def __init__(self, value, suit):
        validSuit(suit)
        self.suit = suit
        self.face = value
        if self.face >= 1 and self.face <= 13:
            if self.face == 1:
                self.face = 'Ace'
            elif self.face == 11:
                self.face = 'Jack'
            elif self.face == 12:
                self.face = 'Queen'
            elif self.face == 13:
                self.face = 'King'
        else:
            self.face = 'Ace'
            
    def getSuit(self):
        return self.suit

    def getFaceValue(self):
        return self.face
        
    def __str__(self): 
        return str(self.face) + ' of ' + str(self.suit)
    
def validSuit(suit):
    if suit != 'Clubs' or suit != 'Spades' or suit != 'Hearts' or suit != 'Diamonds':
        suit = 'Spades'
        return suit
    else:
        return suit

And here is the driver:

from card import *
def main():

    card = Card(14, 'Jordan')
    print(card)
    # prints 'Ace of Jordan'

main()

Also, validSuit() should be

def validSuit(suit):
    if suit in ('Clubs', 'Spades', 'Hearts', 'Diamonds'):
        return suit
    else:
        return 'Spades'
Gribouillis 1,391 Programming Explorer Team Colleague

You can use a regular expression

import re
sp_regex = re.compile(r"[ \t]+$", re.MULTILINE)
filename = "test.txt"
with open(filename) as f_in:
    content = f_in.read()
with open(filename, "w") as f_out:
    f_out.write(sp_regex.sub('', content))
Gribouillis 1,391 Programming Explorer Team Colleague

For example, using this code snippet http://www.daniweb.com/code/snippet323792.html and the ast module, I obtain the following graph for the parsing of an expression

import ast

node = ast.parse("diff(integ(x**2+y**2, 3, 2), 2)")

def rec_traverse(node):
    for n in ast.iter_child_nodes(node):
        yield node, n
        for item in rec_traverse(n):
            yield item
            
def label(node):
    return node.__class__.__name__
            
from fastgraph import graph
graph(rec_traverse(node), label).draw("graph.png", prog="dot") 
import webbrowser
webbrowser.open("graph.png")

from the nodes Name and BinOp and Call, you should be able to obtain the variable names and the function names, and define your own evaluator for the parsed expression. (Remark: in a graphviz representation, the children of a node are not ordered)

Gribouillis 1,391 Programming Explorer Team Colleague

diff(integ(log(anotherCalculatorFunction())))

if I run diff() the way it's written, then it'll try to compile(integ(log(...))) and then eval() it. Unless I'm missing something obvious, it'll choke on this, right?

I tried to play with this code, which evaluates expressions in a fixed namespace, where symbols are added on demand. The function evaluator() take an expression as an argument and returns a function where the unknown variables are ordered alphabetically (for example x and y)

from math import sqrt

EVAL_NAMESPACE = dict()

def varnames(function):
    return func.func_code.co_varnames

def evaluator(expression):
    namespace = EVAL_NAMESPACE
    code = compile(expression, 'expression', 'eval')
    args = []
    for name in (n for n in code.co_names if not n in EVAL_NAMESPACE):
        if name in globals():
            EVAL_NAMESPACE[name] = globals()[name]
        else:
            args.append(name)
    args = tuple(sorted(args))
    func = """
def function(%s):
    return eval(code, namespace, locals())
""" % (", ".join(args))
    exec func in locals()
    function.__name__ = "evaluator(%s)" % repr(expression)
    print "EVALUATOR:", function.__name__
    return function

def foo(expression, a, b):
    func = evaluator(expression)
    return (func(a) + func(b)) * 0.5

def bar(expression, x):
    func = evaluator(expression)
    return func(x+1) - func(x)

def evaluate(expression, *args):
    return evaluator(expression)(*args)

expr = 'foo("x**2 + x", bar("3*x+2", 2), 1)'
print evaluate(expr)

print evaluate("sqrt(evaluate('x**2+y**2', 3, 8))")

For a more complete solution, you should have a look in the ast module. The ast.parse function parses a python expression and returns an abstract syntax tree. You could examine this tree and build your evaluator on this tree.

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a good way to do this. The key points are

  • use generators
  • use list comprehensions
  • use sorted() and it's 'key' argument
# python 2 and 3
import os

# write a generator to decouple the code which creates the data
# from the code which uses it

def gen_triples(folder):
    for (path, dirs, files) in os.walk(folder):
        for file in files:
            name = os.path.join(path, file)
            size = os.path.getsize(name)
            repr = "[{n} size = {s}]".format(n = name, s = size)
            yield name, size, repr # we yield a tuple with 3 values
            
def by_name(triple):
    return triple[0]

def by_size(triple):
    return triple[1]

folder = "."

# use the sorted() builtin function to sort the data

name_sorted = [ repr for (name, size, repr) in sorted(gen_triples(folder), key = by_name)]
size_sorted = [ repr for (name, size, repr) in sorted(gen_triples(folder), key = by_size)]

from pprint import pprint
print("BY NAME")
pprint(name_sorted)
print("BY SIZE")
pprint(size_sorted)
Gribouillis 1,391 Programming Explorer Team Colleague

First I think it can be shortened to

def view(N,W,E,S):
    t = (N, W, S, E)
    st = ("north", "west", "south", "east")
    ft = (fhall, lfhall, frhall, frlhall)

    d = st.index(info_dict["direction"])
    if t[d] != 1:
        pic = fwall
        wall = "yes"
    else:
        x, y = t[(d+1) % 4], t[(d+3) % 4]
        x, y = int(not bool(x-1)), int(not bool(y-1)) # now != 1 means 0
        pic = ft[2 * y + x]
        wall = "no"

Otherwise, to make an importable module, simply save the file as "mymodule.py" and write "import mymodule" in the other files.

Don't program with copy and paste !

Also, use the 'else' keyword in sequences of if statements.

Gribouillis 1,391 Programming Explorer Team Colleague

Use

array = [[float(x) for x in line.strip().split()] for line in open("file.txt")]
Gribouillis 1,391 Programming Explorer Team Colleague

Start with this documentation page http://docs.python.org/tutorial/floatingpoint.html.

A problem is that python's 0.1 is not the mathematical 0.1 because 0.1 can not be represented exactly as a machine binary number.

Gribouillis 1,391 Programming Explorer Team Colleague
def round32(x): return (x+16) & ~31

This seems to work right. Could you please explain what the '&' and '~31' are used for?

When working with bitwise operations (~, &, |, ^), it's better to think of an integer as a semi-infinite sequence of bits. See the examples below

# python 2 and 3
from __future__ import print_function

def tobit(n, width=50):
    m = (1 << (width - 3))
    n = (n & (m-1)) if n >= 0 else ((n & (m-1))+m) & (m-1)
    z = "...{n:0>{w}}".format(n=bin(n)[2:], w=width-3)
    return z

L = [354777,4191,-24522,774,-32]
print("various numbers", L, ":")
for n in L:
    print(tobit(n))
    
    
print("")

x, y = 4577822, 768887

print("x, y, x & y:")
for s in (x, y, x & y):
    print(tobit(s))
print("the bits set in x & y are the common bits set in x and in y")

print("")
print("x, ~x:")
for s in (x, ~x):
    print(tobit(x))
print("the bits set in ~x are the bits unset in x")

print("")    
print("x, ~31, x & ~31:")
y = ~31
for s in (x, y, x & y):
    print(tobit(s))
print("in ~31, only the five lowest bits are unset")
print("x & ~31 is x with the five lowest bits forced to 0")

""" my output --->
various numbers [354777, 4191, -24522, 774, -32] :
...00000000000000000000000000001010110100111011001
...00000000000000000000000000000000001000001011111
...11111111111111111111111111111111010000000110110
...00000000000000000000000000000000000001100000110
...11111111111111111111111111111111111111111100000

x, y, x & y:
...00000000000000000000000010001011101101000011110
...00000000000000000000000000010111011101101110111
...00000000000000000000000000000011001101000010110
the bits set in x & y are the common bits set in x and in y

x, ~x:
...00000000000000000000000010001011101101000011110
...00000000000000000000000010001011101101000011110
the bits set in ~x …
Gribouillis 1,391 Programming Explorer Team Colleague

The main reason is that a 20 lines python program does more job than a 500 lines C++ program.

-ordi- commented: cool! +0
Gribouillis 1,391 Programming Explorer Team Colleague

In the function in_common() when the if fails, there is no return statement, so it returns None.


Also in most situations you don't need if expression == True . Simply write if expression: .

Gribouillis 1,391 Programming Explorer Team Colleague

Use string order

>>> "20091128" < "20101118"
True

This will work for all dates with 8 characters.

edit: to avoid the Y10K syndrome, choose woooee's solution :)

TrustyTony commented: Far thinking scientist (7990 years to be exact) +2
Gribouillis 1,391 Programming Explorer Team Colleague

OOOPs, since python 2.6 there is a better implementation in the standard module heapq

Help on function merge in heapq:

heapq.merge = merge(*iterables)
    Merge multiple sorted inputs into a single sorted output.
    
    Similar to sorted(itertools.chain(*iterables)) but returns a generator,
    does not pull the data into memory all at once, and assumes that each of
    the input streams is already sorted (smallest to largest).
    
    >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))
    [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]

Better use this one !

Gribouillis 1,391 Programming Explorer Team Colleague

I know how to do it using the pari library

>>> from pari import factor
>>> x = 252
>>> g = factor(x, x)
>>> zip(*(eval(str(g[i])[:-1]) for i in (0,1)))
[(2, 2), (3, 2), (7, 1)]
Gribouillis 1,391 Programming Explorer Team Colleague

Write a recursive function

# python 2 and 3

def splitmany(s, seps=""):
    if seps:
        u, seps = seps[0], seps[1:]
        for word in s.split(u):
            for item in splitmany(word, seps):
                yield item
    else:
        yield s
            
if __name__ == "__main__":
    print(list(splitmany('hello. world! hello.', "!.")))
    
"""my output -->
['hello', ' world', ' hello', '']
"""

but why don't you want to use regexes ?

Gribouillis 1,391 Programming Explorer Team Colleague

Here is my attempt, which doesn't use graph algorithms, but the Bezout theorem in arithmetics

Note: this code should be tested more intensively, and it remains to prove that
the solution always work theoretically (find counter example ?)

def bezout(n, m, u):
    """return (a, b, g) such that a * n + b * m = u
    and g = gcd(n, m)"""
    if m:
        q, r = divmod(n, m)
        a, b, g = bezout(m, r, u)
        return b, a - q * b, g
    else:
        q, r = divmod(u, n)
        if r:
            raise ValueError, "No solution"
        return q, 0, n


def pairs(d1, d2, u):
    """yield the pairs x, y such that x * d1 + y * d2 = u
    and x >=0 and y >= 0 with x + y increasing.
    """
    a, b, g = bezout(d1, d2, u)
    e1, e2 = d2 / g, -d1 / g
    if e1 + e2 < 0:
        e1, e2 = -e1, -e2
    if e1 > 0:
        q, r  = divmod(-a, e1)
        kmin = q + (r > 0)
        if e2 > 0:
            q, r = divmod(-b, e2)
            kmin = max(kmin, q + (r > 0))
    else:
        q, r = divmod(-b, e2)
        kmin = q + (r > 0)
    while True:
        x, y = a + kmin * e1, b + kmin * e2
        if x < 0 or y < 0:
            break
        yield x, y
        kmin += 1

def shots(N, C1, C2, G1, G2):
    """try to give a solution …
Gribouillis 1,391 Programming Explorer Team Colleague

Use list comprehensions and sorted

>>> dict1={'12':['123','187','1860','4821','7000','9000'],'18':['1234','4000']}
>>> L = sorted((int(k), sorted(int(x) for x in v)) for k, v in dict1.items())
>>> print L
[(12, [123, 187, 1860, 4821, 7000, 9000]), (18, [1234, 4000])]
>>> M = [(k, x) for k, v in L for x in v]
>>> M
[(12, 123), (12, 187), (12, 1860), (12, 4821), (12, 7000), (12, 9000), (18, 1234), (18, 4000)]
knan commented: This is geat! thanks!!! :) +1
Gribouillis 1,391 Programming Explorer Team Colleague

You can use set

x = set(mu1List)
y = set(mu2List)

a = x - y # set of items in x but not in y (set difference)
b = x & y # set of items in both sets (set intersection)
c = y - x # set of items in y but not in x

example

>>> x = set(range(10))
>>> y = set(range(4, 12))
>>> x
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> y
set([4, 5, 6, 7, 8, 9, 10, 11])
>>> x - y
set([0, 1, 2, 3])
>>> x & y
set([4, 5, 6, 7, 8, 9])
>>> y - x
set([10, 11])
>>> x | y
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
planetPlosion commented: perfect +3
Gribouillis 1,391 Programming Explorer Team Colleague

Use list comprehensions

>>> L = [ list(range(1+k, 4+k)) for k in range(0,9,3)]
>>> L
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> LL = [x[:2] for x in L] + [[x[0], x[2]] for x in L]
>>> LL
[[1, 2], [4, 5], [7, 8], [1, 3], [4, 6], [7, 9]]
Gribouillis 1,391 Programming Explorer Team Colleague

This snippet defines 3 functions to create in a few seconds an image of
a graph containing arbitrary python objects. It uses the module pygraphviz
(available at http://pypi.python.org/pypi/pygraphviz/).

See the example use case at the end of the module.

Gribouillis 1,391 Programming Explorer Team Colleague

I've heard only bad things about eval + strings.
Maybe I'm better off not printing them to files?

I need to be able to search out of order in the lists to compare them

for item in List1:
search List2 for item
if match is found
next item
else print item from list1 in file.txt

So, if anyone could help me with this pseudocode.. I haven't found any operators that let me easily compare contents of lists or a search list function

The only 'bad' thing about eval is that you must not eval a string received from the internet, because it could contain arbitrary code which you don't want to execute on your computer.

But there is nothing wrong in evaluating a string written by your own program. It's like running your own script.

planetPlosion commented: straighted my knowledge of eval out +3
Gribouillis 1,391 Programming Explorer Team Colleague

Then modify the code like this

def thefunction():
    filenames = list(x.strip() for x in list(open("name.txt", "rb")) if x.strip())
    L = [(n, open(n, "rb").read()) for n in filenames]
    return [(x, [int(z) for z in y.strip().split()]) for (x,y) in L]
Gribouillis 1,391 Programming Explorer Team Colleague

Use sorted_list = sorted(list1)

Gribouillis 1,391 Programming Explorer Team Colleague

Oh, I forgot to mention that I can't copy over another list. I have to do all of it with that 1 list.

Sorry guys.

Then start with the end of the list

def del_odd(l):
  for i in range(len(l)-1, -1, -1):
    if l[i] % 2 != 0:
      del l[i]

Notice that l is a bad variable name. Also try to understand the difference between l.remove(l[i]) (bad) and del l[i] (good).

Gribouillis 1,391 Programming Explorer Team Colleague

mylist.sort() works, but it sorts the list in place and returns None

>>> L = "the file I'm working with has all text in the same case, case doesn't matter here".split()
>>> print(L)
['the', 'file', "I'm", 'working', 'with', 'has', 'all', 'text', 'in', 'the', 'same', 'case,', 'case', "doesn't", 'matter', 'here']
>>> L.sort()
>>> print(L)
["I'm", 'all', 'case', 'case,', "doesn't", 'file', 'has', 'here', 'in', 'matter', 'same', 'text', 'the', 'the', 'with', 'working']
>>> print(L.sort())
None

Otherwise, you can use newlist = sorted(mylist) which doesn't change the original list, but returns a new list.

Gribouillis 1,391 Programming Explorer Team Colleague

In a terminal:

$ pydoc xrange

class xrange(object)
 |  xrange([start,] stop[, step]) -> xrange object
 |  
 |  Like range(), but instead of returning a list, returns an object that
 |  generates the numbers in the range on demand.  For looping, this is 
 |  slightly faster than range() and more memory efficient.

AN object like xrange(10) implements the iterator protocol: it has a method __iter__ which returns an object with a __next__ method, so you can write

>>> r = xrange(10)
>>> it = iter(r)
>>> next(it)
0
>>> next(it)
1
>>> next(it)
2

# or
>>> for number in r: ...

but the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] is never built.
In python 3, range replaces xrange so that

python 2    |  python 3
------------------------
xrange(10)  |  range(10)
range(10)   |  list(range(10))

If you want a python 3 behavior in python 2, you can write

import sys
if sys.version_info < (3,):
    range = xrange
Gribouillis 1,391 Programming Explorer Team Colleague

Note that list comprehensions in python come from haskell, so they are also an example of functional programming in python. See this page http://wiki.python.org/moin/PythonVsHaskell for more about python and haskell.

It's true that list comprehension appeared in python 2.0, but it took some time before people considered it to be the norm. Many of us were used to 'map'.

Gribouillis 1,391 Programming Explorer Team Colleague

temp=1
main_list = [['a', 'b', 'c', 'd'], ['e', 'f'], ['g', 'h']]
for each_list in main_list:
for ctr in range(len(each_list) - 1):
temp=ctr +1
while temp < len(each_list) :
print each_list[ctr],"-", each_list[temp ]
temp = temp + 1;

Please learn about code tags http://www.daniweb.com/forums/announcement.php?f=8&announcementid=3
See how better it looks:

main_list = [['a', 'b', 'c', 'd'], ['e', 'f'], ['g', 'h']]
for each_list in main_list:
    for ctr in range(len(each_list) - 1): 
        temp=ctr +1
        while temp < len(each_list) : 
            print each_list[ctr],"-", each_list[temp ]
            temp = temp + 1;
knan commented: Omg! Thank you so much! Ur a saviour... tyvm :) :) +1
Gribouillis 1,391 Programming Explorer Team Colleague

Because if I remove the second login part, before server.sendmail, I get the following error.

And only when I use server.login once more, I get passed the error - any advice regarding that?

Thanks for your reply!

I think you should remove lines 47 to 51 included.

Gribouillis 1,391 Programming Explorer Team Colleague

The variables in a function's body are local to this function and can't be used outside the function. The solution is to return the variable and to catch the return value when the function is called

def example(a):
    alist=[]
    alist.append(a)
    print alist
    return alist # <---- return alist to the calling environment

thelist = example(1) # <----- we catch the returned list
print thelist

Note that we could have used the same name alist instead of thelist. I changed the
name to show that we are dealing with 2 different variables.

Gribouillis 1,391 Programming Explorer Team Colleague

Thank you very much. That was very helpful. How am I going to achieve the 1st and 2nd conditions. I am still trying, but i couldnt figure out a regular expression...

You can write pseudo code to build the regular expression. You want to match this

pattern:
    either:
        symbol1 equal symbol2
        newline
        symbol2 equal symbol1
    or:
        symbol3 equal symbol3
    or:
        symbol4 equal symbol5
    newlines (0 or more)

Each of these elements has an equivalent regex pattern:

symbol1 ->  (?P<symbol1>[a-z])
symbol2 ->  (?P<symbol2>[a-z])
repeated symbol1  -> (?P=symbol1)
repeated symbol2  -> (?P=symbol2)
equal -> [=]
newline -> \n
zero or more -> *

This should give you hints to build the regular expression.

knan commented: Thank you very much!! I think i am nearing the answer. +0
Gribouillis 1,391 Programming Explorer Team Colleague

Each module has its own 'namespace', that is to say its own dictionary of known variable names. In your example, the (global) names defined in the module 'usermodule' are 'Image' and 'usermodule. The names defined in the main program are 'image', 'usermodule' and 'imload'.

It means that the function usermodule() doesn't know that there is a variable imload, since it can only see the namespace of the usermodule module. It's an error to use imload in the function's body. Also, another error is that xstart and ystart are not defined anywhere.

The solution is to pass the value of imload to the function through an argument. You can write

# in usermodule.py
def usermodule(imload, x, y):
    return imload[x,y] # imload, x, y are known names in this scope, since they are parameters

# in main program
print usermodule.usermodule(imload, 1,1)
Gribouillis 1,391 Programming Explorer Team Colleague

Okay...so I understand that you don't recommend variables if loops are to be involved.

However, I have to use a bit of variables here, perhaps, to indicate doubles form 1 to 9 vertically. So if input looks like this:

123456789
222222222

from the raw_input statements

num_1 = str(raw_input("Enter set 1: ")
num_2 = str(raw_input("Enter set 2: ")

Then an error should appear for the second vertical. (Number 2 happened twice vertically there, should be only once for all rows)

So to design this code, i appended variables to indicate the vertical grid:

vertical_0 = num_1[0] + num_2[0]
vertical_1 = num_1[1] + num_2[1]#<--this is where the double 2s occured in the above eg

###...code continues to vertical_8, which is the 9th vertical column.

But like you said, variables does not work well with loops, is there a simpler bypass around this, I am a begginner here so I do feel sort of silly...

As I said, you should use lists to store the user's input. You can build rows and columns like this

rows = list()
for i in range(8):
    rows.append(raw_input("Enter row number %d: " % (i+1))
cols = list()
for j in range(len(rows[0])):
    cols.append(''.join(row[j] for row in rows))

print rows
print cols

Perhaps you should check that all rows have the same length before building the columns.