woooee 814 Nearly a Posting Maven

Did you commit() afterwards? All of my links are pretty old http://eringary.com/python/pysqlite.html

Gribouillis commented: good point +13
woooee 814 Nearly a Posting Maven

You have 2 ?s and one variable. Also, you should use a dictionary as it is more secure.

#update if meshblock_06=='21'
g.execute('UPDATE meshblock_1107 SET etv_1107==:update_1 WHERE meshblock_06==:select_1', {'update_1':pv[0:2], 'select_1':'21'})
woooee 814 Nearly a Posting Maven

Comment the Circle and Box lines and see if you get a line. Then figure out why only Line() works.

from gasp import *
 
begin_graphics()
     
#Circle((200, 200), 60)
Line((100, 400), (580, 200))
#Box((400, 350), 120, 100)
     
update_when('key_pressed')
end_graphics()
woooee 814 Nearly a Posting Maven
woooee 814 Nearly a Posting Maven

For storing a few values, like phone number and e-mail address, you can use a list which is easier to understand and use.

AB={'Joshua' : ['sho0uk0m0o@gmail.com',  '(802) 3-5-2206'],
    'Ashley':  ['a000@gmail.com', '(802) 820-0000']}
print "%s,  e-mail=%s,  phone=%s" % ("Joshua", AB["Joshua"][0], AB["Joshua"][1])

new_name = "Bill"
new_email= "bill@domain.com"
new_phone= "(802) 123-4567"

AB[new_name] = [new_phone, new_email]
print AB
woooee 814 Nearly a Posting Maven

There is gap between your specification and my results by purpose as it is DaniWeb policy to help people to learn, which means letting people finish things by (themselves)

+1 So no one is posting complete code, take what has been posted onward.

The way you have described it: for these lists:

lista = [(3015, 3701), (4011, 5890), (10,40), (150,300)]
listb = [(3045, 3800), (1,2), (100,200), (4500,6000), (20,145)]

aend < bstart = 3701 < 4500
                5890 < None
                  40 < 3045, 100, 4500 
                 300 < 3045, 4500

And similarly for the bend < astart test.

This code has not been thoroughly tested.

lista = [(3015, 3701), (4011, 5890), (10,40), (150,300)]
listb = [(3045, 3800), (1,2), (100,200), (4500,6000), (20,145)]
   
def overlap(lista, listb):
    found_a_less = []
    for tup_a in lista:
        holding = [tup_a]
        for tup_b in listb:
            result=check(tup_a, tup_b)
            if result:
                holding.append(tup_b)

        found_a_less.append(holding)
    return found_a_less
     
def check ((astart, aend), (bstart, bend)):
    if aend <= bstart:
        return 1
#    if bend <= astart:
#        found_b.append((bend, astart))
    return 0
     
result=overlap(lista,listb)
for tup in result:
    print tup[0]
    for ctr in range(1, len(tup)):
        print "   ", tup[ctr]
    
result=overlap(listb,lista)
for tup in result:
    print tup[0]
    for ctr in range(1, len(tup)):
        print "   ", tup[ctr]
woooee 814 Nearly a Posting Maven

At some point you will have to use a list to store multiple values. This is something along the lines of what I think you want.

lista = [(3015, 3701), (4011, 5890), (10,40), (150,300)]
listb = [(3045, 3800), (1,2), (100,200), (4500,6000), (20,145)]
     
def overlap(lista, listb):
    a=0
    b=0
    found_list = []
    while a<len(lista) and b<len(listb):
     
        result=check(lista[a],listb[b])
     
        if result <0:
            found_list.append((lista[a], listb[b]))
            a +=1
        elif result > 0:
            found_list.append((lista[a], listb[b]))
            b +=1
        else:     ## no result found in check()
            a += 1

    return found_list
     
def check ((astart, aend), (bstart, bend)):
    if aend <= bstart:
        return -1
    if bend <= astart:
        return 1
    return 0
     
result1=overlap(lista,listb)
for res in result1:
    print res

An alternate solution that compares every tuple in lista to every tuple in listb:

lista = [(3015, 3701), (4011, 5890), (10,40), (150,300)]
listb = [(3045, 3800), (1,2), (100,200), (4500,6000), (20,145)]
     
def overlap(lista, listb):
    found_a_less = []
    found_b_less = []
    for tup_a in lista:
        for tup_b in listb:     
            found_a_less, found_b_less=check(tup_a, tup_b, \
                                       found_a_less, found_b_less)

    return found_a_less, found_b_less
     
def check ((astart, aend), (bstart, bend), found_a, found_b):
    if aend <= bstart:
        found_a.append((aend, bstart))
    if bend <= astart:
        found_b.append((bend, astart))
    return found_a, found_b
     

result_a, result_b=overlap(lista,listb)
for res in result_a:
    print res
print "-"*50
for res in result_b:
    print res
woooee 814 Nearly a Posting Maven

You can multiply the number by 100 and use integers, or truncate to 2 decimal places when printing floats. On most modern computers a float is a binary number as defined by the IEEE Floating Point Arithmetic Standard and represents numbers 1,000,000,000,000 to 0.0000000000000001 (at a minimum). Floats (actually a C double) have plenty of precision for 2 decimal monetary numbers.

x = 0.1+0.2
print repr(x)
y = "%3.2f" % (x)
print y

x = 0.1+0.2+0.005
print repr(x)
y = "%3.2f" % (x)
print y
woooee 814 Nearly a Posting Maven

Also you should check the value of this statement
out = out + key1[key1.index(i)+3]
to make sure that key1.index(i)+3 isn't greater than the length of the list, key1.

woooee 814 Nearly a Posting Maven

Are there any records in the file? Create a test file so you know what it contains and try it with the program. If the test file works, the problem is the csv file, not the program.

woooee 814 Nearly a Posting Maven

You should also be able to use the list as is, something like this:

for i, record in enumerate(reader):
    if (i > 0) and (len(record) > 7): #skip headers & record has all the fields
        print "date =", record[0]
        print "hk   =", record[1]
        print "ba   =", record[2]
        ## etc.
woooee 814 Nearly a Posting Maven

This implies

it only returns the details of the last user in the list

This implies that you only write the last name. You code should be indented as follows, with the write statement under the for() loop.

for name in listofnames:
    account = api.GetUser(name)
    followers = account.followers_count
    csvout.writerow([name, followers])
    print name + ", " + str(followers)

csvfile.close()
woooee 814 Nearly a Posting Maven

as i said.. not sure what are the big differences between python 2.7 and 3 though.

See "Print Is A Function" here http://docs.python.org/release/3.0.1/whatsnew/3.0.html for the correct way to suppress the newline.

woooee 814 Nearly a Posting Maven

This homework problem comes around every year. horizontal and vertical graphs.

vegaseat commented: thanks for the hint +15
woooee 814 Nearly a Posting Maven

You perhaps want something along the lines of:

class someclass:
    def __init__(self):
        self.somevariable='somevalue'
     
    def somefunction(self):
        print('gotta get here')
     
def someotherfunction(class_instance):
    print "somevariable -->", class_instance.somevariable

    print "somefunction -->", 
    class_instance.somefunction()
     
myclass=someclass()
someotherfunction(myclass)
woooee 814 Nearly a Posting Maven

See "Capturing Output" here http://www.doughellmann.com/PyMOTW/subprocess/index.html#module-subprocess You can do a lot more with subprocess, so continue reading if you want to know more.

woooee 814 Nearly a Posting Maven

Generally, you would store the next time you want to execute, i.e. now+10 seconds,
using a loop,
call the function,
upon the return get the time and calculate the difference between it and the next time and sleep that amount of time,
update the next time, (+10 seconds), and loop again.

Also, Python has a schedule module, as do most operating systems. On Linux you can use cron to execute the program every 10 seconds, if you want to continue forever.

TrustyTony commented: Good advice and not too much. +13
woooee 814 Nearly a Posting Maven

For me by hand and considering rotation and effect through brackets the example should transform like this:

str='A[A[001]BB1A10]11BA10'
-> 'A[A[]BA10]1BA10'
-> 'A[0A[]BA1]1BA10'
-> 'A[A[]BA1]1BA10'
-> 'A[[]BA1]1BA10'
-> 'A[A1[]B]1BA10'
-> 'A[1[]B]1BA10'
-> 'A[1[]B]BA10'

You could further reduce the last line, depending on the bracket rules, as the first "1" is contiguous to "B", ignoring the brackets, so you get
A[[]BA10]BA10
It also depends on when you rotate in the process as
A[001]B
could remain as is if rotated first to A[100]B, or changed completely if the removals are done first. It's all muddy to my feeble brain, so if anyone can post a clear set of rules and their heirarchy it would be helpful.

woooee 814 Nearly a Posting Maven

and if B[A[100]B0] then B[A[100]B] as the 'A' is considered adjacent to the '0'

That doesn't make sense to me at least. How is the final "0" adjacent to "A" even when taking the brackets into consideration.

so how can str='A[A[001]BB1A10]11BA10' become str=A[1A[100]BA]BA10

Where does the first "1" come from in the second string? Just to clear things up, if you have "A[0]" does that convert into just "A" or remain the same because of the brackets. And if the brackets don't matter, with "A[100]" do you test for "A0" before or after the rotation inside the brackets. Finding the previous and next letters, and testing for combinations, is fairly straight forward even when taking the brackets into consideration, but one has to be sure of the rules before that can be done.

woooee 814 Nearly a Posting Maven

I would not be concerned about the differences between 2.6 and 2.7. Using 2.7 is only slightly different than 2.6. There are some third party packages that are not yet available for 2.7 though.

woooee 814 Nearly a Posting Maven

I think Python gets the locale from your computer, so perhaps that changed with the installation. You can try
locale.setlocale() and see if it helps.

woooee 814 Nearly a Posting Maven

The original problem is that the OP is iterating through the list

l=list(s) #['j', 'a', 'n', 'k', 'o', 's', 'i', 'e', 'n', 'a', 'p', 'i', 'v', 'o']
f=[]
for i in l:   ## <-- iterating through the input list
    f.append(l.count(i)) # [1, 2, 2, 1, 2, 1

instead of through a list of letters, which would eliminate the duplicate problem.

l=list(s) #['j', 'a', 'n', 'k', 'o', 's', 'i', 'e', 'n', 'a', 'p', 'i', 'v', 'o']
f=[]
##for i in l:
for i in string.lowercase:   ## "abcdef...etc" --> count each letter once
    f.append(l.count(i)) # [1, 2, 2, 1, 2, 1

but since this is homework, no one wants to give out a complete solution/

woooee 814 Nearly a Posting Maven

Why are you going through the following gyrations instead of using "t". Also, please do not use "i", "l", or "O" as variable names as they can look like letters.

t=s.split()
delimiter= ''
s=delimiter.join(t)
l=list(s)
woooee 814 Nearly a Posting Maven

Instead of 84 lines of code, with no idea what the problem is, compose the program in steps and test after each step. To get you started: (note the difference between final three lines here, and your code).

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

import math
import cmath

class RootFinder():
    def __init__(self, master=None):
        self.fr = tk.Frame(master)
        self.fr.grid()
        self.create_widgets()

    def create_widgets(self):
        self.labelf=tk.Label(self.fr, text="What is f(x)?", font='Arial 10 bold', pady=5)
        self.labelf.grid(row=0, column=0, sticky='w')

        self.sqrcoeff=tk.Entry(self.fr, width=5)
        self.sqrcoeff.grid(row=1, column=0)
        self.sqrcoeff.insert(0, '1')

root = tk.Tk()
RF = RootFinder(root)
root.mainloop()
woooee 814 Nearly a Posting Maven

There are a lot of problems with the code you posted:

## there is no root window
app=RootFinder()
app.mainloop()
#----------  should be 
root = Tk()
app=RootFinder(root)
root.mainloop()
#
## self.outputframe is never declared in the code you posted
    def create_widgets(self):
        self.root1lbl=Label(self.outputframe, text='')

And that is all that I care to examine at this point. See Ene Uran's example for starters.

woooee 814 Nearly a Posting Maven

Match up the parens on the previous, raw_input, statement. Also, the welcome() function does nothing.

vegaseat commented: yes +15
woooee 814 Nearly a Posting Maven

I am guessing that the window doesn't contain anything visible, just containers. (This just displays a button.)

import sys
from PyQt4 import QtCore, QtGui
 
class UI_CMDTester:
    def __init__(self):
        self.__app = None
        self.__win = None
        
        
        
        
    def init(self,    \
             w_title, \
             w_width, \
             w_height):
        
        self.__app = QtGui.QApplication(sys.argv)
        self.__create_win(w_title, w_width, w_height)
        
        sys.exit(self.__app.exec_())
        
    def __create_win(self, w_title, w_width, w_height):
        
        self.__win = QtGui.QWidget()
        self.__win.resize(w_width, w_height)
        self.__win.setWindowTitle(w_title)
        
        close_button = QtGui.QPushButton("&Quit")

        layout = QtGui.QGridLayout()
        layout.addWidget(close_button, 1, 0)
        self.__win.setLayout(layout)

        self.__win.show()
        

if __name__ == "__main__":
    obj_ct = UI_CMDTester()
    obj_ct.init("Window", 800, 600)
woooee 814 Nearly a Posting Maven

This statement will never be true

while decimal == '1' and decimal == '0' :
# ---- and this statement is meaningless
number=number

And str(decimal) will replace the binaryConvert() function. Also, press the code button to include your code in a readable (properly indented) form.

woooee 814 Nearly a Posting Maven

The result is correct since you open it for reading before anything is written to it.

text = "aim low and reach it"

fname = "test7.txt"
 
with open(fname, 'w') as foutp:
    # write text to file
    foutp.write(text)

# read text from file
with open(fname, 'r') as finp:
    mytext = finp.read()
 
print("to file --> %s" % text)
print('-'*30)
print("from file --> %s" % mytext)
bumsfeld commented: clearer +11
woooee 814 Nearly a Posting Maven

I have no time right now, but the error message is correct, equBPressed() has no knowledge of num1 or num2 because they were not passed to the function. You should be using a class for this as it solves a lot of those problems with self.var which is visible to all functions in the class; self.X_O_dict in the following program for example, For now, take a look at how this program uses "partial" to pass the button number to a common function.

from 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 ):
      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)
         self.check_for_winner(self.X_O_dict[player])
         self.check_for_tie()
         self.player = not self.player
      else:
         print "Occupied, pick another"

   ##----------------------------------------------------------------
   def check_for_tie(self):
      if 9 …
woooee 814 Nearly a Posting Maven

It works for me on Slackware Linux as well. Are you behind a firewall?

VulcanDesign commented: Thanks for the help! +2
woooee 814 Nearly a Posting Maven

To illustrate that the function is correct:

from decimal import Decimal
def calculate(num1, num2, oper):
    if(oper=="+"):
        answ = Decimal(num1) + Decimal(num2)
        return answ
    return 0
        
ret_ans = 0
for x in range(1, 6):
    print "%d + %d =" % (ret_ans, x),
    ret_ans = calculate(ret_ans, x, "+")
    print ret_ans
woooee 814 Nearly a Posting Maven

The pointer is positioned at the end of the file so nothing is read.

import tempfile
if __name__ == '__main__':
  test = tempfile.NamedTemporaryFile()
  test.write('asdfsadfsadfsadfasdfasdfsadfsdfsadfsadfs')
  test.seek(0)                      ## offset=0 --> beginning of file
  print "\n test read", test.read()
  print test.name
woooee 814 Nearly a Posting Maven

There are several ways to do this. First, you might want to use a menu, with a number input, instead of keying in "aluminium", etc. as they can be spelled differently (aluminum). Then use a dictionary or list of lists to chain the values to the raw material.

material_dict = {"concrete" : 0.000012,
                 "silver" : 0.000019,
                 "gold" : 0.000014 }     ## etc
# or
material_list = [ ["concrete", 0.000012], \
                  ["silver", 0.000019], \
                  ["gold", 0.000014] ]
woooee 814 Nearly a Posting Maven

wx has a CallAfter method. It will require some implementation of multiprocessing/threads however you do it since you want to do two things at once: 1) wait for a button press, 2) keep track of the time that has passed. This programs waits for 5 seconds, simulating waiting for a button press, and after 5 seconds exits.

import time
from multiprocessing import Process

class TestClass():

   def test_f(self, name):
      ctr = 0
      while True:
         ctr += 1
         print ctr, name
         time.sleep(0.5)

if __name__ == '__main__':
   CT=TestClass()
   p = Process(target=CT.test_f, args=('Simulation of MessageBox',))
   p.start()

   ## sleep for 5 seconds and terminate
   time.sleep(5.0)
   p.terminate()
   p.join()

   print "\n\ndestroy here"
vegaseat commented: nice example +15
woooee 814 Nearly a Posting Maven

Lists are passed by reference, so the tuple contains the memory address of the list, not the list itself, and that doesn't change. Both of these statements will fail

my_tuple = (1, 2, 3, [4, 5, 6])

new_list = [4, 5, 6]
my_tuple[3] = new_list     ## new memory address
my_tuple[1] = "a"
woooee 814 Nearly a Posting Maven

First, there are two types of variables in classes, attributes and instance variables. I think you want instance variables, so you can have more than one human for example, with separate values for each one.

class Human:
    def __init__(self):
        self.isplayer = False
        self.nhealth = 20.0

    def health_add_one(self):
        self.nhealth += 1

## 2 separate humans
instance_1 = Human()
instance_2 = Human()

instance_1.health_add_one()
print instance_1.nhealth
print instance_2.nhealth

Next, store each instance in a dictionary or list that you can pass around the program.

Ene Uran commented: agree with you +13
woooee 814 Nearly a Posting Maven

There is a list on the Python wiki.

woooee 814 Nearly a Posting Maven

You can just code a while() instead of the if() and while().

hours = 0
while int(hours) > 60 or int(hours) < 1:
    hours=raw_input('Hours worked:')
    #
    # the following is poor syle; use if statement instead
    #if hours == 'DONE':
        #break
    #else
    #
    if hours.upper() != 'DONE':
        hwage = 0
        while int(hwage) > 20 or int(hwage) < 5:
            hwage=raw_input('Enter hourly wage:')
#
#etc. for the rest of the input
woooee 814 Nearly a Posting Maven

There is a space between the "def" and the function name, so it is
def __init__(self):

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

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

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

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

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

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

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])