Logical expressions, modules

Program the xor function corresponding to the following table

A

B

A xor B

False

False

False

False

True

True

True

False

True

True

True

False

Use the operations and, or, not and brackets ().

Help: use the following code logic.py and add the term in ... in line 5

# Module logic.py

def xor(A,B):
    """Returns the logical exclusive or of A and B"""
    C=((A or B ) and   (not(A and B)))
    return C

if __name__=='__main__': # if the module is not imported
    # but started with run, the following lines will be executed

    K=((False,False),(False,True),(True,False),(True,True))
    print 'A\tB\tA xor B'
    for k in K:
        A,B=k[0],k[1]
        print A,'\t',B,'\t',xor(A,B)

Open a file with an editor of your choice (I recommend xemacs or nedit) and save the file as logic.py. Use tabs not blanks.

Start ipython and run your program

In [1]: from logic import xor
In [2]: xor(False,False)
Out[2]: False
In [3]: xor(True,False)
Out[3]: True
In [4]: run xor
A B A xor B
False False False
False True True
True False True
True True False
In [5]: help(xor)
In [1]: from scipy import logical_xor
In [2]: logical_xor(True,True)
Out[2]: False

/Solution_XOR

Dictionaries

Program a date function that returns the number of the month (integer) for a given month (string).

Use the string methods .upper() or .lower() to account for capitalization.

/Solution_date

Range

What is the corresponding range() expression for the following lists?

[1, 3, 5, 7, 9]
[5, 8, 11, 14, 17]
[19, 18, 17, 16, 15, 14, 13]

Solution

range(1,10,2)
b=range(5,18,3)
c=range(19,12,-1)

Lists and Strings

Write a program that reads in a textfile and sorts its words in order of the frequency of occurence.

Help: read in a textfile in a string

s=file(’test.txt’).read()

The method .split(arg) cuts the string in a list. The method .count(arg) calculates the frequency of occurence. The method .sort() sorts (in place).

/Solution

Modules

Which subpackages are included in the scipy module?

/Solution_modules

LehreWiki: Python/Exercise1 (last edited 2008-11-03 15:22:05 by DanielKlocke)