sneekula 969 Nearly a Posting Maven

Also look into (wxPython is used by Boa and wxGlade):
Starting wxPython (GUI code)
http://www.daniweb.com/forums/thread128350.html

and:
Python GUI Programming
http://www.daniweb.com/forums/thread191210.html

Some words of advice, GUI programming will be a steep learning curve. You have to rethink your approach to use the best GUI widget/component to do what you want. For instance, most GUI toolkits will give a large number of input (text entry, sliders, check boxes, radio buttons, list boxes ...) and output (labels, sound, image, canvas, plotters, spreadsheet ...) devices. A GUI Builder will only position the selected widget on a window/frame, you still have to write the code to make it do something.

I look at this way, console programs are for learning Python, GUI programs are for showing what you have learned. Learn Python coding real well, then apply it to a GUI!

sneekula 969 Nearly a Posting Maven

Here is an example using the module pygame:

# experiments with module pygame
# free from: http://www.pygame.org/
# load, display and move an image

import pygame as pg

# initialize pygame
pg.init()

# pick an image you have (.bmp  .jpg  .png  .gif)
# if the image file is not in the working folder,
# use the full pathname like "C:/Images/gifs/Pooh.gif"
image_file = "Pooh.gif"

# RGB color tuple used by pygame
white = (255, 255, 255)

# create a 300x300 white screen
screen = pg.display.set_mode((300,300))
screen.fill(white)

# load the image from a file
# convert() unifies the pixel format for faster blit
image = pg.image.load(image_file).convert()

# draw image, position the image ulc at x=50, y=20
screen.blit(image, (50, 20))

# get the rectangle the image occupies
# rec(x, y, w, h)
start_rect = image.get_rect()

# set up the timed event loop
x = 0
y = 0
clock = pg.time.Clock()
keepGoing = True
while keepGoing:
    # set rate of move
    clock.tick(30)
    for event in pg.event.get():
        # quit when user clicks on window x
        if event.type == pg.QUIT:
            keepGoing = False
    # move the image ...
    x += 1
    y += 1
    # stop when x exceeds limit
    if x > 270:
        keepGoing = False
    image_rect = start_rect.move(x, y)
    # this erases the old sreen with white
    screen.fill(white)
    # put the image on the screen at new location
    screen.blit(image, image_rect)
    # update screen
    pg.display.flip()
sneekula 969 Nearly a Posting Maven

There are a number of GUI drag and drop builders.
Boa Constructor:
http://www.daniweb.com/forums/post400296-107.html
wxGlade:
http://www.daniweb.com/forums/post400189-106.html

sneekula 969 Nearly a Posting Maven

You might be thinking about something like this:

# a wxPython frame full display-screen size
# position widgets in the center

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, -1, mytitle, size=mysize)
        # the panel is needed for proper positioning
        panel = wx.Panel(self)
        panel.SetBackgroundColour("green")
        w, h = mysize
        
        self.mychoices = ['image1', 'image2', 'image3', 'image4']

        # create a box with 4 radio buttons, no labels here
        label_choices = [' ', ' ', ' ', ' ']
        self.radiobox = wx.RadioBox(panel, -1,
            " click on a button ",
            choices=label_choices,
            style=wx.VERTICAL)
        # bind mouse click to an action
        self.radiobox.Bind(wx.EVT_RADIOBOX, self.onAction)
        # show first selection
        self.onAction(None)
        
        rbw, rbh = self.radiobox.GetSize()
        # put the radiobox in the center of the display area
        # assume title bar takes about 25 pixels
        self.radiobox.SetPosition(((w-rbw)/2, (h-rbh)/2 - 25))

    def onAction(self, event):
        """show the selected choice"""
        index = self.radiobox.GetSelection()
        s = "Selected " + self.mychoices[index]
        # show the result in the frame title
        self.SetTitle(s)


app = wx.App(0)
# create a MyFrame instance and show the frame
mytitle = 'my title'
# make the frame full display-screen size and show
MyFrame(None, mytitle, wx.DisplaySize()).Show()
app.MainLoop()

In this case you need to calculate the center position for every widget you want to bring up. Easily done.

sneekula 969 Nearly a Posting Maven

Looks like you could simplify your code a little:

data = """\
<SYNC Start=5047><P Class=ENCC>
Back, back, back, back!
<SYNC Start=7235><P Class=ENCC>&nbsp;
<SYNC Start=10725><P Class=ENCC>
Yeah, Dan!"""

# this would be like the file data
lines = data.split('\n')

new_data = ""
for line in lines:
    if not line.startswith('<'):
        new_data += line + '\n'

# test it
print(new_data)

"""
my output -->
Back, back, back, back!
Yeah, Dan!
"""
sneekula 969 Nearly a Posting Maven

I guess you can play around with lists and lists of lists.

For example:

# create a 2D matrix of zeros and populate it

def make_list(size):
    """create a list of size number of zeros"""
    mylist = []
    for i in range(size):
        mylist.append(0)
    return mylist

def make_matrix(rows, cols):
    """
    create a 2D matrix as a list of rows number of lists
    where the lists are cols in size
    resulting matrix contains zeros
    """
    matrix = []
    for i in range(rows):
        matrix.append(make_list(cols))
    return matrix

mx = make_matrix(3, 3)

print(mx)

print('-'*34)

# now populate the zero matrix
# for instance put a 5 in row 0, column 0
mx[0][0] = 5
# put a 7 in row 1, column 1
mx[1][1] = 7
# put a 9 in row 2, column 2
mx[2][2] = 9

print(mx)

"""
my result -->
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
----------------------------------
[[5, 0, 0], [0, 7, 0], [0, 0, 9]]
"""

Another example:

# create a 2D matrix of zeros and populate it

def make_list(size):
    """create a list of size number of zeros"""
    mylist = []
    for i in range(size):
        mylist.append(0)
    return mylist

def make_matrix(rows, cols):
    """
    create a 2D matrix as a list of rows number of lists
    where the lists are cols in size
    resulting matrix contains zeros
    """
    matrix = []
    for i in range(rows):
        matrix.append(make_list(cols))
    return matrix

rows = 5
cols = 5
mx = make_matrix(rows, cols)

# pretty show the matrix
for x in mx:
    print(x) …
sneekula 969 Nearly a Posting Maven

woooee, you only missed this:
ararik pulled up an old thread to attach a homework question.

I already told him not to double post.

sneekula 969 Nearly a Posting Maven

ararik, please do not double post!

You are almost there, as slate says, simply sum up word counts and word lenghts:

myfile = open(filename, "r")
wordcount_sum = 0
wordlength_sum = 0
for line in myfile:
    words = line.split()
    # sum up the word counts
    wordcount_sum += len(words)
    for word in words:
        # sum up the word lengths
        wordlength_sum += len(word)

# invoke floating point division for Python versions < 3.0
wordlength_average = wordlength_sum/float(wordcount_sum)
sneekula 969 Nearly a Posting Maven

use mouseover or mousefocus at X,Y

We are talking about the Tkinter GUI toolkit. There are no such methods.

widget.focus() puts the cursor to a widget

module turtle (uses tkinter) has a method goto(x,y)

sneekula 969 Nearly a Posting Maven

Try something like this:

try:
    lightblue.obex.sendfile(device.getAddr(), c[1],"advertisement.jpg")
except lightblue._obexcommon.OBEXError, error:
    if error.args[0] == 111:
        print "Connection refused!"
    elif error.args[0] == 11:
        print "Resource temporarily unavailable!"
    else:
        pass
sneekula 969 Nearly a Posting Maven

You can use string slicing if you assume a few things:

#!/usr/bin/env python

# has
old = "AND Category 07|Spec 01|ABC 01 AND Category 07|Spec 02|XYZ 02 \
AND Category 07|Spec 03|PQR 03 "
# wants
new = "AND Category 07|Spec 01 AND Category 07|Spec 02 AND Category 07|Spec 03"

# assuming that 'Spec xx' and what you want to remove does not change in length

q = old.split('|S')

for x in q:
    print(x)  # test

print('-'*30)


new2 = ""
for x in q:
    if x.startswith('pec'):
        # skips the chars from index 6 to 12
        x = '|S' + x[:6] + x[13:]
        print(x)  # test
    new2 += x

print('-'*30)

print(new2)

"""
my result -->
AND Category 07
pec 01|ABC 01 AND Category 07
pec 02|XYZ 02 AND Category 07
pec 03|PQR 03
------------------------------
|Spec 01 AND Category 07
|Spec 02 AND Category 07
|Spec 03
------------------------------
AND Category 07|Spec 01 AND Category 07|Spec 02 AND Category 07|Spec 03
"""
sneekula 969 Nearly a Posting Maven

The wx demos sugg because there is too much code bloat! You may be able to figure it out anyway.

BTW, your console code could stand major improvement.

sneekula 969 Nearly a Posting Maven

The easiest way is to use a wx.RadioBox:

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent=None):
        wx.Frame.__init__(self, parent, wx.ID_ANY, size=(300, 160))
        # match to the number of radiobuttons
        self.mychoices = ['image1', 'image2', 'image3', 'image4']

        # create a box with 4 radio buttons, no labels here
        label_choices = [' ', ' ', ' ', ' ']
        self.radiobox = wx.RadioBox(self, wx.ID_ANY,
            " click on a button ",
            choices=label_choices, style=wx.VERTICAL)
        # bind mouse click to an action
        self.radiobox.Bind(wx.EVT_RADIOBOX, self.onAction)

        # show present selection
        self.onAction(None)

    def onAction(self, event):
        """show the selected choice"""
        index = self.radiobox.GetSelection()
        s = "Selected " + self.mychoices[index]
        # show the result in the frame title
        self.SetTitle(s)


app = wx.App(0)
MyFrame().Show()
app.MainLoop()
sneekula 969 Nearly a Posting Maven

you guys sure? Boa looks like it's something I would have written in TP7 when I was a kid... but first looks may be deceiving :)

I've tried Glade3 as well, converted the .glade file to .xml, but couldn't manage to get the script to read it properly for some reason.
btw, can I use glade with the wx module?

On my Ubuntu machine I installed SPE (written in wxPython) and it has wxGlade as a designer tool, seems to work okay. However, the output is an XML file again. You can use wxPython code to import these XML files as resource files.

I filed this code that Vegaseat left some a time ago:

# use an xml resource string or file to create widgets
# you can create .xrc or .xml files with something like wxGlade
# wxGlade from: http://wxglade.sourceforge.net/
# source: vegaseat

import  wx
import  wx.xrc  as  xrc

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(400, 300))

        self.toggle = True

        # load the xml resource file
        # should be in your working folder or use full path
        res = xrc.XmlResource('resource.xrc')

        '''
        # or you can use a resource string directly
        res = xrc.EmptyXmlResource()
        res.LoadFromString(xml_resource)
        '''

        # create the panel from the resource
        self.panel = res.LoadPanel(self, 'MyPanel')
        # bind mouse click to the button in the resource
        self.Bind(wx.EVT_BUTTON, self.onClick,
            id=xrc.XRCID('ColourButton'))
        self.Bind(wx.EVT_BUTTON, self.showInfo,
            id=xrc.XRCID('InfoButton'))

    def onClick(self, event):
        """do something with the button click"""
        if self.toggle:
            self.panel.SetBackgroundColour('green')
            self.toggle = False
        else:
            self.panel.SetBackgroundColour('red')
            self.toggle …
sneekula 969 Nearly a Posting Maven

I find designers rather cumbersome, they throw in more code than you want to have, and you have a much harder time fleshing out to working program.

You are better off collecting a set of working templates of the various widgets you are interested in, and copy and paste from there to create your program.

If you use the wxPython GUI toolkit then Boa-Constructor isn't too bad, since it also is a regular IDE that you can write and run your programs with. It does create Python code rather than XML code.

On my Ubuntu machine I installed SPE (written in wxPython) and it has wxGlade as a designer tool, seems to work okay. This way you can test out your code quickly.

sneekula 969 Nearly a Posting Maven

Tuple elements can be accessed by their index:

my_tup = ('fdasf','dfasf','asdf')
print my_tup[0]  # --> fdasf
print my_tup[2]  # --> asdf
sneekula 969 Nearly a Posting Maven

If you want to import custom module xyq via the Pythonpath
create a file xyq.pth and stick it into a directory python
will look into, like
for Windows:
C:\Python25\Lib\site-packages
for Linux:
/usr/lib/python2.5/site-packages

The .pth file contains a line showing the directory
in which module xyq is located, for instance:
for Windows:
C:\Python25\Mymodules
for Linux in your case:
/home/doriad/Scripts/Python/

sneekula 969 Nearly a Posting Maven

A simple addition to the if statement will help you to treat spaces different:

#!/usr/bin/python

# remove duplicates from text (leave spaces)

text = 'The quick brown fox jumps over the lazy dog'

# create an empty string
new_text = ""
# iterate over all characters of the text
for c in text:
    # check if c is a space or not in new_text
    if c.isspace() or c not in new_text:
        # concatinate c to new_text
        new_text += c

print(new_text)

"""
my result -->
The quick brown fx jmps v t lazy dg
"""

The first line is for my Ubuntu/Linux machine, it shows it where the Python interpreter is located. Windows will ignore this line.

sneekula 969 Nearly a Posting Maven

Python code can be written so it almost reads like pseudo code:

word = "Apple"

# create an empty string
new_word = ""
# iterate through word one  character at a time
for c in word:
    # check if c is already in new_word
    if c not in new_word:
        new_word += c

print(new_word)  # Aple
sneekula 969 Nearly a Posting Maven

You could do something like this:

prompt = "Enter your five character user ID; "
user_id = 'THE' + raw_input(prompt)
sneekula 969 Nearly a Posting Maven

There might be something wrong with your boot order. Here is the spiel from the Ubuntu site:
1.
Restart your computer with the CD still inserted in the drive
2.
When the computer restarts, look very carefully at the initial screen it shows. Look for an option such as <F10> Boot Order or Press DEL to enter setup and press the key which is noted (e.g. the Delete key). There are many different variations, so please see your computer manual if you are unsure which button you need to press.
3.
Find the options relating to Boot Order, Boot Sequence or similar. Ensure that your CD drive is first in the boot order by following the instructions on-screen.
4.
Once satisfied that your CD is first in the boot order, save your changes and restart the computer. It should now start from the Ubuntu installation CD.

On my Vista machine it was the F10 key (press just at the right time during the boot up) that allowed me to set the boot order. I can also press the Escape key during the boot up and change to another medium like a flashcard.

sneekula 969 Nearly a Posting Maven

On problem #1 you are a little messed up. You need to send a list of elements to the your function that contains elements that the len() function can be applied to, like strings for instance. Then you return a list of these lengths.
BTW, do not use 'list' as a variable name.

Since you are talking about the length of strings, I assume that problem #2 asks you to return the list of strings in the order of length. So a list like
mylist =
would be:
mylist = [ 'of', 'list', 'strings']
or:
mylist =

sneekula 969 Nearly a Posting Maven

Do get an understanding girlfriend you need to join a local church. She will teach you good manners and good English.

sneekula 969 Nearly a Posting Maven

Two things:

1) Separate the code that goes into the loop from code that does not loop by using proper indentations

2) Unless this is an exercise in writelines(), it is better to build a temporary string with the names entered in the loop, and then write that temporary string to the file after your break out of the loop. Otherwise you have to worry about appending a file, and if the file exists to start with an empty file.

Here is your code corrected to work properly:

# Anna Huang
# Programming Assignment 16

# start with empty temp string
temp = ""
while True:
    name = raw_input("Enter your name (just Enter to exit): ")
    if name:
        # build up the temp string and end the name with a space
        temp += name + ' '  # same as: temp = temp + name + ' '
    else:
        break

#print temp

fw = open("pa16names.txt", "w")
# write the temp string to file
fw.write(temp)
fw.close()

fr = open ("pa16names.txt", "r")
print "The names you've entered into the text file are:", fr.read()
fr.close()

Please read the comments so you can learn something at least.

sneekula 969 Nearly a Posting Maven

Another way would be to give your secret text string a marker ending, like '~~' and stop encoding or decoding when detected.

sneekula 969 Nearly a Posting Maven

Python is a modern language that has borrowed advanced programming concepts from a number of other languages like C++, Java, Lisp and Haskell. It would be very hard to express these in C.

sneekula 969 Nearly a Posting Maven

The red value of the first pixel. Then when you decode you read this length value first and use it in your loop for the next length characters.

sneekula 969 Nearly a Posting Maven

You could insert the length of your secret message string as the first value.

sneekula 969 Nearly a Posting Maven

I would avoid using the Python shell to write multiline programs. Use one of the Python editors like IDLE, wirte your program, save it and run it. This would have given you an error message like:
NameError: name 'timesflipped' is not defined

Using FengG's advice your program should look like this:

import random

coin_heads, coin_tails, timesflipped = 0,0,0

while timesflipped <100:
    coin_flips = random.randrange(2)
    if coin_flips == 0:
        coin_heads = coin_heads + 1
    else:
        coin_tails = coin_tails + 1
    timesflipped += 1

print "Out of 100 flips " + str(coin_heads) + " were heads and " + \
    str(coin_tails) + " were tails."
sneekula 969 Nearly a Posting Maven

It looks like you only want a 2D matrix, since you are talking about rows and columns.

First of all, do not use list as a variable name since list is a builtin function in Python. Lists have a function append(), so use it. Commonly a basic matrix is populated with zeroes, which you then can replace as needed.

Here is a working example:

# create a 2D matrix of zeros and populate it

def make_list(size):
    """create a list of size number of zeros"""
    mylist = []
    for i in range(size):
        mylist.append(0)
    return mylist

def make_matrix(rows, cols):
    """
    create a 2D matrix as a list of rows number of lists
    where the lists are cols in size
    resulting matrix contains zeros
    """
    matrix = []
    for i in range(rows):
        matrix.append(make_list(cols))
    return matrix

mx = make_matrix(3, 3)

print(mx)

print('-'*34)

# now populate the zero matrix
# for instance put a 5 in row 0, column 0
mx[0][0] = 5
# put a 7 in row 1, column 1
mx[1][1] = 7
# put a 9 in row 2, column 2
mx[2][2] = 9

print(mx)

"""
my result -->
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
----------------------------------
[[5, 0, 0], [0, 7, 0], [0, 0, 9]]

if you pretty it up -->
[
[0, 0, 0], 
[0, 0, 0], 
[0, 0, 0]
]
----------------------------------
[
[5, 0, 0], 
[0, 7, 0], 
[0, 0, 9]
]
"""
sneekula 969 Nearly a Posting Maven

Here % is the modulo operator. It gives you the remainder of a division.

print(3 % 3)  # 0 --> 3 is completely divisable by 3
print(6 % 3)  # 0 --> 6 is completely divisable by 3
print(5 % 3)  # 2 --> division leaves a ramainder of 2

Another thing, in your function you came up with -->

def int(start,finish):

using int would be a solid nono, since int() is a function built into Python and you would make that fuction inoperable!

sneekula 969 Nearly a Posting Maven

Ouch! My baddy!
BeautyfulSoup needs sgmllib.
If you are smart, stay away from Python30 and use Python version 2.5.4 the most stable production grade version.

Consider Python26 and Python30 experimental versions at best.

sneekula 969 Nearly a Posting Maven

You can use this approach to get an input dialog without the Tkinter window:

# use Tkinter's dialogs to ask for input
# dialogs are askfloat, askinteger, and askstring

import Tkinter as tk
from tkSimpleDialog import askstring

root = tk.Tk()
# show askstring dialog without the Tkinter window
root.withdraw()
name = askstring("Name", "Enter your name")

print(name)

With Python 30 use:

# use Tkinter's dialogs to ask for input
# dialogs are askfloat, askinteger, and askstring
# mofified for Python30

import tkinter as tk
from tkinter.simpledialog import askstring

root = tk.Tk()
# show askstring dialog without the Tkinter window
root.withdraw()
name = askstring("Name", "Enter your name")

print(name)
sneekula 969 Nearly a Posting Maven

Somebody mention this in another thread.

You can convert BeautifulSoup.py from Python25 to Python30 with 2to3.py and it will work with Python30. You can use this little utility program:

# convert a Python25 code file to a Python30 code file
# generates a backup file and overwrites the original
# file with the converted file
# to be safe copy the file to be converted into the
# working directory of this program

import subprocess

# the Python2x code file you want to convert ...
python2x_scriptfile = "BeautifulSoup.py"

subprocess.call([r"C:\Python30\Python.exe",
    r"C:\Python30\Tools\Scripts\2to3.py",
    "-w",
    python2x_scriptfile])

]

sneekula 969 Nearly a Posting Maven

Here would be one way to do this:

text = """\
159 J=1661,3169,1679,3181 SEC=SLAB2
66 J=5597,5596,7523,7522 SEC=WALL1"""

print(text)

print('-'*35)

# create a list of words excluding item containing 'SEC=" 
temp_list = [item for line in text.split('\n')
    for item in line.split()
    if not 'SEC=' in item]

#print temp_list  # test

# rebuild the text from the list
mod_text = ""
for ix, word in enumerate(temp_list):
    if ix % 2:
        # add newline
        mod_text += word + '\n'
    else:
        # add space
        mod_text += word + " "

print(mod_text)
    
"""
my result -->
159 J=1661,3169,1679,3181 SEC=SLAB2
66 J=5597,5596,7523,7522 SEC=WALL1
-----------------------------------
159 J=1661,3169,1679,3181
66 J=5597,5596,7523,7522
"""

Using module re makes it look a little simpler:

import re

text = """\
159 J=1661,3169,1679,3181 SEC=SLAB2
66 J=5597,5596,7523,7522 SEC=WALL1"""

print(text)

print('-'*35)

# if SEC= is followed by cap letters and and numbers
p = re.compile( '(SEC=[A-Z, 1-9]*)')
mod_text = p.sub( '', text)

print(mod_text)

"""
my result -->
159 J=1661,3169,1679,3181 SEC=SLAB2
66 J=5597,5596,7523,7522 SEC=WALL1
-----------------------------------
159 J=1661,3169,1679,3181
66 J=5597,5596,7523,7522
"""
sneekula 969 Nearly a Posting Maven

You can play with this:

# draw a dragon curve fractal using Tinter's turtle
# dense version using recursion
# modified from: http://www.rosettacode.org/wiki/Dragon_curve

from turtle import *

def dragon(step, length, zig=right, zag=left):
    if step <= 0:
        forward(length)
        return
    step -= 1
    length /= 1.41421
    zig(45)
    dragon(step, length, right, left)
    zag(90)
    dragon(step, length, left, right)
    zig(45)


# set to False to speed things up (default is True)
tracer(False)

# draw in this color
color('red')

# turtle by default starts at (x=0, y=0) center of display
# lift pen up to move to the left by 130 units and up 70 units
# then drop the pen down to start drawing
up()
goto(-130, 70)
down()

# experiment with step and length
step = 12
length = 300
dragon(step, length)

# gives some viewing time ...
import time
time.sleep(7)
sneekula 969 Nearly a Posting Maven

Something like this:

def isLeapYear(year):
    """
    return True if year is a leapyear
    """
    return (not year%4 and year%100 or not year%400) and True

# Testing ...
print( isLeapYear(400) )
print( isLeapYear(800) )
print( isLeapYear(1600) )
print( isLeapYear(1601) )
print( isLeapYear(2004) )
sneekula 969 Nearly a Posting Maven

ok i have added the 4 spaces and no errors displayed but three dots come

...

so shall i add the rest of the code provide or was it going to print it all automatically

Three dots? Are you using the Python shell?

sneekula 969 Nearly a Posting Maven

The best way for your level would be to build up a string in the loop:

alph = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',\
            'q','r','s','t','u','v','w','x','y','z']
num =[2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9]

# testing only 
phone = "555-GET-FOOD".lower()
#phone = raw_input('enter phone number in the format xxx-xxx-xxxx ').lower()

# build up from an empty string
s = ""
for index in range(len(phone)):
    if phone[index].isalpha():
        s = s + str(num[alph.index(phone[index])])
    else:
        s = s + phone[index]

print s  # 555-438-3663
sneekula 969 Nearly a Posting Maven

Running PyGame from within wxPython will create a conflict, since each use their own event loops, and the event queue will now contain events that won't match.

sneekula 969 Nearly a Posting Maven

Just a note, since count() is a builtin Python function, avoid using it for your own function name. Use something like mycount().

sneekula 969 Nearly a Posting Maven

Looks like the book made a mild error to confuse the student, the output will be in the hash order of the dictionary, so don't worry.

sneekula 969 Nearly a Posting Maven

I need to convert a number (in decimal form) that is between 1 to 4999 to Roman Numeral Form. However, though the code I have is kinda working, its only outputting the thousand digit, not anything less or any part thats less.

def int2roman(number):
    numerals={1:"I", 4:"IV", 5:"V", 9: "IX", 10:"X", 40:"XL", 50:"L",
              90:"XC", 100:"C", 400:"CD", 500:"D", 900:"CM", 1000:"M"}
    result=""
    for value, numeral in sorted(numerals.items(), reverse=True):
        while number >= value:
            result += numeral
            number -= value
        return result
print int2roman(input("Enter a number (1 to 4999) in decimal form: "))

if I input 1994, I get M instead of the MCMXCIV I should be getting. Any corrections and explanations to my code?
Thanks :)

You are almost there, your return statement needs to be outside the for loop.

def int2roman(number):
    numerals={1:"I", 4:"IV", 5:"V", 9: "IX", 10:"X", 40:"XL", 50:"L",
              90:"XC", 100:"C", 400:"CD", 500:"D", 900:"CM", 1000:"M"}
    result=""
    for value, numeral in sorted(numerals.items(), reverse=True):
        while number >= value:
            result += numeral
            number -= value
    return result

print int2roman(input("Enter a number (1 to 4999) in decimal form: "))

Sorry, didn't see Pen's early response.

sneekula 969 Nearly a Posting Maven

Using sys.stdout.writelines() or sys.stdout.write() is kind of cumbersome and on Linux you also need a sys.stdout.flush() to make it work.

I think internally print(s), translates to sys.stdout.write(s)

sneekula 969 Nearly a Posting Maven

A small function that will check if an integer is odd or even:

def is_odd(n):
    """return True if n is an odd integer, else False"""
    if n & 1:
        return True
    else:
        return False
sneekula 969 Nearly a Posting Maven

Makes you sort of wonder which countries are targeted by British nuclear missiles?

sneekula 969 Nearly a Posting Maven

Numpy handles only numeric arrays, not object arrays.
I think VPython actually uses numpy/numeric internally.

sneekula 969 Nearly a Posting Maven

Generally you write a function for that, something like this:

# check the input of an integer between given limits

def check_input(low, high):
    """
    check the input to be an integer number within a given range
    """
    prompt = "Enter an integer number between %d and %d: " % (low, high)
    while True:
        try:
            a = int(raw_input(prompt))
            if low <= a <= high:
                return a
        except ValueError:
            print("Hey, I said integer number!")

# test the function ...
# expecting an integer number between 1 and 50
num_test = check_input(1, 50)
print(num_test)

The function loops until the correct input has been received.

sneekula 969 Nearly a Posting Maven

We all have interesting little snippets lying around. Too bad we can't find some way to create some sort of central index, but it is more than I have time for.

Image Files
     tif to gif
SQLite
     database - create
     database - modify record
Homework problems
     common
          primes - find all up to a certain number
etc.

Well, there is a snippet section, but nobody ever looks there.

sneekula 969 Nearly a Posting Maven

One way to present highly formatted text like text with superscripts is to use wxPython's wx.html.HtmlWindow widget and simplified html code:

# exploring wxPython's
# wx.html.HtmlWindow(parent, id, pos, size, style, name)

import wx
import wx.html

class MyPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, wx.ID_ANY)
        self.SetBackgroundColour("yellow")
        
        htmlwin = wx.html.HtmlWindow(self, wx.ID_ANY, 
            pos=(10,30), size=(200,100))
        htmlwin.SetPage(html_code)


# use simple HTML code ...
html_code = """\
x<sup>3</sup> + y<sup>2</sup> - 15 = 0
"""

app = wx.App(0)
# create a frame, no parent, default ID, title, size
caption = "superscript text with wx.html.HtmlWindow"
frame = wx.Frame(None, wx.ID_ANY, caption, size=(400, 210))
MyPanel(frame)
frame.Show()
app.MainLoop()