-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLecture_2
109 lines (83 loc) · 2.19 KB
/
Lecture_2
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
# in this lecture we studied function 'definitions."
# ex 1:
def square(x):
return mul(x,x)
def sum_squares(x,y):
return add(square(x),square(y))
# // operator rounds the result down to integer
# A function definition can include some descriptions to help understanding.
def pressure(v,t,n):
"""Compute the pressure in pascals of an ideal gas.
Applies the ideal gas law: http://en.wikipedia.org/wiki/Ideal_gas_law
v -- volume of gas, in cubic meters
t -- absolute temperature in degrees kelvin
n -- particles of gas
"""
k = 1.38e-23 # Boltzmann's constant
return n * k * t / v
# we can call help(pressure) to retrieve all those descriptions. It's a good reference.
# note: we can set a value in arguments to some default values.
def pressure(v,t,n = 6)
~~~
return n * k * t / v
pressure(2,3) # will take n = 6, v = 2, t = 3.
pressure(2,3,8) # will take n = 8, because a new value is given.
##############
# hw 1
# Q1 Goal:adding a to the absolute value of b, without calling abs:
from operator import add, sub
def a_plus_abs_b(a,b):
"""Return a+abs(b), but without calling abs.
>>> a_plus_abs_b(2,3)
5
"""
if b < 0:
op = sub
else:
op = add
return op(a,b)
# Q2
def two_of_three(a,b,c):
"""Return x*x + y*y, where x and y are the two largest of a, b, c.
>>> two_of_three(1,2,3)
13
"""
if a > b and b > c:
twolarge = a**2 + b**2
elif a > b and b < c:
twolarge = a**2 + c**2
else:
twolarge = b**2 + c**2
return twolarge
# Q3
def if_function(condition, true_result, false_result):
"""Return true_result if condition is a true value, and false_result otherwise."""
if condition:
return true_result
else:
return false_result
# Q4
def hailstone(n):
"""Print the hailstone sequence starting at n and return its length.
>>> a = hailstone(10) # Seven elements are 10, 5, 16, 8, 4, 2, 1
10
5
16
8
4
2
1
>>> a
7
"""
while n != 1:
if n % 2 == 0:
print(int(n))
n = n / 2
else:
print(int(n))
n = (n * 3) + 1
else:
return 1
#######
# Lecture 2 concluded.