shadwickman 159 Posting Pro in Training

So have a variable that, when set, it deletes each line it encounters until it finds one starting with a >
Then just have this set to True or something once you find a line you want to remove, and it'll remove the lines after that don't start with > (which would the lines with the sequence). Then just set it to False once it encounters a line starting with > again.
Sorry if that wasn't too clear :P This is what I meant:

from __future__ import with_statement

with open ('dna.txt') as fil:
    f = fil.readlines()
    delete_seq = False
    for line in f:
        if line[0] == ">":
            delete_seq = False
            
        if "rs" in line:
            delete_seq = True
        elif not delete_seq:
            print line,

It will set delete_seq to True if it finds an "rs" in the line, and while delete_seq is True, it'll ignore any following lines until one of them starts with ">", which will set it back to False. If you need me to clarify, just ask. Here's my output:

>1|100159271|ENSRNOSNP145|T/A||ENSEMBL:celera|T/A
TCTTATAATTAGTCATTGTGATAACTGCTACAAACAAAGTCACAGGATCTTGTGAGAGAA
>1|101456015|ENSRNOSNP1318|G/C||ENSEMBL:celera|G/C
AACTCTTAGAAGTTAGAACCTGGGGTGGAGAGATGGCTTGGTGGTTGAGAGCATTGACTG
shadwickman 159 Posting Pro in Training

Ok, so I rewrote some stuff and commented it a bit to help you out.

room_num = raw_input("Enter your room number: ")
text_file = open("roombookings.txt", "r")
# store a list containing the lines from the file
whole_thing = text_file.readlines()

# join all the lines into a string to search
if room_num in "".join(whole_thing):
    print "Room number found here is the information:"
else:
    print "Room number not found."
    
# we keep a list of lines that we want to save
lines_to_save = []

# cycle each line in our whole_thing list
for single_line in whole_thing:
    if room_num in single_line:
        print single_line
        # add the line to the saving list
        lines_to_save.append(single_line)
    
# here we open the output file
fileObj = open("courseinfo.dat","w")
# and join our saved lines into one string to write
fileObj.write("".join(lines_to_save))
fileObj.close()

text_file.close()

The comments explain the changes I made pretty well. You had a few issues like that readline() that I explained. You were on the right track though! Remember that the file write(str) function will overwrite all the file's contents with the string passed to it, so if you were to call it during the for loop, it would overwrite everything else it had saved before. Hence saving the lines to a list to write at the end. You could also create the file before-hand and then open it again in append mode, but this works fine for your problem. I hope the comments explain the code properly. If not, just ask me to clarify!

shadwickman 159 Posting Pro in Training

First, your whole_thing variable should be text_file.read() if you want to return all the contents as a string. Or text_file.readlines() if you want to return all the contents as a list of each line. Change this and see if that fixes any problems with your code.

I don't fully understand what you mean by "search results", but I assume you mean the single_line variable if the room number is in that line. If you want to write that line to the "courseinfo.dat" file, the just stick that writing segment inside where you are currently printing the single_line. Like this:

single_line = whole_thing.split('\n')
for single_line in text_file.readlines():
   if room_num in single_line:
        fileObj = open("courseinfo.dat","w")
        fileObj.write(single_line)
        fileObj.close()

If this isn't what you meant, please rephrase your question clearly and maybe include some sort of example of what "roombookings.txt" contains, etc.

shadwickman 159 Posting Pro in Training

By putting "s = d / t" before the conditionals would only calculate speed - but what happens when you give speed and distance for example? It wouldn't calculate time. You have to put each individual case within the appropriate conditional branch like Lardmeister did.

P.S. This kind of program is much more useful for something like cosine law, sine law, quadratic formula, etc. as opposed to the simplistic s = d / t which is just a simple, one-step calculation :P

shadwickman 159 Posting Pro in Training

As for making the keylogger, you may want to have a look at pyhook, which can capture all keyboard events and mouse clicks in Windows (so even when your program's window isn't in focus). Definitely a useful thing to have access to for your purposes.

shadwickman 159 Posting Pro in Training

And I just found this:
http://www.pyinstaller.org/

It claims to make executables for Windows, Linux, and Mac. I have never used it myself though.

shadwickman 159 Posting Pro in Training

You may also want to look into unwrapping, like this example:

coords = [14, 16, 4]
x, y, z = coords
"""result -->
x = 14
y = 16
z = 4
"""
shadwickman 159 Posting Pro in Training

Well first of all, you don't need to make an enumerate_list class as there's already the built-in one enumerate which you can use on lists, strings, tuples, etc. Meaning that you could use this instead:

for i, ch in enumerate(xStr):
    xDict[i] = ch

Also, don't use str as your variable name as that's the name of Python's string object, like int , list , tuple , float , etc.

And, didn't you want any blank indices in the lists to have a zero put there? Like you showed with your yList in your first post. Just put a conditional if statement to handle that in your getxList function.

Finally, I wouldn't use partition for splitting the bracketed pair at the pipe |. Use the split function. It works like this:

s = "a|b|c|d"
t = s.split("|")
""" t -->
['a', 'b', 'c', 'd']
"""

Incorporating that into your getxList function rather than using multiple partition calls would make it much cleaner and simpler looking. Here's a crude example that you can modify to fit into your code properly, but it works and it's much simpler looking:

def getxList(self):
    line = '(x1|y1|z1)(x2||z2)(x3|y3|z3)\n' # example string
    groups = line.split(')(')
    for item in groups:
        item = item.strip().split('|')
        item = filter(lambda x: x != ' ', item)
        item = [x.strip('(').strip(')') for x in item]

Hope I helped a bit!

shadwickman 159 Posting Pro in Training

Well, I posted the tutorial which explains it well. Regardless, put this in a file called setup.py in the same location as your script. Put this in setup.py:

from distutils.core import setup
import py2exe

setup(console=["YOURSCRIPTNAME.py"])  # replace with your program's filename

Then, open the DOS/MS-Windows command prompt, and move to your script's location. Then use this command:

python setup.py py2exe

That should make your .exe. If you have an error, please type out what it says so I can understand what went wrong!

shadwickman 159 Posting Pro in Training

Um... what exactly are you trying to say with the above post? So you posted some code. Good work, but what is your question/motive?

shadwickman 159 Posting Pro in Training

And as a side note, you shouldn't be using stdio.h or stdlib.h as those aren't standard C++ headers. Use cstdio and cstdlib which are the standard C++ headers.

And as u8sand said, you're only executing things through once. Loop until the game is over, then ask to if the player wants to play again, and if so, re-loop it all.

shadwickman 159 Posting Pro in Training

Well here is the py2exe website:
http://www.py2exe.org/
And here is their tutorial that you should follow:
http://www.py2exe.org/index.cgi/Tutorial

This only makes executables which run on Windows. However, most Linux distributions already come with Python installed, so Python .py files should run fine from them as-is.

shadwickman 159 Posting Pro in Training

py2exe can make .exe files for Windows. These .exe files can run without Python installed. However, .exe files will not run on Linux.

shadwickman 159 Posting Pro in Training

That is a better option. And this way you can achieve a nicer output without having to resort to GUI programming. Good luck!

shadwickman 159 Posting Pro in Training

Ohh ok, gotcha. You had me confused there for a moment :P

shadwickman 159 Posting Pro in Training

If you were to take the most updated code, you'd see that it works. This is what Lardmeister posted:

import wx

ID_FILE_QUIT = 101

class MainFrame(wx.Frame):
    def __init__(self, title):
        wx.Frame.__init__(self, None, wx.ID_ANY, title=title)
        self.menuBar = wx.MenuBar()
        self.fileMenu = wx.Menu()
        self.fileMenu.Append(ID_FILE_QUIT, '&Quit\tCtrl+Q')
        self.Bind(wx.EVT_MENU, self.quit, id=ID_FILE_QUIT)
        self.menuBar.Append(self.fileMenu, '&File')
        self.SetMenuBar(self.menuBar)
        self.Show()
        
    def quit(self, event):
        self.Close(True)


app = wx.App()
frame = MainFrame('Ya Mum')
app.MainLoop()

Which tom tetlaw acknowledged as he said "all I need to do is put the function name, not call the function". This is what we're doing by binding the function self.quit, rather than self.quit().

shadwickman 159 Posting Pro in Training

I'd definitely suggest going with G++. MinGW is the port of that for Windows. And as Ancient Dragon said, please don't go for DevC++. That died back in 2005 and so it hasn't been updated since.

shadwickman 159 Posting Pro in Training

Yep, no errors whatsoever with my Python 2.5.4 installation either...

shadwickman 159 Posting Pro in Training

Better test it, that won't work!

Why not? It worked for me when I tested his code... and there's nothing wrong with his binding as I added another menu item with a separate function and ID and that still worked without conflict.

shadwickman 159 Posting Pro in Training

You will have to make separate executables for Windows and Linux too.

shadwickman 159 Posting Pro in Training

And make sure that your file isn't some huge size that you shouldn't be loading into memory all at once. You can just go through the lines with the xreadlines() iterator instead.

# this requires the output file to already exist and it should be
# blank, as opening it with mode "a" will just append lines to it.

fhi = open("input_file", "r")
fho = open("output_file", "a")
for line in fhi.xreadlines():
    if "rs" not in line:
        fho.write(line)
fhi.close()
fho.close()

But if you are loading it all into memory as a list like paulthom suggested, make sure to cycle the file in a way that deleting indices as you go won't mess up the loop, like paulthom's idea would. This below example shows the odd effects of deleting the indices during a for loop:

L = ['a', 'b', 'c', 'd']
for i, item in enumerate(L):
    del L[i]

"""resulting L:
['b', 'd']
"""

You could do it like this though:

fh = open("input_file", "r")
data = fh.readlines()
fh.close()

i = 0
while i < len(data):
    del data[i]
    i += 1
shadwickman 159 Posting Pro in Training

He said he was running it on Dev C++ in his post a few up. Hence my suggestion to use MinGW or a non-dead compiler to keep up to date.

shadwickman 159 Posting Pro in Training

It seems you are just laying down a flat-out request for us to code you something. Not gonna happen. Post the code you have come up with so far and where you got stuck, etc. and I'll try helping from there.

shadwickman 159 Posting Pro in Training

Ah thanks for catching that one line where I forgot to assign the list's value to "c". That's what I get for not testing code! :P

And I think that re.sub may be broken in Python 2.2... well, using a pattern like you did (the preceeding "r" in front of the string). If you give this mail a quick read, you'll see that Guido said it was broken with raw strings.

shadwickman 159 Posting Pro in Training

That error makes no sense. Is the section of code you posted oh here the entirety of it? Or is this a segment of something larger which might be causing the issue? As far as I know, re has sub available even in Python 2.2

Technically, the newest version of Python is 3.0, but I wouldn't go for that yet. It has large overhauls and is not backwards compatible. Plus third-party stuff isn't really updated to it yet. Most people (myself included) stick with 2.6 (or 2.5 too) as it's the best to date cause Python 3.0 is still too new. I'd really strongly recommend upgrading to 2.6 unless you're forced to stick with 2.2.

shadwickman 159 Posting Pro in Training

That makes no sense. Python 2.3 though is when the built-in enumerate function was introduced... your custom one should work fine though. It's outputting "HELLO_PYTHON_WORLD" two times?...

How about an (ugly) alternative method?

s1 = "HelloPythonWorld"
s2 = ""
index = 0
while index < len(s1):
    if c.isupper() and index > 0:
        s2 += '_' + c
    else:
        s2 += c
    index += 1

s2 = s2.upper()
print s2

This doesn't use that custom enumerate class you made. What output does this give you?

shadwickman 159 Posting Pro in Training

I'll formulate this below code based on the presumption that you're printing this and not storing it in a 2D array.

void displayBox ( int width, int height, char FillChar )
{
    for(int y = 0; y < height; y++) {
        for(int x = 0; x < width; x++) {
            // Top or bottom row.
            if(y == 0 || y == height - 1)
                cout << "_";

            // In between top and bottom
            else {
                // Side
                if(x == 0 || x == width - 1)
                    cout << "|";
                // Filler
                else
                    cout << FillChar;
            }
        }
        cout << endl;
    }
}

Cycle through the the y-direction (the height, therefore each row) and then loop across the x-direction of that row (the width) and decide what to output. If it is the first or last row it will display the underscore "_". If it isn't, but if it is the side, it will display the pipe "|", and if it isn't that either, then it must output the FillChar. At the end of each row's x-direction, output a newline.

This worked perfectly for me when I tested it even though I've barely touched C++ :P (Python is for me). I hope that explained it well enough though - tell me if you need me to clarify it more!

shadwickman 159 Posting Pro in Training

This still makes no sense. You can't "call" the other functions to get the variables they had. And besides, you already passed them on to that last function anyways. And what exactly do you mean by "to create a box". Can you give what sample output would look like?

shadwickman 159 Posting Pro in Training

By the way, please use code tags around your code instead of typing "Code" and "end of code".

Anyways, I don't see what your problem is exactly. Don't you just need to actually code in whatever you want performed into the final function and you're all set?

shadwickman 159 Posting Pro in Training

For Python 2.x:
People seem to overlook the usefulness of built-in functions for handling common issues with lists. A lot of times, filter , map , and reduce can easily and efficiently serve typical purposes that most people attempt without these. Here's an example of their usage (I use lambda expressions in them - you can read up on lambda expressions here):

# filter
# in the interactive shell, use help(filter) for more info.
# filter takes a function and a list, and returns a list of
# the items that returned True for the given function.
# This example takes a list and returns one with the
# unallowed words removed.

words = ['This', 'sentence', 'has', 'unallowed', 'words']
unallowed = ['has', 'words']
remainder = filter(lambda x: x not in unallowed, words)

"""result ->
['This', 'sentence', 'unallowed']
"""
# map
# in the interactive shell, use help(map) for more info.
# map takes a function and a list, and returns a list of
# the items after applying the specified function to them.
# This example takes a list and returns one in which
# every index was squared.

data = [2, 5, 9, 16, 31, 35]
squared = map(lambda x: x*x, data)
"""result ->
[4, 25, 81, 256, 961, 1225]
"""
# reduce
# in the interactive shell, use help(reduce) for more info.
# reduce takes a function and a list, and returns a single
# value formed by taking the result of …
Lardmeister commented: nice code examples +5
shadwickman 159 Posting Pro in Training

What operating system are you using? If MS Windows, you can use os.system('cls') to clear the console window before reprinting the progress display. Yes, yes, I know that clearing the screen isn't good because a) this won't work on Mac or GNU/Linux, b) it may cause users to lose any important data they had in the console before running your script, and c) it introduces security issues into your program *. This is what you're looking for though, right? So I guess we can make an exception for clearing the screen in this case...

* as "cls" is a program on Windows that does this, if someone were to put a program named "cls" into the same folder that this script was run out of, then Windows would execute that program rather than the native "cls". Hence, very large security issues. (Thanks to Siddhant Sanyam for bringing that to light.)

P.S. sys.stdout.write is only an output stream, much like the print expression. Although, sys.stdout.write will not put a newline after each call like print, and if you call print "somethinghere", with that comma after, it won't put a newline but it will put one space.

shadwickman 159 Posting Pro in Training

Ok then. It took me a little while to grasp py2exe's workings, but not too long. If you were to follow the tutorial then you'll be fine. Good luck with this idea!

py2exe homepage

shadwickman 159 Posting Pro in Training

When you generate an .exe with py2exe it also makes other files that I think the .exe is dependent on. Like some .pyd files and such. Well, all the .exes I generated with py2exe did that for me, at least. I may have been doing something wrong though, as I haven't used py2exe very much...

shadwickman 159 Posting Pro in Training

Hi again :D
I don't know why, but it wasn't accepting the negative values in the event handling. I just made the "down" values negative and multiplied positive values instead, like this:

import pygame
from pygame.locals import *

screen = pygame.display.set_mode((1024, 768))
background = pygame.image.load('marioscreendesign.bmp')
man = pygame.image.load('superdudepic.bmp')

screen.blit(background, (0,0))
screen.blit(man,(0,0))
pygame.display.flip()
for i in range(100):
   screen.fill((0,0,0))
   screen.blit(background, (0,0))
   screen.blit(man,(i,0))
   pygame.display.flip()
   pygame.time.delay(50)

while 1:
    # USER INPUT
    clock.tick(30)
    for event in pygame.event.get():
        if not hasattr(event, 'key'): continue
        down = event.type == KEYDOWN     # key down or up?
        # I just made the "down" value negative and it accepted that.
        if event.key == K_RIGHT: k_right = -down * 5
        elif event.key == K_LEFT: k_left = down * 5
        elif event.key == K_UP: k_up = down * 2
        elif event.key == K_DOWN: k_down = -down * 2
        # end
        elif event.key == K_ESCAPE: sys.exit(0)     # quit the game
    screen.fill(BLACK)

EDIT:
Change your conditional statements so that they're not 1-liners, which fixes it:

# ...
# excerpt from your code, making the IFs indented
while 1:
    # USER INPUT
    clock.tick(30)
    for event in pygame.event.get():
        if not hasattr(event, 'key'): continue
        down = event.type == KEYDOWN     # key down or up?
        if event.key == K_RIGHT:
            k_right = down * -5
        elif event.key == K_LEFT:
            k_left = down * 5
        elif event.key == K_UP:
            k_up = down * 2
        elif event.key == K_DOWN:
            k_down = down * -2
        elif event.key == K_ESCAPE:
            sys.exit(0)     # quit the game
    screen.fill(BLACK)
shadwickman 159 Posting Pro in Training

Very true. And seeing as he basically did that in Perl I'm sure he won't find the Python syntax too confusing.

shadwickman 159 Posting Pro in Training

You don't really need to be using regular expressions on something this simple though...

shadwickman 159 Posting Pro in Training

You can incorporate this easily into your script as a function, etc.

# split at the first bracket - the function, and the arguments
func, args = f.split("(")
# split the function into its type and name
func = func.split(" ")
# split the arguments at each comma
args = args.split(",")
# get rid of ending bracket and semicolon from last arg
args[-1] = args[-1][:2]
# put both lists together
result = func + args
#strip any leading or trailing whitespace from the items
result = [item.strip() for item in result]
# remove any list indices that are blank strings
result = filter(lambda x: x != "", result)

""" my result on the first line in your file:
['int', 'Function1', 'int arg1', '"0|1"', 'char * arg2']
"""

That's pretty well commented for you to understand. The last little strip() part is because when split at a comma, the following argument would start with a space. By calling strip() on all the resulting items, we ensure that none of them have excess leading or trailing whitespace. And when we split the func list at any spaces (to get the type and name), the space right after the name (before the bracket originally) made a blank index, so later on I added that filter call to weed out any blank-string indices. Tell me if you need any other clarification.
Hope that helps!

shadwickman 159 Posting Pro in Training

If by each "word", you mean strictly at every space, then you could read the file line by line, and perform this on every line:

fh = open('filename', 'r')
for line in fh.readlines():
    # use 'xreadlines()' if the file is large and you just want an iterator
    words = line.split(' ')
    # returns an array of every item between the spaces
    # do something else...
fh.close()

The 'words' list would look like this on the first line in that file:

['int', 'Function1', '(int', 'arg1,', '"0|1",', 'char', '*', 'arg2);']

Notice that some indices still have the commas, brackets, etc in them because they didn't have spaces in between. Is this ok or did you mean "words" as in a list of the function type, name, and the arguments not broken up like split(' ') did? Give an example of what you want the split-up line's list to look like.

shadwickman 159 Posting Pro in Training

I have some really bad ones (and consequently, the funniest) which I don't even think are appropriate to share here... told to me by none other than my uncle haha. I just don't want to get in trouble for posting them, but at the moment they're all I can think up, so I'll get back to this if I remember any others later :P

shadwickman 159 Posting Pro in Training

Firefox 3!
I just can't stand IE for the issues I get with it when writing stuff for the web. It always happens that IE buggers up something by implementing it in a non-standard way, which always complicates things.
And for this reason, I shall never show it any love :P

shadwickman 159 Posting Pro in Training

oh okay. Us Kiwis have it good then huh?

You don't have it good if you don't have that Adam's crunchy peanut butter!

shadwickman 159 Posting Pro in Training

You can just browse the SVN tree in your web browser like you would folders on your computer, and then open and view scripts/files in the browser. Or right-click and select "save link as" on them, or copy the code from the browser and save it in your text editor of choice.

shadwickman 159 Posting Pro in Training

The point is so that you can keep whatever changes you've made to a value. Like:

# double-up a string
def doubleUp(s):
    return s + s

a = "Hello world!"
a = doubleUp(a)
b = doubleUp(a)
print a  # should display  Hello World!Hello World!
print b  # should display  Hello World!Hello World!Hello World!Hello World!

If I just said s = s + s in the function, 'a' wouldn't be changed by saying doubleUp(a) as 's' is a variable in the local scope of the function. If I did this:

def doubleUp(s):
    s = s + s

a = "Hello World!"
doubleUp(a)
print a  # should display  Hello World!

As you can see in the second example, all we did was change the value of 's' inside the function, but a isn't changed because we did not return the value of 's' and assign it back to 'a'.
In C++ you could pass either by pointer or by value, but Python's way of passing is a bit more complicated...
Hope I clarified that!

shadwickman 159 Posting Pro in Training

Oh! That's a simple problem. Use the str object's strip() function. It removes all leading and trailing whitespace. Like this:

>>> a = " \t Hello World!\n "
>>> b = a.strip()
>>> b
'Hello World!'

As you can see, all spaces, tabs, newlines, etc. get removed. When you compare the indices in the list, strip each one first. Alternatively, you can strip each line with a list comprehension when you store the [icode]readlines()[/icode] lists like so:

line_list = [x.strip() for x in open("filename", "r").readlines()]

That way the lists get stored without any whitespace in their indices.

shadwickman 159 Posting Pro in Training

@XTRobot

I know your problem's solved, but I thought I felt like saying that I'd advise against using DevC++. I used to use it, but it's been dead since 2005, so I'd use something like GCC or CodeBlocks now to keep the compiler up to date.

shadwickman 159 Posting Pro in Training

Well, seeing as you didn't read this simple post about using code tags, your Python has no indentation. Brilliant. I'm not going to try to fix your code's indentation so that I can begin to help with your problem. If you can post it with those helpful tags around it, I'll take a look.

shadwickman 159 Posting Pro in Training

Sorry I think it will overwrite on print when its its callers prameters be like its own.or else print will call.
Is it true?

I believe you're thinking of overloading a function, like in C++. Python doesn't have that capability.

shadwickman 159 Posting Pro in Training

What do you mean, a single "filter" result? Filter returns a list... oh wait. Are you using Python 2.x, or are you using Python 3.0? If you are then filter actually returns an iterator. Anyways, what did you mean by "single result"?

shadwickman 159 Posting Pro in Training

Oh damn! I made a mistake there. That line should read:

c = filter(lambda x: x in b, a)

That's embarrassing haha... I typed that in wrong. the statement x in b just returns a boolean of whether or not value "x" is an item in list "b", basically "is x in b?". The "if" shouldn't be there because that starts to define a conditional statement. Sorry about that!

Anyways, lambda functions are just a way of declaring simple functions on-the-go without assigning a name to them.

shadwickman 159 Posting Pro in Training

You can try the built-in filter function. Here's what I tried in the interpreter:

>>> a = [
	'filter',
	'lol',
	'filter',
	'lol',
	'lol',
	'filter',
	'lol'
        ]
>>> b = ['filter']
>>> c = filter(lambda x: if x in b, a)
>>> c
['filter', 'filter', 'filter']

As you can see, it takes each item in the list passed to filter (in this case, "a"), and returns a list of the values that returned True in the function passed to it.
In this case, the lambda function would return True if the current item (x) is in list "b". I hope that simplified your code a lot :P

Here's a Dive Into Python links concerning filter, and lambda.

Nyaato commented: Thanks for helping! +1