woooee 814 Nearly a Posting Maven

This thread appears to use the same data, and so is probably the same homework problem as http://www.daniweb.com/software-development/python/threads/439504/converting-a-list-to-a-a-string-of-integers
We should perhaps combine them into one.

['ID ', ' Last ', ' First', ' Lecture', ' Tutorial', ' A1', ' A2', ' A3', ' A4', ' A5\n']

In the case of the code in this thread, nothing will happen unless the length of the line read.split() is 5. It will be 10 and I don't think the OP can come up with code to

"hmmm... would i slice the string between the 5th and 6th commas ?".

So should we post a "how to read a file, split the line, and access elements 6 through 10"? They probably should test for first character is a number as well.

Also the following code shows that there is no basic understanding of the different types of data containers which means that hints and partial code will not be enough. Either a poor teacher or somebody didn't pay attention in class.

for line in file:
     newline = str(line)
woooee 814 Nearly a Posting Maven

You should be able to do simple debugging like adding print statements to test your code--all code has to be tested.

while (number != "STOP"):
    number = input('Please enter a number, or "stop" to stop: ' )
    if number != "STOP":
        print "breaking out of while loop," number, "not equal 'STOP'"
        break

and

try:
    num = float(number)
except ValueError:
        print("Non numberic data was entered.")
except:
        print("Error with input...")
print "before continue=this line executes no matter what was entered"
continue                            
print "after continue = calc max and min"

Post back with your solution as I think you are completely missing the logic here.

woooee 814 Nearly a Posting Maven

You keep track of the smallest and largest in separate fields. A little trick is to initialize both with the first input value since you don't know the range of the input numbers. For example, if you initialize largest to zero, thinking all numbers will be greater, someone could input negative numbers only.

import random

test_numbers= [random.randint(1, 20) for ctr in range(10)]
print "test_numbers =", test_numbers

largest=0
smallest=0
first_rec=True
for num in test_numbers:
    print num
    if first_rec:     ## initialize with first value input
        smallest = num
        largest = num
        print "begin with smallest and largest =", num
        first_rec=False
    if num < smallest:
        smallest = num
        print "smallest is now", smallest
    elif num > largest:
        largest = num
        print "     largest is now", largest

print "smallest =", smallest, "largest =", largest

And input is generally done something like the following as you can enter a word like "stop" to stop (note this from the instructions "Program will terminate when a non-numeric input is entered"). Plus, if someone wanted to enter -99 as a number, they could not in your original code.

number = 1
while (number.upper() != "STOP"):
    number = input('Please enter a number, or "stop" to stop: ' )
    if number.upper() != "STOP":
        try:
            num = float(number)
        except ValueError:
            print("Non numberic data was entered.")
        except:
             print("Error with input...")

You get the input, then determine if it is stop value or not, and then trigger an except if it is not a float.

woooee 814 Nearly a Posting Maven

Looks like an auto spam bot to me.

woooee 814 Nearly a Posting Maven

It should be obvious that top_down2 should print 2 "dot" triangles and one "star" triangle. Start by getting the "draw the left most triangle" to work, then add the star triangle, then add in the right most triangle. Don't make me sorry I helped you on this.

Note also that you should not hard wire the number of spaces as that will change as my_len changes, as will num_stars (which you can calculate or take the number of dots printed in the final row of the first function). I gave you a hint on how to calculate the number of start spaces for the second function. You will have to figure out the relationship between my_len and the number of start spaces for the first function.

Finally, you pass num_spaces to the function but then re-set to 3 within the function. See "Calling a Function" and "The Return Statement" in this tutorial for info on passing parameters to and getting them from functions. I will not write this program for you.

woooee 814 Nearly a Posting Maven

Automatically executing in the current directory is considered dangerous as an attacker could add their own bash for example in the current directory. It would be executed if the current directory is searched first and could do anything the programmer wished. You can add
PATH=$PATH:.
and export it to .bashrc if you want. In addition we have all been in the situation where there are multiple programs with the same name and we run the wrong one. This is especially true when we duplicate a program name that is in the Python library, like abc.py. The program in the current directory would be imported if it is the first one found.

woooee 814 Nearly a Posting Maven

You are perhaps over thinking this with all of the complicated print statements. You now want a second function with num_dots, num_spaces, and num_stars, and print and then add/subtract from each field accordingly.

def top_down(my_len, spaces):        
    num_dots = 1
    for ctr in range(my_len):
        print ' '*spaces + '.'*num_dots
        num_dots += 2
        spaces -= 1

myChar1 = '*'
myChar2 = '.'
my_len = 3

top_down(my_len, 5)
## as an example only --> but number of spaces will be first number-my_len
## that is 5-3
top_down(my_len, 2) 
woooee 814 Nearly a Posting Maven

Former financial arbitrage trader Jerome Kerviel is the most indebted man on the planet, owing his former employer $6.3 billion.

The amount Kerviel owes to French bank Societe Generale for fraudulent trades made in 2007 and 2008 would make Kerviel one of the 50 richest people in America if those debts were assets.

woooee 814 Nearly a Posting Maven

One is greater than zero=vowels found
Three is greater than zero=vowels found
etc.

woooee 814 Nearly a Posting Maven

The following works for me. Perhaps there is no id="content" for the site you use.

import urllib2
from bs4 import BeautifulSoup

f = open("test.html", "a")
html = urllib2.urlopen('http://www.google.com').read()
soup = BeautifulSoup(html)
content = soup.find(id="csi")
print "content", content
f.write(content.encode('utf-8') + '<hr>')
f.close()
woooee 814 Nearly a Posting Maven

I also want it to display a message when there is no vowel entered

Check the length of a set intersection

test_sentence="The quick brown fox"
v = set(['a', 'e', 'i', 'o', 'u'])
print v.intersection(set(test_sentence))

or set some indicator

msg = input("Enter a sentence: ")
#v = set(['a', 'e', 'i', 'o', 'u'])
a = dict()
vowel_found=False

for letter in "aeiou":
    a[letter] = msg.count(letter)
    if a[letter} > 0:
        vowel_found = True
woooee 814 Nearly a Posting Maven

One of the many Python functions tutorial.

woooee 814 Nearly a Posting Maven

The error message doesn't make any sense as it only references line 3

Traceback (most recent call last):
File "<stdin>", line 3, in <module>
IOError: [Errno 36] File name too long: '\xef\xbb\xbf<!DOCTYPE html PUBLIC "...

which is

from bs4 import BeautifulSoup

Is BeautifulSoup installed correctly?

woooee 814 Nearly a Posting Maven

Use readlines() to get a list of the records. You can then access a record in the list by offset value just like any other list.

woooee 814 Nearly a Posting Maven

The point is MainLoop is not changed if variables does not equal 2.

woooee 814 Nearly a Posting Maven

What happens when "variables != '2'" ?

## Three variables
print "HOW MANY VARIABLES WOULD YOU LIKE?"
for ctr in range(3):
    print ctr+1

names_list=["FIRST", "SECOND", "THIRD"]
MainLoop = 1
while MainLoop == 1:
    name_of_variables=[]
    variables = raw_input ("Enter Variables ")
    for ctr in range(int(variables)):
        name = raw_input ("NAME YOUR %s VARIABLE " % (names_list[ctr]))
        name_of_variables.append(name)

    ## exit testing while() loop
    MainLoop = 0

print name_of_variables
woooee 814 Nearly a Posting Maven

You first split the sentence into words, then print accordingly. I will leave dealing with punctuation to you. A simplified example:

test_input="help I don't know how to do these tables."
test_list=test_input.split()
ctr=0
for outer in range(3):
    for inner in range(3):
        print test_list[ctr],
        ctr += 1
    print
woooee 814 Nearly a Posting Maven

Human.makemove is different from Board.makemove (different "name space"). Read the last part of my first reply again. Also, you can replace

        self.board.append((("["+str(self.mark[0])+"]"),("["+str(self.mark[1])+"]"),("["+str(self.mark[2])+"]")))
        self.board.append((("["+str(self.mark[3])+"]"),("["+str(self.mark[4])+"]"),("["+str(self.mark[5])+"]")))
        self.board.append((("["+str(self.mark[6])+"]"),("["+str(self.mark[7])+"]"),("["+str(self.mark[8])+"]")))
    def updateboard(self):
        self.board = []
        self.board.append((("["+str(self.mark[0])+"]"),("["+str(self.mark[1])+"]"),("["+str(self.mark[2])+"]")))
        self.board.append((("["+str(self.mark[3])+"]"),("["+str(self.mark[4])+"]"),("["+str(self.mark[5])+"]")))
        self.board.append((("["+str(self.mark[6])+"]"),("["+str(self.mark[7])+"]"),("["+str(self.mark[8])+"]")))

with

for ctr in range(0, 9):
    self.board.append("[%d]" % (self.mark[ctr]))
woooee 814 Nearly a Posting Maven

Note how the class Board is declared inheriting Human. Also, the init in Board overrides the init in Human so you have to explicitly call it with "super" in new style classes, otherwise the variables in Human's init are not declared.

class Board(Human):
    def __init__(self):
        super(Board,self).__init__()
        self.board = []
        self.mark = []

The statement Human=Human() does nothing. Also, you will not be able to have more than once instance of the Board class with this code. You have redefined it to be an instance instead since the instance and the class have the same name.

def Round(Board):
    Board.makemove()
    Board.addmove()
    Board.printboard()

#startup
Board = Board()   ## Board is no longer a class
Board.makeboard()
Board.printboard()
##Human = Human()

Round(Board)              

## this won't work as "Board" no longer points to a class.
board_2= Board()  
woooee 814 Nearly a Posting Maven

What is the while loop supposed to do?? Right now it just prints. Note that

    while sum == point:

will never be True because you are comparing an integer and a tuple.

woooee 814 Nearly a Posting Maven

Check the permissions first. Does the user (you) have permission to open the file?

woooee 814 Nearly a Posting Maven
a[0:9:-1]   #why is this not equivilent to a[::-1]

start at a[0], (then -1 = a[-1] which doesn't exist), and go in reverse order until the number is less than 9, which zero is. You want, a[end:start-1:-1], but why even try to reinvent the wheel that is already working.

woooee 814 Nearly a Posting Maven

but I have continuously been getting an error saying that a str object cannot be interpreted as an integer

We have no idea what or where this may be. Post the complete error message which includes the offending line and also state which version of Python you are using as one version will give an error but another version will not for the same line of code.

woooee 814 Nearly a Posting Maven

You are choosing from the dictionary's values not the keys, and then using the values instead of a key for lookup

    while wordlimiter < 10:
        ## returns values linked to first_word
        next_word = random.choice(worddict[first_word])

you possibly want

        next_word = random.choice(worddict.keys())

        ##  or test for membership
        next_word=""
        while next_word not in worddict:
            next_word = random.choice(worddict[first_word])
            first_word = next_word

Also, we are assuming that lines 21 through 23 should all have the same indentation.

woooee 814 Nearly a Posting Maven

And you first want to check that the index is in the dictionary to avoid an error message.

dictionary={a:1, b:2, c:3 ...etc}
lookup=[a, a, b, c, c ... etc]
results = [dictionary[key] for key in lookup if key in dictionary]
woooee 814 Nearly a Posting Maven

Take a look at chapter 19 in the official pygtk tutorial.

woooee 814 Nearly a Posting Maven

First, read the Homework Help thread.

Look at one of the Python Tutorials for assistance as this is pretty basic stuff that is included in most tutorials. Feel free to post back with specific code problems for help.

woooee 814 Nearly a Posting Maven

You did not include the complete error message so we have no idea which variable gives the error. Dagger should possibly be a data attribute/instance variable instead of a class variable
http://www.linuxtopia.org/online_books/programming_books/python_programming/python_ch22s06.html
http://www.diveintopython.net/object_oriented_framework/userdict.html#fileinfo.userdict.init.example

woooee 814 Nearly a Posting Maven

This statement is part of your problem

        self.master.bind('<Configure>', self.resize)

Also, you misspelled "tag". Other than that, moving the circle works fine for me. Since you always print the text in the same place and test the same coordinates, you will always get the same results. You have to keep track of the center of the circle and see if the mouse click location is within the radius, i.e use a right triangle to get the distance from the mouse click to the center and test for less than the radius.

I would make moveCircle less redundant with the following code. Finally, I would suggest that you select different names for the tags as "circle" and "text" can be confusing since Tkinter already uses those names.

    def moveCircle(self, event):
        """move circle up, down, left or right when user clicks an arrow key"""
        x=0
        y=0
        if event.keysym == "Up":
            y = -5
        elif event.keysym == "Down":
            y = 5
        elif event.keysym == "Left":
            x = -5
        else:
            x = 5

        self.canvas.move("circle", x, y)
        self.canvas.move("text", x, y)
        self.canvas.update()
woooee 814 Nearly a Posting Maven

Please read the Homework Help sticky.

woooee 814 Nearly a Posting Maven

Please read the sticky threads
Homework Help

If you have no idea then there is not much that can be done with this problem. I would suggest that you start with something easier where you do have some idea of what to do.

woooee 814 Nearly a Posting Maven

and
board_contains_word_in_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'AN')
--> true

This should be False for column words.

Print column_index as I don't think it is what you think it is.

def board_contains_word_in_column(board, word):
    for column_index in range(len(board)):
        print "column index", column_index

Again, add some tests so you know where the problem is. The obstacle you face is not the coding. The obstacle you face is that you have code that has not been tested.

woooee 814 Nearly a Posting Maven

Plastic was originally developed to be an alternative to shellac (which was made from Lac beetles).

woooee 814 Nearly a Posting Maven

There is no need to reverse the list twice as you can use -1 in a for loop and start at the back end. Other than that, you have to look at all elements from the back of the list to the first non-0xFFFF however you do it.

woooee 814 Nearly a Posting Maven

When will the variable "a" be found in the following code?

    a = ''
    for word in range(len(board)):
        ## do you really want to look for a=''
        if a in make_str_from_row(board, word):
            return True

I have a function that checks if a str is part of a list of list of str and returns (T)rue or (F)alse

The first problem is that "BOX" won't be found in "BOSX" so you have to search letter by letter and keep track of what is found (and add some tests so you know where the problems are). That brings up a second problem, finding a letter only once. So you should not find "keep" in "kept" because the "e" should be eliminated after the first find.

def find_word(input_word):
    list_of_letters=[['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B'], 
    ["K", "E", "P", "T"]]

    for el in list_of_letters:
        print "\ntesting for", input_word, el
        el_copy = el[:]
        found_letters=[]     ## holds all letters found
        for ltr in input_word:
            if ltr in el_copy:
                print "Found", ltr
                found_letters.append(ltr)
                el_copy.remove(ltr) ## remove letter ==> can't be found again
        if len(found_letters) == len(input_word):
            print input_word, "***** found in", el, "*****"

for word in ["BOX", "KEEP"]:
    find_word(word)

Once again, add some tests for each function so you know what is happending.

woooee 814 Nearly a Posting Maven

To get you started:

for ctr in range(8):
    print 2**ctr,
for ctr in range(6, -1, -1):
    print 2**ctr,
print

for ctr in range(2):
    print 2**ctr,
for ctr in range(0, -1, -1):
    print 2**ctr,
print

for ctr in range(1):
    print 2**ctr,
for ctr in range(-1, -1, -1):
    print 2**ctr,
print

To print with all columns lined up correctly, you will have to calculate the final row first, or store all rows in a list, and then print according to the size of the number in the last row. For n rows, the last row will have n+(n-1) columns=8+7 for 8 rows. To place the 3rd row in the middle for example (3rd row contains 5 numbers), subtract the number from total available columns, 15-5=10. Divide by 2=5, which means row 3 would have 5 'empty' elements, then the 5 calculated elements=1, 2, 4, 2, 1, and then 5 more empty elements.

woooee 814 Nearly a Posting Maven

You should send the time value entered to the class, so this statement should be in a function that is called when the "Convert" button is pressed
conv = Converter(5)
and should send the value from the Entry instead of "5" (links to using get to read an entry and callbacks for a button click

Next the class uses "n" which it doesn't have access to
ampm = n[-1]
You should be using "x" or even better self.x

The "Elapsed Minutes Since Midnight" should actually show something which requires a Tkinter variable

Finally you should allow for 2:2P instead of 02:02P which means you should split on the colon instead of the [0:2] and [3:5] slices

woooee 814 Nearly a Posting Maven

Instead of complicated and+or statements without parens so no one knows what the computer is actually doing

elif row1.value == row2.value == row3.value and row4.value == row5.value or row3.value == row4.value == row5.value and row1.value == row2.value:

use --> for unique value in list of rolls/dice, count each unique value and use a dictionary or list to associate with "pair", "3 of a kind", etc.

## Simplified example
import random

dice_values=[random.randrange(1, 7) for die in range(5)]
print "initial values =", dice_values

set_values = set(dice_values)
print "remove duplicates =", set_values

for value in set_values:
    print "%d value occurs %d times" % (value, dice_values.count(value))
woooee 814 Nearly a Posting Maven

Start by printing x, y, and z. And print the return. These are always good places to start.

def calcdist(data):
    for p in data:
        x = p[:1]
        y = p[:2]
        z = p[:3]
        print "x, y, and z =", x, y, z

    for i in range(len(data)):
      dist = sqrt((x[i]-x[i+1])^2 + (y[i]-y[i+1])^2 +(z[i]-z[i+1]^2))
      print "returning", dist, "for", x, y, z
      return dist 

Finally, take a look here http://www.greenteapress.com/thinkpython/html/thinkpython007.html#@default466 for squares and square roots. Hint: the square code is incorrect.

woooee 814 Nearly a Posting Maven

What that post means is, you execute the return from rollin (which is 'None') because of the parens. It should be
rolldice = Tkinter.Button(row2, command=rollin, text = "Roll")
See Click Here for info on bindings and callbacks.

Also, you do not include the parens when you call dx.roll within rollin() so it does nothing. Finally, I like to use Tkinter variables because the widget is updated when the variables change. Otherwise you may have to call update_idletasks().

import random
import Tkinter

win = Tkinter.Tk()
win.title("Die Roller")
class die():
    import Tkinter
    def __init__(self,ivalue,parent):
        win.geometry("75x50+10+10")
        self.label_var = Tkinter.IntVar()
        self.label_var.set(ivalue)
        self.display = Tkinter.Label(parent,relief='ridge', borderwidth=2, 
                       textvariable=self.label_var)
        self.display.pack(side='left')

    def roll(self):
        value = random.randint(1,6)
        self.label_var.set(value)
        print "label_var =", value

def rollin():
    d1.roll()
    d2.roll()
    d3.roll()


row1 = Tkinter.Frame(win)
row2 = Tkinter.Frame(win)
d1 = die(1,row1)
d2 = die(1,row1)
d3 = die(1,row1)
##d1.display.pack(side="left")
##d2.display.pack(side="left")
##d3.display.pack(side="left")
row1.pack()
rolldice = Tkinter.Button(row2, command=rollin, text = "Roll")
rolldice.pack()
row2.pack()
win.mainloop()
woooee 814 Nearly a Posting Maven

It is very easy. Just lay it out in a list and print the list. A simplified example.

to_draw = [[" ", "O"],
           [" ", "|"],
           ["\\", " ", "/"],
           [" ", "|"],
           [" ", "|"],
           ["/", " ", "\\"]]

for each_list in to_draw:
    print "".join(each_list)
woooee 814 Nearly a Posting Maven

What exactly are you trying to do? It is not obvious from the program.

There are other problems in addition to indentation:

while 1>0:

The above is an infinite loop that you never exit.

You open the file '/var/log/kern.log' at least 3 times without previously closing it.

You mix pack() and place() which produces unknown results. Start with a small snippet and test it (it is obvious from the indentation that this program has not been tested). Get that part running and then add more and test it, etc. Post back with specific questions when you run into a problem.

woooee 814 Nearly a Posting Maven

Aready answered Here

woooee 814 Nearly a Posting Maven

I keep getting the error:
"TypeError: expected a character buffer object"

We can't help without the complete error message; which tells where the error is in the program among other things.

    a[i].lower() 

Take a look at this page http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/strings3.html beginning at the paragraph that starts with "Strings are immutable, so no string method can change the original string"

Also,

    index = a[i].find('"enclosure_url":')
    b = a[i].replace(a[:index], "")

what happens if it is not found?

##  NOT Tested
def sanitise(str_in):
    to_find = '"enclosure_url":'
    print "-"*50
    str_in = str_in.lower()
    if to_find in str_in:
        result_list = str_in.split(to_find)
        print "Found", result_list
        return result_list[0]
    else:
        print "NOT found in", str_in
    return []
woooee 814 Nearly a Posting Maven

It appears that the classes are part of the cause of your confusion, so since you do not use them, I have just deleted them and the code runs until it encounters the next error. Note that you will have a problem if you try to split anything after line #9 since "split" is now a variable, changed by the code to no longer be a fuction that splits into parts.

def value(s):
    split_s = s.split('b')
    convert = split_s[0]
    base = split_s[1]
    convert_to_decimal(convert, base)

def convert_to_decimal(s, base):
    v = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8,
         '9':9, 'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15}
    total = 0
    exp = 0
    for i in reversed(range(len(s))):  ## range is already a list
        total += v[s[i]] * (base**exp)
        exp += 1
    return total

if __name__ == '__main__':
    s1 = '1101b2'
    value(s1)
woooee 814 Nearly a Posting Maven

And generally, the input is separate from the rest of the program.

def get_input():
    option = 99
    while option not in [0, 1, 2, 3, 4]:
        print("0 - clear out scores")
        print("1 - input more scores")
        print("2 - display all scores")
        print("3 - get average scores")
        print("4 - end program")
        option = int(input("\n Please select an opition: "))

    return option

scores =[]
option=99
while option != 4:
    option = get_input():

    ## rest of program
    if option == 0:
        clearScores()

Also, you should pass the variable to the function and return it. Lists are mutable so this is not necessary with lists, but for readability it is generally done.

def clear_scores(scores):
    scores = []
    return scores

## called as
scores = clear_scores(scores)

## and the same for
scores = add_scores(scores)
## etc.
woooee 814 Nearly a Posting Maven

Start with a tutorial on MySQL for Python, as your code does not contain enough to comment on. For starters, you don't ever call the function connect_to_database, and the function itself does not connect to any database. Start with opening a database correctly and inserting records, which is in every tutorial, then you can read the text file one record at at time, split it into fields, and insert the fields into the database in the proper place.

woooee 814 Nearly a Posting Maven

Use "SELECT" and "WHERE" to only return record(s) that match from the SQLite database See "Named Placeholders"

woooee 814 Nearly a Posting Maven

File "C:\Python27\code\chidimez\tstcode\employees.py", line 951, in OnOpenEdit
sParameter ='Input parameter: %s ' %(sSQL,sParameter)
TypeError: not all arguments converted during string formatting

This statement
sParameter ='Input parameter: %s ' %(sSQL,sParameter)
accepts one parameter (one %s) but you supply 2 parameters (sSQL,sParameter). Note that this line does not appear in the code you posted.

woooee 814 Nearly a Posting Maven

Start by getting the input from the user, i.e. Name, number of hours, etc. and then work out the math on paper and convert to Python. Post back with problems.