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


1 comment: