Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming Training Main Points: - Working with strings.

Similar presentations


Presentation on theme: "Programming Training Main Points: - Working with strings."— Presentation transcript:

1 Programming Training Main Points: - Working with strings.
- Working with Files - Problem Solving.

2 Arrays / Lists Traversal
ANY COMPUTATION WITH LIST MUST USE THE LOOP FOR. Ways to traverse the list 1) Traverse the list as iterator 2) Traverse the list elements for elem in l : # process elem # endfor n = len(l) for i in range(n) : # process the element l[i] # endfor

3 Input a List n = int(input(‘’n=)) l = [] for i in range(n) :
Suppose that we need a list with n int elements. - read the number of elements in the list - read n elements using a for loop This scheme will work for any programming language. n = int(input(‘’n=)) l = [] for i in range(n) : elem = int(input()) l.append(elem) # endfor

4 Input a List l = input(‘type elements: ’).split()
Suppose that we need a list with int elements. A Python approach: - read some elements and make an array of strings from them - convert them to a sequence of int elements - make a list from this sequence. l = input(‘type elements: ’).split() l = list(map(int, l))

5 Print a List n = len(l) for i in range(n) : print(l[i], end = ‘ ‘)
Suppose that we have a list with n int elements. - use a for loop to print each element This scheme will work for any programming language. print(l[i], end = ‘ ‘) printing on the same line. print(l)  the whole list is printed between [] n = len(l) for i in range(n) : print(l[i], end = ‘ ‘) # endfor

6 Working with Python Files
File definition? - external storage of some data. - sequence of characters or bytes stored externally. - the simplest way to persistently store data. - a file is identified by a name and an extension. Types of files: - text files with content as sequence of characters e.g. input.txt, program.py, etc - byte files with content as sequence of bytes e.g. python.exe, etc Operation with files: - reading from a file -writing to a file or appending to a file

7 Working with Python Files
How to work with Files in Python? - open the file for the needed operation. f = open(’filename.txt’, ‘how’) filename.txt  the name of the file how is a combination of r/w/a, t/b - do the reading and writing as it is required f.read()  read the whole file f.readline() read a single line as a string + \n f.write(str)  write a str to a file - close the file. f.close()

8 Working with Python Files
Example: Read one integer from a file ‘input.txt’ f = open(‘input.txt’, ‘rt’) a = int(f.readline().strip()) f.close() 2) Read three integers from a single line of the file ‘input.txt’ a, b, c = map(int, f.readline().strip().split(‘ ‘))

9 Working with Python Files
Example: 3) Read an array from the file. The file contains the number of elements on the first line and then the array elements on each line. f = open(‘input.txt’, ‘rt’) n = int(f.readline().strip()) array = [] for I in range(n): elem = int(f.readline().strip()) array.append(elem) f.close()

10 Working with Python Files
Example: 4) Writing one integer to a file ‘output.txt’ f = open(‘output.txt’, ‘wt’) f.write(str(a)) f.close() 5) Write three integers to a file ‘output.txt’ on the same line f.write(str(a) + ‘ ‘+ str(b) +’ ‘ + str(c)) f.write(“%d %d %d” %(a, b, c))

11 Working with Python Files
Example: 6) Write n elements of a list to a file ‘output.txt’ each element of a different line f = open(‘output.txt’, ‘wt’) for i in range(n): f.write(str(array[i])+’\n’) f.close()

12 Working with Python String
General facts about strings: str  datatype for Python strings. A string is a sequence of characters between “”. input() returns string Operations on strings str1 + str2  new strings which concatenates two strings str1 * nr  new string which clones str1 nr times str1 in str2  test if str1 is in str2 Indexing / slicing str is a string with n characters str1[i]  String formed only with character I str1[i1:i2]  Slice of str with all the characters between i1 and i2-1. str1[i1:]  Slice with all the characters from i1

13 Working with Python String
Functions on strings  MUST IMPORT string len(str1)  the length of str1 or number of characters. str1 in str2  finds whether str1 is in str2. str2.count(str1)  counts how many times str1 occurs in str2. str1.split(“ch”)  splits str1 in strings on the ch charter str1.joint(list)  makes a new string by 1) joining all list elements 2) separating them using str1 str1.upper() or str1.lower() or str1.dropcase()  to change the letters case

14 Working with Python String
Functions on strings  MUST IMPORT string string.ascii_letters string.ascii_lowercase string.ascii_uppercase string.punctuation string.digits are default strings with all mention elements.

15 Invert a String Inverting a string requires to form a new string with the letters of the first one in reverse. Algorithmic approach: Start from an empty string. Traverse the input string in reverse Append the current letter to the new string Python approach rev_str = str1[::-1]

16 Invert a Sentence Inverting a sentence requires you to invert the order of words in a sentence but preserving the words. Example: “Sabin is teaching the MPT class”  ‘class MPT the teaching is Sabin’ Some questions: 1) how we can acquire the words?  split the string 2) traverse the words in reverse  no problem 3) deal with the ‘.’ if any  just remove it from there e.g. str.remove(‘.’, ‘’) Steps to solve the problem: 1) input the sentence and remove the ‘.’ if there. 2) split the sentence in words. 3) traverse the word list in reverse and add the current word to the new string. 4) add the ‘.’

17 Invert a Sentence Functions to work with: str2.split()
str2.replace(str1, str2) str1 + str2 Better Python solution: ' '.join(str1.replace('.', '').split()[::-1]) Try to understand?

18 Counting Stuff in a String
This requires you to find how many characters are alphabetical, numerical or space. Is str1 is a single character string then you can test its nature str1.isalpha() str1.isdigit() str1.isspace() etc It is a simple counting problem in which: Initialise the counting variables Traverse the string Test the nature of the current character and count

19 To do List Solve the HW problems. Read more about Strings


Download ppt "Programming Training Main Points: - Working with strings."

Similar presentations


Ads by Google