import typing
def leibnizPi(cb: typing.Callable) -> float:
"""
Return an approximation of pi. Returns the approximation for which cb returns True.
"""
# 4/1 - 4/3 + 4/5 ...
pi = 0.0
den = 1
sign = 1
while True: # while not cb(pi):
pi = pi + sign*4/den
den = den + 2
sign = sign * -1
if cb(pi):
return pi
def closeEnoughPi(pi: float) -> bool:
return pi > 3.141 and pi < 3.142
def notCloseEnoughPi(pi: float) -> bool:
return pi > 3 and pi < 4
print(leibnizPi(notCloseEnoughPi))
3.466666666666667
for c in "Hello, world!":
print(c)
H e l l o , w o r l d !
print("hello, world!"[1])
print(range(1, 10)[2])
e 3
print(len("hello"))
print("hello"[4])
s = "Hello, world!"
for i in range(len(s)):
print(s[i])
5 o H e l l o , w o r l d !
x = "Hello, world!"
print(x[1])
x[1] = "u"
<cell>3: error: Unsupported target for indexed assignment ("str") [index]
e
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [19], in <cell line: 3>() 1 x = "Hello, world!" 2 print(x[1]) ----> 3 x[1] = "u" TypeError: 'str' object does not support item assignment
x = [2, 4, 6, 0, 1]
y = [2]
#z = []
print(x[2])
6
def averageOf(l: list[float]) -> float:
"""
Returns the average (arithmetic mean) of the values in the list l.
"""
sum = 0.0
for val in l:
sum = sum + val
return sum / len(l)
print(averageOf([2, 4, 6, 0, 1]))
2.6
x[False]
2
import typing
def contains(
haystack: typing.Sequence,
needle: typing.Any
) -> bool:
"""
Returns True if the value needle is in the sequence haystack, False otherwise.
"""
for val in haystack:
if val == needle:
return True
return False
x = [2, 4, 6, 0, 1]
print(contains(x, 3))
print(3 in x)
print("e" in "hello")
False False True
x = [2, 4, 6, 0, 1]
print(x)
x[1] = 8
print(x)
x.append(42)
print(x)
[2, 4, 6, 0, 1] [2, 8, 6, 0, 1] [2, 8, 6, 0, 1, 42]
def runningAverage(l: list[float]) -> float:
"""
Returns the average (arithmetic mean) of the values in the list l,
while also replacing the values in the list with their running average.
"""
sum = 0.0
for idx in range(len(l)):
sum = sum + l[idx]
l[idx] = sum / (idx+1)
return sum / len(l)
x = [2.0, 4.0, 6.0, 0.0, 1.0]
print(x)
print(runningAverage(x))
print(x)
[2.0, 4.0, 6.0, 0.0, 1.0] 2.6 [2.0, 3.0, 4.0, 3.0, 2.6]