Skip to content

Commit 79d4abb

Browse files
committed
First commit
0 parents  commit 79d4abb

File tree

6 files changed

+195
-0
lines changed

6 files changed

+195
-0
lines changed

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Small code stubs created to be use with Python v3.x
2+
3+
A few code examples were part of the homework for the UCB CS61A course.
4+
5+
Most of the code is WTFPL without any guarantees whatsoever, unless otherwise specified.

distance.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Calculates the distance between the two cartesian coordinates
2+
# (x_start,y_start) and (x_fin,y_fin)
3+
# Please note code works with Python ver 3.x
4+
5+
from ucb import main
6+
from math import sqrt
7+
8+
def square (num):
9+
return num * num
10+
11+
def distance (x_start, y_start, x_fin, y_fin):
12+
""" Calculates the distance between the two cartesian coordinates
13+
(x_start,y_start) and (x_fin,y_fin) """
14+
return sqrt(square(x_fin - x_start) + square(y_fin - y_start))
15+
16+
@main
17+
def main():
18+
x_start = float(input("Enter the starting x co-ordinate : "))
19+
y_start = float(input("Enter the starting y co-ordinate : "))
20+
x_fin = float(input("Enter the ending x co-ordinate : "))
21+
y_fin = float(input("Enter the ending y co-ordinate : "))
22+
print ("Distance is ",distance(x_start, y_start, x_fin, y_fin))

distance3d.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Calculates the distance between the two 3d cartesian coordinates
2+
# (x_start,y_start,z_start) and (x_fin,y_fin,z_fin)
3+
# Please note code works with Python ver 3.x
4+
5+
from ucb import main
6+
from math import sqrt
7+
8+
def square (num):
9+
return num * num
10+
11+
def distance3d (x_start, y_start, z_start, x_fin, y_fin ,z_fin):
12+
""" Calculates the distance between the two 3d cartesian coordinates
13+
(x_start,y_start,z_start) and (x_fin,y_fin,z_fin) """
14+
return sqrt(square(x_fin - x_start) + square(y_fin - y_start) + square(z_fin - z_start))
15+
16+
@main
17+
def main():
18+
x_start = float(input("Enter the starting x co-ordinate : "))
19+
y_start = float(input("Enter the starting y co-ordinate : "))
20+
z_start = float(input("Enter the starting z co-ordinate : "))
21+
x_fin = float(input("Enter the ending x co-ordinate : "))
22+
y_fin = float(input("Enter the ending y co-ordinate : "))
23+
z_fin = float(input("Enter the ending z co-ordinate : "))
24+
print ("Distance is ",distance3d(x_start, y_start, z_start, x_fin, y_fin ,z_fin))

hailstone.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Print the hailstone sequence starting at a given number and
2+
# terminates at 1 and also returns its length.
3+
# This code is compatible with Python v3.x
4+
5+
from ucb import main
6+
7+
def hailstone (num):
8+
""" Print the hailstone sequence starting at a given number and
9+
terminates at 1 and also returns its length. """
10+
step = 0
11+
while num != 1:
12+
if num%2 == 0 :
13+
num = num / 2
14+
step = step + 1
15+
print(int(num))
16+
else:
17+
num = (num * 3) + 1
18+
step = step + 1
19+
print(int(num))
20+
print("Steps taken : ",step)
21+
22+
@main
23+
def main():
24+
num = int(input("Enter a number : "))
25+
if num > 0:
26+
hailstone(num)
27+
else:
28+
print("Invalid number", num)
29+

sumsqr2of3.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from ucb import main
2+
3+
def square (num):
4+
return num * num
5+
6+
def two_of_three( num1, num2, num3):
7+
return (num1 * num1) + (num2 * num2) + (num3 * num3) - square(min(num1, num2, num3))
8+
9+
@main
10+
def main():
11+
num1 = float(input("Enter the number #1 : "))
12+
num2 = float(input("Enter the number #2 : "))
13+
num3 = float(input("Enter the number #3 : "))
14+
print ("Sum of squares of max 2 of 3 numbers is ", two_of_three(num1, num2, num3))

ucb.py

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
"""The ucb module contains functions specific to 61A at UC Berkeley."""
2+
3+
import code
4+
import functools
5+
import inspect
6+
import re
7+
import signal
8+
import sys
9+
10+
11+
def main(fn):
12+
"""Call fn with command line arguments. Used as a decorator.
13+
14+
The main decorator marks the function that starts a program. For example,
15+
16+
@main
17+
def my_run_function():
18+
# function body
19+
20+
Use this instead of the typical __name__ == "__main__" predicate.
21+
"""
22+
if inspect.stack()[1][0].f_locals['__name__'] == '__main__':
23+
args = sys.argv[1:] # Discard the script name from command line
24+
fn(*args) # Call the main function
25+
26+
27+
PREFIX = ''
28+
def trace(fn):
29+
"""A decorator that prints a function's name, its arguments, and its return
30+
values each time the function is called. For example,
31+
32+
@trace
33+
def compute_something(x, y):
34+
# function body
35+
"""
36+
@functools.wraps(fn)
37+
def wrapped(*args, **kwds):
38+
global PREFIX
39+
reprs = [repr(e) for e in args]
40+
reprs += [repr(k) + '=' + repr(v) for k, v in kwds.items()]
41+
log('{0}({1})'.format(fn.__name__, ', '.join(reprs)) + ':')
42+
PREFIX += ' '
43+
try:
44+
result = fn(*args, **kwds)
45+
PREFIX = PREFIX[:-4]
46+
except Exception as e:
47+
log(fn.__name__ + ' exited via exception')
48+
PREFIX = PREFIX[:-4]
49+
raise
50+
# Here, print out the return value.
51+
log('{0}({1}) -> {2}'.format(fn.__name__, ', '.join(reprs), result))
52+
return result
53+
return wrapped
54+
55+
56+
def log(message):
57+
"""Print an indented message (used with trace)."""
58+
if type(message) is not str:
59+
message = str(message)
60+
print(PREFIX + re.sub('\n', '\n' + PREFIX, message))
61+
62+
63+
def log_current_line():
64+
"""Print information about the current line of code."""
65+
frame = inspect.stack()[1]
66+
log('Current line: File "{f[1]}", line {f[2]}, in {f[3]}'.format(f=frame))
67+
68+
69+
def interact(msg=None):
70+
"""Start an interactive interpreter session in the current environment.
71+
72+
On Unix:
73+
<Control>-D exits the interactive session and returns to normal execution.
74+
In Windows:
75+
<Control>-Z <Enter> exists the interactive session and returns to normal
76+
execution.
77+
"""
78+
# use exception trick to pick up the current frame
79+
try:
80+
raise None
81+
except:
82+
frame = sys.exc_info()[2].tb_frame.f_back
83+
84+
# evaluate commands in current namespace
85+
namespace = frame.f_globals.copy()
86+
namespace.update(frame.f_locals)
87+
88+
# exit on interrupt
89+
def handler(signum, frame):
90+
print()
91+
exit(0)
92+
signal.signal(signal.SIGINT, handler)
93+
94+
if not msg:
95+
_, filename, line, _, _, _ = inspect.stack()[1]
96+
msg = 'Interacting at File "{0}", line {1} \n'.format(filename, line)
97+
msg += ' Unix: <Control>-D continues the program; \n'
98+
msg += ' Windows: <Control>-Z <Enter> continues the program; \n'
99+
msg += ' exit() or <Control>-C exits the program'
100+
101+
code.interact(msg, None, namespace)

0 commit comments

Comments
 (0)