Showing posts with label calculator. Show all posts
Showing posts with label calculator. Show all posts

Trinomial Solver

/ 27 Oct 2013 /
Aaaaaaand here is my first program in like 3 weeks, well, in Python at least, pretty simple but idc, till next time.



from math import sqrt
def tri(a, b, c):
    x = (-b)-sqrt(b**2-(4*a*c))
    y = 2*a
    x2 = (-b)+sqrt(b**2-(4*a*c))
    q = x/y
    q2 = x2/y
    print('{:.2f}'.format(q))
    print('{:.2f}'.format(q2))

C++ | Multi-Dimensional Arrays, and printing them

/ 26 Sept 2013 /
This is pretttty cool, think of all the possibilities :')



#include <iostream>
#include <ctime>
using namespace std;

int main() 
{
  int sally[2][3] = {{2, 3, 4}, {8, 9, 10}};
  
  for(int row = 0; row < 2;row++){
   for(int col = 0; col < 3; col++) {
    cout << sally[row][col] << " ";
   }
   cout << endl;
  }
  
}

C++ | Recursion, arrays and for loops

/ /
Look what I made :'), at first I couldn't be bothered, then I thought, wait, what if I can't do it, so I tried it, and it worked :'), but I only got up to a certain number of factorials, because I only used int, i'm guessing if I used a long or a long long, or even a double,(how ever that works) I could of done it, but yep, program4theday..





#include <iostream>
#include <ctime>
using namespace std;

int factorial(int x) {
 if(x==1) {
  return 1;
 } else {
  return x*factorial(x-1);
 }
}

int main() {
 
 int samir[31];
 
 cout << "Element - Value" << endl;
 int a = 0;
 for(int x = 1;x<=30;x++){
  a++;
  samir[x] = factorial(a);
  cout << endl << x << " = " << samir[x] << endl;
 }
 
}

C++ | Average Age

/ 25 Sept 2013 /
This is just a simple c++ program using a while loop, not dependant on the code's number of loops, but the user's amount of input, then it just gives the average of the "ages" entered. (Can be any number really.. )




#include <iostream>
using namespace std;

int main() 
{
 int allages = 0, age = 0, numofppl = 0, avage = 0;
 int x = 0;
 while(age != -1) {
  cout << "Please enter age, or 0 to exit: "; cin >> age;
  allages = allages + age;
  numofppl++; 
 }
 allages --;
 numofppl--;
 avage = allages / numofppl;
 cout << "The number of ages entered is: " << numofppl << endl;
 cout << "The average age of all the people: " << avage << endl;
 return 0;
}

C++ | add()

/ 22 Sept 2013 /
Yup, C++, why not C? Because it was boring, for me, I'm enjoying C++ much better, and going to attempt the famous pythagorus calculator for my next program, just as soon as I learn the sqrt() and the pow() functions, unless that's just what they are, then ha.



#include <iostream>
using namespace std;

int add(int a, int b){
 return a + b;
}

int main()
{
 int a, b;
 cout << "Enter first number: "; cin >> a;
 cout << endl << "Enter second number: "; cin >> b;
 cout << endl << "The answer is " << add(a, b) << endl;
 return 0;
}

C | Ah, alas, we are here.

/ 11 Sept 2013 /
Here is my first C program. I KNOW. Ok, i'm gonna attempt to write the fib sequence, without any help, in C, I know it in python, so it won't be that hard, but yes. This is great.



#include <stdio.h>

main() 
{
 printf("\n");
 
 int a = 1, b = 100;
 while(a < b)
 {
  printf(" %d\n", a);
  a *= 2;
 }
 
 return 0;
}

Python | Late to #CLASSES (geddit lel)

/ 4 Sept 2013 /
Finally, I have gotten the balls to start learning classes, haven't quite got the hang of them, but they are pretty interesting, so, look forward to great things, btw, I still have not given up my goal of creating a snake game before 2013 comes to it's end, I will, trust me, i will.


import math as _math

class Math():
   def __init__(self, x, y):
      self.x = x
      self.y = y
      self.result = 0

   def __str__(self):
       return str(self.result)

class Pythagorus(Math):
    def calculate(self):
        self.result = _math.sqrt(self.x ** 2 + self.y ** 2)

obj = Pythagorus(8,5)
obj.calculate()
print(obj)




class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return 'Hi! My name is {} and I am {} years old!'.format(self.name,self.age)

class Student(Person):
    def __init__(self, name, age, loans):
        Person.__init__(self, name, age)
        self.loans = loans
    def __str__(self):
        return 'Hi! My name is {} and I am {} years old! But I owe ${} :/'.format(self.name, self.age, self.loans)
person = Student('Samir',16,1002)
print(person)




class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        print('Person - ')
        return "My name is {}. I am {} years old. ".format(self.name, self.age)

class Military(Person):
    def __init__(self, name, age, rank):
        Person.__init__(self, name, age)
        self.rank = rank
    def __str__(self):
        print('Military - ')
        return Person.__str__(self) + "I am a {}".format(self.rank)

class Teacher(Person):
    def __init__(self, name, age, sub):
        print('Teacher - ')
        Person.__init__(self, name, age)
        self.sub = sub
    def __str__(self):
        return Person.__str__(self) + "I teach {}".format(self.sub)

class Student(Person):
    def __init__(self, name, age, loans):
        Person.__init__(self, name, age)
        self.loans = loans



class Animal:
    def __init__(self, name, bark):
        self.name = name
        self.bark = bark
    def Dog(self):
        print('{} is a dog, and dogs go {}!'.format(self.name, self.bark))

    
d1 = Animal('Rufus', 'Woof!')
d1.Dog()




class Person:
    population = 0
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print('{} has been born!'.format(self.name))
        Person.population += 1
    def __str__(self):
        return '{} is {} years old'.format(self.name, self.age)
    def __del__(self):
        print('{} is dying! :('.format(self.name))
        Person.population -= 1
    def totalPop():
        print('There are {} people in the world.'.format(Person.population))

        
p1 = Person('Johnny', 20)
print(Person.population)
p2 = Person('Mary', 27)
print(Person.population)
print(p1)
print(p2)

        


class Student:
    def __init__(self, name):
        self.name = name
        self.attend = 0
        self.grades = []
    def addGrades(self, grade):
        self.grades.append(grade)
    def attendDay(self):
        self.attend += 1
    def getAverage():
        return sum(self.grades) / len(self.grades)

JavaScript | Finding a missing angle

/ 13 Aug 2013 /
First of all, don't be an idiot, put this in a directory where bootstrap is available, if you don't know how to, then enjoy a very ugly converter, apart from that, this code is bloody great (probably not, but it is, deal with it)



 <html>
 <head>
 <link href="css/bootstrap.css" rel="stylesheet">
 </head>
 <body>

  <div class='col-lg-3'>
    <div class='well'>

<h2>&nbsp;&nbsp;Find a missing angle</h2>
  <input class='form-control' type='text' id='q' placeholder=' opposite / adjacent'> <br>
    <input class='form-control' type='text' id='e' placeholder=' adjacent / hypotenuse'>  <br>
<br>
<p> sin <sup> -1 </sup>
<input class='btn btn-success' type='button' onClick='aSin()' value='sin'> <input class='btn btn-success' type='button' onClick='aSind()' value='Round'>

<br>
<p> cos <sup> -1 </sup> 
<input class='btn btn-info' type='button' onClick='aCos()' value='cos'> <input class='btn btn-info' type='button' onClick='aCosd()' value='Round'>

<br>
<p> tan <sup> -1 </sup> 
<input class='btn btn-warning' type='button' onClick='aTan()' value='tan'> <input class='btn btn-warning' type='button' onClick='aTand()' value='Round'>
<p id='w'> </p>
  </div>

<script>


function toRadians (angle) {
  return angle * (Math.PI / 180);
}  
  
  function aSin() {
    var a = document.getElementById('q').value;
    var c = document.getElementById('e').value;
    var z = a / c
    var b = document.getElementById('w').innerHTML =  Math.asin(z) * (180 / Math.PI);
  }
  
  function aSind() {
   var a = document.getElementById('q').value;
    var c = document.getElementById('e').value;
    var z = a / c 
    var t = Math.asin(z) * (180 / Math.PI)
    var b = document.getElementById('w').innerHTML =  Math.round(t) + '&#186;';
  }

  function aCos() {
    var a = document.getElementById('q').value;
    var c = document.getElementById('e').value;
    var z = a / c
    var b = document.getElementById('w').innerHTML =  Math.acos(z) * (180 / Math.PI);
  }
  
  function aCosd() {
   var a = document.getElementById('q').value;
    var c = document.getElementById('e').value;
    var z = a / c 
    var t = Math.acos(z) * (180 / Math.PI)
    var b = document.getElementById('w').innerHTML =  Math.round(t) + '&#186;';
  }
  
  function aTan() {
    var a = document.getElementById('q').value;
    var c = document.getElementById('e').value;
    var z = a / c
    var b = document.getElementById('w').innerHTML =  Math.atan(z) * (180 / Math.PI);
  }
  
  function aTand() {
   var a = document.getElementById('q').value;
    var c = document.getElementById('e').value;
    var z = a / c 
    var t = Math.atan(z) * (180 / Math.PI)
    var b = document.getElementById('w').innerHTML =  Math.round(t) + '&#186;';
  }
  
  
</script>
</body>
</html>

Python | Typing Test

/ 11 Aug 2013 /
This is the coolest thing ever ok.




from time import time

q = input('What do you want to type? ')
a = ' '
record = []
while a != '':
    start = time()
    a = input('Type: ')
    end = time()
    v = end-start
    record.append(v)
    if a == q:
        print('Time taken to type chosen word: {:.2f}'.format(v))
    else:
        break
record = record[:-1]
print('Your Highschore is: {:.2f} seconds.'.format(min(record)))

Python | Guessing game

/ /
I've got to stop making these, JOKES



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from tkinter import *
from random import *

app = Tk()
app.title('Guess the number')
app.geometry('400x300')
ment = IntVar()
num = randint(1, 10)
def rand():
    ges = ment.get()
    if ges > num:
        l = Label(app, text='{} is too high!'.format(ges)).place(x=165, y=70)
    elif ges < num:
        l = Label(app, text='{} is too low!'.format(ges)).place(x=165, y=70)
    elif ges == num:
        l = Label(app, text='{} is correct!'.format(ges)).place(x=165, y=70)
        return

la = Label(app, text='Guess the secret number between 1 and 10!').pack()
guess = Entry(textvariable=ment).pack()
guess_button = Button(app, text='Guess!', command=rand).pack()

app.mainloop()

JavaScript | Calculator (literally...)

/ 10 Aug 2013 /
This took me so long, only because I didn't want to copy and paste so I could remember it, well now I do, worth it? YES am I ever going to use it? lol no



 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
<form name ='Calc'>
  <table border=4>
    <tr>
      <td>
        <input type='text' Name='Input' size='16'>
        <br>
      </td>
    </tr>
    <tr>
      <td>
        <input type='button' name='one' value=' 1 ' onClick="Calc.Input.value += '1'">
        <input type='button' name='two' value=' 2 ' onClick="Calc.Input.value += '2'">
        <input type='button' name='three' value=' 3 ' onClick="Calc.Input.value += '3'">
        <input type='button' name='add' value='  +  ' onClick="Calc.Input.value += ' + '">
        <br>
        <input type='button' value=' 4 ' name='four' onClick="Calc.Input.value +='4'">
        <input type='button' name='five' value=' 5 ' onClick="Calc.Input.value +='5'">
        <input type='button' value=' 6 ' name='six' onClick="Calc.Input.value +='6'">
        <input type='button' value='  -   ' name='minus' onclick="Calc.Input.value +=' - '">
        <br>
        <input type='button' value=' 7 ' name='seven' onClick="Calc.Input.value +='7'">
        <input type='button' value=' 8 ' name='eight' onClick='Calc.Input.value +="8"'>
        <input type='button' value=' 9 ' name='nine' onClick="Calc.Input.value +='9'">
        <input type='button' value='  x  ' name='times' onClick="Calc.Input.value +=' * '">
        <br>
        <input type='button' value=' c ' name='clear' onClick="Calc.Input.value = ''">
        <input type='button' value=' 0 ' name='zero' onClick="Calc.Input.value +='0'">
        <input type='button' value=' = ' name='ans' onClick="Calc.Input.value = eval(Calc.Input.value)">
        <input type='button' value='  /  ' name='div' onClick="Calc.Input.value += ' / '">
        


How it looks:




Python | Maths :'(

/ 9 Aug 2013 /
I made two things today (ikr)

Random math quiz:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from random import *
while 1:
    x = randint(1, 101)
    y = randint(1, 101)
    c = x + y
    ask = input('{} + {} = '.format(x, y))
    if int(ask) == c:
        print('Correct!')
    else:
        print('Wrong!')

Pythagorus solver GUI:

 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
from tkinter import *
from random import *
from math import *

py = Tk()
py.title('Pythagorus')
py.geometry('600x400')
ment = IntVar()
ment1 = IntVar()

def pyth():
    x = ment.get()
    y = ment1.get()
    a = x**2 + y**2
    b = sqrt(a)
    label = Label(py, text = b).place(x=1, y=140)


button = Button(py, text='New Question', command = pyth).place(x=20, y=1)
label_o = Label(py, text='x').place(x=1, y=40)
label_t = Label(py, text='y').place(x=1, y=90)
entry_1 = Entry(textvariable = ment).place(x=20, y=40)
entry_2 = Entry(textvariable = ment1).place(x=20, y=90)


py.mainloop()

Python | Notes ... 3?

/ 8 Aug 2013 /

  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 | 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