woooee 814 Nearly a Posting Maven

create a counter that counts how many weeks a certain value gets exceeded

I would suggest using a function for simplicity. Return a "True" or one if the value is exceeded. This also only returns one positive. If it is possible that the value is exceeded more than once in a week, you only want to increment by one per week. Some pseudo python code

def exceeded( values_list, max_value ):
   for value in values_list:
      if value > max_value:
         return 1                   ## exits function on first "found"
   return 0

##---  test it
if __name__ == "__main__":
   exceed_total=0
   values_for_week = [ 1, 2, 3, 4, 5 ]
   result = exceeded(values_for_week, 3)
   exceed_total += result
   result = exceeded(values_for_week, 6)
   exceed_total += result
   print "exceed_total =", exceed_total, " (should equal one)"
woooee 814 Nearly a Posting Maven

One advantage of the class structure is that you don't use globals but self.var_name.

import random
class Cards(object):
    def __init__(self):
        self.cards = {2:4,3:4,4:4,5:4,6:4,7:4,8:4,9:4,10:16,'ace':4}
        self.player = []
        self.playert = 0
        self.comp_tot=0
        self.comp = []
        print self.playert,'hi'
        print "The Game is Blackjack"
    def draw(self):
        f = self.cards.keys()
        a = random.choice(self.cards.keys())
        self.cards[a]-=1
        if self.cards[a] == 0:
            del self.cards[a]
            if len(self.cards)==0:
                print "out of cards"
                return False
        return a
    def First_turn(self):
        print self.comp_tot
        print self.cards
        print self.player
        print self.playert
        card1=self.draw()
        card2=self.draw()
        card2='ace'
        if card1 is not 'ace' and card2 is not 'ace':
            self.player.append(card1)
            self.player.append(card2)
            value=card1+card2
            print "your cards are:",card1,"and",card2
            print value
            playert+=value
        else:
            self.player.append(card1)
            self.player.append(card2)
            count =0
            if card1 =='ace':
                count = 'c1'
                if self.playert+11>21:
                    val = 1
                else:
                    val=11
            elif card2 == 'ace':
                count ='c2'
                if self.playert + 11 >21:
                    val = 1
                else:
                    val = 11
            
                

c = Cards()
c.First_turn()
woooee 814 Nearly a Posting Maven

In context, the post read "Also, both were elected in a year divisible by 20. Reagan was the first President not to die in office" A link to a story about the 20 year Presidential curse. This is too far out there to really be believed IMHO, but is still common to both. http://www.snopes.com/history/american/curse.asp

As to aid to other countries, total dollar amount does not equal aid delivered. Programs like micro-loans, organizations like plenty.org, the Lyons Club recycling glasses, the Peace Corp, and even the one laptop per child project, even thought it hasn't been as successful as projected, are more along the lines of actual aid in that it permanently changes peoples lives for the better. And doesn't have a political motive as may be the case with Cuban doctors. It's the old saw about feeding someone for a day or teaching them to feed themselves.

woooee 814 Nearly a Posting Maven

Just came across this thread. The only surprising thing is that no one has tried to tie the subject to an oxymoron. We Americans are not liked in some parts of the world even though the U.S. does more than any other nation to feed the poor, heal the sick, etc.

Back on topic, does anyone else see parallels between Bush and Reagan. Trickle down theory/tax cuts for the rich yielding a recession, popularity sinking to the mid 30s, somewhere in space most of the time, advisors making the decisions, out of touch with the people. In Reagan's case, his advisors convinced him to cut back on programs favoring the rich (campaign contributors) and between that and actions by the Federal Reserve, the economy recovered. We'll have to see what happens this time. Also, both were elected in a year divisible by 20. Reagan was the first President not to die in office, although I haven't checked the history personally, and Bush is still alive. I wish no one any bad circumstances though.

woooee 814 Nearly a Posting Maven

Not nearly enough info. You'll have to include the code (using code tags because whitespace counts in python-see the "Please use BB Code and Inlinecode tags" thread) and a complete error message
For starters, your code should read

def X(a,b):
   c = a+b

##   note that the backslash is not necessary
x = {"a":"c" , \
       "b":"d"
      }
woooee 814 Nearly a Posting Maven

You can also use the var.find("-s") method for strings and then slice it. It depends on if -s"password" is the only thing in that record or not.

woooee 814 Nearly a Posting Maven

an someone show me some code to convert rankine temperature to kelvin? rankine is in the same scale as fahrenheit, but it starts at absolute zero. so 0R = -459.67F, heres is what I have

So rankine would be fahrenheit -459.67 the way I read what you have said

def to_rankine_from_celsius( tempC ):
   fah = convert_to_fahrenheit_from_celsius(tempC)
   return fah-459.67
#
def from_rankine_to_celsius( tempR ):
   cel = convert_from_fahrenheit_to_celsius(tempR+459.67)
   return cel
#
##   In python you can call arguments individually if this will make it easier
##   The formula for celsius <---> fahrenheit can also be stated as 9C + 160 = 5F
def Cel_Fah( cel=-999, fah=-999):
   if fah > -999:
      ## 9C + 160 = 5F
      ## 9C = 5F - 160
      c9 =(5 * fah) - 160
      c = float(c9) / 9
      print c
      
   if cel > -999:
      ## 9C + 160 = 5F
      ## 5F = 9C + 160
      f5 =(9 * cel) + 160
      f = float(f5) / 5
      print f

Cel_Fah( fah=100 )
Cel_Fah( cel=30 )
woooee 814 Nearly a Posting Maven

Since you enter the Python interpreter, run the program, and then exit the interpreter, I don't think there is a way. The interpreter will always return you to the original directory when it exits. Perhaps someone else will have other ideas on this.

woooee 814 Nearly a Posting Maven

You should be able to do something like the following so you don't have to re-read the file for every record in file_1.

file_1 = csv.reader(open('file_1.csv', 'rb'))
file_2_list = list(csv.reader(open('file_2.csv', 'rb')))
for (ID1, begin1, end1) in file_1:
    for (ID2, begin2, end2) in file_2_list:
woooee 814 Nearly a Posting Maven

biggetst effect in future, and so we need one who can take good strict decisoin!

Margaret Thatcher was no better or worse than any other Prime Minister in the UK. She served for something like 10 years, took on the labor unions, etc., etc. Hopefully, in any election where there is some kind of discrimination, the pro-female/race/age voters and the anti cancel each other out so the race becomes about who will do the best for the people. The US Democratic Party's nomination campaign is more about selfish vs. will try to serve the people perceptions, than it is about gender or race.

woooee 814 Nearly a Posting Maven

A link to a Tkinter tutorial/reference
http://infohost.nmt.edu/tcc/help/pubs/tkinter/

woooee 814 Nearly a Posting Maven

Add some print statements to see what is going on and it should become obvious.

for ID1, begin1, end1 in file_1:
    print "file_1 =", ID1, begin1, end1
    for ID2, begin2, end2 in file_2:
        print "     file_2 =", ID2, begin2, end2
woooee 814 Nearly a Posting Maven

I have one more thing that I don't understand your code. why would you use " if year <5" ?

To stop the loop after 5 iterations, because 5 iterations is more than enough to make the point.

woooee 814 Nearly a Posting Maven

Also, this will not work. You have two separate blocks of memory. I have reduced your code so it only tests the year variable. The value at memory block #2 never changes so that snippet only prints once, (i.e it is initialized as year[memory block #1]+1 = 0+1 at a separate location [memory block #2]). It is not a good idea to use "i", "l", "o" as single character variable names. They look too much like numbers.

year = 0     ## memory block #1
for i in range (year+1):     ## memory block #2
   if year < 5:
      year = year + 1        ## memory block #1
   print year                ## memory block #1
#
#
print "\n\n A while statement will work though since"
print 'there isn't a local variable like there is in the "range" statement'
year = 0                                                                        
ctr = 0                                                                         
while ctr < year+1:     
   if year < 5:
      year = year + 1                                                           
   print year                                                                   
   ctr += 1                                                                     
   if ctr > 1000:     ##  prevent infinite loop
      break
woooee 814 Nearly a Posting Maven

OpenOffice will import comma delimited text files, or any other delimiter that you care to choose. If there are commas in the data then use something like comma+space+space as the delimiter. Here is a dated link for creating the spreadsheet in python. It refers to StarOffice (or something like that), which is a former incarnation of OpenOffice, so hopefully this still works. http://www.oooforum.org/forum/viewtopic.phtml?t=8456 Searching the oooforum will probably yield more hits. Hope this gets you started.

woooee 814 Nearly a Posting Maven

To work the way you want, your original code would have been
c=lasin ()
sum, pile=dela(c)
ordna(pile)
If the function returns two variables, but the calling line only receives one variable, then python returns one tuple, because you only have one block of memory allocated for the return.

woooee 814 Nearly a Posting Maven

We had a topic like this a short while ago. The easiest/most efficient method is to use two sets and compare with set1.difference(set_2) and vice-versa. Also, python has difflib which may or may not be more than you want. http://docs.python.org/lib/differ-examples.html

woooee 814 Nearly a Posting Maven

"list index out of range" has nothing to do with the size of the list AFAIK. If the list were too large there would be some sort of out of memory message.

Is there any other efficient datastructure other than lists and dictionary to serve the purpose ?

SQLite can be used in memory but you'll have to provide some more info on how many records you want to store, what is the size of each record, and what you want to do in order to be more specific.

woooee 814 Nearly a Posting Maven

It might be helpful to take a look at the "Starting Python" at the top of this forum. There are 5 pages, so don't have to wade through 100's of pages to get you started.

woooee 814 Nearly a Posting Maven

Obviously this is not a list of numbers, so you want to take a look at the function that returns this. Add print statements to see what is going on throughout the program until you understand what is happening

woooee 814 Nearly a Posting Maven

If you want to run this program file by itself, put the following at the bottom. You can then run the program from the command line with "python program_name". Take a look at the "Starting Python" thread at the top of this forum.

if __name__ == "__main__":
   opener
woooee 814 Nearly a Posting Maven

You best bet would be to ask the person on python-forum.org who wrote this program. They would understand it better than anyone else. No one wants to spend their time answering a question that has already been answered on another forum.

woooee 814 Nearly a Posting Maven

You are probably calling self.Recite without an if statement. An example

class LawRecite:
   def __init__(self):
      self.ThreeLaws = False
      ## only if ThreeLaws is True
      if self.ThreeLaws:
         self.Recite()
woooee 814 Nearly a Posting Maven

AttributeError: LawRecite instance has no attribute 'ThreeLaws'
Is the program searching for a definition for "ThreeLaws"?

It is searching for self.ThreeLaws in the LawsRecite class. I just ran the test snippet that I posted and it works fine so check the spellings for self.ThreeLaws and LawRecite on your end. Also, you will avoid potential problems if you don't use spaces in directory or file names. "C:\Users\Loren\Desktop\My Robots\Nina Verbal Raw Input.py",

woooee 814 Nearly a Posting Maven

There has to be better code to copy. Unless you have to modify that specific program, I would suggest finding program without the Tkinter stuff and copy that. You can add a GUI later after the rest of it is working. Also, when you copy a program and are trying to understand it, add print statements so so can see what is in the containers, and what is happening in the loops. The first thing though would be to break this up into functions so you have some chance of understanding it, and then test each function individually.

woooee 814 Nearly a Posting Maven

i like eating and coking

favourite things:

scones
homemade tablet
haggis with parsnips and potatoes (mashed)
shortbread

Coking? I though a spell checker would kick that out, but it turns out that coking is the process of making coke while distilling coal. Look at the length of this topic. Perhaps we should start a "Dani's Cooking and Bowling" cook book.

woooee 814 Nearly a Posting Maven

If it is a self.variable_name, then it is global throughout the class. I'm too tired to test this snippet so if there are other problems, post back.

class LawRecite:
   def __init__(self):
      self.ThreeLaws = False
      self.Recite()

   def Recite(self):
      ##speaker.Speak(LOR1)
      ##speaker.Speak(LOR2)
      ##speaker.Speak(LOR3)
      ##speaker.Speak(random.choice(LOR4))
      print "ThreeLaws original =", self.ThreeLaws

      self.ThreeLaws=True
      print "ThreeLaws changed =", self.ThreeLaws

      self.ThreeLaws=3
 
LR = LawRecite()
print "after changing to 3 =", LR.ThreeLaws
woooee 814 Nearly a Posting Maven

You may have more than one block of memory named "LawRecite". If you assign True in a loop or function then it is local to that loop/function and will be destroyed when you exit unless you return the value from the function. Change any variable names that are in a function and are the same as any outside the function/loop. That should clear things up. Also, "if True" and "while True" are redundant as vegaseat already pointed out. It should be

if LawRecite == True:
    print 'Lets talk about the three laws of Robotics'
    ## while LawRecite == True:   redundant
    speaker.Speak(LOR1)
    speaker.Speak(LOR2)
    speaker.Speak(LOR3)
    speaker.Speak(random.choice(LOR4))
else:
    speaker.Speak('Yes please what?')

If this doesn't help, please post more of the code in context.

Edit: This should definitely be a class. Then you can use self.LawRecite throughout and it will be the same variable. If the program is not using a class, someone here will probably help rearrange the code into the class structure.

woooee 814 Nearly a Posting Maven

The problem is I need to take the names of the images in Directory A and apply them to the images in Directory B.

What does this mean? Rename a file with some unknown name combination? See if a name in is both dirs?

woooee 814 Nearly a Posting Maven

And apparently a variable as well
readLines = readLines(line,lines,lineNumber)
isPageValid = isPageValid(testLine,validPages)

Try this instead

def isPageValid(testLine,  validPages_list):
   ##isPageValid = False    <----- Not Used
   for valid_page in validPages_list:
      if testLine in valid_page:     ## or do you want
                                     ## if valid_page in testLine ?
         return True
   return False
woooee 814 Nearly a Posting Maven

To copy a list you would use
a3 = a[:]
print a3

If you don't want an exact copy you would append to another list

a=['city','village','town','capital']
a3=[]
for x in a:
   print "x in a =", x
   if x.startswith( "c" ):
      print "     appending", x, "to a3"
      a3.append(x)
print a3
woooee 814 Nearly a Posting Maven

If you are not changing the contents of one or both of the lists, then use a tuple instead:

tuple1 = tuple(list2)
woooee 814 Nearly a Posting Maven

This is a very simple example of how you could use SQLite in memory. This may be a case of the difficult way actually being the simpliest. Note that this is just a simple/quick example. There is a lot more on the web. If this is of some help you can thank The Blues. I was looking for something that I could do while listening to Bad Dog Blues.

import sqlite3 as sqlite

##----------------------------------------------------------------------
def add_rec(cur, con, add_tuple):
   print "add_rec", len(add_tuple)
   cur.execute("insert into test_it values (?, ?, ?, ?, ?, ?, ?, ?, ?)", add_tuple)
   con.commit()

##----------------------------------------------------------------------
def print_all_recs(cur):
   # Execute the SELECT statement:
   print "Printing all recs"
   cur.execute("select * from test_it")

   # Retrieve all rows as a sequence and print that sequence:
   recs_list = cur.fetchall()
   for rec in recs_list:
      print rec
      print "     stage, REAC_W =", rec[1], rec[5]

##----------------------------------------------------------------------
def add_test_data(cur, con):
   #----->              Stage     REAC_PS  WR(T)/P    TTO       REAC_W    W0       0wR(THCR)E/D  PTO
   data_list=[ ('2.0', 'Stage1', '0.509',  '4.3010', '1602.30', '0.515', '3.191',   '2.8191',   '29.7010'), \
               ('2.0', 'Stage2', '0.488',  '6.0074', '1470.43', '0.500', '3.200',   '3.9309',   '20.4275'), \
               ('2.0', 'Stage1', '0.524',  '4.4623', '1602.30', '0.560', '3.311',   '2.9243',   '29.7010'), \
               ('2.0', 'Stage2', '0.579',  '6.6682', '1444.78', '0.700', '3.320',   '4.3593',   '18.9262'), \
               ('3.0', 'Stage1', '0.524',  '4.4623', '1602.30', '0.560', '3.311',   '2.9243',   '29.7010'), \
               ('3.0', 'Stage2', '0.579',  '6.6682', '1444.78', '0.700', '3.320',   '4.3593',   '18.9262'), \
               ('3.5', 'Stage1', '0.525',  '4.4695', '1602.30', '0.563', '3.316',   '2.9290',   '29.7010') ]

   for data_tuple in data_list :
      add_rec(cur, con, data_tuple)

##----------------------------------------------------------------------
if __name__ == "__main__":
   # Create a connection to the (memory) database file
   con = sqlite.connect(':memory:')

   # …
woooee 814 Nearly a Posting Maven

i'll definitely give the dictionary of classes a try, but i still think i might be missing something...

'results[p] = {}' should only initialize that key's value since every value of 'p' is unique. for example:

dict = {}
dict[0] = 0
dict[1] = {}
dict[2] = 2
print dict

{0: 0, 1: {}, 2: 2}

Either results[p] is unique or it's being overwritten/initialized to an empty dictionary. I don't know which it is without being able to see more data. Add a print statement so you can see what p is in every loop.

woooee 814 Nearly a Posting Maven

New entries are not being over-written. You are initializing to an empty dictionary with the statement results[p] = {}. Perhaps (and just perhaps) a dictionary of classes would serve better. Note that SQLite can also be used in memory, i.e you can store and lookup '2.0' + 'Conditions' + 'Vane2INLET', etc. or however you want to store it. Either would be less confusing IMHO.

class Class1 :
   def __init__ (self) :
      self.field1 = ""
      self.field2 = 0
      self.field3 = "***"

#====================================================
sample_dic = {}
C = Class1()
C.field1 = "Test1"
C.field2 = 1
C.field3 = "Test1A"
sample_dic["test1"] = C

C = Class1()
C.field1 = "Test2"
C.field2 = 2
C.field3 = "Test2A"
sample_dic["test2"] = C

C = Class1()
sample_dic["test3"] = C

##   note that dictionary keys are not in any order
for key in sample_dic.keys() :
   print key, sample_dic[key].field1, sample_dic[key].field2, \
                 sample_dic[key].field3

sample_dic["test3"].field2=3
print "updated field2 =", sample_dic["test3"].field2
woooee 814 Nearly a Posting Maven

Deleting new_num from x does nothing useful. You are using num and deleting new_num which may or may not be in x. You want to append to y if num > 0

for num in x:
   if num > 0:     ## eliminate if num-1 <= zero
      y.append(num-1)
      b+=1
woooee 814 Nearly a Posting Maven

Did the shelve module work or do you still want to debug the dictionary class?

woooee 814 Nearly a Posting Maven

The simpliest way is an easygui or Tkinter/PMW dialog box with one button. However, this is something found on the web long ago. It is probably also possible to do with ncurses.

import termios, sys, os
#import termios, TERMIOS, sys, os
TERMIOS = termios
def getkey():
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        new = termios.tcgetattr(fd)
        new[3] = new[3] & ~TERMIOS.ICANON & ~TERMIOS.ECHO
        new[6][TERMIOS.VMIN] = 1
        new[6][TERMIOS.VTIME] = 0
        termios.tcsetattr(fd, TERMIOS.TCSANOW, new)
        c = None
        try:
                c = os.read(fd, 1)
        finally:
                termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)
        return c

if __name__ == '__main__':
        print 'type something'
        s = ''
        while 1:
                c = getkey()
                if c == 'q':
                        break
                print 'got ("q" = end)', c
                s = s + c

        print s
woooee 814 Nearly a Posting Maven

It's something along the lines of
os.system("firefox http://www.google.com")

woooee 814 Nearly a Posting Maven

Some modifications to your code. First you have to test for zero, and second, the variable "b" is not necessary as you can just use len(x). Hopefully this is what you want to do.

def kopi(x):
    y = []
    for num in x:
        new_num = num - 1
        if new_num < 0:
           new_num=0
        print new_num,
        y.append(new_num)
    y.append (len(x))
    print len(x)
    print "new list inside function", y
    return y

##   15 iterations
if __name__ == "__main__":
   x=[4,4,2]
   print "the beginning list is", x
   for k in range(0, 15):
      x=kopi(x)
      print "the list is now", x, "\n"
woooee 814 Nearly a Posting Maven

Sorry about that. You do want intersection and not union.

woooee 814 Nearly a Posting Maven

Using set.union would give words that are found in both. Again, it is indexed and would be much faster. If you want to use your original idea, then use a dictionary for the words in the base text as the lookup would be 100s of times faster than using 2 lists. This is an example using a dictionary instead of a list.

dic_1 = {}
for word1 in list1:
     if word1 not in dic_1:
          dic_1[word1]=0.
for word2 in list2:
     if word2 in dic_1:
          dic_1[word2] += 1

total_words_found=0
for key in dict_1:
     if dict_1[key] > 0:
          total_words_found += 1
result = float(total_words_found) / (len(list1) + len(list2))
##
##   or
found_set = set_1.union(set_2)
result = float(len(found_set)) / (len(list1) + len(list2))
woooee 814 Nearly a Posting Maven

Maine is the only state whose name is just one syllable.

"Stewardesses" is the longest word typed with only the left hand and "lollipop" with your right.

May or may not be true, but the QWERTY keyboard came about because typewriter companies in the early 1800s wanted their salesmen to be able to type something quickly to show how efficient it was. They could rapidly type the word "typewriter" because all of the letters were placed in the top row on a QWERTY keyboard.

woooee 814 Nearly a Posting Maven

I'm not sure comparing words will give the best results. If two articles use "and", "the", "a", "of", "to", etc. a lot then they will be deemed similar. If you want to do it that way, then go through each of the two files and place unique words in a set (that is if it is not found in that set). Then use can use the number of words from set_a.difference(set_b) to determine how similar they are. Sets are indexed and so should be hundreds or thousands of times faster.

woooee 814 Nearly a Posting Maven

And if you mean something very simple to time some program once, use datetime.

import datetime
import time
start_time = datetime.datetime.now()
time.sleep(2)
print datetime.datetime.now() - start_time
woooee 814 Nearly a Posting Maven

Use code tags and submit some sample data in raw form and how you want it to appear after formatting. There is not enough information in your post.

woooee 814 Nearly a Posting Maven

I do not agree with a word that you say, but I will defend to the death your right to say it.
(Voltaire aka François-Marie Arouet)

Worth quoting a second time.

woooee 814 Nearly a Posting Maven

For God so loved the world that he gave his one and only Son, that whoever believes in him shall not perish but have eternal life.

This does not say anything about the "righteous" being taken up to heaven and the rest will perish in some (un)natural disaster. It is nowhere in the Christian Bible that I know of. The idea itself is full of flaws. One is that heaven, if it does indeed exist (and we don't know if it does or not), is the way that it is because that is the kind of "place" that the angels have made it. To suck a bunch of us mere mortals up all at once would pollute heaven into something much lower, by definition. So it wouldn't be heaven any more. (I know, all it takes is a miracle).

And in the above quote, what does "believes in him" mean. Who is "him". It could be God. It could be Jesus. If could be your own inner soul. Also, there is no time frame. It would make sense, that after another million years of human evolution, the few degenerates that are left would perish. Those would be the people who call themselves "Christian" yet hope for the destruction of others, some of whom are Christian, some not. This is not a good quality for any "human" being to have, let alone a Christian. It goes against everything that Jesus said and stood for. "For God so loved the world". …

woooee 814 Nearly a Posting Maven

Or maybe a dozen EMPs? Naw.

But it does make for occasional interesting reading.

Yes it does. Back up your data to CD/DVD just in case. While there would be definite damage, most critical services have a contingency plan and/or computers that are shielded. Multi-national companies have backup data all over the planet. I think some of this comes from the James Bond film where the villan cracked the Bank of England's computer and was going to electronically transfer the assets and then use an EMP bomb to wipe out the bank's records. Well what happens if he succeeds? Does he drive up to the bank with 100 trucks (excuse me lorries) and say "This computer says I own all of your assets so start loading". The bankers would quietly call the nice men in the white coats. There would be damage, but probably not catastrophic chaos IMHO.

woooee 814 Nearly a Posting Maven