Showing posts with label ncss. Show all posts
Showing posts with label ncss. Show all posts

Python | Science

/ 26 Aug 2013 /
I can honestly say, this is the funnest piece of code, i've ever written, don't ask why, it just is.



n = {}
for line in open('periodic_table.txt'):
    number, element = line.split()
    n[number] = element
    
    
n2 = {}
for line in open('periodic_table.txt'):
    element, number = line.split()[::-1]
    n2[element] = number
    
    
n.update(n2)

q = input('Enter element number or element name: ')

while q:
    try:
        if q.isdigit():
            print('Element number {} is {}'.format(q,n[q]))
        else:
            print('Element number for {} is {}'.format(q,n[q]))
    except:
        print("That's not an element!")
    
    q = input('Enter element number or element name: ')

Python | NCSS Week 3

/ 19 Aug 2013 /
So, I got 100% second week in a row..... hehehehehheheheh ok,

here are the notes in which I used, PLUS at the very bottom is the problem that took me the longest to solve, I bet the solution is way shorter than my response, but whoooo carrreesssss



#       Looping over characters
# Time to combine some of our skills. We want to use our understanding
# of strings, the len function and while loops to print out each
# character of a string, one per line


'''

word = 'Grok'
i = 0
while i < len(word):
    print(i, word[i])
    i += 1

'''

#       String methods
# Since we're discussing strings, let's go over some more useful
# string methods. We've seen how to call a method on a string object, (like upper)
# and introduced a couple of string methods for converting
# strings to uppercase and lowercase, and replacing bits of
# a string with other strings.

'''

s = 'hello world'
print(s.startswith('hello'))
print(s.endswith('rld'))

'''

# Removing whitspace from around a string.

'''

s = '  abc   '
print(s.strip())
print(s.lstrip())
print(s.rstrip())

s = 'hello world'
print(s.find('w'))
print(s.find('x'))


'''

#       Finding factots - the problem
# Let's look at a worked example using loops. We want to write a program
# to find all the factors of 540. A factor of a number n is an int
# that can be multiplied by another int to give n. For example, the factors
# of 9 are; 1,2,4 and 8 since:

'''
1 x 8 = 8
2 x 4 = 8
'''

# And the factors of 24 are 1,2,3,4,6,8,12 and 24:

'''
1 x 24 = 24
2 x 12 = 24
3 x 8 = 24
4 x 6 = 24
'''

# One way of finding factors is to use your calculator and checking all the numbers less
# than n one by one, This works well for small numbers (like 24)
# but quicly becomes impractical for larger numbers (like 540).
# Can you solve it faster using Python?


#       Finding factots - the algorithm
# The first step in solving a programming problem is work out
# the algorithm or method that we need to follow.

# The simplest approuch is to mimic what you would do by hand
# using your calculatr | Cheching each number one by one is called
# brute force solution, Computers are so fast at doing basic calculations
# that the brute force solution is often a good one for problems like this.

# Let's write down the individual steps we need to follow:
# 1. Choose the first number to test, start with 1:
# 2. See if that number divided evenly into 540 using the modulus
# operator, if it does print it out as a factor:
# 3. Choose the next number by adding 1 to your last choice:
# 4. If your number to test is greater than 540 then you have finished,
# otherwise go back to step 2.

# HA, i did it by myself wotofit

'''

i = 1
x = 54324235435
while i <= x:
    if x % i == 0:
        print(i)
    i += 1

'''

#       When a for loops is best
# Every problem that can be solved using a while loop can also be
# solved using a for loop (and vice versa) So how do you know
# which one to use?

# Generall, when you know how many iteratios you need ( either a set
# number ot to iterate through a list) it is easier to use a for loop)

# For example

'''

colours = ['red', 'blue', 'green']
for i in colours:
    print(i)

'''

#       When a while loop is best
# Generally, when you don't know how many iterations you need,
# and you want to keep looping while some condition is true
# a while loop is better, for example:

'''

sum = 0
limit = 10
i = 0

while sum < limit:
    sum += i
    print(i, sum)
    i += 1

'''


#       Storing multiple values
# Imagine writing a program to store a ranking of your favourite
# authors. Given what you know so far, you would use a seperate
# variable for each author's name and mention each variable to print them

'''

authors = ["J.K. Rowling", "P. Pullman", "S. Collins"]
print(authors[0])
print(authors[1])
print(authors[2])


authors = ["J.K. Rowling", "P. Pullman", "S. Collins"]
for author in authors:
  print(author)

'''

'''

numbers = input('What are ur fave numbers: ')
nums = numbers.split()
for i in nums:
    print (i)

'''


# Phonic tester

''' 

line = None
while line != '':
    line = input('Line: ')
    if line == '':
        break
    phonic = line.split()
    start = phonic[0]
    start_4 = phonic [3]
    a = start[0]
    if start_4.startswith(a):
        print('Good!')
    else:
        print("That's not right!")

'''


#       Accessing list elements
# List items can be accessed using indexing (a.k.a subscripting)

'''

colours = ['red', 'blue', 'green', 'yellow']
print(colours[1])
print(colours[-1])

'''

#       Modifying list elements
# You may remember from earlier that strings are
# Immutable, which means that you cannot change their value.
# If you try to alter a character in a string, Python will
# Complain with a type error!

# Lists are different. List elements can be modified by assigning to
# Subscripts:

'''

colours = ['red', 'blue', 'green', 'yellow']
colours[0] = 'crimson'
colours[-2] = 'lime'
print(colours)

'''

#       Appending and sorting
# There are various list methods that can be used to modify lists.
# The append methos adds an item to the end of the list:

'''

numbers = ['one', 'two', 'three']
numbers.append('four')
print(numbers)

'''

# The sort() method sorts the items in order, e.g. string in
# alphabetical order and numbers in ascending order.

'''

pets = ['dog','mouse','fish','cat']
pets.sort()
print(pets)

'''

# The reverse() method sorts the items in reverse order:

'''

pets = ['dog','mouse','fish','cat']
pets.reverse()
print(pets)

'''

#       Reversing a list
# The reverse method reverses the order of the entire list.

# Just like the string methods we saw last week, notice that calls
# to list method name, seperated by a dot, e.g. pets.reverse()
# Any other values the method needs to do its job is provided in a
# normal way e.g 'cat' is given as an extra argument inside the round
# brackets inn pets.append('cat')

# Unlike methods applied to strings, notice that these methods modify
# the original lists rather than creating new ones and so they don't return
# a value. You can tell this because there is no output when you type them into
# the interpreter, so we need to put pets on a separate line to see what happened
# to our list.

#       Looping with append
# Say we want to sort some books for the library catalogue. We ask the user which books they
# are returning (one at a time), and then want to print them out in alphabetical order.

'''

books = []
book = None
while book != '':
    book = input('What book are you returning? ')
    books.append(book)
books.sort()
for i in books:
    print(i)

'''


#       List of characters and words
# Lists can be constructed from strings using the list builtin function

'''

print(list('hello'))

'''

#       Splitting on other characters
# You can also split strings using other characters, or strings, as the seperator, For example
# sometimes you may want to split a string using the colon character ':'

'''

text = input('text: ')
line = text.split(':')
for i in line:
    print(i)

'''

#       Creating sublists from lists
# Slicing also works like on strings to create a new sublist:

'''

a = ['red','blue','green','yellow']
less = a[:2]
print(less)

'''

# This is useful for checking if a word is in a string:

'''

words = ['the', 'fox', 'jumped', 'over', 'the', 'dog']
print('jumped' in words)

'''

#       Joinging a list of strings
# Another useful string method is join which joins a list of strings back together using
# a string as a seperator

'''

sep = ':'
val = ['a','b','c','d']
print(sep.join(val))

'''

#       Splitting and joining
# You'll often see a literal string (like the space ' ') used:

'''

val = ['a','b','c','d']
print('.'.join(val))

'''

# This is handy when you want to remove duplicate spaces from use input.

'''

msg = input('Enter your letters: ')
letters = msg.split()
print('.'.join(letters))

'''

# If the user enters a series of letters with extra spaces between them,
# the program removes these spaces and prints them out with a single space separating each.


# Checking if a word is alphabetical, reversed, or not in any order.

'''

word = input('Word: ')
word = word[0].lower() + word[1:].lower()

al = list(word)
al2 = al.sort()
al3 = ''.join(al)


al_2 = al.reverse()
al_3 = ''.join(al)


alpha = al3
revd = al_3
same = word[0] * len(word)

if word == alpha:
    print('alphabetical')
elif word == revd:
    print('reverse alphabetical')
elif word != alpha or revd:
    print('not alphabetical in any way')


'''

#       Like Yoda, you speak
# Yoda speaks in a bit of a strange way. Imagine you wanted to write a program to speak like
# Yoda. Your program reads in four words from the user and moves them around to create a
# sentence that sounded like Yoda

# he is your father
# -->
# your father he is

# Using a list structure makes this program quite easy to write. Lets write on that
# reads in a single line of text and moves the words around using lists. Like always we first
# break the problem down into smaller steps:

# 1. Read the line of text
# 2. Seperate the line into a list of two words
# 3. Change the words to Yoda-speak order
# 4. Print out the new text.

'''

line = input('You say: ')
yoda = line.split()
yoda = yoda[2] + ' ' + yoda[3] + ' ' + yoda[0] + ' ' + yoda[1]
print('Yoda says: ', yoda)

''' 



rule = []
broken = []
tb = 0
tr = 0
line = ' '
while line:
    lines = input('Line: ')
    line = lines.split()

    
    for word in line:
        
        if 'ie' in word:
            if 'cie' in word:
                tb += 1
            elif word.count('cie') > 1:
                tb += 1
                    
            elif word.count('ie') > 1:
                tr += 1
            elif 'ie' in word:
                tr += 1
                
        if 'ei' in word:
            if 'cei' in word:
                tr += 1
            elif word.count('cei') > 1:
                tr += 1
                    
            elif word.count('ei') > 1:
                tb += 1
            elif 'ei' in word:
                tb += 1
                

            
    
print('Number of times the rule helped: {0}'.format(tr))
print('Number of times the rule was broken: {0}'.format(tb))

Python | Little template....

/ 8 Aug 2013 /

1
2
3
4
5
6
7
8
9
fname = "ncss.txt"

with open(fname) as f:
    for line in f:
        words = line.split()
        for k in words:
            print(k, k.count('EASTS'), k.count('WESTS'), end='-')
        for v in words:
            print()



EASTS versus WESTS
EASTS have scored 25:13
WESTS have scored 26:38
WESTS have scored 40:23
WESTS have scored 42:01

Python | Notes ... 3?

/ /

  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
#        Reading from files
# Python makes reading input from a file (as opposed to the Python shell) very
# simple. In fact, reading multiple lines from files is even easier than
# reading them from the shell using input.

# Before a program can read data from a file, it must tell the operating system
# that it wants to access that file. Files sitting in the same directory as
# the running program in IDLE can be reffered to just by using the filename
# eg. text.txt. This is the setup we will use in the challenge.

#       Directories and paths
# A directory is the technical name for a folder. Accessing files in other
# directories requires extra directions to the file called a path.
# There are two kinds of paths: absolute paths and relative paths.

# An absolute path starts from a fixed (or absolute) location on disk
# called the root(which on Windows is the drive name, like C:).
# This means absolute paths can be accessed in the same way from any directory.
# On windows, absolute paths therefore start with a drive letter. On Mac OS/X
# and Linux, it means an absolute path starts with a forward slate,
# Example: /usr/bin/python3.3

# A relative path starts from (that is, is relative to) the current directory
# goes from there. The relative path... refers to the parent directory
# so ../../data.txt goes up two levels to the parent directory, to find data.txt
# Whereas data/colours/rainbox.txt goes down two levels from the current directory
# inside data, and then colours to find rainbox.txt

# An absolute path is like a set of directions that start from somewhere recognisable
# while a relative path is like a set of directions that start from where the
# person is standing now.

#       Opening files
# The process of requesting access to a file is called opening a file
# just like it is for users, and is done using the builtin function, open or file
#  This creates a Python file object which we can then read from. For instance:
'''

f = open('ncss.txt')
for i in f:
    print(i, end='')
    
'''
# This angle bracket representation is used for types in Python that it doesn't
# make sense to print (like the whole contnts of the file). But it lets you
# know that the file exists and you've successfuly opened it.

#       Looping over files
# Ok, now after all that it's easy to read from an opened file!
# Here's our words.txt file:
'''

f = open('ncss.txt')
for line in f.readlines():
    print(line.strip())
    
'''

# That's all there is to reading in a file! As you can see it is actually
# shorter than using input in a while loop. Notice that we have put a strip
# on the print line. That's because line still has the newline character
# on the end. Try removing it to see what happens to the output.

# Now we can actually make this a bit shorter because we don't need to put the
# file in a seperate variable (f), so we can substitute it straight into the for
# loop itself:
'''

for line in open('ncss.txt'):
    print(line.strip())
    
'''  
# This produces the same output as the example above and is the
# recomended approach to read input from files.
'''

with open('ncss.txt') as f:
    for line in f:
        print(line.strip())
        
'''

#       Reading a list from a file
# Reading from a file into a list is also pretty simple:
'''

colours = []
for line in open('ncss.txt'):
    colours.append(line)
    print(colours)
    
'''

# Notice that the newline characters are still attached to the end of the string.
# To remove the newline characters we would have to chop them off either with
# a slice line[:-1] or with a line.strip() which removes whitespace from the
# right hand side of the string

#       Reading a dictionary from a file
# Reading from a file into a dictionary is a little more complicated because we
# not only want to read the lines, but we also need to split each line into
# the key and the value:
'''

numbers = {}
for line in open('ncss.txt'):
    english, french = line.split()
    numbers[english] = french
print(numbers['three'], numbers['two'], numbers['one'])

'''

#       Functions
# A function is an independant, named chunk of code that performs a specific
# operation. It can be run called by referring to it by name with any information
# called arguments it needs to do its job.
# By now you will have had lots of experience calling builtin functions like input
# or in. Both input and in take a single argument, For input this is the message to
# display to the user, eg. 'Enter a number: ', and for int it is the value
# to be converted into an integer, eg. '10'.

# Different languages (and textbooks) someitimes have different terms for
# functions. They may also be called routines, subroutines, subprograms, procedures
# messages for methods. Mant languages differentiate procedures from functions
# by saying that functions return a value but procedures don't
# Since languags like C/C++ and Java have a void or empty return type
# (equivalent to None in Python) the distinction no longer makes sense.

# Using functions in Python is easy - so east that we have been using them without
# really bothering to properly introduce function calls. On the whole, defining
# your own functions in Python is straight forward. How ever, there are a number
# of tricks that can catch you out occasionally. We mention some of those
# things over the next few notes.

# The clever thing about functions is that the same bit of code can be called
# again and again, rather than having to write out multiple times. If we need
# to make a change to that code we only have to do it in one place rather than
# each copy. Also, we can use functions to hide complicated code so we don't
# have to think about it so carefully when we use it.

#       Function calls
# To call a function you need to know how many arguments the function is expecting
# and what type of values they are. For instance, the abs builtin function takes
# one argument which must be an integer or float (or a complex number)

'''

print(abs(4))
print(abs(-11))
print(abs(-3.14159))

'''

# Hopefully, if the function's purpose is well defined it will be obvious what
# information the function needs and why. That is, unless you have a number, then
# it is meaningless to ask about it's absolute value!

# A function call consits of the function name, which may need to be preceded
# (or qualified by the module name, followed by the arguments surrounded by
# parentheses). A common mistake is to forget to put the brackets when the function
# takes no argumnet

# Unfortunately, abs without the parantheses is not an error since abs is a
# variable which holds the actual code that performs the absolute value. Typing
# abs, is asking to see the contents of the variable, not call the function.



#       Creating your own function
# Functions in Python are created using a definition statement. The def creates
# a function from the indented function body and assigns it to the name of the
# function.
'''

def hello(name):
    return 'Hello ' + name
Name = input('Name: ')
print(hello(Name))

'''

# A definition statement consits of the keyword def, followed by the function
# name (here hello), and then a list of zero or more arguments in parentheses
# (here just one, name). The parentheses must be present even when the function
# takes no argument. The def line must end with a colon (like control statements)
# The code block of the function must be intended as in control statements

#       A function to calculate factorials
# Here is a function that performs factorial, that is for a number n it calculates
# n!=n×(n−1)×(n−2)×…×2×1=∏i=1ni
# so 5 factorial, written 5, is 5x4x3x2x1

'''

def fact(n):
    result = 1
    while n > 1:
        result *= n
        n = n - 1
    return result
intt = int(input('Enter number to calculate in fact: '))
print(fact(intt))

'''

# As you can see those factorial numbers get very large vert quickly!
# To define a function with more than one arg, you can list multiple arguments
# in the parenthesis after the function name, comma seperated.

'''

def add_two_nums(a,b):
    return a+b
print(add_two_nums(5, 10)) # 15


'''

#       The return statement
# As we have seen, some function (such as fact above) need to give the result
# of their execution back to the caller, This is done using a return statement.

'''

def add(x, y):
    return x + y
r = add(5, 10)
print(r)

'''

# A return statement immediately terminates the running function and control is
# passed back to the called, that is, the line of code the function continues
# If return is given an argument, then it is returned to the caller and can be
# stored in a variable, used in an expression, or discarded.

# If return is not given a value, then no value is returned to the caller
# (None is required instead). This is the same as a function which has finished
# executing and does not have a return statement.

#       Exiting a function early
# Because a return statement terminates the execution immediately, it is ften used
# to exit from a function before the last line of code.

'''

def hi():
    print('hello')
    return
    print('there')
hi()

'''

# In this example, print('there') will never get called because the return statement,
# will cause the function to exit before the second print is reached.

# As in the above examples, when a function needs to return an argument, the return
# statement is followed by a single expression which is evaluated and returned to
# the caller. A return statement can appear anywhere, including inside if, for
# and while statements, in which the case the function immediately returns.

'''

while 1:
    def day(name):
        if name in ['Saturday', 'Sunday']:
            return 'This is a weekend!'
        elif name in ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']:
            return 'This is a weekday!'
        else:
            return 'This is not a day!'
    nam = input('Enter week0finder: ').capitalize()
    print(day(nam))

'''

#       More on function arguments
# Another complication is that you can't change values that are passed into a
# function:

'''

def add_one(x):
  x += 1

y = 5
add_one(y)
print(y)

'''

# You might expect that we call this function on a variable, say y, then the value
# of y would be incremented by one after the function call, However, running
# this shows the value of y = 5

# Outside the function nothing has changed, but x inside the function would have
# been incremented by one. This is because Python functions make a copy of
# their arguments (called pass by value) rather than access the original variable.

# So in the case above, a new local variable x has been created containing a copy
# of the contents of the variable y that was passed in as an argument during the function
# call. When we modify x inside the function we are only modifying that local
# variable.

# What this means is that if we want to modify a variable we need to pass it
# in to the funtion and then return it, like this:

'''

def add_one(x):
    return x + 1
y = 5
y = add_one(y)
print(y)

'''

# There is one final complication with passing by value, and that is that Python
# data structures are stored as references. We don't want to go into details of
# that means now, but the gotcha is that they can be modified (but not assigned)
# inside a function call:

'''

def append_one(x,c):
    x.append(1)

y = []
append_one(y)
print(y)
append_one(y)
print(y)

'''

#       More dictionary methods
# Sometime you'll need to either retrieve the value for a particular key from the
# dictionary, or use a default value if the key doesn't exist. This typically takes
# 3 lines of Python.

'''

val = 'default'
if key in d:
   val = d[key]

'''

# However, getting a key-value pair or default is so common, dictionaries provide the
# get method to simplify this:

'''

val = d.get(key, 'default')

'''

# The first argument to get is the key. If the key is in the dictionary then the
# corresponding value is returned, otherwise the second argument to get
# (here'default') is returned

# If you want to copy the key-value pairs from one dictionary to another, Python
# provides the update method.

'''

d1 = {'a': 1, 'b': 5}
d2 = {'a': 4, 'c': 6}
d1.update(d2)
print(d1.sort())

'''

# Notice that not only does the new key 'c' have the value 6 from d2, but the
# value for a has also been updated to the value from d2.

#       Miscellaneous string tricks
# To make a couple of the questions a bit easier, here are a last couple of
# miscellaneous tricks:

# Firstly, the string module has some useful constants:

'''

import string
print(string.punctuation[5])

'''

# If you need to strip off all punctuation, you can now use:

'''

x = 'Hello!'
print(x.strip(string.punctuation))

'''

# Note that the .strip() method only strips off leading and trailing punctuation.

'''

x = '- one - two - three -'
print(x.strip(string.punctuation))

'''

Python | Question 2 - NCSS

/ 6 Aug 2013 /

1
2
3
4
5
6
7
8
line = ' '
list1 = []
while line != '':
    line = input('Line: ')
    list1.append(line)
for line in list1:
    if line != '':
            print(' '.join(word[::-1] for word in line.split()))

Whoops i'm a genius

Python | NCSS Challenge - Cake Sale

/ 5 Aug 2013 /
FINALLY, I HAVE BEEN WAITING MY WHOLE LIFE. IT IS FINALLY TIME FOR THE CHALLENGE. OK, HERE'S THE FIRST QUESTION:

You are at a bake sale and want to choose your cake carefully based on value for money. All the cakes are the same height, but come in different sized square tins, marked by their side length.


Write a program to read in the side length and cost of two cakes and print out the cost of each cake per cm2 for how many cm2, and then say which cake to get, or to Get either!

Took me a little while, BUT I GOT IT IN THE END. HERE IS MY CODE:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
cake_len = float(input('Cake 1 side length (cm): '))
cake_cost = float(input('Cake 1 cost ($): '))
cake1 = cake_cost / cake_len**2

cake2_len = float(input('Cake 2 side length (cm): '))
cake2_cost = float(input('Cake 2 cost ($): '))
cake2 = cake2_cost / cake2_len**2

cm1 = round(cake_len**2)
cm2 = round(cake2_len**2)

print('Cake 1 costs ${:.2f} per cm2 for {} cm2'.format(cake1, cm1))
print('Cake 2 costs ${:.2f} per cm2 for {} cm2'.format(cake2, cm2))

if cake1 < cake2:
    print('Get cake 1!')
elif cake2 < cake1:
    print('Get cake 2!')
elif cake1 == cake2:
    print('Get either!')
 
Copyright © 2010 M(ath)+me, All rights reserved