0% found this document useful (0 votes)
52 views

Unit 3

The document discusses various string manipulation techniques in Python including: 1) Strings can be indexed, sliced, and their length retrieved using len(). 2) Strings are immutable but can be manipulated using slicing to create new strings. 3) For loops can iterate over strings and range can generate numbers to iterate over. 4) Strings can be compared using relational operators and searched with in and not in.

Uploaded by

Sudarshan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Unit 3

The document discusses various string manipulation techniques in Python including: 1) Strings can be indexed, sliced, and their length retrieved using len(). 2) Strings are immutable but can be manipulated using slicing to create new strings. 3) For loops can iterate over strings and range can generate numbers to iterate over. 4) Strings can be compared using relational operators and searched with in and not in.

Uploaded by

Sudarshan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Unit 3

§ strings
§ branching –if/elif/else
§ while loops
§ for loops

2
§ string manipulation
§ guess and check algorithms
§ approximate solutions
§ bisection method

3
§ think of as a sequence of case sensitive characters.
§ can compare strings with ==, >, < etc.
§ len()is
a function used to retrieve the length of the string in the
parentheses
§s = "abc"
§ len(s) >>> evaluates to 3

4
§ square brackets used to perform indexing into a string to get the value at a certain
index/position
§ s = "abc”

§ index: 0 1 2 indexing always starts at 0


§ index: -3 -2 -1 last element always at index -1

§ s[0] >>evaluates to "a"


§ s[1] >> evaluates to "b"
§ s[2] >> evaluates to "c"
§ s[3] >> trying to index out of bounds, error
§ s[-1] >> evaluates to "c"
§ s[-2] >> evaluates to "b"
§ s[-3] >> evaluates to "a"

5
§ can slice strings using [start : stop : step]
§ if give two numbers, [start : stop], step=1. by default
§ you can also omit numbers and leave just colons
§ s = "abcdefgh”
§ s[3:6] >> evaluates to "def", same as s[3:6:1]
§ s[3:6:2] >> evaluates to "df"
§ s[::] >> evaluates to "abcdefgh", same as s[0: len(s): 1]
§ s[::-1] >>evaluates to "hgfedbca", same as s[-1:-(len(s)+1):-1]
§ s[4:1:-2] >> evaluates to "ec"

6
§ strings are “immutable” – cannot be modified
§s = "hello"
§ s[0] = ‘y’ >>>. gives an error
§s = 'y'+s[1:len(s)] >>> is allowed, s bound to new object
"hello"

"yello"

7
§ For loops have a loop variable that iterates over a set of values
§ for var in range(4): >>>> Var iterates over values 0,1,2,3
<expressions>>>> expressions inside loop executed with each value for var
for var in range(4,6): >>> var iterates over values 4,5
<expressions>
§ range is
a way to iterate over numbers, but a for loop variable can iterate
over any set of values, not just numbers!

8
§ these two code snippets do the same thing
§ bottom one is more “pythonic”

s = "aiufgh"
for index in range(len(s)):
if s[index] =='i' or s[index] == 'u':
print("There is an I or u")

for char in s:
if char == 'i' or char == 'u':
print("There is an I or u")

9
an_letters = "aefhilmnorsxAEFHILMNORSX"
word = input("Enter a word: ") an_letters = "aefhilmnorsxAEFHILMNORSX"
i=0 word = input("Enter a word: ")
a=0 i=0
an=0 a=0
while i < len(word): an=0
char = word[i] for char in word :
if char in an_letters: if char in an_letters:
print(" an " + char + "! " ) print(" an " + char + "! " )
an+=1 an+=1
else: else:
print(" a " + char + "! " ) print(" a " + char + "! " )
a+=1 a+=1
i += 1 print ("no of 'an' letters=",an)
print ("no of 'an' letters=",an) print ("no of 'a' letters=",a)
print ("no of 'a' letters=",a)

10
s1 = "mit u rock"
s2 = "i rule mit"
common=0
if len(s1) == len(s2):
for char1 in s1:
for char2 in s2:
if char1 == char2:
print(char1)
common+=1
break
print ("count of common letters",common)

11
§ the process below also called exhaustive enumeration
§ given a problem...
§ you are able to guess a value for solution
§ you are able to check if the solution is correct
§ keep guessing until find solution or guessed all values

12
cube = int(input("please enter the no"))

for guess in range(abs(cube)+1):


if guess**3 >= abs(cube):
break

if guess**3 != abs(cube):
print(cube, 'is not a perfect cube')
else:
if cube < 0:
guess = -guess
print("Cube root of "+str(cube)+" is "+str(guess))

13
§ good enough solution
§ start with a guess and increment by some small value
§ Keep guessing if|guess3-cube| >= epsilon for some small epsilon
§ decreasing increment size >>> slower program
§ increasing epsilon >>> less accurate answer

14
cube = int(input("please enter the no"))
epsilon = 0.001
guess = 0.0
increment = 0.0001
num_guesses = 0
while abs(guess**3 - cube) >= epsilon and guess <= cube :
guess += increment
num_guesses += 1
print('num_guesses =', num_guesses)
if abs(guess**3 - cube) >= epsilon:
print('Failed on cube root of', cube)
else:
print(guess, 'is close to the cube root of', cube)

15
§ half interval each iteration
§ new guess is halfway in between
§ to illustrate, let’s play a game!

GUESS

GUESS

GUESS 16
cube = int(input("please enter the no"))
epsilon = 0.01
num_guesses = 0
low = 0
high = cube
guess = (high + low)/2.0
while abs(guess**3 - cube) >= epsilon:
if guess**3 < cube :
low = guess
else:
high = guess
guess = (high + low)/2.0
num_guesses += 1
print ('num_guesses =', num_guesses)
print (guess, 'is close to the cube root of', cube)

17
§ search space
§ first guess: N/2 ◦
§ second guess: N/4 ◦
§ kth guess: N/2k

§ guess converges on the order of log2N steps


§ bisection search works when value of function varies monotonically with
input.
§ code as shown only works for positive cubes > 1 why?
§ HomeWork
§ modify to work with negative cubes!
§ modify to work with x < 1!
§ Apply it for Cubic equation ax^3 + bx^2 + cx + d = 0

18

You might also like