My solution ...
people = sum(range(8, 13))
print(people)
My solution ...
people = sum(range(8, 13))
print(people)
"Santa is very jolly because he knows where all the bad girls live."
... George Carlin
I heard in Germany an angel brings the presents on Christmas eve. A little more believable for little kids than a fat guy sliding down the non existent chimney.
Even a blind chicked will find a piece of corn every now and then.
Turn an even integer into the next odd integer ...
# x|1 turns an even integer x into the next odd integer
# | is the bitwise or operator
x = 6
print(x, x|1) # (6, 7)
x = 5
print(x, x|1) # (5, 5)
Sometimes it pays to read the manual ...
''' integer_bitlength.py
how many bits does a given integer have
tested with Python27 and Python33
'''
# denary 12 --> binary 1100
n = 12
print("denary {} has {} bits".format(n, n.bit_length()))
''' result ...
denary 12 has 4 bits
'''
*
***
*****
*******
*********
***********
|
Write Python code to print a little tree like this.
If you decorate a function, then some of the information is lost during the debugging process. Python supplies another decorator @wraps to help out. A decorator for a decorator, very interesting.
Here is a typical PySide/PyQt designer project. First the XML file generated by the Designer program (saved as ps_listview_match2.ui) ...
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Match words with a list</string>
</property>
<widget class="QWidget" name="verticalLayoutWidget">
<property name="geometry">
<rect>
<x>9</x>
<y>9</y>
<width>361</width>
<height>281</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Start typing to match words in list:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit"/>
</item>
<item>
<widget class="QListView" name="listView"/>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
Now the Python code that uses the XML file ...
''' run_ps_listview_match2.py
example using PySide's QListView and QAbstractListModel
to match a partially typed word to words in a list
the visible GUI part was generated with PySide's Designer
the Designer's XML file was saved as "ps_listview_match2.ui"
it contains a QWidget form with a QLabel, a QLineEdit and
a QListView stacked into a QVBoxLayout()
this program is a simple loader for the .ui XML file and also
does the connection of the widget's signals
PySide is the official LGPL-licensed version of PyQT
I downloaded the 32 bit version for Python from:
http://qt-project.org/wiki/PySide_Binaries_Windows
The Windows self installer is called:
PySide-1.2.1.win32-py2.7.exe (for Python27)
PySide-1.2.1.win32-py3.3.exe (for Python33)
this also installs the Designer program
'''
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtUiTools import QUiLoader
class MyWindow():
def __init__(self, words, *args):
# create the ui loader
loader = QUiLoader()
# and load the form's ui …
Did you by accident create a file
tkinter.py
in your working directory (where your program code is)?
It would be imported first.
You can also use lambda or a partial function to pass arguments ...
''' tk_button_text102.py
show the text of the Tkinter button that has been clicked
'''
# for Python3 use tkinter
import Tkinter as tk
def click(val):
sf = "clicked: {}".format(val)
root.title(sf)
root = tk.Tk()
root.geometry("300x80+80+50")
text1 = "button1"
cmd1 = lambda: click(text1)
b1 = tk.Button(root, text=text1, command=cmd1)
b1.pack(pady=10)
text2 = "button2"
cmd2 = lambda: click(text2)
b2 = tk.Button(root, text=text2, command=cmd2)
b2.pack()
root.mainloop()
You could bind the event to pass certain arguments ...
# Tkinter, show the text of the button that has been clicked
# for Python3 use tkinter
import Tkinter as tk
def click(event):
s = "clicked: " + event.widget.cget("text")
root.title(s)
root = tk.Tk()
root.geometry("300x50+30+30")
b1 = tk.Button(root, text="button1")
b1.bind("<Button-1>", click)
b1.pack()
b2 = tk.Button(root, text="button2")
b2.bind("<Button-1>", click)
b2.pack()
root.mainloop()
I have to admire the folks that help on the C++ forum. The language can be tough for beginners and the questions are endless. So, I am hiding out on the Python forum, where programming can be downright fun.
If I remember it correctly, I got my Hypocrite Medal during a battle of words on the C++ forum. Was it a memory leak problem? I forgot!
A simple code example on how to play wave sound files with the Python module PyGame.
Actually you can use time.sleep() with Tkinter but you have to use update() too ...
''' tk_image_slideshow_sleep.py
create a very simple Tkinter image slide show
using time.sleep() and root.update()
tested with Python27/33 by vegaseat 03dec2013
'''
import time
try:
# Python2
import Tkinter as tk
except ImportError:
# Python3
import tkinter as tk
# get a series of gif images you have in the working folder
# or use full path name
image_files = [
'Slide_Farm.gif',
'Slide_House.gif',
'Slide_Sunset.gif',
'Slide_Pond.gif',
'Slide_Python.gif'
]
root = tk.Tk()
label = tk.Label(root)
label.pack()
delay = 3.2 # seconds delay between slides
for image in image_files:
image_object = tk.PhotoImage(file=image)
label.config(image=image_object)
root.title(image)
root.update()
time.sleep(delay)
root.mainloop()
Shows how to create a basic slide show with the Python Tkinter GUI toolkit.
Actually rum soaked fruit cake.
Another option ...
mylist = [('cat', 'meow'), ('dog', 'ruff')]
for tup in mylist:
print(" ".join(tup)) # use "" for no space
To break out of a nested loop put it into a function and use return instead of break.
Shows you how to create multiple Tkinter buttons in a loop, each with its own name, label and command response.
Just as an exercise, a mild modification of woooee's code ...
''' bubble_sort_details.py
count the number of tuple swaps performed
'''
import random
def bubble_sort(mylist):
'''mylist is sorted in place'''
swaps_ctr = 0
while True:
swap_flag = False
for ctr in range(0, len(mylist)-1):
if mylist[ctr] > mylist[ctr+1]:
# do a tuple swap
mylist[ctr+1], mylist[ctr] = mylist[ctr], mylist[ctr+1]
swaps_ctr += 1
# print(swaps_ctr) # test
swap_flag = True
# sort is done, break the while loop
# also catches an already sorted list
if swap_flag == False:
return swaps_ctr
# test it with an already sorted list
#mylist = list(range(1, 11))
# or use a random list
mylist = [6, 8, 4, 10, 6, 4, 2, 6, 1, 6, 1, 9, 6, 5, 8, 5, 3, 3, 2, 7]
print("original list:")
print(mylist)
print('-'*40)
swaps = bubble_sort(mylist)
print("sorted list:")
print(mylist)
print('-'*40)
print("number of swaps:")
print(swaps)
print('-'*40)
# extra, give number frequency
for num in set(mylist):
print("num = {} freq = {}".format(num, mylist.count(num)))
''' result ...
original list:
[6, 8, 4, 10, 6, 4, 2, 6, 1, 6, 1, 9, 6, 5, 8, 5, 3, 3, 2, 7]
----------------------------------------
sorted list:
[1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 9, 10]
----------------------------------------
number of swaps:
103
----------------------------------------
num = 1 freq = 2
num = 2 freq = 2
num = 3 freq = 2
num = 4 freq = 2
num = 5 freq = 2
num = 6 freq = 5
num = 7 freq = 1
num = 8 freq = 2
num = 9 freq = 1
num = 10 freq = 1
'''
Please note that Python by tradition uses capitalized variables for class names.
Work on porting the wxPython GUI toolkit to Python3 is progressing steadily. The project is called Pheonix, here is an example with download info ...
''' pwx_Notebook_simple1.py
experiments with wxPython's wx.Notebook() widget
wx.Notebook(parent, id, pos, size, style, name)
tab position style=wx.NB_TOP is default
others are wx.NB_BOTTOM, wx.NB_LEFT or wx.NB_RIGHT
For Python33 on Windows downloaded the most recent
wxPython_Phoenix-3.0.0.0-r75143-win32-py3.3.tar.gz
from
http://wxpython.org/Phoenix/snapshot-builds/
then simply extracted the wx folder to
C:\Python33\Lib\site-packages
Note:
tar.gz also available for Linux versions
recently updated documents are there too
wxPython_Phoenix-3.0.0.0-r75068-docs.tar.gz
'''
import wx
class MyPanel(wx.Panel):
"""
each panel instance gives the notbook page content and colour
"""
def __init__(self, parent, bgcolor, toolbar=False):
wx.Panel.__init__(self, parent, wx.ID_ANY)
self.SetBackgroundColour(bgcolor)
app = wx.App(0)
# create an instance of a frame, parent is None
caption = "testing simple wx.Notebook()"
frame = wx.Frame(None, -1, caption, size=(400,300))
# create an instance of a notebook, parent=frame
notebook = wx.Notebook(frame, -1)
# each panel instance has parent=notebook and gives the page color
panel1 = MyPanel(notebook, "yellow")
panel2 = MyPanel(notebook, "green")
panel3 = MyPanel(notebook, "red")
# now create the notebook pages, add the tab title to each page
notebook.AddPage(panel1, "Page1")
notebook.AddPage(panel2, "Page2")
notebook.AddPage(panel3, "Page3")
# add a label to each of the panels (pages)
# the label will try to autosize to fit text
text1 = "What time does the two o'clock bus leave?"
wx.StaticText(panel1, wx.ID_ANY, text1)
text2 = "He is not 'BALDING' - He is in 'FOLLICLE REGRESSION'."
wx.StaticText(panel2, wx.ID_ANY, text2)
text3 = "She does not 'NAG' - She becomes 'VERBALLY REPETITIVE'."
wx.StaticText(panel3, wx.ID_ANY, …
Just a simple image file slide show using PySide (PyQT).
Unless it's for the exercise, I prefer a while loop over a recursive function and avoid a possible stack overflow.
A few test prints should help ...
''' nltk_tokenize102.py
use module nltk to find the frequency distribution of nouns
in a given text
downloaded and installed:
nltk-2.0.4.win32.exe
from:
https://pypi.python.org/pypi/nltk
tested with Python27
'''
import nltk
import pprint
text = "This ball is blue, small and extraordinary. Like no other ball."
token_text= nltk.word_tokenize(text)
pprint.pprint(token_text)
print('-'*20)
tagged_sent = nltk.pos_tag(token_text)
pprint.pprint(tagged_sent)
print('-'*20)
nouns= []
for word, pos in tagged_sent:
if pos in ['NN',"NNP"]:
nouns.append(word)
pprint.pprint(nouns)
print('-'*20)
freq_nouns = nltk.FreqDist(nouns)
print(freq_nouns)
''' result ...
['This',
'ball',
'is',
'blue',
',',
'small',
'and',
'extraordinary.',
'Like',
'no',
'other',
'ball',
'.']
--------------------
[('This', 'DT'),
('ball', 'NN'),
('is', 'VBZ'),
('blue', 'JJ'),
(',', ','),
('small', 'JJ'),
('and', 'CC'),
('extraordinary.', 'NNP'),
('Like', 'NNP'),
('no', 'DT'),
('other', 'JJ'),
('ball', 'NN'),
('.', '.')]
--------------------
['ball', 'extraordinary.', 'Like', 'ball']
--------------------
<FreqDist: 'ball': 2, 'Like': 1, 'extraordinary.': 1>
'''
I used the app instance for some testing.
MyApp().mainloop()
is simpler, thanks for reminding me.
Need to see your code.
The code sample shows how to get an image from the internet and show it in a Tkinter label widget.
This is the updated version of the Tiny Tkinter Calculator. It has more power, since you can type in functions contained in the Python math module then press the equals key. You can then move the result into memory for other calculations. The code is written in OOP class style as an exercise, still simple and hopefully very readable. Again, you are welcome to improve the functionality, but don't turn it into a HUGE calculator.
This shows you how to create a flashcard like quiz game using a Python dictionary. It's up to you to explore the approach and make this a more meaningful game.
Hint ...
# this test string will have 65 characters
s = 'q' * 65
length = len(s)
if length <= 64:
encrypted = encrypt(s)
else:
print("string exceeds 64 characters")
k = 0
while k < 10:
print(k) # print before increment
k += 1
''' result ...
0
1
2
3
4
5
6
7
8
9
'''
k = 0
while k < 10:
k += 1
print(k) # print after increment
''' result ...
1
2
3
4
5
6
7
8
9
10
'''
Here is another example ...
''' sqlite3_employ101.py
experimenting with a Python sqlite3 database of employees
'''
import sqlite3
# for temporary testing you can use memory only
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
# query language in upper case is optional eye candy
cur.execute('''CREATE TABLE employees(
number INTEGER PRIMARY KEY AUTOINCREMENT,
first TEXT,
last TEXT,
age INTEGER,
weight REAL)
''')
# a list of (first, last, age, weight) tuples
data_list = [
('Heidi', 'Kalumpa', 36, 127.3),
('Frank', 'Maruco', 27, 234),
('Larry', 'Pestraus', 19, 315),
('Serge', 'Romanowski', 59, 147),
('Carolus', 'Arm', 44, 102.5),
('Monika', 'Sargnagel', 21, 175),
('Hans', 'Solo', 37, 167.8),
('Mother', 'Therasa', 81, 93.2)
]
# insert all data_list lines at once ...
cur.executemany("INSERT INTO employees(first, last, age, weight) \
VALUES (?, ?, ?, ?)", data_list )
# testing ...
cur.execute('SELECT * FROM employees')
print("fetch all data rows (raw data):")
for r in cur.fetchall():
print(r)
print('-'*42)
cur.execute('SELECT * FROM employees ORDER BY last')
print("fetch all data rows (sorted by last name):")
for r in cur.fetchall():
print(r)
print('-'*42)
cur.execute('SELECT * FROM employees WHERE age>50')
print("fetch all data rows where age is above 50:")
for r in cur.fetchall():
print(r)
print('-'*42)
cur.execute('SELECT * FROM employees WHERE number=3')
print("fetch the data row of employee number 3:")
for r in cur.fetchall():
print(r)
print('-'*42)
# finally ...
cur.close()
''' result ...
fetch all data rows (raw data):
(1, 'Heidi', 'Kalumpa', 36, 127.3)
(2, 'Frank', 'Maruco', 27, 234.0)
(3, 'Larry', 'Pestraus', 19, 315.0)
(4, 'Serge', 'Romanowski', 59, 147.0)
(5, 'Carolus', 'Arm', 44, 102.5)
(6, 'Monika', 'Sargnagel', …
Version information ...
''' pwx_version.py
get the version info of the wxPython GUI
for Python33 download the wxPython Phoenix version (4nov2013)
wxPython_Phoenix-3.0.0.0-r75123-win32-py3.3.tar.gz
from
http://wxpython.org/Phoenix/snapshot-builds/
then simply extracted the wx folder to
C:\Python33\Lib\site-packages
'''
import wx
import sys
# Python version
print(sys.version)
# wx version
print(wx.version())
app = wx.App()
# create the basic window, let's call it win
# (there is no parent, -1 is the default ID)
win = wx.Frame(None, -1, size=(360, 80))
win.SetBackgroundColour('white')
sf = " {}".format(wx.version())
# create a label, default is auto-size
label = wx.StaticText(win, -1, sf)
font = wx.Font(16, wx.SCRIPT, wx.NORMAL, wx.LIGHT)
label.SetFont(font)
# show the window
win.Show(True)
# start the GUI event loop
app.MainLoop()
''' results (Python27 or Python33) ...
2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]
2.9.1.1 (msw-unicode)
3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)]
3.0.0.0-r75123 msw (phoenix)
'''
Example on how to modify a CSV file ...
# data string from typical csv file
# header removed
csv_data = '''\
2011/07/01 00:00,318,6.6
2011/07/01 00:15,342,5.5
2011/07/01 00:30,329,6.6
2011/07/01 00:45,279,7.5'''
mylist = csv_data.split('\n')
#print(mylist) # test
newlist = []
for line in mylist:
line_list = line.split(',')
#print(line_list) # test
#print(line_list[0]) # test
#print(line_list[0].split()) # test
date, time = line_list[0].split()
newlist.append([date, time, line_list[1], line_list[2]])
#print(newlist) # test
csv_data_new = ""
for item in newlist:
#print(','.join(item)) # test
csv_data_new += ','.join(item) + '\n'
print(csv_data)
print('-'*30)
print(csv_data_new)
# optionally add header string
header = "Fecha,Hora,DirViento,MagViento\n"
csv_data_new = header + csv_data_new
fname = "new_data.csv"
with open(fname, "w") as fout:
fout.write(csv_data_new)
''' result ...
2011/07/01 00:00,318,6.6
2011/07/01 00:15,342,5.5
2011/07/01 00:30,329,6.6
2011/07/01 00:45,279,7.5
------------------------------
2011/07/01,00:00,318,6.6
2011/07/01,00:15,342,5.5
2011/07/01,00:30,329,6.6
2011/07/01,00:45,279,7.5
'''
Now you can read the modified CSV file into pandas ...
''' pandas_read_csv101.py
file new_data.csv content ...
Fecha,Hora,DirViento,MagViento
2011/07/01,00:00,318,6.6
2011/07/01,00:15,342,5.5
2011/07/01,00:30,329,6.6
2011/07/01,00:45,279,7.5
used Windows installer
pandas-0.12.0.win32-py3.3.exe
'''
import pandas as pd
data = pd.read_csv('new_data.csv')
print(data)
''' result ...
Fecha Hora DirViento MagViento
0 2011/07/01 00:00 318 6.6
1 2011/07/01 00:15 342 5.5
2 2011/07/01 00:30 329 6.6
3 2011/07/01 00:45 279 7.5
'''
Hint ...
# using module bisect to determine grades
import bisect
# both sequences have to be sorted or be in order
# A is 85 or higher, B is 75 to 84 etc.
grades = "FEDCBA"
breakpoints = [30, 44, 66, 75, 85]
def grade(total):
return grades[bisect.bisect(breakpoints, total)]
print grade(66) # C
print grade(33) # E
print grade(85) # A
print grade(77) # B
print grade(27) # F
The richest 1% of the people in the U.S. earn 21.2% of the total U.S. income.
A Python sort with a helper function to allow for mixed order sort like age descending and weight ascending.
One way to find the shortest distance between a series of surface (x, y) points is to let Python module itertools find the non-repeating combinations of point pairs. Now you can apply the Pythagoras' theorem to find all the distances and the minimum distance.
I found this C# code snippet from our friend ddanbe and couldn't help to translate it to IronPython.
Here is the C# code ...
// small_form101.cs
// C# form with a label
// can be compiled with:
// SnippetCompiler.exe
// from:
// http://www.sliver.com/dotnet/SnippetCompiler/
using System.Windows.Forms;
class Class1
{
static void Main()
{
Label label = new Label();
label.Text = "Hello world!";
Form form = new Form();
form.Controls.Add(label);
Application.Run(form);
}
}
Here is the corresponding IronPython code ...
''' ip_small_form101.py
form with a label
using IronPython from
http://www.codeplex.com/ironpython
'''
import clr
clr.AddReference('System.Windows.Forms')
import System.Windows.Forms as swf
class Class1(swf.Form):
def __init__(self):
label = swf.Label()
label.Text = "Hello world!"
self.Controls.Add(label)
form = Class1()
swf.Application.Run(form)
Your snippet works well using ...
SnippetCompiler.exe
from:
http://www.sliver.com/dotnet/SnippetCompiler/
I had to run this in IronPython, here is the code ...
''' ip_small_form101.py
using IronPython from
http://www.codeplex.com/ironpython
'''
import clr
clr.AddReference('System.Windows.Forms')
import System.Windows.Forms as swf
class Class1(swf.Form):
def __init__(self):
label = swf.Label()
label.Text = "Hello world!"
self.Controls.Add(label)
form = Class1()
swf.Application.Run(form)
Starting with Python 3.3 you now have access to a high resolution time counter (nanoseconds and better).
Just another loan calculation, this time using a handy function in Python module numpy.
Shows you how to get a Python object's memory size. Notice that there can be a difference between Python versions.
A simple way to find out a Python module's location on your drive.
Try this ...
'''
wants
"MATHEICS" not "ACEIHMST"
'''
s = "Mathematics".upper()
s3 = ""
for c in s:
if c not in s3:
s3 += c
print(s3) # MATHEICS
Create a password generator.