0% found this document useful (0 votes)
38 views4 pages

Bakerfranke Github Io

The document contains code examples for working with lists, strings, dictionaries, and files in Python. It includes examples for copying lists, removing negative values from a list, initializing a 2D list with zeros, counting character frequencies in a string, checking for duplicate elements, constructing lists of tuples from dictionaries, and reading/reversing lines from a file.

Uploaded by

Jonathan Nguyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views4 pages

Bakerfranke Github Io

The document contains code examples for working with lists, strings, dictionaries, and files in Python. It includes examples for copying lists, removing negative values from a list, initializing a 2D list with zeros, counting character frequencies in a string, checking for duplicate elements, constructing lists of tuples from dictionaries, and reading/reversing lines from a file.

Uploaded by

Jonathan Nguyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

1 import copy

2 import string
3 ################# Ch 6 ###################
4 # 1. Based on Textbook R6.3
5 # write a loop to copy a list to L2
6 L1 = [1,3,5,7,8,6,4,3,0]
7
8 L2 = [] #create L2, which is empty
9 # 2 ways
10 # for i in range(len(L1)) : #this i is the index. #or for i in L1:
11 # for i in L1: #this i is the actual element in the list
12
13 for element in L1:
14 L2.append(element)
15
16 #use list comprehension to create L2 instead.
17
18 L2 = [elem for elem in L1] #now it is 1 line
19
20
21 # show how the list contents are the same
22 print(L1 == L2) #checks for content being the same
23
24 # but L1 and L2 are 2 different lists
25 print(L1 is L2) #checks the two references are pointing to the same memory block
26
27 #copy a list, without using a loop
28 L2 = list(L1)
29 L2 = L1.copy()
30 #2 Based on Textbook R6.18
31 # Write code to remove all negative values from a list
32 data = [2, -8, 12, -3, 24, -9, -10, -3, 29, 94]
33 #use while loop
34 i = 0
35 while i < len(data):
36 if data[i] < 0 :
37 data.pop(i)
38 else:
39 i += 1 #only go to next index if we didnt remove data.
40 #we recreate a new data(the list) from the existing data(the list)
41 data = []
42 data = [elem for elem in data if elem >= 0]
43 print(data)
44 # 3. Based on Textbook R6.28
45 # Create a table of m rows and n cols and initialize with 0
46 m = 3
47 n = 4
48 # The long way:
49 # table =
50 table = [] #empty
51 for row in range(m) : #loop m times for m rows.
52 aRow = [0] * n #Aroll is a list of n 0's, or n columns of 0
53 table.append(aRow) # add aRow to the table
54 # The short way:
55 table = [[0] * n for row in range(m)]
56 # write a function to print the table in row, column format,
57 # then call the function
58
59 def printTable(t):
60 for r in range(len(t)) : #goes through all rows
61 for c in range(len(t[0])): #goes through all columns of each row
62 print(table[r][c], end = " ") #print all values of 1 row on 1 line
63 print() #print newline after printing 1 row
64 # what does the following print?
65 for i in range(m): #i: 0, 1, 2
66 for j in range(n): #j: 0,1,2,3 0,1,2,3 0,1,2,3
67 table[i][j] = i + j #0,1,2,3 1,2,3,4 2,3,4,5
68
69 printTable(table)
70
71 #0 1 2 3
72 #1 2 3 4
73 #2 3 4 5
74 # ############################################10/29/18 ###########################################################
75 # copy table to table2
76 # To really copy a list of lists, we need to use deep copy
77 table2 = copy.deepcopy(table) # correct way, will create a deep copy that is separate from original
78 # fill elements of bottom row of table2 with -1's
79 #first way: use a for loop to walk the bottom row and put -1 in:
80 for i in range(n) : # n = number of columns #0,1,2,3... n-1
81 table2[-1][i] = -1 # taking -1 # table[-1] is last row, table[-1][i] is for the column to
82 #second way:
83 table2[-1] = [-1] * n #table at -1, the last row , assign with row of -1 of n columns...
84 # and all elements of left col of table2 with 0's
85 for i in range(m): #m is number of rows
86 table2[i][0] = 0 #first index i is to go through each row, second index of 0 means left most colum
87 #first index value = row (horizontal list)
88 #second index value = column (vertical list)
89 #walk through every row, at column i, fill it with 0
90 # [0] [] []
91 # [0] [] []
92 # second way
93 for num in table2 : #(each num is a list)
94 num[0] = 0
95 #num is element of table2, which is a list
96 #1 index value because accessing 1 single list
97 ################# Ch 8 ###############################################################################################
98 # 4. Given 2 strings:
99 str1 = "Guido Van Rossum first came up with Python in the late 1980s."
100 str2 = "Rossum released the first version of Python code (0.9.0) in February 1991."
101 # print the set of letters that are both in str1 and in str2
102 #first need to create of set of letters of str1 and str2
103 set1 = set() #create empty set
104 for char in str1:
105 if char.isalpha() :
106 set1.add(char)
107 #string.ascii_letters #use import string at top, string.ascii_letters will return a list of all case insensitive c
108 allLetters = set(string.ascii_letters)
109 set2 = set(char for char in str2 if char in allLetters) #set comprehension # for char in str2 -> if char in allL
110 set2 = set(char for char in str2 if char.isalpha()) #same thing as first way
111
112 set3 = set1 & set2
113 print(set3)
114
115 # print the set of letters that are not in either str1 or str2
116 set4 = allLetters - set1 - set2 #everything not in set1 and set2
117 print(set4)
118
119 # print the set of non-letters that are in both strings
120
121 nonSet1 = set(char for char in str1 if not char.isalpha()) #every character in set1 that is not letter
122 nonSet2 = set(char for char in str2 if not char.isalpha()) #every character in set2 that is not letter
123
124 nonSetBoth = nonSet1 | nonSet2
125 print(nonSetBoth)
126
127 # 5. Write code that counts how often each character occurs
128 # in a string
129 str1 = "Guido Van Rossum first came up with Python in the late 1980s."
130 # dictionary will be very useful to keep count
131
132 #V a n _ R o s u m
133 #1 1 1 1 1 1 2 1 1
134
135 countD = {} # empty dictionary to begin with
136 for key in str1 :
137 if key in countD: #check if key is in dictionary:
138 countD[key] = countD[key] + 1 #second time, 's' is already in dict, adds 1 to countD[char],
139 else:
140 countD[key] = 1 #first time run into dictionary, create an 's' key and initialize to 1
141
142 print(countD)
143 countD = {}
144 for char in str1 :
145 countD[char] = countD.get(char, 0) + 1 #adding key for first time, if non existing
146 #^ will return 0 on first time
147 # subsequent times, get returns actual count, which is the value
148 print(countD)
149
150 #nicer way:
151 for key,value in sorted(countD.items()):
152 print(key,value) #print char, count
153 # 6. How do you tell if there are duplicate elements in a list?
154 L = [1,2,4,5,3,2,4,2]
155
156 if len(L) == len(set(L)) : # len(L) is 8. len(set(L)) = 5 (taking L and converting to set.)
157 print("There are no duplicates") # will add 1 2 4 5 3 to set, but '2 4 2' wont be in
158
159 # How do you tell if there are duplicate letters in str1?
160 # str1 = "Guido Van Rossum first came up with Python in the late 1980s."
161 if len(str1) == len(set(str1)) :
162 print("There are no duplicates") # same thing is possible
163
164 # 7. How do you construct a list of tuples (example below) from the keys
165 # and values of a dictionary?
166 # [ (key1,value1), (key2,value2), (key3,value3) ]
167
168 #let's say we have D which is a dictionary
169
170 L = [] #create an empty list
171 for k,v in D.items() :
172 L.append(k,v)
173 #comprehension way of above :
174 L = [(k,v) for k,v in D.items()]
175
176 # faster way
177 L = [t for t in D.items()] #D.items() returns tuples, so t = a tuple
178
179 # How do you construct a dictionary from a list of tuples?
180
181 D = dict(L) #[ (key1,value1), (key2,value2), (key3,value3) ] -> dict
182 # 8. How do you get a list of keys and a list of values
183 # from a dictionary?
184 k = D.keys()
185 v = D.values()
186 # How do you construct a dictionary from 2 parallel lists?
187 #assume we have k = [k1, k2, k3] #names
188 #and v = [v1, v2, v3] #phone number
189
190 # we use zip to create a sequence of tuples: (k1,v1), (k2,v2), (k3,v3)
191 # zip will go across the list and get each 1 at a time
192 D = dict( zip(k,v) ) #zip, then convert to a dictionary
193
194 L = list(zip(k,v)) # or you can construct list from 2 parallel lists
195 ################# Ch 7 ############################
196 done = False
197 while not done:
198 try:
199 answer = input("Enter a filename: ")
200 while answer != "" : #while loop that stops at enter key
201 with open(answer) as infile : #open file. #EXCEPTION CAN HAPPEN HERE
202 done = True #done = True when reach here
203 aList = [] #create empty list
204 totalChars = 0
205 for line in infile : #read in each line into variable line
206 line = line.rstrip() # remove \n and store in a new string
207 aList.append(line) #add the line into the list
208 totalChars += len(line) #running sum of total number of chars
209 #print(aList) #prints ['Mary had a little lamb\n', 'Its fleece was white as snow\n', 'And everywhere tha
210 aList.reverse() #method of the list. reverses the list itself
211 print(aList) #prints ['The lamb was sure to go', 'And everywhere that Mary went\n', 'Its fleece was whit
212 print("Total lines: ", len(aList)) #total lines = length of list.
213 print("Total chars: ", totalChars) #total chars = lengths of each lines of list
214
215
216 with open("outputfile.txt", "w") as outfile : #opens output file, #w mode is write file mode...
217 for line in aList : #go through each line in the list
218 outfile.write(line + '\n') #print the line to file. adds a new line by concatenating. outfile.w
219
220 """
221 The lamb was sure to go
222 And everywhere that Mary went
223 Its fleece was white as snow
224 Mary had a little lamb
225 """
226
227
228 answer = input("Enter a filename: ")
229 except IOError :
230 print ("Can't find", answer)
231 answer = input("Enter a filename: ") #reloop

PDF document made with CodePrint using Prism

You might also like