woooee 814 Nearly a Posting Maven

See this post. If you're not in the same class and have a different problem, post back with the differences.

woooee 814 Nearly a Posting Maven

Well?? What happend to the code? Code to, say, find the lowest divisor to start?

My quick and dirty solution, so I can delete this code.

def find_divisor(input_number):
    sq = int(input_number**0.5) + 1
    print("-->sq for %d = %d" % (input_number, sq))
    for ctr in range(2, sq+1):
        if 0 == input_number%ctr:
            return ((ctr, input_number/ctr))
    return((input_number, 1))

# 252 = 2*2 * 3*3 * 7*1
input_number = 252
divisors = []
found = True
while found:
    ## hey baby, nice pair (of numbers)
    smaller_1, larger_1 = find_divisor(input_number)
    print(smaller_1, larger_1)

    ## do again for the second (larger) number of the pair found
    if smaller_1 != input_number:      ## divisor found
        smaller_2, larger_2 = find_divisor(larger_1)
        print("     ", smaller_2, larger_2)
        divisors.append((smaller_1, smaller_2))
        input_number = larger_2     ## larger number of the 2nd pair
    else:              # no divisor=(original_number and 1)
        ## eliminate (1,1); a number like 6 will return (2, 3) and (1, 1)
        if smaller_1 != 1:    
            divisors.append((smaller_1, larger_1))
        found = False 
            
print(divisors)
woooee 814 Nearly a Posting Maven

Post the code as it is now. Note that you should now be using a tuple, so code has to be changed, like this example:

# pick one randomly from the sequence
word_tuple = random.choice(words_and_hints)
 
# create a variable to use later to see if the guess is correct
word = word_tuple[0]
correct = word
woooee 814 Nearly a Posting Maven

Well?? What happend to the code? Code to, say, find the lowest divisor to start?

woooee 814 Nearly a Posting Maven

Start with the smallest divisor, 2; see if it is a divisor and increase up to the square root + 1. So in this case
252 / 2 = 126
So 2 is a divisor. Then using 126 (divide by 2 up to square root 126 + 1)
126 / 2 = 63 -----> 2*2
Using 63
63 / 2 = False
63/3 is a divisor = 21
21 / 2 = False
21 / 3 = 7 (square root + 1 = 3)
and repeating the process yields no other divisors --> 1
You could use recursion for this, but I don't like recursion so would suggest a while loop. Come up with some code to start us off. I did a sloppy quick try using a while loop to call a function and came up with 25 lines of code.

woooee 814 Nearly a Posting Maven

To get you started if you want to roll your own, you would iterate over each character and append to a list unless the character is one of the dividers. If it is a divider, you would join and append the sub-list to the final list, initialize sub-list as an empty list, and continue appending until the next divisor.

woooee 814 Nearly a Posting Maven

What happens if the first "Steve" is 7 instead of 1 -----> , , ], etc. Should it be at the end of the first list or at the end of all of the items? Generally, you would flatten the list and then sort if all items are to be sorted equally.

import itertools
import operator

r =[[['steve',7, 40], ['steve',3, 20], ['steve',2, 30]],
    [['john',5, 50], ['john',6, 40], ['john',4, 30]]]

r_flat = list(itertools.chain(*r))
r_flat.sort(key=operator.itemgetter(1))
print r_flat
#
#output =[['steve', 2, 30], ['steve', 3, 20], ['john', 4, 30], 
#         ['john', 5, 50], ['john', 6, 40], ['steve', 7, 40]]
vegaseat commented: fine observation +13
woooee 814 Nearly a Posting Maven

I must fix a code so I can write roman letters (bigger than 3999)

For Arabic, if it is larger than 3999 subtract 1000 and add 1000 to a separate field until it is less than 4000. You would then divide the "thousands" field by 1000, convert and print with parentheses, since 4000=(IV). Do the reverse for Roman, i.e. convert then parens to Arabic and multiply by 1000, then add to the rest of the number.

woooee 814 Nearly a Posting Maven

Rolling your own is the best way to go. Alternatively you could replace "?" and "!" with "." and split on the period, but that requires many loops through the file.

woooee 814 Nearly a Posting Maven

You are going to have to store the widgets in a list or dictionary to do that, and tell remove() which one you want to delete. The following is a program that shows how to associate a button to a specific dictionary member by binding a unique instance of the function handler() to each button. You would use a function like cb_handler to destroy the appropriate widgets. You might also consider using a separate frame for each widget group and then destroying the single frame. Note that since you use the same variable for all widgets, self.l_host, etc. always contains the last widget created.

from Tkinter import *

class ButtonsTest:
   def __init__(self, top):
      self.button_dic = {}
      top.title('Buttons Test')
      self.top_frame = Frame(top, width =400, height=400)
      self.buttons()
      self.top_frame.grid(row=0, column=1)
      exit = Button(self.top_frame, text='Exit', command=top.quit).grid(row=10,column=1, columnspan=5)

   ##-------------------------------------------------------------------         
   def buttons(self):
      b_row=1
      b_col=0
      for j in range(1, 11):
         self.button_dic[j] = "self.cb_button_%d()" % (j)
         b = Button(self.top_frame, text = str(j))
         b.grid(row=b_row, column=b_col)

         def handler ( event, self=self, button_num=j ):
                return self.cb_handler( event, button_num )
         b.bind ( "<Button-1>", handler )

         b_col += 1
         if b_col > 4:
            b_col = 0
            b_row += 1

   ##----------------------------------------------------------------
   def cb_button_1(self):
      print "push button 1 and this code is executed"

   ##----------------------------------------------------------------
   def cb_button_2(self):
      print "push button 2 and this code is executed"

   ##----------------------------------------------------------------
   def cb_button_3(self):
      print "push button 3 and this code is executed"

   ##----------------------------------------------------------------
   def cb_handler( self, event, cb_number ):
      print "cb_handler", cb_number, self.button_dic[cb_number]                
      if cb_number < 4:
         exec(self.button_dic[cb_number])

##===================================================================
root = Tk()
BT=ButtonsTest(root)
root.mainloop()
woooee 814 Nearly a Posting Maven

Read up on accessing a list by the index 10.2 Lists are mutable, here, as well as the writing or updating comments in 10.3. Initialize a list (using a for loop to append zero each time) so it has one element equaling zero up to the maximum number+1. Under a new loop, generate a number using randint. The number will correspond to the list. So if the number is 5, add one to element #5 of the list, etc. I can't do it for you, but post back with code for any part that isn't working.

woooee 814 Nearly a Posting Maven

trying to do it with a while loop

Post your code so we have something to comment on. Also, using a dictionary or list is separate from the for() or while() loop.

woooee 814 Nearly a Posting Maven

Do you want to take each record and print it as a column under the heading?

woooee 814 Nearly a Posting Maven

Search for something like geometry in Tkinter's winfo, which you would have to call at the time the first window closes. I've never done anything like this so am not sure if it will work or not, so post back with any success or failure for future question.

woooee 814 Nearly a Posting Maven

You should sort both words and compare. Your code will compare "a" to "aa" and find them equal. Note that any anagram program will take "odg" and return "god" and "dog" which is all it can do.

infile = open ("/usr/share/dict/american-english", "r")
## "dict" is a reserved word
words_in = infile.readlines()
 
scrambled = raw_input("Enter the scrambled word: ")
scrambled = scrambled.lower()
scrambled_list = list(scrambled)
scrambled_list.sort()

for word in words_in:
    word_list = list(word.strip().lower())
    word_list.sort()
    ## you don't really have to compare lengths when using lists as the
    ## extra compare takes about as long as finding the first difference
    if word_list == scrambled_list:
        print word, scrambled
woooee 814 Nearly a Posting Maven

I don't understand your point, unless it is to shorten the number of keystrokes for some reason.

condition = 'False'
if condition == 'True':
    print 'Condition True'
else:
    print 'Condition False'
woooee 814 Nearly a Posting Maven

There is no real difference:

if condition == True:
if condition == "True":
woooee 814 Nearly a Posting Maven

I get a result of an integer 1 - 5, say 3 - I would then like the script to tell me what string is assigned to it, in this case 'a'...

Except that no one realized that the dictionary is bass-ackwards.

ltr_dic = {1: 'a',
           2:'a', 
           3:'a', 
           4:'b', 
           5:'c'}
# ~ insert process here ~
# number 3 returned
x = ltr_dic[3]
print x
for x in range[1, 6]:
    print x, ltr_dic[x]
woooee 814 Nearly a Posting Maven

How to start programming is not within the scope of most forums. Start with a tutorial
http://www.pasteur.fr/formation/infobio/python/ch11s02.html
http://www.freenetpages.co.uk/hp/alan.gauld/tutloops.htm
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
We can and will help with code that is formated properly but does not function as expected.

woooee 814 Nearly a Posting Maven

To emphasize what Tony said:

actorNode = findNode(graph,actorName)
        if actorNode == None:
            actorNode = mkNode(actorName)
            print "created", actorNode
            graph.append(actorNode)
            print "graph", graph

You want to test each function individually before going on to the next function, or you have 56 lines of code to debug and no idea what the problem is.

woooee 814 Nearly a Posting Maven

what happens if someone enters an "X" or any letter other than "N".
yet,
because my current code is not working.

You don't want all of the code under the
if (d == 'N'):
loop. Instead try something like this:

# player=1 --> computer
# player=2 --> human
player = 2
if (d == 'N'):
    player=1

winner = False
while not winner:
    print "Getting choice for player", player
etc.
woooee 814 Nearly a Posting Maven

This is a tic-tac-toe program that I coded some time ago. I doubt you will be able to use much of it, but it illustrates how much simpler it is when you break everything up into small pieces.

import random

class TicTacToe:
   def __init__(self):
      ## 0=No winner,      1=Player #1 wins,
      ## 2=Player #2 wins, 3=Tie
      self.winner = 0

      self.board = [0, 0, 0, 0, 0, 0, 0, 0, 0,]
      self.num_moves = [0, 0, 0]
      self.player = 1
      self.win_combos = (set([0, 1, 2]),
                         set([3, 4, 5]),
                         set([6, 7, 8]),
                         set([0, 3, 6]),
                         set([1, 4, 7]),
                         set([2, 5, 8]),
                         set([0, 4, 8]),
                         set([2, 4, 6]) )
      self.play_a_game()

   ##-----------------------------------------------------------------
   def play_a_game(self):
      while not self.winner:
         self.num_moves[self.player] += 1
         ##  a list of all squares not occupied
         squares_to_choose = [ctr for ctr, square in enumerate(self.board) \
                              if square==0]
         print "Choose from", squares_to_choose
         ##  choose a random available square
         square = random.choice(squares_to_choose)
         print("---> player %d occupies %d" % (self.player, square))
         self.board[square] = self.player
         self.print_squares()

         winner = self.we_have_winner()
         if not winner:
             self.tie()
 
         self.player = [0, 2, 1][self.player]

   ##-----------------------------------------------------------------
   def print_squares(self):
      for row in range(0, len(self.board), 3):
         for col in range(3):
            print self.board[row+col],
         print

   ##-----------------------------------------------------------------
   def tie(self):
     if 0 not in self.board:
         self.winner = 3
         print("Tie, you kissed your sister")

   ##-----------------------------------------------------------------
   def we_have_winner(self):
       """ extract all of the squares occupied for this player into 
           a set and check if it has a winning combo as a subset
       """
       moves = set([ctr for ctr, person in enumerate(self.board) \
                    if person==self.player])
       for win_combo in self.win_combos:
          if win_combo.issubset(moves):
               self.winner = …
woooee 814 Nearly a Posting Maven

I think the problem may be that you are not entering "N" for the "do you want to go first" question as you have an infinite while loop, and not one the doesn't repeat. The main problem with this code is that you have 54 lines of code that have not been tested. Take Tony's style, and some of his code, and start with a function to get the input. Check for a valid entry = an unoccupied row or column, and test it before going further (right now, you can enter 10 for the row and it will not catch it but will instead error out at "while (m[a]!='__'): )". Keep your functions short and sweet and you won't be confused. A maximum of 10 to 20 lines makes them easy to test and debug. Next on the coding list is a function to generate the computer's choice. After that is one function to fill the space chosen. You can pass "X" or "O", and the coordinates to the same function and use the same code for either, and test that function. Hopefully you get the idea.

woooee 814 Nearly a Posting Maven

See geometry strings here. "Geometry" sets the size and location of a widget.

woooee 814 Nearly a Posting Maven

Do I have to make the columns go from int to str?

No, use a tuple, as in my previous post, which can contain a mix of strings and integers. And comparing integers is usually superior to comparing strings, so if record[1] is an integer for example, the tuple would be built with
key1_tuple = (record[0], int(record[1]), record[2])

it takes the program forever to run. Any ideas on how can I make it more efficient?

Comparing tuples should be faster, but disk I/O is usually the time waster. Take a look at Parallel Python if you are on a multi-core machine. It seems pretty straight-forward.

woooee 814 Nearly a Posting Maven

i dont know how to make it produce 2d movements

If you have an graph with an x and y axis, you can advance in a postive or negative direction for either axis. To keep it simple, point 1=(3,1) for x and y, point 2=(-3, 2) for x and y, etc., so you have to change both x and y for 2D movements. You appear to be changing x only.

y
            2  |
               |  1
x -------------+-------------------
               |
woooee 814 Nearly a Posting Maven

Code this one step at a time. So first, get the input and check that it is indeed 'r', 'p', or 's'. Then generate a random choice for the computer, etc. BTW you have a lot of redundant code in this function.

def play_RPS(x, num_games):
    print 'Press q at any time to quit'
    text=''
    while text!='q':
        text=raw_input("Please choose rock(r), paper(p), or scissors(s):")
        if text=='q':
            print "Thanks for playing!"
            break 

        if text not in ['r', 'p', 's']:
            print "incorrect letter entered"
        else:
            random_throw=random.choice(x)
            num_games += 1
            return random_throw, num_games

    return "*", num_games


##----- the rest of the code repeats the same thing
        elif text== 'r':
            random_throw=random.choice(x)
            print random_throw 
        elif text=='s':
            random_throw=random.choice(x)
            print random_throw
        elif text=='p':
            random_throw=random.choice(x)
            print random_throw
        else:
            print "Invalid input!"]
woooee 814 Nearly a Posting Maven

"i" and "j" (terrible names for variables, "i" can look like a one, and neither is descriptive) still have the newline character from the file, so you want to strip them.

print i.strip(), j.strip()
##
##   also, eliminate the multiple splits
for i in f1line:
    split_i = i.split()
    for j in f2line:
        split_j = j.split()
        if (split_i[0] == split_j[0]) and (split_i[1] == split_j[1] and \
           (split_i[2]==split_j[2]):
            print i.strip(), j.strip()
#
#     or you can use a loop, which may be easier to read
#
for i in f1line:
    split_i = i.split()
    for j in f2line:
        split_j = j.split()
        match = True
        for k in range(0, 3):
            if split_i[k] != split_j[k]:
                match = False
        if match:
            print i.strip(), j.strip()
woooee 814 Nearly a Posting Maven

You have to iterate through the entire array, whether you write you own or use a built in method. Since you also want the max also, go through the array once, storing any number that is larger than the current maximum, along with it's position.

woooee 814 Nearly a Posting Maven

I works fine on my Slackware system. Try it with just "gnome-terminal". You may have to pass "shell=True" depending. Also, are there any error messages as it should kill the subprocess or report some kind of error. Finally, try it split into two lines, although that shouldn't matter

proc1 = subprocess.Popen(args=["gnome-terminal"], shell=True)
os.kill(proc1.pid, signal.SIGTERM)
woooee 814 Nearly a Posting Maven

You can use a tuple of the first 3 columns as a dictionary index.

f_list=open(sys.argv[1]).readlines()

## you can use a set or dictionary
unique_dic = {}
for rec in f_list:
    sub_str = rec.split()
    key = (sub_str[0], sub_str[1], sub_str[2])
    if key not in unique_dic:
        unique_dic[key] = 1

for rec in open(sys.argv[2]):
    sub_str = rec.split()
    key = (sub_str[0], sub_str[1], sub_str[2])
    if key in unique_dic:
        print rec
woooee 814 Nearly a Posting Maven

I use os.kill(), but some of these are OS dependent and Python version dependent. Take a look at Doug Hellmann's examples for starters.

woooee 814 Nearly a Posting Maven

You are continually drawing one oval on top of another, so Tkinter has to keep track of more and more widgets, not to mention that you could reach the recursion limit. Change the color instead. This code is a little crude, but I don't have any time right now.

import time
from Tkinter import *

def change_color(canvas, ov, color):
    print "color =", color
    if color == 'blue':
        color = 'yellow'
    else:
        color = 'blue'
    canvas.itemconfig(ov, fill=color)

    return color

root = Tk()
root.title('Canvas')
canvas = Canvas(root, width=200, height=200)

color = 'black'
ov=canvas.create_oval(10,10,50,50, fill=color)
canvas.pack()

root.update_idletasks()
for x in range(5):
    time.sleep(1.5)
    color = change_color(canvas, ov, color)
    root.update_idletasks()

root.mainloop()
woooee 814 Nearly a Posting Maven

Not recursion, but proof of concept only (and done quickly). Returns zero if it is a palindrome.

def ispalindrome(pal): return sum([0 if x == pal[(ctr+1)*-1] else 1 for ctr, x in enumerate(pal) if ctr < len(pal)/2])

sentence = "Red Roses run no risk, sir, on nurses order."
sentence_clean = ''.join(c.lower() for c in sentence if c.isalpha())
print ispalindrome(sentence_clean)
print ispalindrome("abcdef")
woooee 814 Nearly a Posting Maven
for lines in textf:
    if ask in textf:

Print "textf" before the "if" statement so you know what you are testing. Using logic like this, entering a word like "the" will find "the", "then, "either", etc. You might want to split the file input into words and check for equal condition with "ask".

woooee 814 Nearly a Posting Maven

but it is obvious I'm too dum to learn

or to use a spell-checker. Converting from one data type to another is called "type casting", so to an integer would use int().

str_list = ["1", "3", "5"]
for x in str_list:
   print x, type(x)
print
int_list = [int(x) for x in str_list]
for x in int_list:
   print x, type(x)
woooee 814 Nearly a Posting Maven

Indentation is covered in the style guide. Most IDEs will also auto-indent according to python standards when editing a ".py" file.

woooee 814 Nearly a Posting Maven

Yes, both can be done. You would use a for() loop to traverse the strings, or convert to a list, in both cases.

woooee 814 Nearly a Posting Maven

Generally, an IDE has a "convert tabs to spaces" option which takes care of this, and I show tabs in lines 11 and 12.

woooee 814 Nearly a Posting Maven

Generally you pass as arguments like this simplified code:

## program run.py
def print_args(name, passwd):
   print name
   print passwd

## calling program
import run
input_name = raw_input("Enter name ")
input_passwd = raw_input("Enter password ")
run.print_args(input_name, input_passwd)
woooee 814 Nearly a Posting Maven

Read about conditional statements here.

woooee 814 Nearly a Posting Maven

whenever i add in line "n = fin.readline()", i get an Mixed Iteration variable error:

for line in fin:
and
n = fin.readline()
do the same thing. Choose one or the other. You can also do a
for line in open("constitu.txt"):
(is the same thing) as well. Also, a hint below. And note that punctuation will be included in the word length if you don't remove it.

def main():
    splash()
    wordTotal = 0
    longestWord = 0
 
    fin = open("constitu.txt")
 
    for line in fin:
         #n = fin.readline()
        wordLine = line.split()
        ##------------------------------------
        for word in wordLine:
            print len(word), word, len(word) > longestWord
        ##------------------------------------
        #word = wordLine.split()
        wordTotal += len(wordLine)
         #if len(word) >= 15:
             #longestWord += 1
             #print word
woooee 814 Nearly a Posting Maven

See this link. The same question (summing items) was asked 2 days ago.

woooee 814 Nearly a Posting Maven

There is an error here (from the original code) so use add.lower() instead:

elif add == 'y' or 'Y':
#     This breaks down into
    elif add == 'y'
# or
    elif 'Y'     #which is always true
woooee 814 Nearly a Posting Maven

1) Choose a title that will get people to read the question
2) Sort the list and replace the first 5 numbers with the last 5

woooee 814 Nearly a Posting Maven

You enter all of the values each time so they would be whatever was entered for each while() loop. Note that if something other than "y" is entered for trimming and wastage, the total will not be calculated. It is simpler to read the code if it is in the following form:

if add != 'y' and add != 'Y':
#
#     use instead
    if add.lower() != 'y':
#
#     or
    if add in ['y', "Y"]:
#
# 
    trim_waste = 0.05
    add = raw_input('Add 5% for Trimming and Wastage? (Y/N): ')
    print "\n-------------------------\n"
    if add.lower() != 'y':
        trim_waste = 0.0
    last = total + (total * trim_waste)
woooee 814 Nearly a Posting Maven

See this link for the same question.

woooee 814 Nearly a Posting Maven

But i want the file to call out the numbers, instead of a list

If you can't print a simple list, then you want to start at the very beginning, since counting is more complicated than printing (which is a simple loop). Some links to on-line books
http://www.greenteapress.com/thinkpy...tml/index.html
http://diveintopython.org/toc/index.html
(see "Beginner's Guide" and "Python Books") http://wiki.python.org/moin/

woooee 814 Nearly a Posting Maven

Duplicate post deleted. This seems to be duplicate post day.

woooee 814 Nearly a Posting Maven

The easiest way is to use Python's count() function (and then test for a result > 0) for smaller groups of numbers. Some info on using lists. A list can also be used by element or index number. Element[0] = the number of zeros found, element[1] = number of ones, etc. which can then be multiplied by the element/index number to get the result. You can also use a dictionary, with the key equal to the number, pointing to an integer that counts the number of times the number appears.

number_list = [5, 3, 11, 3, 7, 3, 5, 5, 11, 7, 7 ]
for num in range(12):
    print "%d:%d:%d" % (num, number_list.count(num), num*number_list.count(num))