1 / 22

Example Scripts

Example Scripts. Lists. Script: Removing Duplicates in a List. Goal: Given a list L, construct a list K containing all the distinct elements of L maintaining the ordering in L. L = [2,8,1,2,3,6,3,8,6,1]  K = [2,8,1,3,6] One thought – convert to a set, then convert the set to a list:

darin
Download Presentation

Example Scripts

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Example Scripts Lists

  2. Script: Removing Duplicates in a List • Goal: Given a list L, construct a list K containing all the distinct elements of L maintaining the ordering in L. • L = [2,8,1,2,3,6,3,8,6,1]  K = [2,8,1,3,6] • One thought – convert to a set, then convert the set to a list: >>> K = list(set(L)) >>> K >>> [1,2,3,6,8] • Obviously, this does not preserve the order • Well, what shall we do, then? • How about forming the set, then for each element val doing the following: • find the first index j where val is found • remove all occurrences of val after that index • We will use functions for these steps

  3. File uniqueify.py # file: uniqueify.py defremove_all(K,val): while val in K: K.remove(val) defremove_repeats(K,val): j = K.index(val) if j == -1: # no occurrences return if j == len(K)-1: # only occurs at end of list return remove_all(K[j+1:],val) defuniqueify(K): S = set(K) for val in S: remove_repeats(K,val)

  4. File uniqueify.py # file: uniqueify.py continued# testing the uniqueify function L = [5,1,5,2,3,5,6,2,3,9,0] print('Original list L =',L) print('List order not preserved doing list(set(L)):', list(set(L))) uniqueify(L) print('Uniquefyingretains order:',L) # end of uniqueify.py Execution Output:>>> Original list L = [5, 1, 5, 2, 3, 5, 6, 2, 3, 9, 0] List order not preserved doing list(set(L)): [0, 1, 2, 3, 5, 6, 9] Uniquefying retains order: [5, 1, 2, 3, 6, 9, 0] >>>

  5. Another Solution • While the preceding was quite useful for illustrating a number of programming techniques, there is a much simpler way. • The sort method of the str class has a keyword parameter key • You can specify a function to be applied to the values being sorted before comparisons are done defuniqueify(K): J = list(set(K)) J.sort(key=K.index) #sort based on K.index(val) return J • One difference: K is not modified in place, so when you use it, you write L = uniqueify(L) not uniqueify(L)

  6. Python Script File Structure • The preceding is an example of a standard Python file structure. # imports import os, sys . . . # function definitions def func1(): . . . # Statements to be executed # “body” of the script # Some of the statements will involve functions from # modules and from the function definitions section above . . .

  7. Script: Earliest Date • We would now like to write a Python script to determine which of two dates entered by the user is the earlier date. • The user will enter a date of the form mm/dd/yyyy, where mm is the month (like 5), dd is the day (like 29) and yyyy is the year (2012) • So here is how out script would start. date1 = input('Please enter the first date (mm/dd/yyy): ') date2 = input('Please enter the second date (mm/dd/yyy): ') • So how do we determine which comes first? • First we compare the years; then if they are the same, • we compare the months; if they are the same, • we compare the days. • To get the components of a date we do the following: m1,d1,y1 = date1.split('/')m2,d2,y2 = date2.split('/')

  8. Script: Earliest Date • So here is the rest of the script. if y2>y1 or (y2==y1 and m2>m1) or (y2==y1 and m2==m1 and d2>d1): print(date1,'is earlier than',date2) elif y1>y2 or (y1==y2 and m1>m2) or (y1==y2 and m1==m2 and d1>d2): print(date2,'is earlier than',date1) else: print(date1,'is the same as',date2)

  9. Alternate Solution for Dates Problem • Here is another script for the same problem. date1 = input("Enter the first date: ") date2 = input("Enter the second date: ") m1,d1,y1 = date1.split('/') m2,d2,y2 = date2.split('/') L1 = [y1,m1,d1] L2 = [y2,m2,d2] if L1 < L2: print(date1,'is earlier than',date2) elif L2 < L1: print(date2,'is earlier than',date1) else: print(date1,'is the same as',date2)

  10. Script: Anagrams • We next build a script to test whether two strings are anagrams. • Strings are anagrams if they have exactly the same number of each alphabetic character, where case is ignored (as are all non-alphabetic characters) • The obvious tool here is the count method of the str class. s = input('Enter first string: ') t = input('Enter the second string: ') s = s.upper() t = t.upper() anagrams = True for ch in set('ABCDEFGHIJKLMNOPQRSTUVWXYZ'): if s.count(ch) != t.count(ch): anagrams = False break if anagrams: print('The strings are anagrams') else: print('The strings are not anagrams')

  11. Input Validation • It is often the case that user input must satisfy certain conditions • Input validation involves checking the conditions and asking the user to re-enter the values if the input does not satisfy the conditions. • The next example illustrates a way of doing this. h = float(input('Enter the height h (10<=h<=20): ')) while h < 10 or h > 20: print('Invalid; must be between 10 and 20, inclusive') h = float(input('Enter the height h (10<=h<=20): ')) print('You entered a height of ',h)

  12. Input Validation • A variation, with a Python feature that beginners often try (unsuccessfully) in other languages! h = float(input('Enter the height h (10<=h<=20): ')) while not(10 <= h <= 20): print('Invalid; must be between 10 and 20, inclusive') h = float(input('Enter the height h (10<=h<=20): ')) print('You entered a height of ',h) Sample run of the script: >>> Enter the height h (10<=h<=20): 25 Invalid; must be between 10 and 20, inclusive Enter the height h (10<=h<=20): 8 Invalid; must be between 10 and 20, inclusive Enter the height h (10<=h<=20): 15 You entered height 15.0 >>>

  13. Circular Shift of Characters • We next look at one of the oldest cryptographic ciphers, which is to say method of encrypting a message • It supposedly goes back to the days of Julius Caesar and is called the caesarclipher. • The cipher key is a shift amount k and both the sender and receiver must know the key value. • Each letter is replaced by shifting it by the shift amount k, with wrap around at the end of the letters • That is, 'a' is considered the successor of 'z', etc. • Here is the translation table for a shift amount of 5: a b c d e f g h i j k l m n o p q r s t u v w x y z f g h i j k l m n o p q r s t u v w x y z a b c d e • Thus every 'a' would be replaced by 'f', every 'b' by 'g', … every z by 'e'. • Typically, spaces and punctuation would be omitted. • The message 'meet me at dawn' would be encrypted as 'rjjyrjfyifbs'

  14. Circular Shift of Characters • Here is the translation table for a shift amount of 5: a b c d e f g h i j k l m n o p q r s t u v w x y z f g h i j k l m n o p q r s t u v w x y z a b c d e • Suppose the first line represents the entries of a list L. How would we construct the list represented by the second line? >>> L = list('abcdefghijklmnopqrstuvwxyz') >>> L ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] >>> L[5:] ['f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] >>> L[:5] ['a', 'b', 'c', 'd', 'e'] >>> L ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] >>> K = L[5:]+L[:5] >>> K ['f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e']

  15. Circular Shift of Characters • We are now prepared to write out shift function. >>> def shift(ch,k): L = list('abcdefghijklmnopqrstuvwxyz') if ch.lower() not in L: return ‘’ if k not in range(26): return None K = L[5:]+L[:5] return K[L.index(ch)] • Testing: >>> shift('a',5) 'f' >>> shift('a',6) 'g'

  16. Circular Shift of Characters • And now for our caesar cipher encryption function. >>> defcaesar_cipher(s,k): if k not in range(26): return None t = '' for i in range(len(s)): if s[i].isalpha(): t += shift(s[i].lower(),k) return t • Testing: >>> caesar_cipher('hello',5) 'mjqqt' >>> caesar_cipher('mjqqt',21) 'hello'

  17. List Comprehensions • We now introduce a powerful method for constructing new lists from old lists (and more) • The construction is called a list comprehension. • Format: L = [ <expression> for item in <coll> [if <expression>]] • Simple Examples • L = [2*k for k in [1,2,3,4,5,6] ]sets L equal to [2,4,6,8,10,12] • L = [2*k for k in [1,2,3,4,5,6] if k%2 == 1] sets L equal to [2,6,10] • More complex examples: • For simple applications, a 2-dimensional matrix may be represented as a list of lists • M = [[1,2,3],[4,5,6],[7,8,9]] represents a 3x3 matrix of integers, where the entries in M are the rows of the matrix. 1 2 3 4 5 6 7 8 9 • So, how can we extract the columns? • col1 = [row[1] for row in M ] • [[1,2,3],[4,5,6],[7,8,9]]  [2,5,8]

  18. List Comprehensions • M = [[1,2,3],[4,5,6],[7,8,9]] represents a 3x3 matrix of integers, where the entries in M are the rows of the matrix. 1 2 3 4 5 6 7 8 9 • How about lists for the diagonal and counter-diagonal? • diagM = [M[i][i] for i in range(3)] 12 3[0][0] 4 56[1][1] 7 8 9[2][2] • cdiagM = [M[i][2-i]] for i in range(3)] 1 2 3 [0][2] 4 56 [1][1]7 8 9[2][0]

  19. List Comprehensions • M = [[1,2,3],[4,5,6],[7,8,9]] represents a 3x3 matrix of integers, where the entries in M are the rows of the matrix. 1 2 3 4 5 6 7 8 9 • How about lists for the diagonal and counter-diagonal? • diagM = [M[i][i] for i in range(3)] 12 3[0][0] 4 56[1][1] 7 8 9[2][2] • cdiagM = [M[i][2-i]] for i in range(3)] 1 2 3 [0][2] 4 56 [1][1]7 8 9[2][0]

  20. Magic Squares print('We have formed the following 4x4 matrix:\n') for row in M: print('\t'.join([str(val) for val in row])) print() columnsM = [] for i in range(4): col = [row[i] for row in M] columnsM.append(col) diagM = [M[i][i] for i in range(4)] cdiagM = [M[i][3-i] for i in range(4)] rowsums = [sum(row) for row in M] colsums = [sum(col) for col in columnsM] diagsum = sum(diagM) cdiagsum = sum(cdiagM)

  21. Magic Squares print('row sums: ',rowsums) print('column sums:',colsums) print('diagonal sum:',diagsum) print('contra-diagonal sum:',cdiagsum) print() S = ( set(rowsums) | set(colsums) | set([diagsum]) | set([cdiagsum]) ) if len(S) > 1: print('The matrix is not a magic square') else: print('The matrix is a magic square with common', 'value',diagsum)

  22. Magic Squares Enter on one line the integers from 1 to 16 in any order, separated by spaces. We will form a 4 by 4 matrix from your entries and tell you if it is forms a magic square. Enter the values: 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 We have formed the following 4x4 matrix: 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 The matrix is a magic square with common value 34

More Related