woooee 814 Nearly a Posting Maven

I need to take the first name as the key and the other names in the first block as the values, ie, list of strings.

Adding to a dictionary is pretty straight forward (code is not tested)

first_name_dict = {}
f = open('profiles.txt', 'r').readlines()
for line in f:
    line = line.strip()
    print line
    if "," in line:
        line_as_list = line.split(',')
        if len(line_as_list) > 1:
            first_name = line_as_list[1].strip()
            last_name = line_as_list[0].strip()
            print "     ", first_name, last_name
            if first_name in first_name_dict:
                first_name_dict[first_name].append(last_name)
            else:
                first_name_dict[first_name]=[last_name]

print first_name_dict

Are members of the group the name before or after "Flying Club", etc. In any case you want to store the names in a list if there is a comma, and do something with that list when there isn't a comma in the record.

woooee 814 Nearly a Posting Maven

Some info on what you are trying to do
Reading Files
Lists and Dictionaries or http://www.diveintopython.net/native_data_types/lists.html and http://www.diveintopython.net/native_data_types/index.html#odbchelper.dict

See if this code helps get you started

f = open('profiles.txt', 'r').readlines()
for line in f:
    line = line.strip()
    print line

    if "," in line:
        line_as_list = line.split(',')
        if len(line_as_list) > 1:
            print "     ", line_as_list[1].strip(), line_as_list[0].strip()
woooee 814 Nearly a Posting Maven

Traceback (most recent call last):
File "compundids.py", line 13, in<module>
record = Entrez.read(handle)

There is something wrong with the read. Does your input file have any empty records? Add a print statement to print "line" before the error to see which record is causing this.

woooee 814 Nearly a Posting Maven

You don't check the last element, so possibly want to use

        for x in range(0,len(mylist)-1):
            ## don't compare "x" to itself and go to the end of the list
            for y in range (x+1,len(mylist)):

This will give you a count for each item, so you will get three different "3" counts. Since the list is sorted, you can store the number in a separate variable and compare this number with previous number and only count if they are different.

woooee 814 Nearly a Posting Maven

Dive Into Python has a good command line tutorial IMHO.

woooee 814 Nearly a Posting Maven

We don't have the code that creates "maze" so have no idea what kind of object it is, but you should access it the same way whatever the object.
if maze[row-1,col] == 'O' or 'F': --> this doesn't make sense to me and will always be "True"
if maze(row,col) == 'F': --> this implies that maze is a function

And you should test your code as you go along instead of trying to figure out what is wrong with 100+ lines of code.

woooee 814 Nearly a Posting Maven

I want to either figure out how to open the individual python files when I click on a button

That is too much code to go through, but you would include the "open the file" code in the call back function.

try:
    import Tkinter as tk     ## Python 2.x
except ImportError:
    import tkinter as tk     ## Python 3.x
#
def open_file():
    fp = open("./test_file", "r")
    for rec in fp:
        print rec
    fp.close()
#
## create a test file to open
fp = open("./test_file", "w")
fp.write("This is a test file\n")
fp.write("Second line")
fp.close()
#
root = tk.Tk()
tk.Button(root, text="Open a File", command=open_file).grid()
root.mainloop()
woooee 814 Nearly a Posting Maven

When I run the code, it results in this error

File "./test_1.py", line 110, in <module>
l,w=eval(input("Please enter length and width of room #"+str(x)))
TypeError: eval() arg 1 must be a string or code object

eval() is used to evaluate formulas or code so is not appropriate here and is generally considered bad practice as it will run anything that is entered i.e someone can enter a command to delete all of your files if they want to. Get the program to run first and then work on the room number problem. If you are using Python2.X (you didn't say) then input returns an integer so you can't separate the entries as that requires entering a non-integer character like a comma.

Formatting and concatenating strings http://www.diveintopython.net/native_data_types/formatting_strings.html
A Python2.x example

for i in range (5):
    x=x+1
    entry=raw_input("Please enter length and width of room ")
    l,w = entry.split(",")
    sum=sum+int(l)*int(w) 
woooee 814 Nearly a Posting Maven

the problem is when i click the vnc button, this app has own windows - for ask password and show messages like "unable to connect" - and this stay under the fullscreen main window.

You can use focus_set, i.e self.parent.focus_set(), self.password_entry.focus_set(). Start by reading this page

woooee 814 Nearly a Posting Maven

You call randomNumGenerator() twice, once in each of the two functions and so are working with two different values (althought it is possible to return the same value twice). If you are going to tutor then you should try to follow the Python Style Guide and stop using the half-camelCase naming convention.

Also, in this code

   for u in userPos:
       for r in randPos:
           if(u == r):
               if(userPos.index(u) == randPos.index(r)):
                    posCount = posCount + 1

index will only find the first letter's position so if you have multiples of the same letter it will not work as expected. In addition

for u in userPos:
       for r in randPos:
           if(u == r):

will compare "u" to every postion in randPos, so if there is only one "2" in userPos and 2 in randPos it will report two postions that are the same which is not true. You want to compare the first postions of both strings/lists, then the second postion of both, etc. Finally, why do you convert to a string in randomNumGenerator() and then convert it back to it's original form, a list, in the functions?

woooee 814 Nearly a Posting Maven

So how would I replace "-" with the correctly guessed letter

There are 3 containers here, the "secret word", the hangman list, and the letter quessed. You would iterate over the "secret word" and compare letters. If the letters match then replace the "-" at the same postion in the hangman list..

for position in range(len(secret_word)):
    letter = secret_word[position]
woooee 814 Nearly a Posting Maven

And have you or anyone else figured out how to post code without indenting every freakin line an extra four spaces?

# test using a comment to mark the beginning of the code---Doesn't Work

for choice in ["this sucks", "what was wrong with the original", "lucky your job doesn't depend on this"]:
print choice

woooee 814 Nearly a Posting Maven

When/it the stickys come back, let's start one for the undocumented new formatting options.

woooee 814 Nearly a Posting Maven

If you want to use split (and how do you post code that is not indented, like the following. If we have to add 4 extra space to every freaking line of code that we post, I'm finding a new forum)

test_line="Youngstown, OH[4110,8065]115436"

# your way
for item in test_line.split():
    print item
print


# a better way
test_list=test_line.split("[")
for item in test_list:
    print item
print test_list[1].split("]")
woooee 814 Nearly a Posting Maven

When clicking the "Edit" button on an existing post, you are presented with the post and just an "Edit Post" and "Cancel" button at the bottom, neither of which post the edited version. Is there a FAQ for the new methods? If not then there should be. Also posting a url link is now different for those reading this post. Click the "link" button and it will show that a combination of [noparse] [text] and (link) [/noparse] is now required.

woooee 814 Nearly a Posting Maven

Start by testing your functions. This is very basic stuff. So in the function "table", print tableString at the end. Also you should be getting a syntax error on this line
if name = 'main':

Try one of the many tutorials on the web. The correct way for "name = main" is towards the bottom.

woooee 814 Nearly a Posting Maven

For completeness, you can also use a dictionary

def F1(*args):
    if len(args) == 4:
        to_dict ={}
        to_dict["v"]=args[0]
        to_dict["u"]=args[1]
        to_dict["a"]=args[2]
        to_dict["t"]=args[3]

        for key in to_dict:
            print key, to_dict[key]     ## while testing
            if to_dict[key] == None:
                ## etc
woooee 814 Nearly a Posting Maven

Copied to preserve the code tags.

def program(List, Name, Detail):
    for entry in List:
        if entry[0] == Name:
            ## changed to add to the entry containing "Name" not 
            ## entry[1] as it is [Detail, Counter] so would become
            ## [Detail, Counter, [Detail_2, Counter_2]]
            entry.append([Detail,Counter])  ## "Counter" has not been declared
#-----------------------------------------------------------
#   return=You exit the function here if the name is found,
#   i.e. the following code is never reached and so is not
#   the problem
#-----------------------------------------------------------
            return
           
    List.append ([Name,[Detail]])
    for entry in index:           ## "index" is never declared
        if entry[0] == Name:
            entry[1].append(Counter)
woooee 814 Nearly a Posting Maven

I already did with the print statements in the first code snippet. Enter "ab" only so do don't get tons of output. Hint: the problem is caused by changing the list you are iterating over.

woooee 814 Nearly a Posting Maven

Looks good to me. hailstone() and maxLength() do the same thing so you should be able to use one function for both. Also, IsOdd would usually be formated like this

def isOdd(num):
    if num % 2 != 0:
        return True
    else:
        return False
#
#  or
 def isOdd(num):
    if num % 2 != 0:
        return True
 
   return False
woooee 814 Nearly a Posting Maven

In addition, the slow down also comes from using a list. Use a set or dictionary to store and lookup the id. It is something like 1000 times faster.

woooee 814 Nearly a Posting Maven

Usually import statements are at the beginning of the program, and you then call a function within the imported program.

import _level1


    elif choice in ['go north', 'Go north', 'Go North', 'n', 'N', 'north', 'North']:
        print " "
        _level1.function_to_run()
woooee 814 Nearly a Posting Maven

Receive the variables as a tuple and then use each item as your variable.

def test_num_variables(*args):
    print "number of variables =", args, type(args), len(args)
    os = -1
    if None in args:
        os=args.index(None)
        print "finding None =", os, args[os]
    else:
        print "None was not found"
        return

    ## assumes that the check for numbers has already been done
    total = 0
    for idx in range(len(args)):
        if idx != os:
            total += args[idx]
    print "adding test =", total

test_num_variables(1, 3, 5, None)
woooee 814 Nearly a Posting Maven

Your code looks like it should work fine. Post back if you run into further problems.

woooee 814 Nearly a Posting Maven
if maxLength(num) > MAXLEN:
                    MAXLEN = maxLength(num)
                    MAXNUM = num
            print ("\n%d has the longest chain of %d\n") % (MAXNUM, MAXLEN)

The maxLenth function does not process the number more that once because of the "return num" statement, so the largest number will always be at the end of the range. Is the return statement indented properly, and do you want to return num or length?

woooee 814 Nearly a Posting Maven

I need to find the records that contain duplicate <id> tags.

Which duplicate records do you want to delete, the first or last? In any case, with a 3GB file you probably want to iterate over the file one record at a time instead of trying to read it into memory. And just for clarity, we are assuming that one record group = from <tag> to </tag>, so you first want to store one record group and either save the id number and write the group to a file, or ignore the group if you want to delete it.

woooee 814 Nearly a Posting Maven

For future reference there isn't much response for someone who can solve there own problem with a few print statements. This will get you started but there are errors in your logic.

for x in Alpha:
    y = 25- count
    print "first x, y", x,y
    while x in I > 0:
        print "     second x-->replacing", I[I.index(x)], "with", Alpha[y]
        I[I.index(x)] = Alpha[y]
        print "     ", I
    count += 1
    continue
 
print(I)

Your code is bass-ackwards in that you want to iterate through the input and then find the letter in the a-z string, and it is usually better to append the new letter to a second list instead of replacing letters in a list that you iterate over.

from_input = raw_input("Enter message: ")
Alpha = "abcdefghijklmnopqrstuvwxyz"
 
for ltr in from_input:
    ## allow for capital letters
    ltr=ltr.lower()
    count = Alpha.index(ltr)
    y = 25- count
    print ltr, count, Alpha[y]
woooee 814 Nearly a Posting Maven

That can be a permission problem. Make sure that user has access to program file and the directory it is in.

woooee 814 Nearly a Posting Maven

i've managed to read in the file, and store it as a dictionary,

Probably not in the way you think. Print the dictionary and see what it contains. The dictionary key is the respondant's number, not the question number so at best you can count how many questions the respondant voted on, which is not what the question asked. There aren't many responses to this thread because the standard way to do this is with groupby

from itertools import groupby

test_data="""1 23 1
1 18 1
1 28 2
1 24 1
1 12 3
1 26 3
1 29 1
1 23 5
2 23 3
3 15 2
3 17 1 """
things=test_data.split("\n")

for group in groupby(things, lambda x: x[0]):
    for ctr, gen in enumerate(group):
        print ctr, list(gen)

but you will probably say that you can't use, or don't know how to use groupby. This might happen for the next solution as well, etc, etc.. So it is difficult to come up with a solution for someone who doesn't have any "count" code (and didn't even test the dictionary contents by printing it), i.e. putting each record into a dictionary is no different from reading each record from a file when it comes to counting something. Come up with a better solution, at least on paper, and code what you can and post back in a new thread with a better attempt.

woooee 814 Nearly a Posting Maven

Use a class and instance variables. You can call separate functions within the class using multiprocessing and they will all have access to the instance variables.

woooee 814 Nearly a Posting Maven

Also, you should check that numbers were entered on input and ask the use to enter again if there was an error. The program now will error out if you try to eval an entry that is not a number.

woooee 814 Nearly a Posting Maven

Use a list

some_dict={}
for key in ["a", "b", "a", "c", "c"]:
    if key not in some_dict:
        some_dict[key]=[]
    some_dict[key].append(key)

print some_dict
woooee 814 Nearly a Posting Maven

Assuming the data is correct (and I'm not sure it is), try something along these lines

name_list=['romney','santorum','gingrich','paul']
 
found=False
for item in big_list:
 
    if item[0] == "paul":
        found=True
    
    ## if another name then stop processing
    elif item[0] in ['romney','santorum','gingrich']:
        found=False

    if found:
        for word in item:
            if word in paul_dict:
                paul_dict[word]+=1
            else:
                paul_dict[word]=1
woooee 814 Nearly a Posting Maven

First, you use the button variable for 2 different things

button1=Button(win,Point(2.5,2.5),3,2,"Button 1")
    button1=1

It can't be both at the same time. Next, find a tutorial for the graphics module so you know how to spell the text widget, and how to add it to the window. Next, each of the if() statements for the buttons will print every time.

if button1==ans and button1.clicked(pt)==True:
            text(Point(5,2),"You win")
        else:
            text(Point(5,2),"You lose")

In the above, the else statement will be executed if button1 does not equal ans, or if button1 was not clicked, so it will execute if button2 or 3 is clicked. You want something more along the lines of

if button1.clicked(pt)==True:   ## don't execute if button 2 or 3 is clicked
            if 1==ans:
                text(Point(5,2),"You win")
            else:
                text(Point(5,2),"You lose")
#
#========================================================================
# You can use a for() loop to avoid redundant code
def main():

    win=GraphWin("Three button monte")
    win.setCoords(0,0,10,10)
    #win.setBackround("red")

    button1=Button(win,Point(2.5,2.5),4,2,"Button 1")
    button2=Button(win,Point(5,5),4,2,"Button 2")
    button3=Button(win,Point(7.5,7.5),4,2,"Button 3")
    button1.activate()
    button2.activate()
    button3.activate()
    quitButton = Button(win, Point(7,1), 3,2, "Quit")
    quitButton.activate()

    pt=win.getMouse()
    while not quitButton.clicked(pt):
        ans=random.choice([1, 2, 3])
#        button1=1
#        button2=2
#        button3=3
        for ctr, button in enumerate([button1, button2, button3]):
            if button.clicked(pt):
                if ans==ctr+1:
#            text(Point(5,2),"You win")
                    print "You win"
                else:
                    print "You lose", ans
        pt=win.getMouse()

    win.close()
        
        
main()
woooee 814 Nearly a Posting Maven

Print some of the details, like the date.

line_of_list = line.split()
        date_port = ' '.join(line_of_list[0:2])     ## month and day
        date_list = date_port.split(':')  ## no ':' in date_port

And has_key is deprecated so use "in" instead.

##        if desc_ip.has_key(ip_address):
        if ip_address in desc_ip:
woooee 814 Nearly a Posting Maven

Start with the simple basics; print big_list and make sure it contains what you think it does and is in the form you expect to be in. You can also add a print statement after
for item in big_list:
to print the item, but it is basically the same thing.

woooee 814 Nearly a Posting Maven

This should give you an idea. There is also a problem with get_code(). You should first test what you post as much as possible.

def decode(code_dict,message):
    coded_message = []
    for ch in message:
        if ch in code_dict:
            coded_message.append(code_dict[ch])
        else:
            coded_message.append(ch)
    print "".join(coded_message)

decode({"t":"x", "b":"y"}, "the quick brown fox")
woooee 814 Nearly a Posting Maven

From Ripley’s Believe It or Not!

St. Patrick, the Patron Saint of Ireland, was not Irish. He was a Frenchman. His real name was Succat, his father’s name was Calpurnius and his mother was a sister of St. Martin, the Bishop of Tours.

St. Patrick (385-461 A.D.) did not see Ireland until he was kidnapped by Irish Raiders! (he was sent to tend sheep as a slave at age 16)

The first celebration of St. Patrick’s Day in the U.S. was a dinner and a parade by The Charitable Irish Society of Boston, Mass., on March 17, 1737.

woooee 814 Nearly a Posting Maven

The else statement will execute for all input except 'n'. That includes upper case 'N'. You want something more along the lines of the following. Also, use a while statement to call the function multiple times. When level() calls itself you can reach the recursion limit.

choice = choice.lower()
    if choice in ['go south', 'south', 's']:
        print "You can't get through the trees to the south.\n"
        level()

    elif choice in ['go north', 'north', 'n']:
        import _level1
 
    else:
        print "I don't understand."
        print " "
        level()
HiHe commented: the way to go +5
woooee 814 Nearly a Posting Maven

There are two ways to do this.
1. Use a list of lists. The inner list contains the cut off grade and an int which is incremented each time a grade is found in each category. You can loop through the grades once and find the first grade in the inner list that is greater or equal to the actual grade and add one to the counter. So if you want to test for grades in the 50, 70, and 100 ranges, the initial list would contain [[50, 0], [70,0], [100, 0]] and each "0" would be incremented each time a grade is found in that particular range.

2. Pass a list and the particular target grade to a function. The function will iterate through the list and increment a variable/counter for each grade that is less than or equal to the grade passed to the function, otherwise the grade will be added to a new list. The counter and the new list will be returned from the function so the next target grade can be tested.

If you do not know how to do either of these then you do not know enough about Python to solve this problem.

woooee 814 Nearly a Posting Maven

The only time you can do multiple things at once is when you use a tool for that, like multiprocessing or parallelpython, otherwise you have to do things one at a time.

woooee 814 Nearly a Posting Maven

IMHO the only time to use the keyword "is" is when you want to test that 2 objects point to the same block of memory, otherwise you can get unexpected results. This is a simple example of equal returning a True and is returning a False for the same comparison.

x="abc"
y = "a"
print "is", x is y, x, y     ## False
print "==", x==y, x, y       ## False

y += "bc"
print "\nis", x is y, x, y   ## False
print "==", x==y, x, y       ## True
woooee 814 Nearly a Posting Maven

Thanks for both of these good solutions guys.

Also, woooee, why is using "i", 'I' and "O" bad?

They can look like numbers and you are interviewing, usually, with someone who is interested in code that can be easily maintained, so they don;t want anything that can be confusing. In fact single letter variables are not a good idea at any time. You should use something more descriptive, outer and inner, or row and col, etc.

woooee 814 Nearly a Posting Maven

First, test that row1 < row2 and the same for columns. Also you should test for them being in the correct range. Then you can iterate using a for loop for rows and a sub-loop for columns and this code assumes that "board" is a list of lists.

def is_occupied(row1, col1, row2, col2, board):
    if row1 >= row2:
        print "row2 must be greater than row1"       
        return -1

        ## or switch them
        row2, row1 = row1, row2

    if col1 >= col2:
        print "column2 must be greater than column1" ## or switch them
        return -1

    one_row = len(board[0])                  ## max value for row and column
    for num in [row1, row2, col1, col2]:     ## assumes a square board
        if not -1 < num < one_row:           ## must be 0-->9 if 10 rows and columns
            print "all rows and columns must be in the range 1 through 9"
            return -1

    for row in range(row1, row2+1):
        for col in range(col1, col2+1):
            square_to_test = board[row][col]
woooee 814 Nearly a Posting Maven

.join() is more efficient than string concatenation, so I would expect to see at least one join(). Also, don't use "i", "l", or "O" in an interview.

for outer in range(1,13):
    print '\t'.join(str(outer*inner) for inner in range(1, 13))
woooee 814 Nearly a Posting Maven

No, because we have no idea how big comp_board is and since you did not post the entire error message, no idea if the error message is actually in the code posted. Print x and y before the statement
str_print += "_%s_|" % (comp_board[x][y])
and compare to the dimensions of comp_board.

This code works, so the print statements are O.K. when the board dimensions are correct.

comp_board = [['o' for x in range(10)] for y in range(10)]
letters = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' ]
print "_____________________________________________"
print "|===|_0_|_1_|_2_|_3_|_4_|_5_|_6_|_7_|_8_|_9_|"
for x in range(0, 10):
    str_print = "|_%s_|" % (letters[x])
    for y in range(0, 10):
        str_print += "_%s_|" % (comp_board[x][y])
    print str_print
woooee 814 Nearly a Posting Maven

You have to know what you are coding before you can write the code. What solution are you trying to write. Just throwing code against the wall to see what sticks doesn't work. If you draw it out, it becomes somewhat clear.

Hint: it has to do with the length being odd or even.

woooee 814 Nearly a Posting Maven

You did not state any error so there is no question to answer. In Python we generally use the "in" operator instead of iterating. Also, sets will allow you to get the difference between string2 and string1 which is what you want.

# Pseudo code 

list_2 = []
for ch in "IamLearningPython":
    if ch not in string_2:
        add it to list_2
join list_2 and print
woooee 814 Nearly a Posting Maven

Data length is data length and will be the same no matter where you split. If you read one record at a time instead of the entire file it should not be a problem. More info is necessary though. What code are you using and how big is the file. In today's gigabytes of memory world, very few files are too large so it may also be something else that is causing the problem,

woooee 814 Nearly a Posting Maven

For starters you can almost always use a list or dictionary instead of many if/elif statements. Also, globals are not necessary for this problem and point to a lack of understanding.

## replace of of these if/elif with a list of lists
"""   
if amount = 4:
riskCode = 1
riskType = high
elif amount = 3:
riskCode = 2
riskType = moderate
elif amount = 2:
riskCode = 3
riskType = moderate
eif amount = 1:
riskCode = 4
riskType = low
elif amount = 0:
riskCode = 5
riskType = no
else:
riskCode = 0
riskType = 0
if amount = 4:
riskCode = 1
riskType = high
elif amount = 3:
riskCode = 2
riskType = moderate
elif amount = 2:
riskCode = 3
riskType = moderate
eif amount = 1:
riskCode = 4
riskType = low
elif amount = 0:
riskCode = 5
riskType = no
else:
riskCode = 0
riskType = 0
"""

def calc_risk(amount):
    """ associate the offset of a list to the amount,
        i.e. amount=0 --> risk_code_type[0]
    """
    risk_code_type=[[5, "no"], [4, "low"], [3, "moderate"],
                    [2, "moderate"], [1, "high"]]
    risk_code=0     ## defaults for amount < 0 or amount > 4
    risk_type=0
    if 0 <= amount <= 4:
        code_type = risk_code_type[amount]
        ## print for testing
        print "sub-list for amount=", amount, code_type        
        risk_code=code_type[0]
        risk_type=code_type[1]

    return risk_code, risk_type

for amount in [-1, 0, 1, 2, 3, 4, 5]:
    rcode, rtype = calc_risk(amount)
    print "amount=%d, risk code=%d, risk_type=%s" % (amount, rcode, rtype)
#
#---------- you can also use 2 lists --------------------------------------
print "-"*50

risk_code=[5, 4, 3, 2, 1]
risk_type=["no", "low", "moderate", "moderate", "high"]
amount=2
print "risk code =", risk_code[amount]
print "risk type =", risk_type[amount]