sneekula 969 Nearly a Posting Maven

Ah, the pros and cons on posting on an old thread.
If you are interested in a regex solution, I would start a new thread and put regex in the title.

sneekula 969 Nearly a Posting Maven

Well, you could do something like this:

# File_lister2.py
# create a list of all the files and sizes in a given direcory
# and optionally any of its subdirectories (Python2 & Python3)
# snee

import os

def file_lister(directory, subs=False):
    """
    returns a list of (size, full_name) tuples of all files
    in a given directory
    if subs=True also any of its subdirectories
    """
    mylist = []
    for fname in os.listdir(directory):
        # add directory to filename for a full pathname
        full_name = os.path.join(directory, fname)
        # size in kb
        size = int(os.path.getsize(full_name)//1024) + 1
        if not os.path.isdir(full_name):
            # append a (size, full_name) tuple
            mylist.append((size, full_name))
        elif subs==True:
            # optionally recurse into subdirs
            file_lister(full_name)
    return mylist

#dir_name = r"C:\Python31\Tools"  # Windows
dir_name = "/home/dell/Downloads"  # Linux
file_list = file_lister(dir_name)

# show the list sorted by size
for file_info in sorted(file_list, reverse=True):
    print(file_info)

print('-'*66)

print( "The largest file is: \n%s (%skb)" % \
    (max(file_list)[1], max(file_list)[0]) )

"""a typical partial output -->
(24144, '/home/dell/Downloads/ActivePython-2.6.2.2-linux-x86.tar.gz')
(23320, '/home/dell/Downloads/ActivePython-3.1.0.1-linux-x86.tar.gz')
(9288, '/home/dell/Downloads/Python-3.1.tar.bz2')
...
...
------------------------------------------------------------------
The largest file is:
/home/dell/Downloads/ActivePython-2.6.2.2-linux-x86.tar.gz (24144kb)
"""
sneekula 969 Nearly a Posting Maven

Here is a simple number project:

Prime numbers are positive integer numbers that are only divisible by itself or one. For example 2, 3, 5, 7, 11, 13, 17, are prime numbers, by convention 1 is not a prime number.

Palindrome numbers are numbers in which the decimal digits are the same read left to right as they are read right to left. For example 77, 131, 1441.

Your mission is to write a script that determines and prints all palindrome prime numbers less than 100000. Exclude the simple stuff like one digit numbers.

vegaseat commented: interesting +14
sneekula 969 Nearly a Posting Maven

You could do:

for c in "Hello World":
    print c ,

In Python2 the comma puts in a space and keeps it on the same line.

sneekula 969 Nearly a Posting Maven

How do you know when to use a function by wraping the content between parentheses "function(x) or through dot notation x.function()
? thanks.

You are somewhat confused about functions.

sneekula 969 Nearly a Posting Maven

Rugby could become a sport, if they ever show it on the tele in the US.

sneekula 969 Nearly a Posting Maven

Hi i am new to daniweb.com, i was looking around this website and i saw that i needed to register. I am 17 years old and im from Gibraltar, i am studying French Spanish and Computing. I am hoping that i could learn a lot from other members as at the moment i really need it, as this summer i got my A.S results and the only subject that i failed was Computing which rlly pissed me off as that was the subject that i rlly wanted to pass the most :sad:

This year i have been allowed to do A.S and A.2 computing with French and Spanish, but this time i am hoping that i can get help to pass Computing.

Well the homework i have been given was to design and make a program that would convert binary code into a denary integer also backwards from denary to binary code.

I have done a bit of research through the internet, and i have seen some simple programs just by using text boxes and buttons to convert. But atm i do not know much about programming as i am a begginer, if anyone has any free time or have anything that could help me do my homework plz

Thanks ;)

Google gives you 3,870 hits for "Binary To Denary Program", much of it Visual Basic.

sneekula 969 Nearly a Posting Maven

"The hardest thing in the world to understand is the income tax."
~~~ Albert Einstein

sneekula 969 Nearly a Posting Maven

An apple turnover and a cup of hot chocolate.

sneekula 969 Nearly a Posting Maven

Kindly go to the C++ forum.

I went to the C++ forum, but nothing happened. :)

Nick Evan commented: :) +0
sneekula 969 Nearly a Posting Maven

I have a handful of cherry granola cookies with my coffee.

sneekula 969 Nearly a Posting Maven

I made an attempt on user friendly data entry with just such a simple temperature converter program, see:
http://www.daniweb.com/forums/showthread.php?p=992595#post992595

sneekula 969 Nearly a Posting Maven

The ultimate user friendly Temperature Converter program. If you put an 'F' or 'f' on the end of the temperature you enter it will give you Celsius. Otherwise it simply assumes you entered a Celsius value and want Fahrenheit:

# a Fahrenheit/Celsius program easy on the user
# tested with Python25
# snee

def f2c(t):
    """given t Fahrenheit return Celsius"""
    return 5/9.0 * (t - 32)

def c2f(t):
    """given t Celsius return Fahrenheit"""
    return 9/5.0 * t + 32

def extract_number(s):
    """
    extract the numeric value from string s
    (the string can contain only one numeric value)
    return the number or None
    """
    ts = ""
    for c in s:
        if c in '1234567890.-':
            ts += c
    if ts:
        # convert number to int or float
        return eval(ts)
    else:
        return None

def pick_cf(s):
    """given a numeric string s select f or c calculation"""
    t = extract_number(s)
    print('')
    if not t:
        print("***need a number***")
        return False
    if 'f' in s.lower():
        print( "%0.2f Fahrenheit is %0.2f Celsius" % (t, f2c(t)) )
    else:
        print( "%0.2f Celsius is %0.2f Fahrenheit" % (t, c2f(t)) )
    return True
    
prompt = """
Enter a temperature ending with an F to calculate Celsius
otherwise the temperature is assumed to be Celsius and will
give the result in Fahrenheit (press just enter to quit): """

while True:
    s = raw_input(prompt)
    if not s:
        break
    s = pick_cf(s)

Yes Gloria, if you entered $12.99 it will give you the Fahrenheit temperature of 12.99 Celsius.

Ene Uran commented: nicely done bud +8
Lardmeister commented: good thinking +6
sneekula 969 Nearly a Posting Maven

As a beginner use for loops first, later on 'list comprehensions' become more natural.

sneekula 969 Nearly a Posting Maven

Looks like one of the 638 web pages is not available. You should use a try/except trap for this case.

sneekula 969 Nearly a Posting Maven

At first, I would adopt consistent indentations! Very important in Python. Most people use 4 spaces.

sneekula 969 Nearly a Posting Maven

And don't forget to use self to turn those functions into methods for the instance, like
def moveup(self):

sneekula 969 Nearly a Posting Maven

Something like that might do. I avoided the use of float() until the end to keep time-stamp and port info from turning into floats:

raw_data = """\
501 	 0 	 0.932 0.933 0.931 0.931 0.929 0.933 0.93 0.928
501 	 1 	 0.974 0.98 0.978 0.976 0.974 0.974
501 	 2 	 0.953 0.949 0.944 0.951 0.942 0.942 0.942 0.948
501 	 3 	 0.933 0.934 0.934 0.935 0.931 0.933 0.932 0.934
501 	 4 	 0.939 0.934 0.934 0.934 0.937 0.932 0.938
501 	 5 	 0.944 0.942 0.942 0.943 0.939 0.95 0.942 0.948
501 	 6 	 0.974 0.976 0.974 0.971 0.97 0.967 0.971 0.974
501 	 7 	 0.986 0.984 0.984 0.986 0.986 0.984
502 	 0 	 0.927 0.933 0.931 0.931 0.929 0.933 0.93 0.928
502 	 1 	 0.974 0.98 0.978 0.976 0.973 0.971 0.974
502 	 2 	 0.953 0.949 0.951 0.942 0.942 0.942 0.948
502 	 3 	 0.933 0.934 0.934 0.935 0.931 0.933 0.932 0.931
502 	 4 	 0.939 0.934 0.934 0.932 0.937 0.932 0.938
502 	 5 	 0.944 0.942 0.942 0.943 0.939 0.95 0.95 0.948
502 	 6 	 0.974 0.974 0.974 0.971 0.97 0.967 0.971 0.974
502 	 7 	 0.986 0.984 0.984 0.986 0.984 0.986"""

fname = "my_data.dat"
# write the test file
fout = open(fname, "w")
fout.write(raw_data)
fout.close()

# read the test file
fin = open(fname, "r")
data_hol = []
for line_hol in fin:
    line_hol = [x for x in line_hol.split() ]
    data_hol.append(tuple(line_hol))

my_datalist = []
for line in data_hol:
    #print(line[1], line[2:])  # test
    port = line[1]
    # now you can use float()
    data_sum = sum([float(x) for x in line[2:]])
    my_datalist.append((port, data_sum))

# test the list of (port, data_sum) tuples
for tup in my_datalist:
    print(tup)

"""my output -->
('0', 7.4470000000000001)
('1', 5.8559999999999999)
('2', 7.5709999999999997)
('3', 7.4660000000000002)
('4', 6.548)
('5', 7.5500000000000007)
('6', 7.7770000000000001)
('7', 5.9099999999999993)
('0', 7.4420000000000002)
('1', 6.8260000000000005)
('2', 6.6270000000000007)
('3', 7.4630000000000001)
('4', 6.5460000000000003)
('5', 7.5579999999999998)
('6', 7.7749999999999995)
('7', 5.9099999999999993)
"""
sneekula 969 Nearly a Posting Maven

Rice Pudding with Cinnamon

sneekula 969 Nearly a Posting Maven

Bottom Round Steak, pink inside, with cauliflower.

sneekula 969 Nearly a Posting Maven

With wxPython code you can give py2exe an XML based manifest to force it to adopt the Windows XP theme.

sneekula 969 Nearly a Posting Maven

To make more sense you should have written your class this way:

class Animal:
    def __init__(self, legs):
        self.legs = legs
        
cow = Animal(4)
chicken = Animal(2)
octopus = Animal(8)
# Bob is a pet chicken with 1 leg missing
bob = Animal(1)

print( octopus.legs )  # 8
print( chicken.legs )  # 2
sneekula 969 Nearly a Posting Maven

well ok i can go back to pygame then , thanks
but first i whant to try the thing above !!


EDIT:
Dude thanks i tried that and it worked =)
i really appreciate your help
thanks again, and no im not using all the features only the wav playing
thanks!!!

Now I am curious, did that work for Python26?

sneekula 969 Nearly a Posting Maven

Works fine on my Ubuntu machine. I copied the Python25/26 source from the webpage and saved it as cTurtle.py in my working directory. The module has a number of demos built in that look great and work well. I used the IDLE IDE, my normal IDE DrPython bitched about a foreign character somewhere and went on strike as usual.

sneekula 969 Nearly a Posting Maven

Nice, looks like Python3 has bit your fancy.
Sooner or later we all have to follow your example.

sneekula 969 Nearly a Posting Maven

Which Computer Language would you like to know more about, or even start to learn?

sneekula 969 Nearly a Posting Maven

As you start coding larger projects with Python, remember to go in small steps, test each step, ask question here. Python can be fun!

Python is in many ways more advanced and modern than some of the old stale standby languages like Basic, C, C++, C# and Java. There is a lot of power under that hood, so drive responsibly.

sneekula 969 Nearly a Posting Maven

If you own a stopwatch, here is your chance to benchmark the various versions of Python on recursion performance. The Ackermann function gives the old computer quite a workout.

sneekula 969 Nearly a Posting Maven

Phyllobates terribilis (the Golden Poison Frog or the Golden Dart) is the most poisonous frog. A tiny fraction of a drop, 0.00000007 ounces, of its skin secretion is enough to kill a person.

sneekula 969 Nearly a Posting Maven

Plato
> Is <
Boring

sneekula 969 Nearly a Posting Maven

What does not destroy me, makes me stronger.
~~~ Friedrich Nietzsche

sneekula 969 Nearly a Posting Maven

Be careful when you fight the monsters, lest you become one.
~~~ Friedrich Nietzsche

sneekula 969 Nearly a Posting Maven

Two jumbo eggs sunny side up, oat-nut bread toast, and coffee.

sneekula 969 Nearly a Posting Maven
# now all input strings/characters are upper case
choice = raw_input ("A, B, or C\n").upper()
sneekula 969 Nearly a Posting Maven

Simply call the dispatch(choice) function with your choice as argument:

#!/usr/bin/python

def dispatch(choice):
    if choice == 'A':
        functionA()
    elif choice == 'B':
        functionB()
    elif choice == 'C':
        functionC()
    else:
        print "An Invalid Choice"
        
def functionA():
    print "WRONG!"
def functionB():
    print "CORRECT!"
def functionC():
    print "WRONG!"
    
choice = raw_input ("A, B, or C\n")
print "Your answer is", choice
# call the dispatch function with the argument in choice
dispatch(choice)
sneekula 969 Nearly a Posting Maven

I think the last time Google bothered to visit DaniWeb was about a year ago.

sneekula 969 Nearly a Posting Maven

Just finished a little medley of portabella mushrooms, spinach, tomatoes on penne noodles. The spinach and tomatoes came from my folks' garden.

sneekula 969 Nearly a Posting Maven

jcmeyer, could you do me a favor and test this in your code, it makes things a lot more readable, and may avoid errors like you exerienced:

cur_ex = """
INSERT INTO DatabaseName (C1, C2, C3, C4, C5) 
SELECT ?, C2, C3, C4, C5 FROM DatabaseName WHERE C1=?
"""
self.cursor.execute(cur_ex, [newC1Value, copiedC1Value])
self.connection.commit()

BTW, nice solution on your part.

sneekula 969 Nearly a Posting Maven

Like gerard4143 says, you have to make the print statement part of the function, since Tf is local to the function. The other option would be to return Tf to make it available outside the function:

#Convert C to F
def Tc_to_Tf ():
    Tc = input ("What is the Celsius Temperature ?   " )
    Tf = 9.0/5.0 * Tc + 32
    return Tf

Tf = Tc_to_Tf ()
print 'The temperature is ', Tf, ' Degrees Fahrenheit'

Please use the [code=python] and [/code] tag pair to enclose your python code.

sneekula 969 Nearly a Posting Maven

I looked over your code and made the following observations:

To expand your widgets with the frame you need to use a sizer and not absolute positioning.

You sql command string might have errors due to:
1) choices in the combobox needs to be a list of valid choices for fund_id
2) starting and ending dates need to be valid or use a default

BTW, you should be able to rewrite that long sql string this way:

sql = """
        Select * from table where fund_id = '%s' and 
        datetime >= to_date('%s','DD/MM/YYYY') and 
        datetime <= to_date('%s','DD/MM/YYYY')
        """ % (fund_id,start_date,end_date)

Works well with Python's sqlite3

sneekula 969 Nearly a Posting Maven

You mean you want to graph stock values?

sneekula 969 Nearly a Posting Maven

Fibonacci numbers and prime numbers are always a hot topic! Your contribution is welcome!

sneekula 969 Nearly a Posting Maven

Just a little cosmetic code:

# a simple way to display plural strings

def visits(n):
    # adds an s to 'time' if n > 1
    return "I visited you %d time%s" % (n, ['','s'][n>1])

for n in range(1, 4):
    print( visits(n) )

"""my result -->
I visited you 1 time
I visited you 2 times
I visited you 3 times
"""
sneekula 969 Nearly a Posting Maven

Just a quick example on how to use the wx.grid.PyGridTableBase with wxPython's wx.grid.Grid. Provides a simple way to create, load and use a spreadsheet like grid:

# exploring wxPython's wx.grid.Grid()
# load grid via a '(row, col): value' dictionary and a table class
# that inherits and applies wx.grid.PyGridTableBase
# snee

import wx
import wx.grid

class MyFrame(wx.Frame):
    def __init__(self, header_list, data_dict):
        wx.Frame.__init__(self, None, wx.ID_ANY,
            title="ACME Inc. Staff Stats", size=(510,200))

        self.grid = wx.grid.Grid(self)
        self.grid.SetRowLabelSize(30)     # sets leading row width
        self.grid.SetDefaultRowSize(20)   # sets all row height
        self.grid.SetColLabelSize(30)     # sets leading col height
        self.grid.SetDefaultColSize(80)  # sets all col width

        # select the cell with a mouse left click
        self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.cell_click)

        # the table takes care of all the grid stuff
        table = MyTable(header_list, data_dict)
        self.grid.SetTable(table, True)
        
        # optional, calculate rows of data needed for fun stats
        self.rows = max(data_dict.keys())[0] + 1

    def cell_click(self, event):
        """cell has been left clicked"""
        row = event.GetRow()
        col = event.GetCol()
        # move the grid's cursor to frame the cell
        self.grid.SetGridCursor(row, col)
        # you can do some fun stats with the numbers
        num = []
        if col > 0:
            #num = []
            for nrow in range(self.rows):
                num.append(float(self.grid.GetCellValue(nrow, col)))
        val = self.grid.GetCellValue(row, col)
        if num:
            sf = "r%dc%d %s  max=%.1f min=%.1f avg=%.1f" % \
               (row, col, val, max(num), min(num), sum(num)/nrow)
        else:
            sf = "r%dc%d %s" % (row, col, val)
        self.SetTitle(sf)


class MyTable(wx.grid.PyGridTableBase):
    def __init__(self, header_list, data_dict):
        wx.grid.PyGridTableBase.__init__(self)
        self.data = data_dict
        # calculate rows and cols needed to fit the data
        self.rows = max(data_dict.keys())[0] + 1
        self.cols = max(data_dict.keys())[1] + …
sneekula 969 Nearly a Posting Maven

Gribouillis is right, global constants have their place, but like he mentioned, make them stick out. One time when all upper case is appropriate.

sneekula 969 Nearly a Posting Maven

You can also read up on Fibonacci numbers here:
http://www.daniweb.com/code/snippet216645.html
Mentions the slow recursive function and the faster generator function.
BTW, the generator function is 25,000 times faster than the recursive function when calculating the first 30 members of the Fibonacci series.

sneekula 969 Nearly a Posting Maven

The reason I am using

print( "comment found at line %d"  % i )

is that it works with Python2 and Python3.

sneekula 969 Nearly a Posting Maven

Help, I can't find my Ticker code!

sneekula 969 Nearly a Posting Maven

Some simple changes will do:

comments = []
inComment = False
for i, line in enumerate(open(filename)):
    if "//***" in line:
        inComment = not inComment
    elif inComment:  # changed to elif
        print( "comment found at line %d" %i )  # test
        # optionally strip trailing '\n' char
        line = line.rstrip()
        comments.append((i, line)) 

print( comments )

for comment in comments:
    print( comment[1] )
sneekula 969 Nearly a Posting Maven

If you are new to Python, I wouldn't 'putz' around with old Python2. There are simply too many things that Python3 has to offer. Otherwise, after a few years you will be stuck with old Python2 code that does not easily convert to Python3. The little 2to3.py utility program only handles simple stuff.