Friday, August 26, 2016

Square spiral - drawing with 3D effect (turtle graphics)

By Vasudev Ram

I was doing some work with Python turtle graphics for a project, and came up with this simple program that draws a square-ish spiral in multiple colors. It has a bit of a 3D effect. You can see it as a pyramid with you above, the levels ascending toward you, or you can see it (again from above) as a well with steps, going downward.

Here is the code and a screenshot of its output:
'''
square_spiral.py
A program that draws a "square spiral".
Author: Vasudev Ram
Copyright 2016 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: http://jugad2.blogspot.com
Product store: https://gumroad.com/vasudevram
'''

import turtle
t = turtle

colors = ['blue', 'green', 'yellow', 'orange', 'red']

def pause():
    _ = raw_input("Press Enter to exit:")

def spiral(t, step, step_incr, angle):
    color_ind = 0
    colors_len = len(colors)
    t.pencolor(colors[color_ind])
    while True:
        t.forward(step)
        step = step + step_incr
        if step > 500:
            break
        t.right(angle)
        color_ind = (color_ind + 1) % colors_len
        t.pencolor(colors[color_ind])

    t.hideturtle()
    pause()

t.speed(0)
spiral(t, 20, 5, 90.2)


- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

My Python posts     Subscribe to my blog by email

My ActiveState recipes



Tuesday, August 16, 2016

Count line frequencies with OrderedDict in Python

By Vasudev Ram


Python programs to count the frequencies of words in a string or from a file are used as common examples. They are often done using dicts. Here is a small program that counts the frequencies of lines in its input. There are some uses for this functionality. I will show those, and also compare and contrast this program with other tools, later.

The program uses an OrderedDict from the collections module of the Python standard library.

The program could also be written using either a regular dict or a defaultdict (also from the collections module), or a collections.Counter, with slightly different code in each of those cases.
from __future__ import print_function
"""
linefreq.py
A program to find the frequencies of input lines.
Author: Vasudev Ram
Copyright 2016 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: http://jugad2.blogspot.com
Product store: http://gumroad.com/vasudevram
"""
import sys
from collections import OrderedDict

def linefreq(in_fil):
    counts = OrderedDict()
    for line in in_fil:
        counts[line] = counts.get(line, 0) + 1
    print("Freq".rjust(8) + ": Line")
    for line, freq in counts.items():
        print(str(freq).rjust(8) + ": " + line, end="")
    print('-' * (10 + max(map(len, counts))))
    for line, freq in reversed(counts.items()):
        print(str(freq).rjust(8) + ": " + line, end="")

def main():
    sa, lsa = sys.argv, len(sys.argv)
    if lsa == 1:
        linefreq(sys.stdin)
    elif lsa == 2:
        with open(sa[1], "r") as in_fil:
            linefreq(in_fil)
    else:
        print("Only one filename argument supported.")

if __name__ == '__main__':
    main()
I ran it on this input file:
line 1
line 2
line 2
line 3
line 3
line 3
line 4
line 4
line 4
line 4
where "line 1" occurs once, "line 2" occurs twice, etc., with this command:
$ python linefreq.py infile1.txt
and got this output:
Freq: Line
       1: line 1
       2: line 2
       3: line 3
       4: line 4
-----------------
       4: line 4
       3: line 3
       2: line 2
       1: line 1
The reversed lines are output just to show that it is possible to use reversed() on an OrderedDict, unlike on a dict.
I also got the same output, as expected, when I ran this form of the command:
$ cat infile1.txt | python linefreq.py
This line:
    print('-' * (10 + max(map(len, counts))))
is used to print a row of dashes as long as the longest output line from above it.
The length of the longest line can also be computed inline in the first for loop.


- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

My Python posts     Subscribe to my blog by email

My ActiveState recipes



Test post - ignore.

By Vasudev Ram

Test post - ignore.

- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

My Python posts     Subscribe to my blog by email

My ActiveState recipes



Monday, August 8, 2016

How to kill yourself in Python

By Vasudev Ram

Here's a simple Python program that shows how the os.kill function from Python's standard library, along with the os.getpid function and the signal module [1], can be used to terminate the current program - the one it is called from:
'''
Program: test_self_kill.py
A program to show that the os.kill function 
can be used to terminate the current program.
Author: Vasudev Ram
Copyright 2016 Vasudev Ram
https://vasudevram.github.io
http://jugad2.blogspot.com
https://gumroad.com/vasudevram
'''

from __future__ import print_function
import sys, os, signal

print("Python version:", sys.version)
print("This line will be printed.")
os.kill(os.getpid(), signal.SIGTERM)
print("If os.kill works, this line will not be printed.")
Program output when run in Python 2.7:
$ python test_self_kill.py
Python version: 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:40:30) [MSC v.1500
 64 bit (AMD64)]
This line will be printed.
Program output when run in Python 3.6:
$ python test_self_kill.py
Python version: 3.6.0a2 (v3.6.0a2:378893423552, Jun 14 2016, 01:21:40) [MSC v.19
00 64 bit (AMD64)]
This line will be printed.
As you can see, the second call to the print function does not run, because the program terminates itself.
You can read about Unix signals here and here.

- Vasudev Ram - Online Python training and consulting



My Python posts     Subscribe to my blog by email

My ActiveState recipes



Friday, August 5, 2016

The D Language Playground site

By Vasudev Ram


The D language playground site:


is a web site (created somewhat recently, IIRC), where you can write or paste in a chunk of D code into a text box, click Run, and it will run it on their server, and send back the results to be displayed. It also has a tour of the language, and you can go from one example to another, and just run, or modify and run, each of them. So the same site serves both as an online sandbox to experiment with D language snippets, and as an interactive tutorial for D. In both these ways it is similar to the Go language playground/tour site. Either or both are worth checking out, if you are interested in those languages.

- Vasudev Ram - Online Python training and consulting




My Python posts     Subscribe to my blog by email

My ActiveState recipes