-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·565 lines (409 loc) · 11.4 KB
/
main.py
File metadata and controls
executable file
·565 lines (409 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
#!/usr/bin/env python3
from datetime import date
print('\n** Sum all items in a list \n')
items = [4, 3, 2, 1, 22, 7]
def sum_list(items):
total = 0
for i in items:
total += i
return total
# multiply all items in a list
def multiply_list(items):
total = 1
for i in items:
total *= i
return total
# return the largest number in a list
# slow way
def return_largest(items):
items = sorted(items)
return items[-1]
# fast way
max(items)
# return the smallest item in a list
# slowest way
def return_smallest(items):
items = sorted(items)
return items[0]
# slow way
def return_smallest_faster(items):
smallest = items[0]
for i in items:
if smallest > i:
smallest = i
return smallest
# fast way
min(items)
numbers = [8, 17, 121, 65, 93, 44, 5, 20, 4, 1 ]
print('Sum of all numbers is: ', sum_list(numbers))
print('All numbers multiplied is: ', multiply_list(numbers))
print('Largest number is: ', return_largest(numbers))
print('Smallest number is: ', return_smallest(numbers))
print('\n\n** Function that calculates the collatz sequence ')
print('Collatz sequence : ')
def collatz(num):
num = int(num)
# print(num)
if num % 2 == 0: # even
calc = num // 2
else: # odd
calc = (3 * num) + 1
print(calc)
return calc
#number = input("Enter a number: ")
number = 3
number = collatz(int(number))
while number != 1:
number = collatz(number)
print('\n')
# Count number of strings in a list that meet a set of requirements
# * characters > 2
# * first and last letter the same
strings = ['24', 'xyzzz', 'abbbbba', '1221', '0fiaslkdj0']
count = 0
for string in strings:
if len(string) > 2 and string[0] == string[-1]:
count += 1
print('Expected Result : ', count)
print('\n')
# Sort a list of tuples by last element of tuple
sample = [(2,5), (1,2), (4,4), (2,3), (2,1)]
def second_element(t):
return t[-1]
final = sorted(sample, key=second_element)
print(final)
print('\n** Print twinkel twinkle little star.')
msg = 'Twinkle, twinkle, little star, \n'
msg += '\t How I wonder what you are! \n'
msg += '\t\t Up above the world so high, \n '
msg += '\t\t Like a diamond in the sky.\n'
msg += 'Twinkle, twinkle, little star,\n'
msg += '\t How I wonder what you are\n'
print(msg)
print('\n** Print python version ')
import sys
print("Python Version")
print (sys.version)
print("Version info")
print(sys.version_info)
print('\n')
print('\n')
def div42by(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: You tried to divide by zero')
print('\n** Error handling ')
print(div42by(0))
print(div42by(1))
## error handling input
#numCats = input('How many cats do you have? ')
#try:
# if int(numCats) >= 4:
# print('That is a lot of cats')
# else:
# print('That is not that many cats')
#except ValueError:
# print('You did not enter a number')
#print('\n\n')
print('\n** Looking at lists with range ')
supplies = ['pens', 'staplers', 'binders', 'flask']
def indexes(listinput):
for i in range(len(listinput)):
print('Index ' + str(i) + ' in listinput: ' + listinput[i])
indexes(supplies)
## inputs
#name = input('What is your name? ')
#birth_year = input('What year were you born? ')
#password = input('Please type in a password. ')
#
# calculations
#age = date.today().year - int(birth_year)
#hidden_pass = '*' * len(password)
#
## outputs
#print(f'{name}, you are {age} years old')
#print(f'Your password {hidden_pass} is {len(password)} letters long.')#
# print('\n\n')
print('\n** More List Methods with a fruit basket')
basket = ['Bananas', 'Apples', 'Oranges', 'Blueberries']
#1. remove Bananas
basket.remove('Bananas')
#2. Remove Blueberries
basket.pop()
#3. Add 'Kiwi' to the end
basket.append('Kiwi')
#4. Add Apples at the beginning
basket.insert(0, 'Apples')
#5. Count how many Apples in the basket
apple_count = basket.count('Apples')
print(f'There are {apple_count} apples in the basket.')
#6. Empty the basket
#basket.clear()
print('\n** Sorted list of friends')
friends = ['Simon', 'Patty', 'Joy', 'Carrie', 'Amira', 'Chu']
new_friend = ['Stanley']
friends.extend(new_friend)
print(sorted(friends))
print('\n\n** List unpacking ')
a,b,c, *other, d = [1,2,3,4,5,6,7,8,9]
print(a)
print(b)
print(other[3])
print(d)
print('\n\n** Dictionaries ')
# dictionary for users in game
user1 = {
'username': 'Bono',
'age': 20,
'weapons': ['sword'],
'is_active': True,
'clan': 'Lumsden'
}
user1['weapons'].append('knife')
user1.update({'is_banned': True})
user2 = user1.copy()
user2.update({'username': 'Dono', 'age': 25})
print(user1)
print(user2.values())
print('\n\n** Sets ')
# unordererd collection of unique objects
school = {'Bobby', 'Tammy', 'Jammy', 'Sally', 'Danny'}
attendance_list = ['Bobby', 'Jammy', 'Sally', 'Danny']
print(f'{school.difference(attendance_list)} skipped class today.')
print('\n\n** Ternary Operator (Conditional Expression)')
# condition_if_true if condition else condition_if_false
is_friend = True
can_message = 'message allowed' if is_friend else 'not allowed to message'
print(can_message)
print('\n\n** Short Circuiting')
is_Friend = True
is_User = True
if is_Friend or is_User:
print('BFFs! ')
print('\n\n** Logical Operators')
is_magician = False
is_expert = False
# check if magician AND expert
if is_magician and is_expert:
print('You are a master magician')
# check if magician but not expert
elif is_magician and not is_expert:
print('Your journey has begun')
# check if you're not a magician
elif not is_magician:
print('Seek the powers of magic')
print('\n\n** Loop through dictionaries ')
# iterable - list, dictionary, tuple, set, string
# any collection of items can be iterated
# iterate - one by one, check each item in the collection
# for item in <data structure>:
# for dictionaries, the keys will be iterated
user = {
'name': 'Golem',
'age': 5006,
'can_swim': False
}
# methods for iterating dictionaries
for item in user.items():
print(item)
for item in user.values():
print(item)
for item in user.keys():
print(item)
for key, value in user.items():
print(key, value)
print('\n\n** Loop through list ')
my_list = [1,2,3,4,5,6,7,8,9,10]
total = 0
for num in my_list:
total = total + num
print(total)
print('\n** Loop Tools ')
# common looping tools -- range, enumerate
for number in range(0, 30, 3): # step over 3 or use -1 for reverse
print(number)
for i,char in enumerate('abc'): # give us an index for each item
print(i, char)
for i,char in enumerate(list(range(100))):
if char == 50:
print(i)
print('\n** While Loops, break, continue, pass ')
# To jump out of a while loop:
# turn condition False (ex: with a counter or else)
# break
# Python3 code to iterate over a list
list = [1, 2, 3, 4, 5]
# Iterating using the for loop
print('Iterating using for loop ')
newlist = []
for i in list:
newlist.append(i)
print(newlist)
# Getting length of list
length = len(list)
i = 0
# Iterating using while loop
print('Iterating using while loop ')
while i < length:
print(list[i])
i += 1
# Very useful to use with input()
#While True:
# response = input('say something: ')
# if (response = 'bye'):
# break
print('\n** Exercise: Make your first GUI')
picture = [
[0,0,0,1,0,0,0],
[0,0,1,1,1,0,0],
[0,1,1,1,1,1,0],
[1,1,1,1,1,1,1],
[0,0,0,1,0,0,0],
[0,0,0,1,0,0,0],
]
# way #1
graphic = []
for line in picture:
graphicline = []
for item in line:
if item == 0:
graphicline.append(' ')
else:
graphicline.append('*')
graphic.append(graphicline)
# oops forgot the print part
# way #2
for row in picture:
for pixel in row:
if (pixel ==1):
print('*', end='')
else:
print(' ', end='')
print('')
print('\n** Exercise: Check for duplicates in a list')
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
#count_dict = dict.fromkeys(some_list, 1)
some_dict = {}
# for each item in some_list, check if in count_dict
# if item exists as key, value=+1
for key in some_list:
if key in some_dict.keys():
# print(f' Element {key} exists in dict')
some_dict[key] += 1
else:
# print(f' Adding {key} to dict')
some_dict[key] = 1
dups = []
for key, value in some_dict.items():
if value > 1:
dups.append(key)
print('Way of the Jen: ', end = '')
print(dups)
# way #2
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates = []
for value in some_list:
if some_list.count(value) > 1:
if value not in duplicates:
duplicates.append(value)
print(f'Way of the python warrior: {duplicates}')
print('\n** Exercise: Make some functions')
def checkDriverAge(age=0):
'''
Takes an age argument and checks to see if you can drive yet.
'''
if int(age) < 18:
print("Sorry, you are too young to drive this car. Powering off")
elif int(age) > 18:
print("Powering On. Enjoy the ride!")
elif int(age) == 18:
print("Congratulations on your first year of driving. Enjoy the ride!")
checkDriverAge()
#help(checkDriverAge) # print the docstring
print('\n** *args and **kwargs')
def super_func(*args, **kwargs):
#print(*args)
total = 0
for items in kwargs.values():
total += items
return sum(args) + total
print(super_func(1,2,3,4,5, num1=5, num2=10))
print('\n** Exercise: Print the highest even number')
def highest_even(li):
evens = []
for item in li:
if item % 2 == 0:
evens.append(item)
return max(evens)
print(highest_even([10,2,3,4,6,7,8,11]))
#print('\n** walrus operator')
#inputs = list()
#while (current := input("Write something: ")) != "quit":
# inputs.append(current)
print('\n** scope')
a = 1
def confusion():
a = 5
return a
print(confusion())
print(a)
def outer():
x = "local"
def inner():
nonlocal x
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
outer()
print('\n** ')
def newthing():
pass
print('what')
print('\n** OOP : Classes')
class PlayerCharacter:
# Class Object Attribute
membership = True
def __init__(self, name, age):
if (self.membership):
self.name = name
self.age = age
def introduce(self):
print(f'My name is {self.name}')
# returns None because nothing is returned
player1 = PlayerCharacter('Dragon', 40)
player2 = PlayerCharacter('Bear', 25)
player2.attack = 50
print(player1.name)
print(player2.age)
print(player2.introduce())
print(player2.attack)
print('\n** Exercise : Cats Everywhere')
# Given the below class:
class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
# 1 Instantiate the Cat object with 3 cats
cat1 = Cat('Willow', 107)
cat2 = Cat('Lenny', 24)
cat3 = Cat('Murray', 37)
# Create a function that finds the oldest cat
def oldest(*argv):
old = max(*argv)
return old
fuck = oldest(cat1.age, cat2.age, cat3.age)
print(f'The oldest cat is {fuck} years old.')
# Print out: "The oldest cat is x years old.".
# x will be the oldest cat age by using the function in #2
print('\n** OOP : 4 Pillars')
# Encapsulation
# Abstraction
# Inheritance
# Polymorphism
print('\n** Exercise : Pets Everywhere')
# Exercise from this URL
# https://repl.it/@aneagoie/inheritance-exercise
print('\n\n**** ') # end