sneekula 969 Nearly a Posting Maven

Notice in a farmer's field:
The Farmer Allows Walkers To Cross The Field
For Free, But The Bull Charges.

sneekula 969 Nearly a Posting Maven

Merry Christmas and a Happy New Year from the Great White Midwest!

sneekula 969 Nearly a Posting Maven

Write a programmer's calculator that shows a numeric integer entry in denary (base10), binary(base2), octal(base8) and hexadecimal (base16). Allow entry in any of these bases.

Also does some simple binary stuff like shift-left and shift-right, binary or, binary and and binary xor.

If the integer falls into the ASCII range, display its character or meaning.

sneekula 969 Nearly a Posting Maven

There is a small introduction at:
http://www.daniweb.com/forums/post764519-155.html

sneekula 969 Nearly a Posting Maven

Decorator functions can simplify Python coding, here is an example:

# exploring decorator functions (new since Python24)
# which are higher functions that create new functions
#
# decorator functions are constructed using a function
# within a function (sometimes called wrapper functions)
# when you define a function inside of another function,
# any undefined local variables in the inner function will
# take the value of that variable in the outer function
# snee

def check_num(func):
    """
    a decorator function to check if another 
    function's argument is a number
    """
    def inner(arg):
        # arg is the argument of function func"""
        if type(arg) in (int, float):
            return func(arg)
        else:
            print("need numeric value as argument")
    return inner


# you apply the decorator with prefix @
# directly above the function you want to check
# this is equivalent to print_num = check_num(print_num)
@check_num
def print_num(n):
    print("Number = %s" % n)


# test ...
print_num(7)    # Number = 7
print_num(7.11) # Number = 7.11
print_num('a')  # need numeric value as argument

print('-'*40)

# check alternative approach ...
def print_num2(n):
    print("Number = %s" % n)

print_num2 = check_num(print_num2)

# test ...
print_num2(7)    # Number = 7
print_num2(7.11) # Number = 7.11
print_num2('a')  # need numeric value as argument

I am using the print() function, so it will work with Python25 and Python30.

sneekula 969 Nearly a Posting Maven

Instead of a listbox, use a 2 column listcontrol, where the second column is for the value.

sneekula 969 Nearly a Posting Maven

If the word you enter is 'xp11' then it will do that.

BTW you don't have to subtract one from wordsize, randrange() work like range().

Give it a test:

import random

#word = raw_input("Enter a word: ")
word = "consumer"
wordsize = len(word)
for k in range(10):
    randomnumber = random.randrange(0, wordsize)
    print word[randomnumber]
sneekula 969 Nearly a Posting Maven

If I did my job as poorly as it seems the bank and auto execs are doing, that is, if 80+ students a term end up knowing less than when they started the term (which often isn't much), would I be getting a bonus and keeping my job? I think not.

Apparently the entitlement mentality exists at both ends of the spectrum.

Help a needy executive!
(apologies if this has already been posted, I can't remember where I first saw it linked.)

The ultimate donate your money commercial!

sneekula 969 Nearly a Posting Maven

Do they celebrate by throwing their shoes at foreigners?

sneekula 969 Nearly a Posting Maven

In a laundromat:
Automatic washing machines, please remove
all your clothes when the light goes out.

sneekula 969 Nearly a Posting Maven

The wx.RichTextCtrl() widget allows the user to create formatted text with color, size, font, bullets, images and more:

# experiment with wxPython's
# wx.RichTextCtrl(parent, id, value, pos, size, style=wx.RE_MULTILINE, 
#    validator, name)
# allows you to create formatted text with color, size, font, images ...
# snee

import wx
import wx.richtext

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
        self.SetBackgroundColour("white")
        
        self.rich = wx.richtext.RichTextCtrl(self, wx.ID_ANY, value="")
        self.rich.WriteText("Default is black text.\n")
        self.rich.BeginBold()
        self.rich.WriteText("Write this text in bold")
        self.rich.BeginTextColour('red')
        self.rich.WriteText(" and this text in bold and red.\n")
        self.rich.EndTextColour()
        self.rich.EndBold()
        
        self.rich.BeginFontSize(30)
        self.rich.WriteText("This text has point size 30\n")
        self.rich.EndFontSize()
        
        font = wx.Font(16, wx.SCRIPT, wx.NORMAL, wx.LIGHT)
        self.rich.BeginFont(font)
        self.rich.WriteText("This text has a different font\n")
        self.rich.EndFont()
        self.rich.Newline()
        # indent the next items 100 units (tenths of a millimeter)
        self.rich.BeginLeftIndent(100) 
        
        # insert an image you have in the work directory
        # or give the full path, can be .bmp .gif .png .jpg
        image_file = "Duck2.jpg"
        image= wx.Image(image_file, wx.BITMAP_TYPE_ANY)
        # wx.BITMAP_TYPE_ANY   tries to autodetect the format
        self.rich.WriteImage(image)
        self.rich.Newline()
        self.rich.EndLeftIndent()
        

app = wx.App()
mytitle = 'testing wx.RichTextCtrl'
width = 560
height = 400
# create the MyFrame instance and show the frame
MyFrame(None, mytitle, (width, height)).Show()
app.MainLoop()
sneekula 969 Nearly a Posting Maven

What I mean by code blocks are specific to this board. When you post code on the board you should enclose the code in code tags so that it is more readable. You are correct that in the Python language code is grouped together by indentation only.

The difference between input and raw_input is that input accepts an integer and raw_input accepts a string. The general consensus on this board seems to be that you should almost always use raw_input and then use other code to validate the response. A different thread talked about security vulnerabilities that could open up when you assume that the user is going to enter an integer. I used input for this example because I was just demonstrating and I didn't want to muddy the water by validating the input, converting to an integer, etc.

I agree! Most IDE editors made for Python, like IDLE or DrPython, will help you with the indented blocks. Pretty much the standard is to indent 4 spaces. Don't use tabs since they change with the editor settings.

The good news is that the latest Python version 3.0 (aka Python30) has done away with the input()/raw_input() confusion. From now on it's only input() and that one returns a string.

sneekula 969 Nearly a Posting Maven

Take a look at Python module struct in the Python manual.

sneekula 969 Nearly a Posting Maven

Take a stare at:
C:\Python30\Tools\Scripts\2to3.py
and use something like:
2to3 -w example.py

sneekula 969 Nearly a Posting Maven

Chances are good that it will not run!

sneekula 969 Nearly a Posting Maven

Python30 has been released, install it and go through much of the existing sample Python code and rewrite it so it will work on Python30.

sneekula 969 Nearly a Posting Maven

My father owns a lot of tobacco stock, please don't quit smoking!

~s.o.s~ commented: Haha, nice one. +26
sneekula 969 Nearly a Posting Maven

I don't know who did the math, but $25/hour times 2080 hours in a work year is $52K, not 44K.

>>We are not talking bailouts, but loans.
Bailouts for the banks are loans too. "Bailouts" doesn't mean free money with no repayments.

Don't forget that the average US worker has to work January through May every year just to pay the taxes.

sneekula 969 Nearly a Posting Maven

Sorry if I am post in "/forums/forum152.html" category, but I am think it's the most suitable.
Stay not long time before christmas and happy new years holidays. I am have big famaly and now I am even not know what kind of gifts make to my friends and famaly.
So my kids, husband, siters, brother and my and husban's parents. :)
Who also don't know what to present to they? What gifts (not expensive) I can present to my famaly? Any ideas?
What your friends and parent get from you on christmas? :)
Thank you!

An English Dictionary comes to mind.

sneekula 969 Nearly a Posting Maven

Over 60% of all hits on the internet are on seggs-sites!

sneekula 969 Nearly a Posting Maven

I like my coffe hot.

sneekula 969 Nearly a Posting Maven

What delights us in visible beauty is the invisible.
~~~ Marie von Ebner-Eschenbach

sneekula 969 Nearly a Posting Maven

What do you think about bailing out the top slime at the banks, so they can carry home their million dollar bonuses at taxpayer's expense?

sneekula 969 Nearly a Posting Maven

Bail out the UAW for the bargain price of only $500 billion!

Some blogger didn't do the required homework again. The $75 attributed to the UAW autoworker includes all the benefits and the retiree burden. The actual wage of a UAW worker is $28. I have many friends that work for the auto industry and none of them makes close to $75, that is just utter BS.

We are not talking bailouts, but loans.

Over time, all cars will be made in China or India were folks are willing to work for $1/hour. Of course that will be the fate of a lot of other US industries.

sneekula 969 Nearly a Posting Maven

What is your price range?
If yo have XP now, prepare to get used to Vista, but then Linux would be even a steeper learning experience.

Why not Dell?
I am happy with my hand-me-down Sony Multimedia machine.

sneekula 969 Nearly a Posting Maven

Last week I stated that this woman was the ugliest woman I had ever seen. I have since been visited by her sister and now wish to withdraw that statement.

sneekula 969 Nearly a Posting Maven

There are as many colours in a rainbow as there are drops of rain.

sneekula 969 Nearly a Posting Maven

You can do it this way ...

house= ["computer", "laptop", "tv", "nintendo DS", "table", "Empty"]

print "items in my house are:"
print house

menu = """\
Pick an item to fill in the empty space:
1 - Lamp
2 - bed
3 - NDS
q - to quit
"""

print menu

while True:
    print
    choice = raw_input("Type a number and press enter: ")

    if choice =="1":
        house[5] = "lamp"
        print "Items in my house are now:"
        print house

    elif choice =="2":
        house[5] = "bed"
        print "Items in my house are now:"
        print house

    elif choice =="3":
        house[5] = "NDS"
        print "Items in my house are now: "
        print house

    elif choice.lower() == 'q':
        break

    else:
        print "\nYou need to pick a number from 1-3 \a"

raw_input("\n\nPress the enter key to exit. ")
sneekula 969 Nearly a Posting Maven

Looks like one of those made up news stories that fill in when there isn't much news. Wonder what will happen to all those kids who were name 'George Walker Bush' by their excited tax-relieved parents.

sneekula 969 Nearly a Posting Maven

Immanuel Kant wrote:
Science is organized knowledge. Wisdom is organized life.

sneekula 969 Nearly a Posting Maven

Here the Python module struct will come to the rescue, check the Python manual.

sneekula 969 Nearly a Posting Maven

what is the reason why Python doesn't have switch statement ?

Even in C the switch/case is not as efficient as multiple if/else and the cases are rather limited.

Actually, a dictionary makes an excellent replacement for a switch/case and is very high speed on the lookups:

# a dictionary switch/case like statement to replace
# multiple if/elif/else statements in Python

def switch_case(case):
    return "You entered " + {
    '1' : "one",
    '2' : "two",
    '3' : "three"
    }.get(case, "an out of range number")

num = raw_input("Input a number between 1 and 3: ")
print switch_case(num)
sneekula 969 Nearly a Posting Maven

One way to do this:

# creates variables qq1 - qq4 and initializes to 77
for i in range(1, 4):
    exec "%s = %d" % ('qq' + str(i), 77)

print qq1  # 77
sneekula 969 Nearly a Posting Maven

Murtan's code is the cleaner code. In paulthom12345's code range(len(w1)) changes as w1 gets shorter, always a dangerous thing to do in a for loop.

If you want to use one more random option, here it is:

import random
w1 = ["abacus", "biology", "chemistry", "dog",  "elf", "ghost"]
# make a list of unique random index values 0 to 5 here
ix_list = random.sample(range(len(w1)), len(w1))
for ix in ix_list:
    print w1[ix]
sneekula 969 Nearly a Posting Maven

p = re.compile(r'(href="(.*?)")')

will do the trick

sneekula 969 Nearly a Posting Maven

To represent a floating point number in a formatted form for print, you have to store the result as a string in your list:

# representing print formatted floats in a list

list_floats = [1/3.0, 1/6.0, 3.124567, 5.01]

print list_floats

"""
my output (note the typical float representation problem) -->
[0.33333333333333331, 0.16666666666666666, 3.1245669999999999, 5.0099999999999998]
"""

# create a new list of floats using round()
list_floats2 = []
for n in list_floats:
    list_floats2.append(round(n, 5))

print list_floats2

"""
my output (notice we are still dealing with floats) -->
[0.33333000000000002, 0.16667000000000001, 3.1245699999999998, 5.0099999999999998]
"""

# to make round() stick for your print
# you have to store the result as a string
list_floats3 = []
for n in list_floats:
    list_floats3.append(str(round(n, 5)))

print list_floats3

"""
my output -->
['0.33333', '0.16667', '3.12457', '5.01']
"""

# or ...
list_floats4 = []
for n in list_floats:
    list_floats4.append("%0.5f" % n)

print list_floats4

"""
my output -->
['0.33333', '0.16667', '3.12457', '5.01000']
"""

The behaviour of a floating point number you notice here is typical of many computer languages.

sneekula 969 Nearly a Posting Maven

The same way as you do with Python.

sneekula 969 Nearly a Posting Maven

******() is not allowed as a function name. A function name has to start with a letter or an underscore and can contain numbers.

sneekula 969 Nearly a Posting Maven

You could also use:

def fuzzy_equals(a, b, delta=0.0001):
    """
    returns true if (b-delta) < a < (b+delta)
    used for comparison of floating point numbers a and b
    """
    return abs(a-b) < delta

Adjust your delta to suit you.

sneekula 969 Nearly a Posting Maven

Please use code tags for your code.

You are getting close, but you need to find if the score is a new minimum or maximum each time through the loop. Something like this:

infile = open("test_scores.dat", "r")
mylist = infile.readlines()
infile.close()

# remove the header, first item in the list
del mylist[0]

max_score = 0
min_score = 100
for line in mylist:
    # split each line into a list at space/whitespace and unpack
    last_name, first_name, ID, score = line.split()
    # for testing only
    print last_name, first_name, ID, score
    # create integer scores
    if score.isdigit():
        score = int(score)
        # check if it is a new max
        if score > max_score:
            max_score = score
        # check if it is a new min
        elif score < min_score:
            min_score = score

Then just print out the max_score and min_score results.

Please study the code and the comments!

sneekula 969 Nearly a Posting Maven

Just a note, don't use function names like list as variable names.

mylist =  ["very", "hot", "day"]
print "".join(mylist)  # veryhotday

# or use this, might be more descriptive for a beginner

# empty string
s = ""
for word in mylist:
    # concatenate words
    s += word

print s  # veryhotday
sneekula 969 Nearly a Posting Maven

Please use code tags around your code.
Something like this will do the summation:

sum = 0
n = 1
while n < 101 :
    sum += n
    print n, sum
    n = n+1

Note that sum += n is the same as sum = sum + n

Proper code tags are
[code=python]
your Python code here

[/code]

sneekula 969 Nearly a Posting Maven

Since I don't have any of the many versions of Linux, I can not test wx.Clipboard. I think it would be easier to store your text in a file for use across programs.

If you use a wx.TextCtrl, can you highlight, rightclick and copy/cut and paste from the popup menu? That would use the clipboard.

sneekula 969 Nearly a Posting Maven

wx.TextCtrl has a wx.TE_RICH style, but it works under Windows only!

sneekula 969 Nearly a Posting Maven

Nobody is ever bored on DaniWeb!

http://www.growingkids.co.uk/AvoidingBoredom.html

sneekula 969 Nearly a Posting Maven

So he's chosen as his Chief of Staff someone who was very much in bed with Freddie and Fannie; on his economy team is the governor of a state that's in economic shambles.

Yes, this will work out really well.

Change. That's all we'll have left in our pockets.

Did you get the 4 feet of snow?

sneekula 969 Nearly a Posting Maven

Oprah is the devil.

I have seen the devil and she doesn't look anything like Oprah!

sneekula 969 Nearly a Posting Maven

They have finally found a good use for computers!

sneekula 969 Nearly a Posting Maven

Pretty close to real life! Let's hope this poll retains the voters' privacy! Unlike the nasty one by Mister Dave.

sneekula 969 Nearly a Posting Maven

Pretty underhanded trick!
Let's avoid any DaniWeb polls in the future!