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

Tuesday, February 21, 2017

Python One Liner Wonders!

Python:
#!/usr/bin/env python
# set, list, tuple, dict, deque, heapq, OrderedDict, defaultDict, Counter

p = (4,5) # tuple packing
x, y = p
(x, y) = p # typle unpacking
entry = [ 'name', 20, 1.1, (2017, 12, 31) ]
a,b,c,date = entry # d = (2017, 12, 31)
_, x, y, _ = entry # x = 20, y = 1.1
name, *_, (*_, date) = entry # name = 'name', date = 31


s = 'string'
a,b,c,d,e,f = s # a='s', b='t', and so on
*head, tail_one = s # head = 'strin' tail_one = 'g'


# What are these?
x = set(["Postcard", "Radio", "Telegram"])
y = {"Postcard","Radio","Telegram"}
myList=[i*i for i in range(10)]
myArray=[[1,2],[3,4]]
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
   cnt[word] += 1
print(cnt)
c = Counter(a=4, b=2, c=0, d=-2)

def drop_first_last (list):
   fst, *mdl, lst = list
   return avg(mdl)


Perl:
# To get the same results... 
#

sub pairwise_sum {
   my ($arg1, $arg2) = @_;
   my (@result) = ();
   @list1 = @$arg1;
   @list2 = @$arg2;
   $len = @list1; # same as length(@list1)
   $max_index = $#list1;
   for ($i=0; $i < length(@list1); $i++) {
      push (@result, $list1[$i] + $list2[$i]);
   }
   return (\@result);
}


JavaScript:
var cars = ["Saab", "Volvo", "BMW"];
var cars = new Array("Saab", "Volvo", "BMW");
var name = cars[0];
document.getElementById("demo").innerHTML = cars[0];

// This is array
var person = ["John", "Doe", 46];
// This is object
var person = {firstName:"John", lastName:"Doe", age:46};


C++:
#include <iostream>
using namespace std;

int foo [] = {16, 2, 77, 40, 12071};
int another_foo [5] = { 16, 2, 77, 40, 12071 };

int jimmy [3][5];   // is equivalent to
int jimmy [15];     // (3 * 5 = 15) 
 
#define WIDTH 5
#define HEIGHT 3

int jimmy [HEIGHT][WIDTH];
int n,m;
int main ()
{
    for (n=0; n<HEIGHT; n++)
        for (m=0; m<WIDTH; m++) {
            jimmy[n][m]=(n+1)*(m+1);
        }
}



Wednesday, November 16, 2016

Python 102.

Stddraw

import math
import stddraw

x0 = 0.0
y0 = 0.0
x1 = 1.0
y1 = 0.0
t = math.sqrt (3.0) / 2.0
stddraw.line (x0, y0, x1, y1)
stddraw.point(0.5, t/3.0)
stddraw.setXscale(x0, x1)
stddraw.setYscale(y0, y1)
stddraw.show()

# stddraw.setCanvasSize(w, h)
# stddraw.setXxcale (x0, x1)
# stddraw.setYsclae (y0, y1)
# stddraw.setPenRadius(r)

stddraw.setXscale (0,n)
stddraw.setYscale (0,n)
for i in range (n+1)
    stddraw.line (0, n-i, i, 0)
stddraw.show()

xd = [x-r, x, x+r, x]
yd = [y, y+r, y, y-r]
stddraw.polygon(xd, yd)

# stddraw.circle(x, y, r)
# stddraw.square(x, y, r)
# stddraw.rectangle (x, y, w, h)
# stddraw.polygon(x, y)
# stddraw.text (x,y,s)
# stddraw.setPenColor(color)
# stddraw.setFontFamily(font)
# stddraw.setFontSize(size)
# stddraw.clear(color)



Tuesday, August 30, 2016

Python 101


  • Variables
  • Assignment Statements
  • Data Types and Data Structure
  • Arrays
  • Flow of Control
  • Input / Output
  • Graphics

Tips
  • // is floored division (In Python 2, '/' is the same as '//'. In Python 3, '/' is floating point division)

Example
import sys
import stdio
import math

a = int(sys.argv[1])
b = float(sys.argv[2])
c = float(sys.argv[3])

total  = a + b
diff   = a - b
prod   = a * b
quot   = a // b
rem    = a % b
exp    = a ** b

stdio.writeln(str(a) + ' // ' + str(b) + ' = ' + str(quot))
stdio.writeln(str(a) + ' %  ' + str(b) + ' = ' + str(rem))
stdio.writeln(str(a) + ' ** ' + str(b) + ' = ' + str(exp))

discriminant = b*b - 4.0*c
d = math.sqrt(discriminant)
stdio.writeln((-b + d) / 2.0)
stdio.writeln((-b - d) / 2.0)
e = int (round (d))

# % import math
# % help(math)
# math.sin(), math.cos(), math.tan() = math.sin()/math.cos()

# Python functions:
# type() - returns type
# id() - returns id
# repr() - returns string representation of an object

# other built-in functions:
# max(), min(), sum(), float(), eval(), open(), file()

# boolean/logic
(not (a < b) and not (a > b))

if x > y:
    maximum = x
else:
    maximum = y

if random.randrange(0, 2) == 0:
    stdio.writeln('Heads')
else:
    stdio.writeln('Tails')

i = 4
while i <= 10:
    stdio.writeln(str(i) + 'th Hello')
    i = i + 1

for i in range(4, 11):
    stdio.writeln(str(i) + 'th Hello')

for i in range(n+1):
    stdio.writeln(str(i) + ' ' + str(power))
    power *= 2

n = int(sys.argv[1])

for i in range(1, n+1):
    # Write the ith line.
    for j in range(1, n+1):
        # Write the jth entry in the ith line.
        if (i % j == 0) or (j % i == 0):
            stdio.write('* ')
        else:
            stdio.write(' ')
    stdio.writeln(i)

if   income <      0: rate = 0.00
elif income <   8925: rate = 0.10
elif income <  36250: rate = 0.15
elif income <  87850: rate = 0.23
elif income < 183250: rate = 0.28
elif income < 398350: rate = 0.33
elif income < 400000: rate = 0.35
else:                 rate = 0.396


Arrays and Stdarray
x = [0.30, 0.60, 0.10]
y = [0.40, 0.10, 0.50]
suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades']

total = 0.0
for i in range(n)
    total += x[i]*y[i]

a = [] # creates an empty array
for i in range(n)
    a += [0.0]

n = len(a)
for i in range(n // 2):
    temp = a[i]
    a[i] = a[n-1-i]
    a[n-1-i] = temp

total = 0.0
for v in a:
    total += v
average = total / len(a)

y = a  # array aliasing

# the following is array copying
y = []
for v in x:
    y += [v]
# array slicing
y = x[:]

# list
# numpy - to operate big array
# stdarray - create, read, write 2-d array

SUITS = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10',
         'Jack', 'Queen', 'King', 'Ace']
rank = random.randrange(0, len(RANKS))
suit = random.randrange(0, len(SUITS))
stdio.writeln(RANKS[rank] + ' of ' + SUITS[suit])

deck = []
for rank in RANKS:
    for suit in SUITS:
        card = rank + ' of ' + suit
        deck += [card]

a = [[18, 19, 20], [21, 22, 23]]

# rectangular array
a = []
for i in range(m):
    row = [0.0] * n
    a += [row]
for i in range(m):
    for j in range(n):
        stdio.write(a[i][j])
        stdio.write(' ')
    stdio.writeln()
# same as
for row in a:
    for v in row:
        stdio.write(v)
        stdio.write(' ')
    stdio.writeln()

# matrix operation
c = stdarray.create2D(n, n, 0.0)
for i in range(n):
    for j in range(n):
        c[i][j] = a[i][j] + b[i][j]

c = stdarray.create2D(n, n, 0.0)
for i in range(n):
    for j in range(n):
        # Compute the dot product of row i and column j
        for k in range(n):
            c[i][j] += a[i][k] * b[k][j]

# ragged arrays
for i in range(len(a)):
    for j in range(len(a[i])):
        stdio.write(a[i][j])
        stdio.write(' ')
    stdio.writeln()

for row in a:
    for v in row:
        stdio.write(v)
        stdio.write(' ')
    stdio.writeln()


Stdio

  • stdio.isEmpty()
  • stdio.readInt(), stdio.readFloat(), stdio.readBool(), stdio.readString()
  • stdio.hasNextLine()
  • stdio.readLine()
  • stdio.readAll(), stdio.readAllInts(), stdio.readAllFloats(), stdio.readAllBools()
  • stdio.readAllStrings(), stdio.readAllLines()

# random sequence
import random
import sys
import stdio

n = int(sys.argv[1])
for i in range(n):
    stdio.writeln(random.random())

# standard write/output functions
# stdio.write stdio.writeln stdio.writef 
stdio.writef('pi is approximately %.2f\n', math.pi)
stdio.writef('The square root of %.1f is %.6f', c, t)

format = '%3s  $%6.2f   $%7.2f   $%5.2f\n'
stdio.writef(format, month[i], pay, balance, interest)

# standard read/input functions
import sys
import stdio
n = int(sys.argv[1])
total = 0
for i in range(n):
    total += stdio.readInt()
stdio.writeln('Sum is ' + str(total))


Useful Links