woooee 814 Nearly a Posting Maven

The first thing you have to do is to store the points (usually in a list). Then calculate m. Σxiyi = sum of the xy products, and Σxi^2 = sum of the x's squared. There are many pages explaining regression lines on the web. If you aren't sure how to calculate m then calculate it in more than one way and provide an answer for each one, since this isn't a math class. That is not the formula that one usually sees for a regression line but it may have been simplified for purposes of the program.

woooee 814 Nearly a Posting Maven

There are so many (tax) breaks that 45 percent of U.S. households will pay no federal income tax for 2010, according to estimates by the Tax Policy Center, a Washington think tank.

woooee 814 Nearly a Posting Maven

This is not clear:

if x == 'a' or x == 'b' and y == 'z':

It should be:

if (x == 'a' or x == 'b') and y == 'z':
#
# or
if x == 'a' or (x == 'b' and y == 'z'):
#
# or better yet
if y == 'z' and x in ['a', 'b']:
#
# "or" is the same as if(), elif()
# if x == 'a' or (x == 'b' and y == 'z'):
if x =='a':
elif x == 'b' and y == 'z':
#
# "and" is the same as nested if() statements
x = 'a'
for y in ['w', 'z']:
    if x == 'a' or x == 'b':
        if y == 'z':         ## x=='a' and y=='z'
            print(y, 'OK')
        elif y == 'w':
            print(y, 'OK2')  ## x=='a' and y=='w'
woooee 814 Nearly a Posting Maven

It depends on which version of Python you are using as x could be a string or an integer so print the type().

x = input('write something: ')
    print type(x)
assert("1"==1), "Not equal"

And don't use tabs to indent as the tab can be set to anything on any computer, so is not the same as yours.

woooee 814 Nearly a Posting Maven

Note that the variables in the original post are set to the value of lowercase "o" but the principle is the same. Another example of why not to use it as a single letter name. You could also use a list of 81 elements, ignoring the [0] element, although the dictionary is more straight forward.

element = 69
r,p = divmod(element, 4)
print "r=%d, p=%d" % (r, p)

print "element =", r*4+p
woooee 814 Nearly a Posting Maven
frame_top=Frame(root,name='frame_top')
frame_top.pack()
 
name_label = Label ( frame_top,text='Name' )
name_label.grid(row = 1, column =0)

You can not use both grid() and pack() in the same program. See the Warning here, and then pick one or the other.

woooee 814 Nearly a Posting Maven

To associate name and score you would use a list, tuple or dictionary of pairs, so as to keep them together. The name and score that you print do not necessarily go together. The Python sorting HowTo is here.

import operator

name_score = []

## example data
name = "Joe"
score = 5 
name_score.append([name, score])

name = 'Steve'
score = 2
name_score.append([name, score])

name = 'Mike'
score = 7
name_score.append([name, score])

print name_score

name_score.sort()   ## in name order
print "\nname order", name_score

## itemgetter[1] = memory offset X 1 = second item = score
score_sorted = sorted(name_score, key=operator.itemgetter(1))
print "\nscore order", score_sorted
e-papa commented: Thanks +1
woooee 814 Nearly a Posting Maven

i don't understand

That's because you don't know what the program is doing, so add some print statements, for example:

def get_k(data):
    print "get_k data", data
    for k in data:
        print "testing", k
        return k

Also, both functions are the same so eliminate one of them, and it is not obvious what you are trying to do, so if you add a description to the function we can tell what it is supposed to do and perhaps have more to say.

woooee 814 Nearly a Posting Maven

Easter eggs dyed and inscribed with a person's name and birth date were honored in courts of law as birth certificates in Germany.

In Czechoslovakia during Easter week it’s good luck to beat your wife or the girl you fancy with a pomlázka, or a braided whip. While this may sound strange It’s not meant in a demeaning way or as an insult, in fact pomlázka, means “make young.” The idea behind the tradition is that anyone hit with the whip will be healthy and happy during the upcoming year.

A Seattle school has renamed Easter Eggs because of political correctness. They are now "Spring Spheres". That's not even a decent name.

woooee 814 Nearly a Posting Maven

I would use multiprocessing. See Doug Hellmann's "Signaling between processes with event objects" here. In multiprocessing, you can also use a dictionary or list to store a value. Some examples, plus see "shared namespaces" here. Start with running two processes and then add in the variable.

vegaseat commented: good info +13
woooee 814 Nearly a Posting Maven

Line 41 = Line 32 in your code. It is an infinite loop;

while channels < prevchannels:
    randint(0,15)

Also the variable "channels" has not been defined for the findchannel scope.

def findchannel(state):
    if state==1:
        prevchannels=channels <--- channels not yet defined

I would suggest that you add a test function to test each function as there are other errors. You will get scope errors because variables have not been declared in many functions as well as from those function calls. Test the code and get it to the point where it will at least run and then post back with the test results that are incorrect, or the __complete__ error message if there is an error.

woooee 814 Nearly a Posting Maven

Please mark this thread "Solved".

woooee 814 Nearly a Posting Maven

Is python int by default a 32 bit- signed int?

Python uses the system's, so 32 bit on a 32bit system and 64 bit on a 64 bit system. Note that there is no difference in length between a signed integer and an unsigned integer. A signed integer just uses one of the bits as a sign, so an 8 bit unsigned can store 0-->255, and an 8 bit signed -127-->127 because one bit is used as a sign.

There is bitstring, bitbuffer and bitarray, Also, check PyPi for existing packages whenever you run into a problem like this .

woooee 814 Nearly a Posting Maven

The answer depends on what OS you are running, but hopefully all OS's won't let you determine anything for any other user, especially root, except if you are already root. So the only way you can determine if there is a different user is if you run the program as root (or su, sudo, etc.).

woooee 814 Nearly a Posting Maven

recreate the script from class

We don't have the script from class and don't do your homework for you.

Anyone up for this coding challenge? I'm interested to see who can get the code the fastest

That's just calling us stupid.

Ezzaral commented: Agreed. +14
woooee 814 Nearly a Posting Maven

You should probably ask this on the Qt forum as this doesn't have anything to do with Python. I would suspect, but don't have any idea, that it has to do with the 2 separate installations for the two versions of Python.

e-papa commented: Thanks +1
woooee 814 Nearly a Posting Maven

Your picker code
word = picker(picker(combine))
first picks a tuple, then a word from the picked tuple. While this works, our "debug sensors" were alerted as this would not be obvious down the road when someone is debugging the code. A more accepted version is to combine all of the tuples and pick a random word from the combination by calling picker() once.

terms = ('designing', 'programming', 'development', 'analysis', 'coding')
company = ('Microsoft', 'IBM', 'Apple', 'Intel', 'Google', 'AMD', 'DELL')
language = ('Java', 'Ruby', 'Python', 'Jython', 'Javascript', 'Perl', )
sub_systems = ('software', 'hardware')
inventor = ('Gates', 'Jobs', 'yang', 'Torvalds', 'filo')
combine = terms + company + language + sub_systems + inventor
print combine
woooee 814 Nearly a Posting Maven

I thought you wanted a goose (but it won't come from me). Why do you call "picker" twice?

def run():
    """this function runs the program"""
    word = picker(picker(combine))

Also, you can reach the maximum recursion level since run() calls decision() which calls run(), etc. And there is more recursion in decision()

def decision():
    """prompts user for decision after program execution"""
    decide = input('Do you want to try again (Y/N)')
    decide = decide.upper()
    if decide == 'Y':
        run()
    elif decide == 'N':
        quit()
    else:
        print('It\s either Y or N')
        decision()
#
#--------------------------------------------------------------------
    decide = input('Do you want to try again (Y/N)')
    decide = decide.upper()
    while decide not in ["N", "Y"]:
        print("It's either Y or N")
        decide = input('Do you want to try again (Y/N)')
        decide = decide.upper()
    return decide  ## to run, decide is now "N" or "Y"

Then return the "decide" variable to run(), which will use it to test a while loop for "Y".

woooee 814 Nearly a Posting Maven

When a tree falls in the woods and nobody hears it, does it make a sound? If you don't know how old you really are, are you old?

woooee 814 Nearly a Posting Maven

You can easily convert a date to a datetime object. I would suggest a function which you pass the date, shelf life, and date entered by the user. There are timedelta examples in the docs. Also, datetime objects can be subtracted from each other and can be compared (datetime_1 <= datetime_2). For additional help, post back with the function that does this as reading the file, creating the dictionary, etc. does not affect this part of the code.

now = datetime.date(2003, 8, 6)
difference1 = datetime.timedelta(days=1)
difference2 = datetime.timedelta(weeks=-2)

print "One day in the future is:", now + difference1
#=> One day in the future is: 2003-08-07

print "Two weeks in the past is:", now + difference2
#=> Two weeks in the past is: 2003-07-23
woooee 814 Nearly a Posting Maven

I would use 2 comboboxes and 2 buttons. Of course each of the buttons will be bound to different functions. Post some code for additional help.

woooee 814 Nearly a Posting Maven

You have to use the absolute or full path.

##--------------------------------------------------------------------
def get_files(parent):
    files_list = os.listdir(parent)
    for a in files_list:
        full_name = os.path.join( parent, a )
        if os.path.isdir(full_name):
            get_files(full_name)
        else:
            print full_name

get_files("/home")
woooee 814 Nearly a Posting Maven

You do not have an instance of the class "inv" so the program will not run as is. Especially, see the "To create a Point" part here, which explains instantiation. You would pickle.dump and pickle.load the list "inventory". I would strongly suggest that you print it as you go along as it may or may not contain what you think. Start with the add function only, and __test__ the code by adding and printing, then add in the next function. Also, option 6=exit should change the while loop's variable and not use a SystemExit.

while con==1:
    print("What would you like to do?")
    decl()
    dec=None
    while not dec in range(1,7):
        try:
            dec=int(input("<1-6>: "))
            if not dec in range(1,7):
                 print("Enter a number between 1 and 6")
        except ValueError:
            print("Enter a number between 1 and 6")
    
    if dec==1:
        inv.add(inventory)
    if dec==2:
        inv.remove(inventory)
    if dec==3:
        inv.empty(inventory)
    if dec==4:
        inv.visrep(inventory)
    if dec==5:
        inv.save(inventory)
    if dec==6:
        con = 0
#        import sys
#        raise SystemExit
woooee 814 Nearly a Posting Maven

What is the purpose of this code? If it has a legitimate purpose then I will respond, but if you are just yanking our chain, then please don't abuse the volunteers' time. A hint: divide the length by 2 and print the first half and second half, although you will have to adjust for a string who's length is an odd number.

woooee 814 Nearly a Posting Maven

Qt also has to be installed as PyQt is just a wrapper between the two.

import sipconfigure
no module named sipconfigure

Sip should be included in Qt4. This should be the download, but am not sure since on Linux we just ask the repository to install it.

woooee 814 Nearly a Posting Maven

To start with you have to have a root or main or whatever window, and pass it to the class if the Tk() class is called outside of your class, where is will be named "master" because that is what __init__() receives.
root = Tk()

Note that "center of the screen" depends on the size of the screen so you will have to place that yourself. Tkinter makes some assumptions of course, which affects the final layout, so to be really precise you will have to use one container for each line of widgets and place them in the container how you want. I doubt anyone here has the time to be anyone's intro tutor so you will have to find some resources on the web. In addition to the link above there is http://www.ferg.org/thinking_in_tkinter/index.html and http://www.cs.mcgill.ca/~hv/classes/MS/TkinterPres/ You might also want to install the PMW extension to Tkinter as it allows you to align labels and easily create buttons among many other things. A simple example follows

from Tkinter import *

class GUIFramework():
    def __init__(self,master=None):

      ## set the title of the main window
      master.title("Lab Management Hosts")

      ## set the size of the master window
      master.geometry("200x100+10+10")

      ## add a frame as a container
      top_frame = Frame(master)

      ## add label to the frame

      label1 = Label(master, text = " ")   ## spacer
      label1.grid(row=1,column=1)

      label = Label(master, text = "Lab Mangement Application")
      label.grid(row=1,column=2, columnspan=5)

if __name__ == "__main__":
    root=Tk()
    guiFrame = GUIFramework(root) …
woooee 814 Nearly a Posting Maven

File "/myHomeDirectory/NetBeansProjects/creatureLists/src/Creatures.py", line 6, in <module>
File "/myHomeDirectory/NetBeansProjects/creatureLists/src/Creatures.py", line 9, in Creature
NameError: name 'false' is not defined

This says that line 6 in "Creatures.py" is calling line 9 = false not defined. Nothing like that in the code you posted. Are you running from another directory that also contains a "Creatures.py" program?

woooee 814 Nearly a Posting Maven

Add one more closing parens to this line
f3.write('%s %s\n' % (beginning, endings[ctr]))

woooee 814 Nearly a Posting Maven

Use random.shuffle instead.

random.shuffle(endings)

for ctr, beginning in enumerate(beginnings):
    ## assumes there are at least as many endings as beginnings
    f3.write('%s %s\n' % (beginning, endings[ctr])
woooee 814 Nearly a Posting Maven

I would suggest you start with grid which allows you to specify a row and column. This is a tic-tac-toe program that uses a 3X3 grid to place the buttons.

rom Tkinter import *
from functools import partial

class TicTacToe:
   def __init__(self, top):
      self.top = top
      self.button_dic = {}     ## pointer to buttons and StringVar()
      self.X_O_dict = {"X":[], "O":[]}  ## list of "X" and "O" moves
      self.top.title('Buttons TicTacToe Test')
      self.top_frame = Frame(self.top, width =500, height=500)
      self.buttons()
      self.top_frame.grid(row=0, column=1)

      exit = Button(self.top_frame, text='Exit', \
             command=self.top.quit).grid(row=10,column=0, columnspan=5)

      self.player = True   ## True = "X", False = "O"

   ##-------------------------------------------------------------------         
   def buttons(self):
      """ create 9 buttons, a 3x3 grid
      """
      b_row=1
      b_col=0
      for j in range(1, 10):
         self.button_dic[j] = StringVar()
         self.button_dic[j].set(str(j))
         b = Button(self.top_frame, textvariable = self.button_dic[j], \
                    command=partial(self.cb_handler, j))
         b.grid(row=b_row, column=b_col)

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

   ##----------------------------------------------------------------
   def cb_handler( self, square_number ):
      print "cb_handler", square_number
      if self.player:                       ## True = "X", False = "O"
         player = "X"
      else:
         player = "O"

      ##--- square not already occupied
      if square_number not in self.X_O_dict["X"] and \
         square_number not in self.X_O_dict["O"]:

         self.button_dic[square_number].set(player)
         self.X_O_dict[player].append(square_number)
         print player, 
         self.check_for_winner(self.X_O_dict[player])
         self.player = not self.player
      else:
         print "Occupied, pick another"

   ##----------------------------------------------------------------
   def check_for_winner( self, list_in ):

      winner_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], \
                     [1, 4, 7], [2, 5, 8], [3, 6, 9], \
                     [1, 5, 9], [3, 5, 7]]
      for winner in winner_list:
         if set(winner).issubset(set(list_in)):
            print 'Is A Winner *****'
            self.top.quit()


##===================================================================
root = Tk()
BT=TicTacToe(root) …
woooee 814 Nearly a Posting Maven

There is no way to get it to match anything other than the entire string, so there is another problem with the program logic, i.e. you are telling it something different.

itemname = ["email to", "password", "user"]
for w in ("Password","User","Server", "to", "email", "Email to"):
    if w.lower() in itemname:
        print "%-25s" % (w+" Found")
    else:
        print "%25s Not Found" % w
woooee 814 Nearly a Posting Maven

You can use a tuple to replace several parts of the code in fact, but first this:

#ycoord=y     ## replace with the following
ycoord = int(y)

#if ycoord>8:     ## replace with the following
if 1 <= ycoord <= 8:
    ## code goes here
    xcoord=xcoord.lower()
    x_choices = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
    if xcoord in x_choices:
        ## code goes here
        xcoord = x_choices.index(xcoord) +1  ## replaces all of the if() statements
    else:
        print x, 'is not a-->h'
else:
    print "The 'Y' co-ordinate you entered is invalid" 
#
#-----------------------------------------------------------
# replace this (only part of the block of code)
"""
upleft_xcoord=xcoord-1
upleft_ycoord=ycoord+2
upright_xcoord=xcoord+1
upright_ycoord=ycoord+2
rightup_xcoord=xcoord+2
rightup_ycoord=ycoord+1
"""
#
#   with a tuple of sub-tuples=(move_x, move_y, 'literal description')
#
moves_tuple = ( (-1, 2, 'Up to the left'),
                (1, 2, 'Up to the right'),
                (2, 1, 'Right then up') )

#
# then loop through the tuple instead of using all of the if() statements
xcoord = 1     ## for testing
ycoord = 5
valid_moves = []
for move in moves_tuple:
    new_x = xcoord + move[0]
    new_y = ycoord + move[1]
    if (1 <= new_x <= 8) and (1 <= new_y <= 8):
        print move[2], new_x, new_y
        valid_moves.append((new_x, new_y, move[2])) ## list of all moves from this position

print valid_moves
woooee 814 Nearly a Posting Maven
woooee 814 Nearly a Posting Maven

, it gives me memory locations for each instantiation

That is true as that is what you are storing in the list. First, this statement,
random.randint(1,3) == a
should either yield a True or False (as it is an assert that one side of equation equals the other), or an error if "a" is not declared. I don't think that is what you want. The problem with the code is that there is too much code that has not been tested. Test each function as you go along. So, to print the number of each class type, use something similar to this to get you started on how classes work, but this will only give you an idea of how it is to work as your code requires some cleaning up first.

def printChest(self):
    totals_dict = {"Health Potion":0, "Armor":0, "Sword":0}
    for class_instance in self.contents:
        if class_instance.name in totals_dict:
             totals_dict[class_instance.name] += 1
        else:
            print "Error -->", class_instance.name

    print totals_dict
woooee 814 Nearly a Posting Maven

Giudo Van Helsing today announced that the use of a main() function in Python will now generate an error. After stating that "Python is not C" he went on to say that for backward compatibility the programmer can import a module for programs already using main(). "...and since the people who use main() are also the people who disregard naming conventions, it is"

from USELESScRUFT import main

The new main() function will also be required to return an integer or an error will be generated.

woooee 814 Nearly a Posting Maven

Try

if userInput in ['r', 'R']:
# ----- or -----
if userInput.lower() == "r":
woooee 814 Nearly a Posting Maven

Some print statements should help:

for i in number[1]:
    print "test i =", i
    if int(i) >= 5:
        print "     deleting", number[0]
        del number[0]
        print "     deleting", number[0]
        del number[0]
        print "     deleting", number[0]
        del number[0]
    print "     after, number =", number, "len(number) =", len(number)

And __definitely__ test this with numbers greater than 10.

woooee 814 Nearly a Posting Maven

I used a for loop just for a little variety. And I would also think it should be (but that is just my opinion)

p     p
 l   l
  aa     <-- not reversed
  cc     <-- reversed
 e   e
s     s
woooee 814 Nearly a Posting Maven

It is a courtesy to others readers to mark the thread as "Solved" when it is finished so volunteers don't waste their time reading threads that are finished. Sometimes the posts don't end there but it is something to keep in mind.

woooee 814 Nearly a Posting Maven

When meeting someone, you get an idea of what kind of a person they are, instead of how they look.

woooee 814 Nearly a Posting Maven

I had a job delivering groceries for a small, local store. I doubt there are many small groceries left, let alone any that deliver.

One more: my parents say "ice box" and their grandkids say "refrigerator".

woooee 814 Nearly a Posting Maven

The "self.deck.deal([player])" would be a good place to check except self.deck, self.deck = BJ_Deck(), does not have a deal() function. Generally you want to check every time before you deal or hit as you will also catch it if the burn card or the hit card reduce the deck to less than an acceptable number of cards.

woooee 814 Nearly a Posting Maven

I think you are trying to make this too difficult. Format a string to print the line as you want it, and then print the string.

import itertools

def histo(dict_words):
	
    ## length of words from 10 letters to one letter
    for length in range(10, 0, -1 ):
        this_line = '%3d-|%9s' % (length, '-|')  
 
        ## allow for the possibility that the dictionary may 
        ## not contain all lengths from 1-10
        if length in dict_words:
            ## multiply '*' by the number of times this length was found
            this_line += '*' * dict_words[length]

        print this_line

    print '%3d-|       -|----0----1----1----2' % (0)  
    print '              1-3-5----0----5----0'  

text = "This is a sample text for this example to work."
text += 'and the quick brown fox jumped over the lazy, lazydogdog'
word_list = []
word_seq = []
dicta = {}

text = text.strip()

for punc in ".,;:!?'-&[]()" + '"' + '/':
	text = text.replace(punc, "")

words = text.lower().split()

for word in words:
    word_count = len(word)
    word_list.append(word_count)

word_list.sort()

for key, iter in itertools.groupby(word_list):
    word_seq.append((key, len(list(iter))))
    
print("%s %7s" % ( "Length", "Count"))

for num, count in word_seq:
	print("%5d %10d" % (num, count))

dicta = dict(word_seq)

print(histo(dicta))
woooee 814 Nearly a Posting Maven

n yea... m new to python !!

This is not high school nor does anyone want to become a personal assistant for the lazy http://tinyurl.com/6eavfzu

woooee 814 Nearly a Posting Maven

One advantage of using a dictionary is that it is simple to add or delete options, so a similar method is used for menus. An example (not tested):

def conv(g):
    grade_dict = {'A':5, 'B':4, 'C':3, 'D':2, 'E':1, 'F':0}
    if g in grade_dict:
        return grade_dict[g]
    else:
        print(g, "is not a valid letter grade")
woooee 814 Nearly a Posting Maven

And please do a reasonable number of tests of your code before posting. This is a truncated version of the function to point out the error:

def isprime(n):
    for ctr in range(2,n):  ## do not use 'i', 'l', 'O' as they can look like numbers
        if n%ctr==0:
            return 'Not a prime number',ctr,'is a factor'
        else:
            return 'Prime number'

print isprime(9)  ## 9 is not prime-->3**2
woooee 814 Nearly a Posting Maven

This code can be simplified.

if 2 <= c_no <= 10:
    gpa(c_no)
#
## replaces, (and note that the "pass" does nothing)
if c_no==2: #if the no of courses inputed is 2
    gpa(2)
elif c_no==3: #if the no of courses inputed is 3
    gpa(3)
elif c_no==4: #if the no of courses inputed is 4
    gpa(4)
elif c_no==5: #if the no of courses inputed is 5
    gpa(5)
elif c_no==6: #if the no of courses inputed is 6
    gpa(6)
elif c_no==7: #if the no of courses inputed is 7
    gpa(7)
elif c_no==8: #if the no of courses inputed is 8
    gpa(8)
elif c_no==9: #if the no of courses inputed is 9
    gpa(9)
elif c_no==10: #if the no of courses inputed is 10
    gpa(10)
else:
    pass

Also, you can use a dictionary to shorten the first block of code if you are familiar with dictionaries. And if you want input until a correct number is entered and also not error out when an alpha is entered:

c_no = 0
while c_no not in range(2, 11):
    c_no=input('Number of courses offered')

    try:
        c_no = int(c_no)        ## allows for any alpha characters
    except:
        c_no = 0

gpa(c_no)
e-papa commented: Cool comment, hope to help others like you someday +1
woooee 814 Nearly a Posting Maven

tuple_dict = {} receives "TypeError: unhashable type: 'list'"

I would suggest that you print the values and note also that a list can not be used as a dictionary's key. If that is indeed what you want to do, convert to a tuple first.

def histogram(s):
    tuple_dict = {}
    ## don't use "i", "l", or "O" as variable names as they can look like numbers
    for val in sorted(s.values()):
        print type(val), val
        ## comment the rest of the code until you get this problem solved

Also there is a problem with the last line of your code.

woooee 814 Nearly a Posting Maven

You have to retrieve and store the RadioButton object. This code stores the grid() object:

#
Radiobutton(canvas, variable=xy, value=x,command=self.move).grid(row=row,column=column)
#
# instead use
#
self.rb =Radiobutton(canvas, variable=xy, value=x,command=self.move, image=xxx.)
self.rb.grid(row=row,column=column)  # using "row" and "column" as names is confusing
#
# and then
self.rb.configure(image=yyy)

For configure options see http://www.astro.princeton.edu/~rhl/Tcl-Tk_docs/tk/button.n.html

woooee 814 Nearly a Posting Maven

there are 31 days in the month so i'm trying to take the last 5 days in this case

That would be something along the lines of:

print range(32)[-5:]