vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Sex addiction seems to be more of a problem for our male Senators or Evangelists. :)

susheelsundar commented: Truth enough +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is an example of the use of module fileinput ...

# module fileinput allows for line by line processing of files
# fileinput.input(files=None, inplace=False, backup='', bufsize=0, 
#     mode='r', openhook=None)
# notice that the default mode is 'r' for reading text files 
# tested with Python27 and Python32  by vegaseat

import fileinput

# create a text file for testing
text = """\
Hello
World    
"""
fname = "aaa1.txt"
fout = open(fname, "w")
fout.write(text)
fout.close()

# can handle a tuple of files like files=(fname1, fname2, ...)
# the backup file fname.bak is optional
# in this case the original file is saved as "aaa1.txt.bak" 
fin = fileinput.input(files=fname, inplace=True, backup='.bak')

# process each line of the file
for line in fin:
    # print is overloaded to add 'booh!' to each line of file
    # does not actually print on the console screen
    print(line.strip() + " booh!")

# now check the processed file ...
for line in open(fname):
    print("new line --> %s" % line.strip())

'''result ...
new line --> Hello booh!
new line --> World booh!
'''

Investigate what other line by line processing you can do.

bumsfeld commented: nice concept +11
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"Don't compromise yourself. You are all you've got."
-- Janis Joplin

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"There is always some madness in love. But there is also always some reason in madness."
-- Friedrich Wilhelm Nietzsche

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Darn Brutus, that wasn't a nice thing to do!

by Julius Caesar

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A hint on how to access information from a nested Python dictionary ...

# accessing information from a nested dictionary

# example of a nested dictionary
friends = {
'Fred' : {'city' : 'Pasadena', 'age' : 45},
'Adam' : {'city' : 'Dallas', 'age' : 27},
'Lisa' : {'city' : 'Chicago', 'age' : 31},
'Ulla' : {'city' : 'Las Vegas', 'age' : 19},
'Mark' : {'city' : 'New York', 'age' : 24}
}

# dictionaries consist of key:value pairs
# and are indexed by the keys
# so if you want to know where Ulla lives
# you use the keys 'Ulla' and 'city'
print(friends['Ulla']['city'])       # Las Vegas

# how old is Adam ...
print(friends['Adam']['age'])        # 27

# or loop through all your friends
for friend in friends:
    print("%s lives in %s" % (friend, friends[friend]['city']))

''' result ...
Lisa lives in Chicago
Ulla lives in Las Vegas
Mark lives in New York
Adam lives in Dallas
Fred lives in Pasadena
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The way you do it, soiling the internet with spam.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines.
-- Ralph Waldo Emerson

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python comes with a lot of highly tested and optimized modules. Knowing what they can do will help greatly to simplify code ...

# a simple character count using collections.defaultdict() 

from collections import defaultdict

s = 'mississippi'
dd = defaultdict(int)
for k in s:
    dd[k] += 1

print(dd)
print(dd.items())
print('-'*40)

# sorted by character alphabetically
for c, freq in sorted(dd.items()):
    #print("%s  %d" % (c, freq))
    # Python27 or Python3
    print("{}  {}".format(c, freq))

''' result ...
defaultdict(<type 'int'>, {'i': 4, 'p': 2, 's': 4, 'm': 1})
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
----------------------------------------
i  4
m  1
p  2
s  4
'''

print('-'*40)

# same thing but sorted by frequency
for c, freq in sorted(dd.items(), key=lambda q: q[1]):
    #print("%s  %d" % (c, freq))
    # Python27 or Python3
    print("{}  {}".format(c, freq))

''' result ...
m  1
p  2
i  4
s  4
'''

Another approach ...

# a simple character count using collections.Counter()
# needs Python27 or Python3 

from collections import Counter

s = 'mississippi'
cnt = Counter(s)

print(cnt)
print(cnt.items())
print('-'*40)

for c, freq in sorted(cnt.items()):
    #print("%s  %d" % (c, freq))   # older C style
    print("{}  {}".format(c, freq))

''' result ...
Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
----------------------------------------
i  4
m  1
p  2
s  4
'''
Lardmeister commented: helpful +6
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Simple Python coding rules:
import
define
main program flow

Giving your code a common sense structure makes it easier to read and understand for people you are asking for help.

Also, a few temporary test-prints will help you a lot here!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can use operator.itemgetter() as shown in this example ...

# count words in a text and show them by decreasing frequency 
# using operator.itemgetter()
# collections.Counter() needs Python27 or Python3 

import collections
import operator

# sample text for testing (could come from a text file)
text = """\
If you see a turn signal blinking on a car with a southern license plate, 
you may rest assured that it was on when the car was purchased. 
"""

# create a word list of the words in text 
# remove given punctuation marks and change to lower case    
word_list = [word.strip('.,!?:;"').lower() for word in text.split()]

#print(word_list)  # test

cnt = collections.Counter()
for word in word_list:
    cnt[word] += 1

#print(cnt)  # test

print("The most frequent words are:")
# operator.itemgetter(1) implies v (frequency)
freq = operator.itemgetter(1)
for k, v in sorted(cnt.items(), reverse=True, key=freq):
    print("%3d  %s" % (v, k))

""" result (Python 2.7) >>>
The most frequent words are:
  3  a
  2  you
  2  was
  2  on
  2  car
  1  it
  1  rest
  1  see
  1  purchased
  1  if
  1  when
  1  plate
  1  assured
  1  that
  1  may
  1  southern
  1  blinking
  1  with
  1  license
  1  signal
  1  turn
  1  the
"""
e-papa commented: Great +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

“The weak can never forgive. Forgiveness is the attribute of the strong.”
-- Mahatma Gandhi (2 October 1869 – 30 January 1948)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This will give you the size of the display screen area usable by your program ...

# get the size of your usable display screen area
# root will not show up

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

root = tk.Tk()
# make window full displayable size:
root.state('zoomed')
root.update()

width = root.winfo_width()
height = root.winfo_height()
print("The usable screen size (w x h) is: %s x %s" % (width, height))
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Go to:
http://pypi.python.org/pypi/pep8/0.4#downloads
download:
pep8-0.4.tar.gz
extract contents into a temp folder using WinRAR.exe or alike
find file pep8.py and copy it to a folder with your code

Take a look at pep8.py with an editor, it has all the help built-in

e-papa commented: Thanks a million. +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Numpy arrays allow for numeric elements of a certain type only. Those can be integer, float or complex numbers. You can convert a Numpy array to a Python list ...

# using Python module numpy to create a multi-dimensional array/list

import numpy as np

# create a 2x3 array of ones
xf = np.ones((2, 3), float)
print(xf)
'''
[[ 1.  1.  1.]
 [ 1.  1.  1.]]
'''

# convert to a 2x3 Python list
print(xf.tolist())
'''
[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]
'''

You can create Python multidimensional list this way ...

# creating a multi-dimensional list
# elements can be any object

multi_list = [[1 for col in range(3)] for row in range(2)]

print(multi_list)  # [[1, 1, 1], [1, 1, 1]] 

# use [row][col]
multi_list[0][1] = 2
multi_list[0][2] = 3
print(multi_list)  # [[1, 2, 3], [1, 1, 1]]

My advice, if you have certain number types and need the high speed and some nice array functions, use numpy. Otherwise go for the dictionary approach ...

# create a 3x4x2 3D-array using a dictionary with (x,y,z):value pairs

import pprint

# initializes values to zero
arr3d = dict(((x,y,z), 0) for x in range(3) for y in range(4)
    for z in range(2))

# Python3 has dictionary comprehension to simplify this
#arr3d = {(x,y,z):0 for x in range(3) for y in range(4) for z in range(2)}

pprint.pprint(arr3d)

"""my output -->
{(0, 0, 0): 0,
 (0, 0, 1): 0,
 (0, 1, 0): 0,
 (0, 1, 1): 0,
 (0, 2, 0): 0, …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Folks are using Tkinter's expansion modules. A nice example of the tix.ComboBox came up in the forum. Here is a modified version of this example ...

# explore the tix.ComboBox()
# the Tix (Tk Interface Extension) module comes with the
# Python27 and Python31+ installation

try:
    import Tix as tix  # Python27
except ImportError:
    import tkinter.tix as tix  # Python31 and higher

def selected(event=None):
    color = combo.entry.get()
    root.title("value is %s" % color)
    root['bg'] = color


root = tix.Tk()
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (330, 80, 200, 150))
root.title("tix.ComboBox()")

# apply a label and make the combo entry editable
combo = tix.ComboBox(root, label='Color:', editable=1)
combo.pack(side='left', padx=10, pady=10)

# load the combobox listbox
color_list = ['red', 'green', 'blue', 'yellow', 'white', 'magenta']
for item in color_list:
    combo.insert('end', item)

# set the initial color
# make combobox editable to do this
combo.entry.insert(0, 'red')
# start with the color in the entry
selected()

# left mouse click on a list item to display selection
combo.slistbox.listbox.bind('<ButtonRelease-1>', selected)

root.mainloop()

Actually, the label within the combo box is rather neat.

Ene Uran commented: tix is interesting +13
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Introducing color to your PyQt widget ...

# testing the PyQT GUI toolkit
# use setStyleSheet(format_string)
# to set the background color of the specified widget
# also use the newer style of signal/slot connect
# tested with PyQT483 and Python27/Python32  vegaseat

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyForm(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(100, 150, 320, 100)
        self.setWindowTitle("change background color")

        # create a widget to display the color in
        self.display = QWidget(self)
        self.display.setGeometry(0, 0, 50, 50)
        # takes colors in "#RRGGBB" format
        # initial color is white
        self.display.setStyleSheet("QWidget { background-color: #FFFFFF }") 

        btn_red = QPushButton("red")
        # bind the button click to a function reference
        # newer style ...
        btn_red.clicked.connect(self.change_color)

        btn_green = QPushButton("green")
        # bind the button click to a function reference
        # newer style ...
        btn_green.clicked.connect(self.change_color)        

        btn_blue = QPushButton("blue")
        # bind the button click to a function reference
        # newer style ...
        btn_blue.clicked.connect(self.change_color)        

        # use a grid layout for the widgets
        grid = QGridLayout()
        # addWidget(widget, row, column, rowSpan=1, columnSpan=1)
        # widget display spans 3 rows
        grid.addWidget(self.display, 0, 1, 3, 1)
        grid.addWidget(btn_red, 0, 0)
        grid.addWidget(btn_green, 1, 0)
        grid.addWidget(btn_blue, 2, 0)

        self.setLayout(grid)

    def change_color(self):
        button = self.sender()
        # button texts are the dictionary keys
        color_key = str(button.text())
        # takes colors in '#RRGGBB' format
        colors = {'red': '#FF0000', 'green': '#00FF00', 'blue':  '#0000FF'}
        sf = "QWidget { background-color: %s }" % colors[color_key]
        self.display.setStyleSheet(sf)    


app =  QApplication([])
form = MyForm()
form.show()
app.exec_()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A simple explanation of a Python class object ...

# a look at Python's class constructor, method and instance
# class names are capitalized by convention to aid readability

class Animal:
    def __init__(self, animal, sound):
        """
        The constructor __init__() brings in external
        parameters when an instance of the class is created,
        self keeps track of the specific instance and makes
        instance variables global to the class so the class
        methods can use them
        """
        self.animal = animal
        self.sound = sound
        
    def animal_sound(self):
        """
        a class method has self for the first argument
        note that self.animal and self.sound are global 
        to the class and specific to the instance
        """
        print( "The %s goes %s" % (self.animal, self.sound) )


# create an instance of the class
# you have to supply the animal and it's sound
# as shown in the class __init__() method
cow = Animal('cow', 'mooh')

# create another instance
dog = Animal('dog', 'woof')

# now let's do something with each instance
# the instance name is dot_connected to the method
cow.animal_sound()  # The cow goes mooh

dog.animal_sound()  # The dog goes woof
e-papa commented: Thanks for the explanation. +1
Legnoduro commented: Very understandable explanation. +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The tkSnack sound module was developed at KTH in Stockholm, Sweden. A great module to generate sound, play and analyze sound files and speech. It was written using Tkinter and its native TCL language. Alas, the latest release is from 2005. However, the important file tkSnack.py can be converted to Python3 syntax very readily using the 2to3.py utlity file than comes with the Python3 installation.

Just a note: snack2210-py.zip has download size 745K

I show you a simple tone generator that will work fine with Python32 ...

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Tix (Tk Interface Extension) module provides an additional rich set of widgets. to the Tkinter GUI toolkit. Here is one example for you ...

# Tix_ScrolledListBox2.py
# Tkinter extension module tix comes with Python27 and Python31+
# explore the tix.ScrolledListBox
# vertical or horizontal scroll bars appear as needed (automatic)
# for more info check ...
# http://docs.python.org/library/tix.html  
# http://doc.astro-wise.org/Tix.html
# actually Tix imports Tkinter so you can call it all tix

try:
    import Tix as tix  # Python27
except ImportError:
    import tkinter.tix as tix  # Python31 and higher

def get_list(event=None):
    """
    function to read the listbox selection
    and put the result in a text/edit widget
    """
    # get selected line index
    index = slbox.listbox.curselection()[0]
    # get the line's text
    # optionally add newline char to end
    seltext = slbox.listbox.get(index) + '\n'
    # put the selected text in the edit field
    edit.insert('end', seltext)
    edit.focus

root = tix.Tk()
root.title('tix.ScrolledListBox (click on a name)')

# create a text/edit widget (width/height in characters)
edit = tix.Text(root, width=35, height=15)
edit.pack(side='left')

# create scrolled listbox
slbox = tix.ScrolledListBox(root, scrollbar='auto')
# background color of listbox part
slbox.listbox.configure(bg='yellow')
slbox.pack(fill='both', expand=1)

friend_list = [
'Steve', 'Tom', 'Mark', 'Adam', 'Alison', 'Ethel',
'Barb', 'Tiny', 'Tim', 'Pete', 'Sue', 'Zack', 'Fred',
'Lars', 'Detlev', 'Akiko', 'Heidrun', 'Udo',
'supercalifragilisticexpialidocious']

# load the listbox
for item in friend_list:
    slbox.listbox.insert('end', item)
    
# left mouse click on a list item to display selection
slbox.listbox.bind('<ButtonRelease-1>', get_list)

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

... somebody writes:

I am a one month old Python programmer.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The example in the Python32 docs elucidates that in earlier versions of Python here was a difference, the str() result was rounded off ...

import math
print(repr(math.pi))
print(str(math.pi))

'''
result (Python31 and earlier) -->
3.141592653589793
3.14159265359
result (Python32) -->
3.141592653589793
3.141592653589793
'''
danholding commented: very helpfull thanks +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

For the casual developer of software working with PyQT had always a certain worry about licensing associated with it. That has now been eliminated with the PySide LGPL version of PyQT.

The GNU Lesser General Public License (LGPL) is a free software license published by the Free Software Foundation (FSF).

Here is an example of PySide code (looks much like PyQT code) ...

# PySide is the official LGPL-licensed version of PyQT
# I downloaded and used the Windows self-extracting installer
# PySide-1.0.0qt472.win32-py2.7.exe
# from: http://developer.qt.nokia.com/wiki/PySide_Binaries_Windows
# tested with pyside472 and Python27
 
from PySide.QtCore import *
from PySide.QtGui import *
 
class MyFrame(QWidget):
    def __init__(self, parent=None):
        # create the frame/window (this will be instance self)
        QWidget.__init__(self, parent)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(100, 150, 300, 50)
        self.setWindowTitle('button connected to a label')

        # create a button
        self.button = QPushButton("Click me")
        # when clicked connect button to method action()
        self.button.clicked.connect(self.action)

        # create 2 Qt labels
        self.label1 = QLabel()
        self.label2 = QLabel()

        # use grid layout to position the 3 widgets
        grid = QGridLayout()
        # addWidget(QWidget, row, column, rowSpan=1, columnSpan=1)
        grid.addWidget(self.button, 0, 0)
        grid.addWidget(self.label1, 1, 0)
        grid.addWidget(self.label2, 2, 0)

        self.setLayout(grid)
        
    def action(self):
        s = "You clicked the button!"
        self.label1.setText(s)
        # for optional color use HTML code
        html = "<font color=red>You clicked the button!</font>"
        self.label2.setText(html)
        # optional wave sound
        # sound file (.wav files only) should be in working folder
        # or give full file path 
        QSound.play("boing.wav")
 
# create the Qt Application
app = QApplication([])

frame = MyFrame()
frame.show()

# …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I assume you are using the Windows OS and Python 3.2, simply do this ...

For PyQT download and run the Windows 32 bit self-extracting installer
PyQt-Py3.2-x86-gpl-4.8.3-1.exe
from http://www.riverbankcomputing.co.uk/.../pyqt/download

Py3.2 indicates that this the installer for Python 3.2, there are installers for other versions of Python too.

You can copy, click on (Toggle Plain Text) first, and paste the typical PyQT code below and run it from an IDE like IDLE that comes with your Python installation ...

# use PyQT to draw a simple vertical bar chart
# tested with PyQT4.8 and Python3.2

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class BarChart(QWidget):
    def __init__(self, data, parent=None):
        # create the window (will be instance self)
        QWidget.__init__(self, parent)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(300, 300, 360, 320)
        self.setWindowTitle('Simple Bar Chart')
        self.data = data

    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        
        # set color and width of line drawing pen
        painter.setPen(QPen(Qt.black, 2))
        
        # drawLine(x1, y1, x2, y2) from point (x1,y1) to (x2,y2)
        # draw the baseline
        painter.drawLine(20, 280, 340, 280)        

        # set up color and width of the bars
        width = 20
        painter.setPen(QPen(Qt.red, width))
        delta = width + 5
        x = 30
        for y in self.data:
            # correct for width
            y1 = 280 - width/2
            y2 = y1 - y + width/2
            # draw each bar
            painter.drawLine(x, y1, x, y2)
            # add values to the top of each bar
            s = str(y)
            painter.drawText(x-8, y2-15, s)
            x += delta        

        painter.end()


# data to be …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
e-papa commented: thanks +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I assume you are using the Windows OS and Python 3.2, simply do this ...

For PyQT download and run the Windows 32 bit self-extracting installer
PyQt-Py3.2-x86-gpl-4.8.3-1.exe
from http://www.riverbankcomputing.co.uk/software/pyqt/download

For PyGame download and run the Windows 32 bit self-extracting installer
pygame-1.9.2pre.win32-py3.2.exe
from http://www.lfd.uci.edu/~gohlke/pythonlibs/

The Windows installers take care of everything else and will install the packages in
for instance directory C:\Python32\Lib\site-packages\PyQt4 or
C:\Python32\Lib\site-packages\pygame
Your Python interpreter will find them there.

Test PyQT with this simple program ...

# a simple template to test PyQT widgets
# PyQT free from:
# http://www.riverbankcomputing.co.uk/software/pyqt/download
# used Windows installer PyQt-Py3.2-x86-gpl-4.8.3-1.exe
# tested with PyQT4.8 and Python3.2

from PyQt4.QtCore import *
from PyQt4.QtGui import *

app = QApplication([])
# create the window and set the title
win = QWidget()
# setGeometry(x_pos, y_pos, width, height)
# 1, 1 --> widget will expand to fit lable size
win.setGeometry(100, 150, 1, 1)


html_code = """\
<h1><i>Hello </i>
<font color=red>PyQT!</font><h1>
"""
# create the label and insert html code as text
label = QLabel(html_code)

# use the grid layout manager
grid = QGridLayout()
# addWidget(widget, row, column, rowSpan=1, columnSpan=1)
grid.addWidget(label, 0, 0)
win.setLayout(grid)


win.show()
app.exec_()

Test PyGame with this example code ...

# use module pygame to display random circles
# tested with PyGame1.9.2 and Python3.2

import pygame as pg
from random import *

pg.init()

# create a 640x480 pixel window and set its title
screen = pg.display.set_mode((640, 480))
pg.display.set_caption('Pygame …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Create a Tkinter image button that easily toggles between two images ...

# create Tkinter image objects and display them ...
# create all image objects in __main__ to be persistent
# Note: if you create the image object and tie it to a
# function scope variable, then when the function is done
# the image will be garbage collected

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

def toggle_image(event):
    """toggle between the two button images"""
    print(button['image'], type(button['image']))  # test
    if button['image'] == 'pyimage2':
        button['image'] = image1
    else:
        button['image'] = image2

root = tk.Tk()
root.title("Click the image button")

# pick images you have in the working directory
# or give full path
image1 = tk.PhotoImage(file='Btn_next.gif')
image2 = tk.PhotoImage(file='Btn_prev.gif')

# create a button to display the image
button = tk.Button(root, image=image1, relief='raised', bd=10)
button.grid(row=1, column=1, padx=100, pady=10)
# bind left mouse click
button.bind('<Button-1>', toggle_image)  

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is a simple way to accomplish transparency using the Tkinter GUI toolkit ...

# explore Tkinter transparency (simplified)

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

root = tk.Tk()

# use opacity alpha values from 0.0 to 1.0
# opacity/tranparency applies to image and frame
root.wm_attributes('-alpha', 0.7)  

# use a GIF image you have in the working directory
# or give full path
photo = tk.PhotoImage(file="LAKE.gif")

tk.Label(root, image=photo).pack()

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here's to a long life and a merry one
A quick death and an easy one
A pretty girl and an honest one
A cold beer and another one!
-- Irish Saying

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here's to a long life and a merry one
A quick death and an easy one
A pretty girl and an honest one
A cold beer and another one!
-- Irish Saying

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

n = 1 has to stay outside the for loop, or you would reset n all the time to 1

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can expand on something like this ...

'''
ttk_multicolumn_listbox2.py

Python31 includes the Tkinter Tile extension ttk.

Ttk comes with 17 widgets, 11 of which already exist in Tkinter:
Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton,
PanedWindow, Radiobutton, Scale and Scrollbar

The 6 new widget classes are:
Combobox, Notebook, Progressbar, Separator, Sizegrip and Treeview

For additional info see the Python31 manual:
http://gpolo.ath.cx:81/pydoc/library/ttk.html

Here the TreeView widget is configured as a multi-column listbox
with adjustable column width and column-header-click sorting.

Tested with Python 3.1.1 and Tkinter 8.5
'''

import tkinter as tk
import tkinter.font as tkFont
import tkinter.ttk as ttk

class McListBox(object):
    """use a ttk.TreeView as a multicolumn ListBox"""
    def __init__(self):
        self.tree = None
        self._setup_widgets()
        self._build_tree()

    def _setup_widgets(self):
        s = """\
click on header to sort by that column
to change width of column drag boundary
        """
        msg = ttk.Label(wraplength="4i", justify="left", anchor="n",
            padding=(10, 2, 10, 6), text=s)
        msg.pack(fill='x')

        container = ttk.Frame()
        container.pack(fill='both', expand=True)

        # create a treeview with dual scrollbars
        self.tree = ttk.Treeview(columns=car_header, show="headings")
        vsb = ttk.Scrollbar(orient="vertical",
            command=self.tree.yview)
        hsb = ttk.Scrollbar(orient="horizontal",
            command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set,
            xscrollcommand=hsb.set)
        self.tree.grid(column=0, row=0, sticky='nsew', in_=container)
        vsb.grid(column=1, row=0, sticky='ns', in_=container)
        hsb.grid(column=0, row=1, sticky='ew', in_=container)

        container.grid_columnconfigure(0, weight=1)
        container.grid_rowconfigure(0, weight=1)

    def _build_tree(self):
        for col in car_header:
            self.tree.heading(col, text=col.title(),
                command=lambda c=col: sortby(self.tree, c, 0))
            # adjust the column's width to the header string
            self.tree.column(col,
                width=tkFont.Font().measure(col.title()))

        for item in car_list:
            self.tree.insert('', 'end', values=item)
            # adjust column's width if necessary to fit each value
            for ix, val in enumerate(item):
                col_w = tkFont.Font().measure(val)
                if self.tree.column(car_header[ix],width=None)<col_w:
                    self.tree.column(car_header[ix], width=col_w)


def sortby(tree, col, descending):
    """sort …
Gribouillis commented: Nice widget demo +5
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Erste Algemeine Verunsicherung (an Austrian band)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Ideal for folks who can't make up their mind which dessert to eat. Such an easy recipe!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Rule of thumb is that it takes about ten good C++ programmers to do what 1 good Python program can accomplish in a given time span. So, yeah there are a lot more C++ jobs out there!

On could imagine that with the help of AI future computers could do the bulk of the programming chores themselves.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Something like this could do it ...

listA = [1, 5, 3, 4]
# index to be excluded
index = 1

mx = 0
for ix, n in enumerate(listA):
    if n > mx and ix != index:
        mx = n

print(mx)
Smed commented: perfect, thanks! +3
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Prosciutto with shmear on a whole wheat bagel, and a handful of Mexican grape tomatoes.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This little code snippet shows you how you save a wxPython canvas drawing to a standard image file.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just one caveat ...

# sorting a list of alphanumeric data numerically

a = ['77', '123', '18']

# sort alphabetic
a.sort()

print(a)  # ['123', '18', '77']

# sort numeric
a.sort(key=int)

print(a)  # ['18', '77', '123']
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Mathematica may use a Miller Rabin type algorithm ...

def miller_rabin_isprime(a, i, n):
    """
    Miller-Rabin primality test
    returns a 1 if n is a prime
    usually i = n - 1
    """
    if i == 0:
        return 1
    x = miller_rabin_isprime(a, i // 2, n)
    if x == 0:
        return 0
    y = (x * x) % n
    if ((y == 1) and (x != 1) and (x != (n - 1))):
        return 0
    if (i % 2) != 0:
        y = (a * y) % n
    return y

print('-'*50)

n = 73465414651314146513116546432131
i = n - 1
p = miller_rabin_isprime(2, i, n)
if p == 1:
    print n, "is a prime"
else:
    print n, "is not a prime"

print('-'*50)

n = 73465414651314146513116546432133
i = n - 1
p = miller_rabin_isprime(2, i, n)
if p == 1:
    print n, "is a prime"
else:
    print n, "is not a prime"

print('-'*50)

'''result -->
--------------------------------------------------
73465414651314146513116546432131 is not a prime
--------------------------------------------------
73465414651314146513116546432133 is a prime
--------------------------------------------------
'''
Thisisnotanid commented: Very helpful, wrote a program to illustrate the concept for me! +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is an example using PIL ...

# use the Python Image Library (PIL) to load and flip an image
# convert the two PIL images to Tkinter images and display
# tested with Python26  by  vegaseat

import Tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
cv = tk.Canvas(root, width=500, height=500)
cv.pack(fill='both', expand='yes')

# pick an image file you have .bmp  .jpg  .gif.  .png
# if not in the working directory, give full path
# open as a PIL image object
pil_image = Image.open("ladybug.gif")
# flip the image around a vertical axis
# for horizontal axis use: Image.FLIP_TOP_BOTTOM
pil_image_flip = pil_image.transpose(Image.FLIP_LEFT_RIGHT)   

# convert PIL image object to Tkinter PhotoImage object
tk_image = ImageTk.PhotoImage(pil_image)
tk_image_flip = ImageTk.PhotoImage(pil_image_flip)

# 'nw' uses upper left corner of the image as anchor
# position first image at canvas coordinates x=30, y=20
cv.create_image(30, 20, image=tk_image, anchor='nw')
# position second image at canvas coordinates x=100, y=20
cv.create_image(100, 20, image=tk_image_flip, anchor='nw')

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

It might be simpler to draw a Koch fractal using the module turtle that comes with your Python installation ...

import turtle as tu

def Koch(length):
    """draw a Koch fractal curve recursively"""
    if length <= 2 :
        tu.fd(length)
        return
    Koch(length/3)
    tu.lt(60)
    Koch(length/3)
    tu.rt(120)
    Koch(length/3)
    tu.lt(60)
    Koch(length/3)


tu.speed(0)
length = 300.0
# move to starting position
tu.penup()
tu.backward(length/2.0)
tu.pendown()
tu.title('Koch fractal curve')
Koch(length)
# keep showing until window corner x is clicked
tu.done()

RP770

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Hey, I'm new to Python and wondering about the following bit of code. It tells me that the module random has no attribute randint. I've looked at the documentation and such and I think I'm doing it correctly, but obviously something's wrong. Any ideas? Thanks!

import random

int1=random.randint(1, 6)
int2=random.randint(1, 6)

print "Die one was "+str(int1)
print "Die two was "+str(int2)
print "Your total was "+str(int1+int2)

Something tells me that you saved one of your programs as random.py. Avoid naming any of your programs with module names.

Python looks into the working directory first for imports. If it finds random.py (your homemade program) there, it doesn't look any further. What you really want is the random.py module file that is in the Lib directory that would be searched later in the PYTHONPATH.

So, if you have a random.py file in your working directory, rename it to something else to avoid this conflict.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Yes, a major improvement!

A word of coding advice, using the single letter 'l' as a variable name is rather poor, since it looks so much like the number '1'. I don't even like 'i' or 'j'.

The Python profiler is your friend. To run a profile you have to put all the time critical code into one function. Check out these two codes and thou shall see ...

import profile

def primenumbers1(n):
    s = range(0, n+1)

    x = 1
    y = 2

    while y < len(s):
        z = y + (s[y]*x)
        while (z < len(s)) and (s[y] != 0) :
            s[z] = 0
            x += 1
            z = y + (s[y]*x)
        x = 1
        y += 1
    s = list(set(s))
    s.sort()
    s.remove(0)
    s.remove(1)        
    return s

#n = int(raw_input("Num: "))
n = 1000000

profile.run('primenumbers1(n)')


# test
s = primenumbers1(n)
# show the first 10 primes
print(s[:10])
# show the last 10 primes
print(s[-10:])

"""result Python26 -->
         4775217 function calls in 11.296 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  4775209    4.504    0.000    4.504    0.000 :0(len)
        1    0.025    0.025    0.025    0.025 :0(range)
        2    0.000    0.000    0.000    0.000 :0(remove)
        1    0.001    0.001    0.001    0.001 :0(setprofile)
        1    0.046    0.046    0.046    0.046 :0(sort)
        1    0.004    0.004   11.294   11.294 <string>:1(<module>)
        1    6.715    6.715   11.291   11.291 prime_profile1.py:3(primenumbers1)
        1    0.000    0.000   11.296   11.296 profile:0(primenumbers1(n))
        0    0.000             0.000          profile:0(profiler)


[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
[999863, 999883, 999907, 999917, 999931, 999953, 999959, 999961, 999979, 999983]
"""

Also …

Thisisnotanid commented: Very helpful +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"With or without religion, good people will do good, and evil people will do evil. But for good people to do evil, that takes religion."
-- physicist Steven Weinberg

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"God made the integers; all else is the work of man."
-- German mathematician Leopold Kronecker

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Create your random numbers inside the loop, something like this ...

# generate random number a certain number of times

import random

# now print different number 10 times
for count in range(1,11):
    # create random numbers
    d1= random.randint(1,10)
    d2= random.randint(1,10)
    print (d1,d2)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I am running Python 25, 26, 27 and 31 in my Windows7 machine. The trick is to use an IDE like Editra that allows you to specify which Python version to use.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

... when you still chase women, but can't remember what to do after you catch one.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

It's hard to be nostalgic when you can't remember anything.

~s.o.s~ commented: :( +0