Chapter 10: Character strings

Program 10.1, Page number: 197

In [1]:
import sys

def concat(result,str1,n1,str2,n2):                 #Calculations
        
        #copy str1 to result
        for i in range(0,n1):
                result[i]=str1[i]
        
        #copy str2 to result        
        for j in range(0,n2):
                result[n1+j]=str2[j]


def main():

        #List Declaration
        s1 = [ 'T', 'e', 's', 't', ' ']
        s2 = [ 'w', 'o', 'r', 'k', 's', '.' ]
        s3=[0]*11

        concat(s3,s1,5,s2,6)                        #Fucntion call

        for i in range(0,11):                       #Result
                sys.stdout.write("{0}".format(s3[i]))

        sys.stdout.write("\n")


if __name__=='__main__':
        main()
Test works.

Program 10.2, Page number: 199

In [2]:
def stringLength(string):
        count = 0
        while(string[count]!='\0'):                  #Calculation
                count+=1
        return count

def main():

        #List Declaration
        word1 = [ 'a', 's', 't', 'e', 'r', '\0' ]
        word2 = [ 'a', 't', '\0' ]
        word3 = [ 'a', 'w', 'e', '\0' ]

        #Result
        print("{0}  {1}  {2}\n".format(stringLength (word1),stringLength (word2),stringLength (word3)))


if __name__=='__main__':
        main()
5  2  3

Program 10.3, Page number: 202

In [3]:
def concat(result,str1,str2):                            #Calculations
        
        #copy str1 to result
        for i in str1:
                result.append(i)
        
        #copy str2 to result        
        for j in str2:
                result.append(j)
                

def main():

        #String Declaration
        s1 = "Test "
        s2 = "works."
        s3=[]

        concat(s3,s1,s2)                                 #Fucntion call
        print(''.join(s3))                               #Result


if __name__=='__main__':
        main()
Test works.

Program 10.4, Page number: 204

In [4]:
def equalStrings(s1,s2):
        
        #Calculation
        if(s1==s2):
                areEqual=True
        else:
                areEqual=False
        return areEqual



def main():

        #String Declaration
        stra = "string compare test";
        strb = "string";

        #Result
        print("{0}".format(equalStrings (stra, strb)))
        print("{0}".format(equalStrings (stra, stra)))
        print("{0}".format(equalStrings (strb, "string")))


if __name__=='__main__':
        main()
False
True
True

Program 10.5, Page number: 207

In [1]:
def main():
        print("Enter Text:\n")

        #User Input
        s1,s2,s3=map(str,"System expansion bus".split())
        #s1,s2,s3=map(str,raw_input().split())
        
        
        #Result
        print("\ns1={0}\ns2={1}\ns3={2}\n".format(s1,s2,s3))


if __name__=='__main__':
        main()
Enter Text:


s1=System
s2=expansion
s3=bus

Program 10.6, Page number: 209

In [2]:
def main():

        #List declaration
        line=['sample text']
        for i in range(0,3):
                readLine(line)                         #Function call
                print("{0}\n".format(''.join(line)))   #Result


def readLine(line):
        
        line.pop()
        line.append("This is a sample line of text"+" ")
        #line.append(raw_input()+" ")


if __name__=='__main__':
        main()
This is a sample line of text 

This is a sample line of text 

This is a sample line of text 

Program 10.7, Page number: 211

In [6]:
def alphabetic(c):
        if ( (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') ):
                return True
        else:
                return False


def countWords(string):
        
        #Variable Declaration
        wordCount=0
        lookingForWord=True
        
        #Calculations
        for i in string:
                if(alphabetic(i)):
                        if(lookingForWord):
                                wordCount+=1
                                lookingForWord=False
                else:
                        lookingForWord=True
        return wordCount


def main():

        #String Declaration
        text1 = "Well, here goes."
        text2 = "And here we go... again."
        
        #Result
        print("{0} - words = {1}\n".format(text1,countWords(text1)))
        print("{0} - words = {1}\n".format(text2,countWords(text2)))


if __name__=='__main__':
        main()
Well, here goes. - words = 3

And here we go... again. - words = 5

Program 10.8, Page number: 214

In [3]:
def readLine(line):
        
        line.pop()
        line.append("This is a dummy text to replace raw_input()"+" ")
        #line.append(raw_input()+" ")


def alphabetic(c):
        if ( (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') ):
                return True
        else:
                return False


def countWords(string):
        
        #Variable Declaration
        wordCount=0
        lookingForWord=True
        
        #Calculations
        for i in string:
                if(alphabetic(i)):
                        if(lookingForWord):
                                wordCount+=1
                                lookingForWord=False
                else:
                        lookingForWord=True
        return wordCount



def main():
        #Variable Declaration
        totalWords=0
        endOfText=False
        text=['sample']

        print("Type in your text.\n")
        print("When you are done, press 'RETURN'.\n\n")
       
        readLine (text)
        
        #Increment Counter
        totalWords += countWords(''.join(text))
        
        #Result
        print("\nThere are {0} words in the above text.\n".format(totalWords))


if __name__=='__main__':
        main()
Type in your text.

When you are done, press 'RETURN'.



There are 9 words in the above text.

Program 10.9, Page number: 220

In [7]:
class entry:
        def __init__(self,w,d):
                self.word=w
                self.definition=d


def equalStrings(str1,str2):
        if(str1==str2):
                return True
        else:
                return False

def lookup(dictionary,search,entries):
        for i in range(0,entries):
                if ( equalStrings(search, dictionary[i].word) ):
                        return i;
        return -1;

def main():

        entries=10
        global entry
        dictionary=[]
        
        dictionary.append(entry("aardvark","a burrowing African mammal"))
        dictionary.append(entry("abyss","a bottomless pit"))
        dictionary.append(entry("acumen","mentally sharp keen"))
        dictionary.append(entry("addle","to become confused"))
        dictionary.append(entry("aerie","a high nest"))
        dictionary.append(entry("affix","to append; attach"))
        dictionary.append(entry("agar","a jelly made from seaweed"))
        dictionary.append(entry("ahoy","nautical call of greeting"))
        dictionary.append(entry("aigrette","an ornamental cluster of feathers"))
        dictionary.append(entry("ajar","partially opened"))


        print("Enter word:")
        word='ajar'                            #word=raw_input()
        entry=lookup(dictionary,word,entries)

        #Result
        if(entry!=-1):
                print("{0}".format(dictionary[entry].definition))
        else:
                print("Sorry, the word {0} is not in my dictionary.\n".format(word))


if __name__=='__main__':
        main()
Enter word:
partially opened

Program 10.10, Page number: 224

In [8]:
class entry:
        def __init__(self,w,d):                 #Class constructor
                self.word=w
                self.definition=d


def compareStrings(s1,s2):

        #Calculations
        if( s1 < s2 ):
                answer = -1;
        elif( s1 == s2 ):
                answer = 0;
        else:
                answer=1

        return answer



def lookup(dictionary,search,entries):
        
        #Variable Declaration
        low=0
        high=entries-1

        #Calculations
        while(low<=high):
                mid=(low+high)/2
                result=compareStrings(dictionary[mid].word,search)

                if(result==-1):
                        low=mid+1
                elif(result==1):
                        high=mid-1
                else:
                        return mid

        return -1


def main():

        #Variable Declaration
        entries=10
        global entry
        dictionary=[]
        
        dictionary.append(entry("aardvark","a burrowing African mammal"))
        dictionary.append(entry("abyss","a bottomless pit"))
        dictionary.append(entry("acumen","mentally sharp keen"))
        dictionary.append(entry("addle","to become confused"))
        dictionary.append(entry("aerie","a high nest"))
        dictionary.append(entry("affix","to append; attach"))
        dictionary.append(entry("agar","a jelly made from seaweed"))
        dictionary.append(entry("ahoy","nautical call of greeting"))
        dictionary.append(entry("aigrette","an ornamental cluster of feathers"))
        dictionary.append(entry("ajar","partially opened"))

        print("Enter word:")
        word='ahoy'                             #word=raw_input()
        entry=lookup(dictionary,word,entries)

        #Result
        if(entry!=-1):
                print("{0}".format(dictionary[entry].definition))
        else:
                print("Sorry, the word {0} is not in my dictionary.\n".format(word))


if __name__=='__main__':
        main()
Enter word:
nautical call of greeting

Program 10.11, Page number: 229

In [9]:
def strToInt(string):
        
        return int(string)

def main():

        #Result
        print("{0}\n".format(strToInt("245")))
        print("{0}\n".format(strToInt("100") + 25))
        print("{0}\n".format(strToInt("13")))


if __name__=='__main__':
        main()
245

125

13