Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Sunday

Python: Love shaped graph


Python source code
{

import matplotlib.pyplot as plt
import numpy as np

x1 = np.linspace(-2, 2, 1000)
x2_left = np.linspace(-2, 0, 1000)
x2_right = np.linspace(0, 2, 1000)

# right top half semicircle from theorem Pythagoras using y=sqrt(1-x²)
# shift graph right using "x-1"
# create another left top half semicircle at the negative x-axis
#   using y(x) and y(-x) or y(|x|)
y1 = np.sqrt(1 - (abs(x1)-1)**2)

# left bottom half sqrt curve line using y=(x)**0.5
# vertical reflection for the graph using y = -1*(x)**0.5
# shift graph left using "x+2"
y2_left = -1*(x2_left+2)**0.5
# create another right bottom half sqrt curve line using
#   vertical reflection y = -1*((-x) + 2)**0.5
y2_right = -1*((-x2_right) + 2)**0.5

plt.plot(x1, y1, color="red")
plt.plot(x2_left, y2_left, color="red")
plt.plot(x2_right, y2_right, color="red")

plt.fill_between(x1, y1, color="red")
plt.fill_between(x2_left, y2_left, color="red")
plt.fill_between(x2_right, y2_right, color="red")

plt.text(0.0, -1.0, "Love", fontsize=24, color="blue",
         horizontalalignment="center")

plt.title("Love", fontsize=24, color="blue")
plt.xlabel("x axis" + r"$\rightarrow$")
plt.ylabel('y axis' + r"$\rightarrow$")

plt.show()

}

Program output:
❤️ 

Saturday

Python 3 Tutorials and Notes

2to3.py
2to3 Python program that reads Python 2 source code and applies a series of fixers to transform it into valid Python 3 code.

example1.py file content of Python 2 code at "C:\Python3\" folder:
def greet(name):
    print "Hello, {0}!".format(name)
print "What's your name?"
name = raw_input()
greet(name)

C:\Python3> python example1.py
  File "example1.py", line 2
    print "Hello, {0}!".format(name)
                      ^
SyntaxError: invalid syntax

C:\Python3> python "C:\Python3\Tools\Scripts\2to3.py" -w example1.py

C:\Python3> python example1.py
What's your name?
Linux Mint Mate
Hello, Linux Mint Mate!
A backup of the original Python version 2 file is made and the new file name is called "example1.py.bak".

2to3.py writes the needed modification right back to the source file.
Writing the changes back is enabled with the -w flag.
example1.py file content of Python 3 code:
def greet(name):
    print("Hello, {0}!".format(name)) #changed
print("What's your name?") #changed
name = input() #changed
greet(name)

Note that, this is not a fool-proof conversion though, and you'll likely need to do some bug-fixing here and there, but it may well be quicker.

Program IDLE Python 3 GUI 64 bit: Shell and File Editor
Start Menu > Python 3 > IDLE (Python 3 GUI - 64 bit)

Python 3 Shell window:
>>> import os
>>> os.getcwd()
'C:\\Python3'
>>>

Python 3 File Editor:
Shell Menu > File > New File Ctrl+N
On the file editor window > press Ctrl+S
Save the file name as time_sleep_eg1.py
Click the Save button

time_sleep_eg1.py file content:
###
import time

repeat = "y"
sentence = []

def sentenceinput():
    global sentence, repeat
    sentence_length = input("Sentence length: ")
    sentence_length = int(sentence_length)
    iteration = 0
    while iteration < sentence_length:
        print("Sentence word ", iteration+1, "? ", sep="", end="")
        sentence.append(input())
        iteration += 1
    print(*sentence)
    repeat = input("Repeat? (y/n): ")

print("Let us create one sentence only.")
while True:
    time.sleep(1)
    if repeat == "y":
        sentenceinput()
    else:
        print("Goodbye!")
        break

###

On the file editor window, press F5 to run the module file

Shell output:
###
>>> ================================ RESTART ================================
>>>
Let us create one sentence only.
Sentence length: 3
Sentence word 1? word1
Sentence word 2? word2
Sentence word 3? word3
word1 word2 word3
Repeat? (y/n): y
Sentence length: 2
Sentence word 1? word4
Sentence word 2? word5
word1 word2 word3 word4 word5
Repeat? (y/n): n
Goodbye!
>>>
###

Edit your .py script and press F5 as needed to re-run the script.

Write your Own Function
Code:
def frange(start, stop, step):
    i = start
    # use floating point inequality check formula
    # avoid "while i < stop:"
    while (abs(stop-i) > 1e-6):
        #print("{0:.1f}".format(i))
        yield i
        i += step

#frange(0.0, 0.9, 0.1)

for i in frange(0.0, 0.9, 0.1):
    #print("{0:.1f}".format(i), end=" ")
    print(round(i,1), end=' ')
print()  #print new line
Output:
0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8

Float point inequality test formula:
abs(b - a) > epsilon-error-tolerance

Control structure: while loop
Code:
*listofthings, loops = range(6)
print(listofthings)
print(loops)
loop = 0
while loop < loops:
    listofthings[loop] = "thing"+str(loop)
    loop += 1
print(listofthings)
Output:
[0, 1, 2, 3, 4]                                                                                     
5                                                                                                   
['thing0', 'thing1', 'thing2', 'thing3', 'thing4'] # listofthings is still a list data structure but the list values modified using array syntax

Function range()
In Python 2 range() produced a list.

In Python 3, the range() function got its own type. In basic terms, if you want to use range() in a for loop, then you're good to go. However you can't use it purely as a list object. For example, you cannot slice a range type.

sh-4.2# python                                                                                      
Python 2.7.5                                       
>>> range(5)                                                                                        
[0, 1, 2, 3, 4]                                                                                     
>>> type(range(5))                                                                                  
<type 'list'>                                                                                       
>>> exit                                                                                            
Use exit() or Ctrl-D (i.e. EOF) to exit                                                             
>>> exit()
sh-4.2#                                                                                        

sh-4.2# python3                                                                                     
Python 3.3.2                            
>>> range(5)                                                                                        
range(0, 5)                                                                                         
>>> type(range(5))                                                                                  
<class 'range'>                                                                                     
>>> exit()                                                                                          
sh-4.2#

Note that in Python 3, you can still produce a list by passing the generator returned to the list() function as follows:
list1 = list(range(5))
print(list1)
# output is [0, 1, 2, 3, 4] 

Human Input syntax
input([prompt])

Python 2 statement uses raw_input to get your input data.

Code:
name = input("What's your OS name? ")
print("My OS name is", name)
Output:
What's your OS name? Linux Mint Mate                                                               
My OS name is Linux Mint Mate  

Code:
a = input("Enter first number: ")
b = input("Enter second number: ")
a, *numbers, b = range(int(a),int(b)+1,1)
print("The first number is ", a, ",",
"\nthe second number is ", b, " and",
"\nthe numbers between them are ", numbers, ".", sep="")
Output:
Enter first number: 5                                                                               
Enter second number: 10                                                                             
The first number is 5,                                                                              
the second number is 10 and                                                                         
the numbers between them are [6, 7, 8, 9].

Data Structure Dictionary
Code:
dict1 = { "1":"word1", "2":"word2", "3":"word3" }
for key in dict1:
    print(key, ":", dict1[key])
Output:
1 : word1                                                                                           
2 : word2                                                                                           
3 : word3 

Data Structure List
list1=["word1", "word2", "word3", "."]
print(list1)
print(len(list1))
print(*list1)
del list1[:]
print(list1)
#Output:
# ['word1', 'word2', 'word3', '.']
# 4                                                                  
# word1 word2 word3 .                                                                                 
# []

The asterisk allows for each item to be called individually rather than the list.

print syntax
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

sep --- parts separator, by default it is a space, you can change it to any compatible character that Python allows - this can be used to make the line shorter or include mathematical operator such as >.
print("Hello, World!")

print("1","2","3", sep="<")
# output is 1<2<3

num = 4
print("The number num is ", num, " or 2*2=", 2*2, sep="")
# output is:
# python3 main.py                                                                             
# The number num is 4 or 2*2=4 

end --- end of the line, to leave a space rather than starting a new line, you can use print(x, end=' '). By default, it creates a line break.

print("line1","line1;",end=" ")
print("line1 also")
# output is line1 line1; line1 also 

file=sys.stdout --- you construct the string as you would normally to print out anything and then append the file option

From Python 2 code:
print >>sys.stderr, "an error"
print "no error"

To Python 3 code:
import sys
print("an error", file=sys.stderr)
print("fatal error", file=sys.stderr)
print("no error")

flush --- if True will force the print stream to flush after execution

Python Comment Symbol
Python comment symbol is #
# single line comment

Python Abbreviations
PEP --- Python Enhancement Proposal

PSF --- The Python Software Foundation is an organization devoted to advancing open source technology related to the Python programming language

PyPI --- Python Package Index

Python 3 Information
Python 3 was to make changes to the language primarily to remove the warts that had grown in the preceding versions.

Python 3 was not to be a complete redesign(revolution), but instead an evolution of the language.

Maintaining "full" backward compatibility, unnecessary syntax, unnecessary semantic acceptable with Python 2 were explicitly off-the-table.

Python 2 code can be translated fairly easily to Python 3, sometimes entirely mechanically by such tools as 2to3. There is also non-trivial subset of the language that will run without modification on both versions 2 and 3.

The end of life for Python 2.7 has been announced.
Python 2.7 itself is the last version of the Python 2.x line with firm plans to not release a Python 2.8.

Python 2.7 will stop receiving bug fixes and other updates in 2020.

Get your code ported over to Python 3.

Python 4 that is not going to happen any time soon so you should be fine to safely port to version 3 without worrying about a massive jump in the future.

Internet Resources
Download Python 3
https://www.python.org/downloads/
Online Python 2 Interpreter
http://repl.it/languages/Python

Online Python 3 Interpreter
http://www.tutorialspoint.com/execute_python3_online.php

Stack Overflow, this website operates on a reward system for correct answers, so people are always willing to pitch in and help out others
http://stackoverflow.com/

Linux Questions
http://www.linuxquestions.org/

What is new in Python 3.0
https://docs.python.org/3/whatsnew/3.0.html

Python Web Programming with CherryPy

Python v2.7 64-bit Web Programming with CherryPy v3.2.3 64-bit

Download and install Python v2.7.8 64-bit (Python Interpreter) from
https://www.python.org/downloads/windows/

Download and install PyScripter v2.5.3 64-bit (Python IDE) from
https://code.google.com/p/pyscripter/downloads/list

Download and install pip-1.5.6.win-amd64-py2.7.exe from
http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip

Download and install setuptools-5.8.win-amd64-py2.7.exe from
http://www.lfd.uci.edu/~gohlke/pythonlibs/#setuptools

Download and install CherryPy-3.2.3.win-amd64.exe from
https://bitbucket.org/cherrypy/cherrypy/downloads/CherryPy-3.2.3.win-amd64.exe

Download and install pywin32‑219.win‑amd64‑py2.7.exe from
http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32

Download and install simplejson-3.6.4.win-amd64-py2.7.exe from
http://www.lfd.uci.edu/~gohlke/pythonlibs/#simplejson

Add the below two paths to the Windows OS environment variables path:
C:\Python27\Scripts
C:\Python27

Open PyScripter Python IDE

Type the following in the PyScripter Python Interpreter console window to check if the correct cherrypy version has been installed:
>>> import cherrypy
>>> cherrypy.__version__
'3.2.3'
>>>

Type the following in the PyScripter File Editor window:
{
import cherrypy

class HelloWorld(object):
    def index(self):
        return "Hello, World!"
    index.exposed = True

cherrypy.quickstart(HelloWorld())
}
Click on the {Toolbar > Play button}

Open the browser and point at http://127.0.0.1:8080 to see the web page output.

Click on the {PyScripter IDE > Toolbar > Stop button}

Open the .py file at
C:\Python27\Lib\site-packages\cherrypy\tutorial\tut02_expose_methods.py
Click on the {Toolbar > Play button}

Sunday

Online Python Script Interpreter(s)

Read-Evaluate-Print Loop IT
url: http://repl.it/languages/Python
notes: file editor by clicking on the play icon, console interpreter by hitting the enter key
try:
Python 2.7.2 (default, Jul 20 2011, 02:32:18)
[GCC 4.2.1 (LLVM, Emscripten 1.5, Empythoned)] on linux2
   [n for n in range(0,10,1) if n%2==1] #odd numbers
=> [1, 3, 5, 7, 9]

Codecademy Labs
url: http://labs.codecademy.com/#
notes: file editor and console interpreter
try:
You're running Python version 2.7.2. To get started, type in the console below or the text editor to the left. Want to learn more about Python? Take Codecademy lessons!
>  print time.localtime()
time.struct_time(tm_year=2010, tm_mon=11, tm_mday=12, tm_hour=1, tm_min=22, tm_sec=33, tm_wday=4, tm_yday=333, tm_isdst=0)
# dst is the daylight savings time 
> import os
> os.getcwd()
=> '/sandbox'

Python Tutor, Line-by-line Code Visualization
url: http://pythontutor.com/visualize.html#mode=edit
notes: only file editor, you can change the drop down box value to "show only outputs" if there is any output, has Python versions 2 and 3
LEARN programming by visualizing code execution
Helps students overcome a fundamental barrier to learning programming: understanding what happens as the computer executes each line of a program's source code. Using this tool, a teacher or student can write a Python program in the Web browser and visualize what the computer is doing step-by-step as it executes the program.
try:
Write: Python 2.7 code here or load an example:
    name = raw_input('What is your name?\n')
    print 'Hi, %s.' % name
Program Output:
    What is your name?
    Name1
    Hi, Name1.

codepad is an online compiler/interpreter and a simple collaboration tool
url: http://codepad.org/
notes: file editor only, select radio button Python
try:
Paste your code below, and codepad will run it and give you a short URL you can use to share it in chat or email.
text area:
print """
What is duck typing?
  It is a term used in dynamic languages
that do not have strong typing.
  The idea is that you don't need a type
in order to invoke an existing method on an object -
if a method is defined on it, you can invoke it.
  The name comes from the phrase
"If it looks like a duck and
quacks like a duck,
it's a duck".
"""
Click on the Submit button
Output:
01
02  What is duck typing?
03    It is a term used in dynamic languages
04  that do not have strong typing.
05    The idea is that you don't need a type
06  in order to invoke an existing method on an object -
07  if a method is defined on it, you can invoke it.
08  The name comes from the phrase
09  "If it looks like a duck and
10  quacks like a duck,
11  it's a duck".
12

Wandbox, [Python] python 2.7.3
url: http://melpon.org/wandbox/
notes: file editor only, choose compiler: [Python] python 2.7.3
try:
input code:
import calendar
print calendar.month(2013, 2)
print "Display multiplication table of 13"
for i in range(1,11):
   print 13,'x',i,'=',13*i
click the button "Run (or Ctrl+Enter)"
#1
Start
   February 2013
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28


Display multiplication table of 13
13 x 1 = 13
13 x 2 = 26
13 x 3 = 39
13 x 4 = 52
13 x 5 = 65
13 x 6 = 78
13 x 7 = 91
13 x 8 = 104
13 x 9 = 117
13 x 10 = 130

0

Finish
input stdin: empty text area box
Tick two checkboxes: No Wrap, Expand

Ideone is an online compiler, IDE, and debugging tool which allows you to compile source code and execute it online in more than 60 programming languages.
url: http://ideone.com/
notes: only file editor, click run button to get the script output
Choose a programming language, enter the source code with optional input data... and you are ready to go!
try:
</> enter your source code or insert template or sample or your template:
# your code goes here
def factorial(n):
  if n == 0:
    return 1
  else:
    return n * factorial(n - 1)
print factorial(5)
Choose Python programming language from the drop-up list box
Click the "spectacles" icon for secret
Click on the link "few options" if there is any
Success
stdin:
Standard input is empty
stdout:
120

Execute Python Script Online (Python 2.7.4)
url: http://www.compileonline.com/execute_python_online.php
try:
notes: file editor only
try:
#!/usr/local/bin/python2.7
print 'a' "b" """c"""
Executing the program....
$python2.7 main.py
abc


References:
- http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html

Wednesday

How to install, run, and test VPython, the 3D graphics module for Python programming language?

Download and install Python-2.7.2 from http://www.python.org/download/. Important: Install it in C:\Python27.

Download and install VPython-Win-Py2.7-5.72 from http://vpython.org/contents/download_windows.html.

Start the VPython program with "Python 2.7 IDLE (Python GUI)" shortcut on the Start menu.

In the Python 2.7.2 shell, type the following:
>>> from visual import *
>>> sphere ()
<vis.primitives.sphere object at 0x0275EE10>
>>>

A 3D object window will pop up.

Right button drag on a mouse to rotate camera to view scene.
Left and right buttons drag up or down to zoom in or out.

Monday

PyBrain v0.3 Installation on Ubuntu Linux


Download and extract http://www.pybrain.org/files/PyBrain-0.3.zip to user directory

Download and copy http://peak.telecommunity.com/dist/ez_setup.py to the PyBrain directory

$ sudo apt-get install python-scipy
$ sudo apt-get install python-numpy
$ sudo apt-get install python-matplotlib
$ sudo apt-get install python-setuptools
$ sudo python ez_setup.py
$ sudo python setup.py install
$ python --version
Python 2.6.5
$ python
>>> import numpy
>>> numpy.__version__
'1.3.0'
>>> import scipy
>>> scipy.__version__
'0.7.0'
>>> import matplotlib
>>> matplotlib.__version__
'0.99.1.1'
>>> quit( )
// test it
PyBrain-0.3/examples/supervised/evolino$ ls -al
-rwxr-xr-x   superimposed_sine.py
PyBrain-0.3/examples/supervised/evolino$ python superimposed_sine.py
// wait for ½ hour

References:
1. http://www.pybrain.org/docs/
2. https://github.com/pybrain/pybrain/wiki/installation
3. https://github.com/pybrain/pybrain/wiki/Dependencies

Multiple Languages in Spoken Words

Lax lah. - English, Malay.   Sik Zo Mei, Chi1, Simi Lay. = Chinese1, Chinese2, Chinese3. This barang is cikai one lah. = English, Malay, Chi...