Electric Python

Simple Fibonacci Number Class

chandramde | 19 June, 2010 14:53

This simple class of Fibonacci number generator is offering a faster function. Instead of using an iteration, function uses a simple addition operator. Enjoy...

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
29
30
31
32
33
34
35
#************************************************************
# Fibonacci Class
# Offering faster and stack friendly non-iterative function
#
# Chandra MDE - chandramde@telkom.net
# Electric Python
#************************************************************
 
class Fibonacci:
    def __init__(self):
        self.firstten = (1,1,2,3,5,8,13,21,34,55)
 
    def fib(self, n):
        if n<=10:
            return self.firstten[n-1]
        else:
            self.lfib = list(self.firstten)
            for i in range(10, n):
                self.lfib.append(self.lfib[-2]+self.lfib[-1])
            return self.lfib[-1]
 
    def fiblist(self, n):
        if n<10:
            return self.firstten[:n]
        elif n==10:
            return self.firstten
        else:
            self.fib(n)
            return self.lfib
 
# Example
F = Fibonacci()
print "First ten of Fibonacci number:", F.firstten
print "The twentieth of Fibonacci number:", F.fib(50)
print "The first twenty of Fibonacci:", F.fiblist(15)

The result:

First ten of Fibonacci number: (1, 1, 2, 3, 5, 8, 13, 21, 34, 55)
The twentieth of Fibonacci number: 12586269025
The first twenty of Fibonacci: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

Simple Logic Gates Truth-Table Class

chandramde | 15 June, 2010 15:24

As a newbie, I'm getting deeper in love with Python. I like Basic, I like Pascal, and I like C. But after a few weeks with Python, now I love Python. Still far from being an expert though, but  it doesn't matter. If you know what I'm talking about, I'm sure you feel the passion inside of my programs. Hahaha... :D

The TruthTable class will generate the truth-table of the selected logic gate with n inputs. I think it's good for programming practice. Let's take a look...

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#****************************************************
# Logic Gates Truth Table Generator for n logic input
# Gates: AND, OR, NAND, NOR
#
# Chandra MDE - chandramde@telkom.net
# Electric Python
#****************************************************
 
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Logic = {'0': False, '1': True}
Logix = {False: '0', True: '1'}
 
# Function AND with tuple input
def f_and(inputs):
    l = Logic[inputs[0]]
    for i in range(1, len(inputs)):
        l = l and Logic[inputs[i]]
    return l
 
# Function OR with tuple input
def f_or(inputs):
    l = Logic[inputs[0]]
    for i in range(1, len(inputs)):
        l = l or Logic[inputs[i]]
    return l
 
# Function NAND with tuple input
def f_nand(inputs):
    return not f_and(inputs)
 
# Function NOR with tuple input
def f_nor(inputs):
    return not f_or(inputs)
 
# Map gate's name with it's correspondence function
Gates = {'AND': f_and, 'OR': f_or, 'NAND': f_nand, 'NOR': f_nor}
 
# Function integer-to-binary-string
def int2bin(intvalue, digit):
    binstr = ''; val = intvalue
    while val>0:
        if val % 2 == 0:
            binstr = '0' + binstr
        else:
            binstr = '1' + binstr
        val = val >> 1
    if len(binstr)<digit:
        binstr = '0'*(digit-len(binstr)) + binstr
    return binstr
 
# Simple Truth-Table Class
class TruthTable:
    "Generate a truth table for a logic gate with n inputs"
    def __init__(self, gate, numofinputs):
        if numofinputs<2:
            numofinputs = 2
        self.gate = gate.upper()
        self.numberofinputs = numofinputs
        self.logicoutput = []
        self.labels = [LETTERS[i] for i in range(self.numberofinputs)]
        self.labels.append('Y')
        self.logicinput = [tuple(int2bin(i, self.numberofinputs)) for i in range(2**self.numberofinputs)]
        for i in self.logicinput:
            l = Gates[self.gate](i) # This is Python!
            self.logicoutput.append(l)
 
    def display(self):
        print
        print self.gate, "Gate with %i-Inputs" % self.numberofinputs + " Truth Table"
        print len(self.labels)*6*'-'
        for i in self.labels:
            print "%4s" % i,
        print
        print len(self.labels)*6*'-'
        x = 0
        for i in self.logicinput:
            for j in i:
                print "%4s" % j,
            print "%4s" % Logix[self.logicoutput[x]]
            x += 1
        print len(self.labels)*6*'-'
        print
 
 
# Example
T1 = TruthTable('or', 3)
T2 = TruthTable('NAnd', 2)
T1.display()
T2.display()

The result is:

OR Gate with 3-Inputs Truth Table
------------------------
   A    B    C    Y
------------------------
   0    0    0    0
   0    0    1    1
   0    1    0    1
   0    1    1    1
   1    0    0    1
   1    0    1    1
   1    1    0    1
   1    1    1    1
------------------------


NAND Gate with 2-Inputs Truth Table
------------------
   A    B    Y
------------------
   0    0    1
   0    1    1
   1    0    1
   1    1    0
------------------

Integer To Binary-String Function

chandramde | 14 June, 2010 17:26

Converting an integer value into binary-string is good for programming practice. So, here is my version of this kind of function. Hopefully, someone will show me a better one.

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
#***********************************
# Function int2bin(intvalue, digit)
#
# Chandra MDE - chandramde@telkom.net
# Electric Python
#***********************************
 
def int2bin(intvalue, digit):
    "Convert an integer into binary string"
    binstr = ''; val = intvalue
    while val>0:
        if val % 2 == 0:
            binstr = '0' + binstr
        else:
            binstr = '1' + binstr
        val = val >> 1
    if len(binstr)<digit:
        binstr = '0'*(digit-len(binstr)) + binstr
    return binstr
 
 
# Example                   Result
print int2bin(7, 8)         # 00000111
i = 2365
print int2bin(i, 16)        # 0000100100111101
print int2bin(i, 4)         # 100100111101

If the value of 'digit' parameter entered in the function is less than the length of string produced by the function, the function ignored this parameter and return the string without leading-zero.

Calculate R Series And Parallel (2)

chandramde | 10 June, 2010 18:34

Here's another example of how to calculate R Series and Parallel with list as parameter. This program also show the usage of reduce function (see RParallel function).

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
29
30
31
32
33
34
35
#****************************************
# Calculate R Series and Parallel - 2
#
# Chandra MDE - chandramde@telkom.net
# Electric Python
#****************************************
 
from __future__ import division
 
def RSeries(RLIST):
    RTot = 0
    for i in RLIST:
        RTot += float(i)
    return RTot
 
def RParallel(RLIST):
    def RPar(R1, R2):
        if float(R1)==0:
            return float(R2)
        if float(R2)==0:
            return float(R1)
        return (float(R1)*float(R2))/(float(R1)+float(R2))
    return reduce(RPar, RLIST)
 
 
print "Calculate R in Series"
print "Enter R Values split with space"
RValues = raw_input("Input R values: ").split()
 
RP = RS = 0
 
RS = RSeries(RValues)
RP = RParallel(RValues)
 
print "RS = %.3f, RP = %.3f" % (RS, RP)

Calculate R Series and Parallel

chandramde | 10 June, 2010 16:34

Here is a simple program to calculate R Series and Parallel.

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
29
30
31
#****************************************
# Calculate R Series and Parallel
#
# Chandra MDE - chandramde@telkom.net
# Electric Python
#****************************************
 
from __future__ import division
 
def RSeries(R1, R2):
    return R1 + R2
 
def RParallel(R1, R2):
    if R1==0:
        return R2
    if R2==0:
        return R1
    return (R1*R2/(R1+R2))
 
 
print "Calculate R in Series"
print "Enter R Values split with space"
RValues = raw_input("Input R values: ").split()
 
RP = RS = 0
 
for i in RValues:
    RS = RSeries(RS, float(i))
    RP = RParallel(RP, float(i))
 
print "RS = %.3f, RP = %.3f" % (RS, RP)

 

1 2  Next»
 
Accessible and Valid XHTML 1.0 Strict and CSS
Powered by LT - Design by BalearWeb