Closed philipc2 closed 1 month ago
None
ChecksFill out the following code snippets.
foo = [1, 2, None, 3]
bar = None
# Check whether bar is equal to None (True if it is, False if it isn't)
if bar == None:
is_bar_none = True
else:
is_bar_none = False
# Find how many times None occurs in the list "foo"
n_none = foo.count(None)
# create a dictionary of counts for each unique element in the list "foo"
#### Count with numpy
fooo = np.array(foo, dtype=float)
keys, values = np.unique(fooo, return_counts=True)
count = dict(zip(keys, values ))
#### Count with Counter package
##### Ref: https://stackoverflow.com/questions/12282232/how-do-i-count-occurrence-of-unique-values-inside-a-list
from collections import Counter
counts = dict(zip(Counter(foo).keys(), Counter(foo).values()))
@rytam2
Made a small correction to the second question. I had this before
a = 1
b = 2
But it should of been
a = 1
b = 1
class MyClass:
foo = "bar"
def foo():
return "bar"
MyClass.fooprint = print
1. What does MyClass.foo
return? Is it what you expected? Why do you think this is the case?
It returns the method foo instead of the attribute foo
's value. No but not sure why,
2. What does MyClass.foo()
return?
It returns the value "bar"
.
3. What does MyClass.fooprint = print
do? Try calling MyClass.fooprint()
Create an attribute fooprint
under the class MyClass
and assigns the function print to the attribute. When MyClass.fooprint()
is called, it will print the object in the parenthesis.
a = 1
b = 1
print(id(a), id(b)
c = 2024
d = 2024
print(id(c), id(d))
1. What is the id()
function doing above?
Getting the memory address of the object.
2. What values did you get for a
, b
, c
, and d
.
a
, b
returns the same id, but c
, d
have a unique address respectively.
3. Try the same exercise for values of 255, 256, and 256, -5, and -6 ?
4. Can you explain the behavior you are observing? (You may find this CPython
file usefull)
Python would reuse the same object for values within [-5,257)
Ref: https://stackoverflow.com/questions/53168093/integer-caching-for-numbers-greater-than-256-and-less-than-5
Python Check In
UXarray, which is the package you will be contributing to this summer, is written in pure Python. Durring the first week, we will meet to check in on how comfortable you feel working with Python.
You are free to use the internet (including generative AI tools), but try to answer them without explicitly copying the answer and code.
Tools & Environments
Python Style & Syntax
Question 1: Builtins &
None
ChecksFill out the following code snippets.
Question 2: Classes & Attributes
MyClass.foo
return? Is it what you expected? Why do you think this is the case?MyClass.foo()
return?MyClass.fooprint = print
do? Try callingMyClass.fooprint()
Question 3: CPython & Unexpected Behavior
id()
function doing above?a
,b
,c
, andd
.CPython
file usefull)Question 4
Do you have any specific questions for me regarding Python?