Trigonometry Puzzle Game

I have been working on a project for the 9th graders. They had a small puzzle game where they were supposed to find trigonometric ratios and built the puzzle piece by piece by colouring it. Children liked it and as a team we decided to build it in scratch. I took up the responsibility and build a scratch program similar to the game they had in their text book. Here’s the program.

Children were excited and they started building the program themselves.

Python Learning

This week I had a good time with python. Yes, I have learnt few things which I feel worth to share here.
Counter:
It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. One can find out  the number of occurrence of the list items.
Example:#
>>>from collections import Counter
# list1 is a list/array which contains numbers
>>>list1 = [1,2,4,5,7,3,5,0,8,5,4,5,4,5,6,7,3,1,2,0,8,3,4,5,2,1,2,3,1,2]
# Counter will convert list1 into dictionary
>>>count = Counter(list1)
>>># most_common function will give the series of all the elements and its corresponding occurrences.
>>>count.most_common()
[(5, 6), (2, 5), (1, 4), (3, 4), (4, 4), (0, 2), (7, 2), (8, 2), (6, 1)]
>>># get the most common element by sending 1 to the function
>>>count.most_common(1)
[(5, 6)]
>>>count.most_common(1)[0] # get element & no. of occurrence as dict
(5, 6)
>>>most_common = count.most_common(1)[0][0] # Get the most common element
5

Strip() :
In the past I have used strip to strip out some letters from a string. Example
>>>AuraAuro.strip(A)
uraAuro
But I strip() is also used to remove all whitespace at the start and end, including spaces, tabs, newlines and carriage returns.
Rename:
I was looking for a module in python which used to rename all the specific type (eg. .docs, .txt, .py) files in a particular directory.
# Go to a directory get all the files of specific type ( lets say “.xls”)
# and rename it with ‘os.rename’
>>> import glob  # used to get all the dir / file from a specified path
>>>import os
>>>path = C:\\Users\\Vaidegi\\Desktop\\*.xls
>>>file_names_with_path = glob.glob(path+“*.xlsx) # to get all the excel files name
>>>for i in range(len(file_names_with_path )):
. . .          os.rename(file_names_with_path[i], student+i+.xls)

Linear, Log and exponent plots – Sratch

I was always confused with log. Sometimes its difficult for me  to handle log based problems . So, I decided to do project in log in scratch to visualize the curve and also to get a clear picture of that.  I started with comparing all the basic curves. First I created Y = X and Y = X^2 as follows,

Then, I went for log(x) and log (x^2). There is no much difference in these two. The plots are same in shape.

At last I plotted the exponent curve (e^x) as follows,

Matplotlib Animation – calling animation from a function

Creating Animation in Matplotlib:
#——————————————————————————
# ANIMATION- DYNAMIC PLOTS
#——————————————————————————
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.figure import Figure
import time
def animated_plot():
def data_gen(t=0):
“””
Generator – generating data to plot the graph
“””
cnt = 0
while cnt < 1000:
cnt += 1
t += 1
a = time.localtime() # used to get seconds
yield t, a.tm_sec  # this ‘yield’ will generate two point continuously.
def init():
“””
Initiation – create the base frame upon which the animation takes place.
“””
ax1.set_ylim(0,60)
ax1.set_xlim(0, 10)
del xdata1[:]  # to clear
del ydata1[:] # to clear
line1.set_data(xdata1, ydata1)
return line1,
def run1(data):
“””
To run the animation(draw function)
“””
t1, y1 = data
xdata1.append(t1)
ydata1.append(y1)
xmin, xmax = ax1.get_xlim()
if t1 >= xmax:
ax1.set_xlim(xmin, 2*xmax)
ax1.figure.canvas.draw()
line1.set_data(xdata1, ydata1)
return line1,
fig = plt.figure(figsize =(4,1.5))
ax1 = fig.add_subplot(1, 1, 1) #  1×2 mmatrix, 1st subplot
ax1.tick_params(axis=’both’, which=’major’, labelsize=8)
line1, = ax1.plot([], [], lw=2)
ax1.grid()
fig.patch.set_facecolor(‘white’)
xdata1, ydata1 = [], []
animatn = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=1000,repeat=False, init_func=init)
plt.show()
return animatn # must to put return when the animation is calling from a function
Animat=animated_plot() # calling the function. Here ‘Animat’ is must (it just a variable). Otherwise it will return null

Important points to note:

  • Use ‘return’ to return all the values to continue the animation (when you need to call it from a function). Otherwise animation will stop at its first iteration.
  • Call the function with name. ex. ‘Animat=animated_plot()’ not simply ‘animated_plot()’. In the latter case, all the values are collected as garbage values. So it won’t draw anything in the canvas.

 

Passing ‘Global Variable’ across the files in Python

Passing global variable – Attachment

I have encounter a situation where i need to pass a variable from one file to another file. This is like passing global variable across the files. I’ve created three files to demonstrate this as follows,

main.py   # name of the file
import subfile1
import subfile2
subfile1.globle_pas()
print(settings.x)
subfile2.change_glob_var()
print(settings.x)
subfile1.py     # name of the file
x = 0
def globle_pas():
global x
x = 1 # Default value of the ‘x’ configuration setting
subfile2.py     # name of the file
import settings
settings.globle_pas()
def change_glob_var():
settings.x = 9

Tooltip for Canvas items

Tooltip : Attachment 

Tooltip:
I am presently  creating a GUI in python. One of features is when I go on top of any button it should show the name of the button.  Tooltip can do this in python. Unfortunately it doesn’t work with images (My all buttons are made up of images) because it doesn’t consider image as widget. So I have come up with following method to create namebox.

******************************Tooltip for canvas Items ******************************

# Globals
tw = 0
tt_yes = 0
def tooltip_create(text, x,y): # inputs are text = display name; x,y = where should be positioned.
global tw, tt_yes
x -= 5
y += 15
# creates a toplevel window
tw = Toplevel(home_root)
# Leaves only the label and removes the app window
tw.wm_overrideredirect(True)
tw.wm_geometry(“+%d+%d” % (x, y))
label =Label(tw, text=text, justify=’left’,
background=’white’, relief=’solid’, borderwidth=1)
label.pack(ipadx=1)
tt_yes = 1
def tooltip_close(): # close the namebox window
global tw, tt_yes
if tt_yes:
tw.destroy()
def  hover_enter(event):
tooltip_create(“Save”, x,y)
return
def  hover_leave(event):
tooltip_close()
return
# Photoimage ( which requires the tooltip)
image=os.path.abspath(y+’images\\images2\\save.gif’)
img_save = PhotoImage(file = image)
canvas.create_image(x= X, y = Y,image=img_save,tags=”hover_functn”)
canvas.tag_bind(“hover_functn “,’<Any-Enter>‘, hover_enter)
canvas.tag_bind(“hover_functn “,’<Any-Leave>‘, hover_leave)

Installation of standalone python34

STEP1:

Download python34 (python3.4.0 msi)  from following website,
https://www.python.org/downloads/release/python-340/
After you have installed it go to command terminal(cmd) and put this python in your path as first priority
PATH=C:\Python34;C:\Python34\Scripts;%PATH%     (or)
Go to Control Panel -> System and Security -> System ->  Advanced system settings -> environment variables -> system variables -> path and paste C:\Python34;C:\Python34\Scripts;

STEP2:

Download PySide-1.2.4-cp34-none-win32.whl from https://pypi.python.org/pypi/PySide/1.2.4
In the cmd, cd into the directory where PySide-1.2.4-cp34-none-win32.whl is present and run,
pip install PySide-1.2.4-cp34-none-win32.whl

STEP3:

Download spyder2.3 from https://pypi.python.org/pypi/spyder/2.3.0
In the cmd,
cd spyder-2.3.0
python setup.py install
should install your spyder in the python setup.

STEP4:

Download pyinstaller from https://pypi.python.org/pypi/pypiwin32/219
in the cmd,
pip install pypiwin32-219-cp34-none-win32.whl

STEP5:

Download pyinstaller from https://github.com/pyinstaller/pyinstaller/releases
In the cmd,
cd PyInstaller-3.1.1
python setup.py install

STEP6:

Download xlrd package from  https://pypi.python.org/pypi/xlrd/0.9.3
In the cmd,
cd xlrd-0.9.4
python setup.py install

STEP7:

Download pyglet package from https://pypi.python.org/pypi/pyglet/1.2.3
In the cmd,
pip install pyglet-1.2.3-py3-none-any.whl

STEP8:

Download psutil( download exe since .whl file didn’t work ) from https://pypi.python.org/pypi/psutil 
and run it.
Note:
If you encounter an error saying,
return psutil.phymem_usage().percent AttributeError: ‘module’ object has no attribute ‘phymem_usage’
Open the system.py file:
C:\Python34\Lib\site-packages\spyderlib\utils\system.py
In that file, replace return psutil.phymem_usage().percent line with
return psutil.virtual_memory().percent

zfill in python

Description

The method zfill() pads string on the left with zeros to fill width.

Syntax

Following is the syntax for zfill() method

Parameters

width — This is final width of the string. This is the width which we would get after filling zeros.

eg;

str = “happy new year”

print str.zfill(40)

print str.zfill(15)

Output:

00000000000000000000000000happy new year
0happy new year

Tkinter Toplevel Widget

The Toplevel widget work pretty much like Frame, but it is displayed in a separate, top-level window. Such windows usually have title bars, borders, and other “window decorations”.

The Toplevel widget is used to display extra application windows, dialogs, and other “pop-up” windows.

ref: http://effbot.org/tkinterbook/toplevel.htm