<jupyter_start><jupyter_text>Variables and Data Structures BIOINF 575 - Fall 2020  Interactive python apps commands&emsp; python – open a plain python console in current terminal     &emsp; http://jupyter.org/ - The evolved form of iPython     &emsp; ipython or jupyter-console – open an iPython console in the current terminal     &emsp; jupyter-qtconsole – open an iPython session in a qt console (console uses qt GUI library, more functional window)        &emsp; jupyter notebook – start a notebook session and open in in a web browser     &emsp; Jupyter-lab – start a jupyter lab session, the future of the notebook     &emsp; spyder – launch the Spyder IDE     &emsp;&emsp;    https://www.spyder-ide.org/     &emsp; anaconda-navigator – launch the Anaconda Navigator  https://www.dataquest.io/blog/jupyter-notebook-tutorial/ A markup language is a system for annotating a document where the text does not read very well but the result makes the content easier to understand Example: using color, different font styles, different font size, indentation, itemizing, numberingThe idea started from the "marking up" of paper manuscripts.Markdown is a tool to convert text to HTML.Markdown is lightweight markup language with plain text formatting syntax. Its design allows it to be converted to many output formats, but the original tool by the same name only supports HTML.Markdown is often used to format readme files, for writing messages in online discussion forums, and to create rich text using a plain text editor.https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet  The Zen of Python, by <NAME><jupyter_code>import this<jupyter_output>The Zen of Python, by <NAME>

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!<jupyter_text>Variables Naming conventions* underscore separated - variable_name - preference* Camel case - VariableNameThere are many others:* https://en.wikipedia.org/wiki/Naming_convention_(programming)Use meaningful names, your future self will thank you! Assign a value to a variable. The assignment operator is: "="<jupyter_code>message = "Let's get started!"<jupyter_output><empty_output><jupyter_text>Check the value of a variable<jupyter_code>message
print(message)
a = 2
b = 5
print(a)
print(b)<jupyter_output>2
5<jupyter_text>EXERCISE Assign the value 10 to a variable.Assign the value True to a variable.Assign the value 100 to the variable attendance_percentage.Assign the value of the variable attendance_percentage to the variable quiz_percentage.Multiple assignment: assign the value 20 to two variables at the same time. Then check the value of the two variables.<jupyter_code>dog_weight = 10
is_Tuesday = True
attendance_percentage = 90
print(dog_weight)
# Multiple assignment
x = y = 20
print(x)
print(y)
print(z)
x,y = 25,25
print(x)
print(y)
cat_weight = 10
print(cat_weight)
is_Wednesday = False
print(is_Wednesday)
attendance_percentage = 100
print(attendance_percentage)
quiz_percentage = attendance_percentage
print(quiz_percentage)
attendance_percentage = 90
print(attendance_percentage)<jupyter_output>10
False
100
100
90<jupyter_text>Remove the value from a variable using None.<jupyter_code>message
message = None
message
print(message)<jupyter_output>None<jupyter_text>Remove a variable from the environment using the function del().<jupyter_code>del(message)<jupyter_output><empty_output><jupyter_text>Now let's try to see what value variable message hasWhat do we expect?<jupyter_code>message<jupyter_output><empty_output><jupyter_text>python complained! http://greenlining.org/wp-content/uploads/2013/10/COMPLAIN.jpg List the type of a variable with the function type().<jupyter_code>message = "Let's test the type."
message
type(message)
message = 10
message
type(message)<jupyter_output><empty_output><jupyter_text>Typing is dynamic but strict in python (objects have type).The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions.Numeric Types — int (subtype: bool), float, complex.Sequence Types — string, list, tuple, range.There are two major categories: mutable and immutable types.Immutable variables cannot be changed, while Mutable variables can be changed.Integer, Floats, Strings, Tuples, Boolean are immutable.List are mutable types.https://docs.python.org/3/library/stdtypes.html List functions and attributes in strings using the dir(str) function.<jupyter_code>dir(str)
type("test")
"test".capitalize()<jupyter_output><empty_output><jupyter_text>Functions preceeded by \_\_ (e.g. \_\_lt\_\_ - less than) are special internal funtions used by python funtions and operators EXERCISE Test more of the string functions: upper(), strip(), ...<jupyter_code>"test".upper()
"  test  text  ".strip()
"test".index("es")<jupyter_output><empty_output><jupyter_text>Get more information regarding strings using the help(str) function.<jupyter_code>help(str)<jupyter_output>Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(self, format_spec, /)
 |      Return a formatted version of the string as described by format_spec.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  [...]<jupyter_text>NumericBasic math operations: int (natural numbers), float (decimal numbers), complexInteger, arbitrarily long, convert from floats or strings with int()Floats, convert from str or int types with float()Convert to string with str() No automatic coercion of  types, explicit conversion onlyException: print() - converts to strings where possible<jupyter_code>dir(int)<jupyter_output><empty_output><jupyter_text>Computing the area of a rectangle.<jupyter_code>length = 6
width = 4
area = length * width
area
type(4.0)<jupyter_output><empty_output><jupyter_text>Float division<jupyter_code>type(4/2)
4/2
type(4//2)
4//2
4/2<jupyter_output><empty_output><jupyter_text>Explicit conversion<jupyter_code>float(4)
float("4.5")
type("4.5")
float("DNA sequence")
int("4")
repr(4)
str(4)
# remainder/modulo
5%2
# exponent
5**2
message = "test"
number = 10
message * number<jupyter_output><empty_output><jupyter_text>BooleanBoolean is a subtype of integerTrue, False values1 == True, 0 == Falseempty structure == False<jupyter_code>type(True)
dir(bool)
cond_result = True
cond_result
cond_result1 = False
cond_result1<jupyter_output><empty_output><jupyter_text>Logical operators not and or<jupyter_code>not cond_result
cond_result and cond_result1
cond_result or cond_result1<jupyter_output><empty_output><jupyter_text>Comparison operators  strictly less than less than or equal\> strictly greater than>= greater than or equal== equal!= not equalis object identityis not negated object identity not cond_result<jupyter_code>cond_result = 2>=3
cond_result
int(True)<jupyter_output><empty_output><jupyter_text>EXERCISE Assign a numeric value to a variable.Write a composite condition to check if the variable is in the range 10 to 100.Write a composite condition to check if the variable is lower than -10 or higher than 10.Write a composite condition to check if the variable is lower than -10 or higher than 10 and if it can be divided by 5 or 7.<jupyter_code>class_size = 15
print(class_size > 10 and class_size < 100)
print(class_size < -10 or class_size > 10)
print(abs(class_size) > 10)
print((class_size < -10 or class_size > 10) and (class_size%5 == 0 or class_size%7 == 0))<jupyter_output><empty_output><jupyter_text>Sequence types: String, List, and Tuple - are iterable  StringSequence of characters - immutable Concatenation<jupyter_code>"Complex " + 'text'<jupyter_output><empty_output><jupyter_text>Simple, double or triple quotes:<jupyter_code>"Don't worry about apostrophes"
'She said: "Good day!"'
test_message = """Trying the triple quotes"""
test_message
'''
I am testing the 
triple quotes - a comment
'''
# this is a COMMENT
test_message = '''Trying the simple triple quotes'''
test_message<jupyter_output><empty_output><jupyter_text>Common Sequence operationsOperation Description:x in sTrue if an item of s is equal to x, else Falsex not in sFalse if an item of s is equal to x, else Trues + tthe concatenation of s and ts * n or n * sequivalent to adding s to itself n timess[i]ith item of s, origin 0s[i:j]slice of s from i to js[i:j:k]slice of s from i to j with step klen(s)length of smin(s)smallest item of smax(s)largest item of ss.index(x[, i[, j]])index of the first occurrence of x in s (at or after index i and before index j)s.count(x)total number of occurrences of x in s<jupyter_code>"ll" in "collection"
"test this, string." in "Collection"
"rep"*4
"collection"[0]
"collection"[1:3]
"collection"[1:3]
"testing the subsetting"[3:16:3]
"testing the subsetting"[3:1000]
test_string = "testing the subsetting"
test_string[:len(test_string)]
len(test_string)<jupyter_output><empty_output><jupyter_text>Subsetting s[i:j:k]If i or j is negative, the index is relative to the end of sequence s: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.The slice of s from i to j is defined as the sequence of items with index k such that i If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.The slice of s from i to j with step k is defined as the sequence of items with index x = i + n\*k such that 0 In other words, the indices are i, i+k, i+2\*k, i+3\*k and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to len(s) if they are greater. When k is negative, i and j are reduced to len(s) - 1 if they are greater. If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.https://docs.python.org/3/library/stdtypes.html<jupyter_code>len("collection")
"collection".index("ll")
min("collection")
"A" < "a"
ord("a")
ord("A")
max("collecTion")
"collection".count("l")
cooper = 20
Cooper
s = "collection"
s
s.index("e")<jupyter_output><empty_output><jupyter_text>Exercise Create the sequence "blablabla" by using the operator *. Find the position of the second o in "collection".Retrieve the word "other" from "immunotherapy" using subsetting.<jupyter_code>"bla"*3
s = "another test"
subs = "t"
s.index(subs, s.index(subs)+1)<jupyter_output><empty_output><jupyter_text>String formatting - much more in a future session.Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".%s - String (or any object with a string representation, like numbers) %d - Integers%f - Floating point numbers%.&lt;n&gt;f - Floating point numbers with a fixed (n) amount of digits to the right of the dot.<jupyter_code>name = "John"
print("Hello, %s!" % name)<jupyter_output><empty_output><jupyter_text>Range - an immutable sequence of numbers It is commonly used for looping a specific number of times. range(stop)range(start, stop[, step])<jupyter_code>dir(range)

list(range(10))
range(10)
list(range(5, 31, 5))<jupyter_output><empty_output><jupyter_text>List - a collection of elements, allows duplicates, is orderred, and is mutable (changeable) A list may be constructed in several ways:Using a pair of square brackets to denote the empty list: []Using square brackets, separating items with commas: [a], [a, b, c]Using a list comprehension: [x for x in iterable]Using the type constructor: list() or list(iterable)<jupyter_code>dir(list)
patient_BMIs = [25, 18, 30, 16, 22, 32, 28]
patient_BMIs<jupyter_output><empty_output><jupyter_text>Size/length of a list<jupyter_code>len(patient_BMIs)<jupyter_output><empty_output><jupyter_text>Save the list in a different variable<jupyter_code>patient_BMIs_followup = patient_BMIs 
patient_BMIs_followup<jupyter_output><empty_output><jupyter_text>Retrieve elements from a list subsetting/slicing<jupyter_code>patient_BMIs_followup[2:4]<jupyter_output><empty_output><jupyter_text>Negative indexing - retrieving elements from the end of the list<jupyter_code>patient_BMIs[-4:-1]<jupyter_output><empty_output><jupyter_text>Change a value in a list<jupyter_code>patient_BMIs_followup[1] = 20
patient_BMIs_followup
patient_BMIs<jupyter_output><empty_output><jupyter_text>patient_BMIs_followup and patient_BMIs are references to the same objectWhen the referred object changes the values display for both referring variables change. To make a copy of a list: copy_list = initial_list[:] Similarly we can do copy_list = list(initial_list)<jupyter_code>patient_BMIs_followup = patient_BMIs[:]
# patient_BMIs_followup = list(patient_BMIs)
patient_BMIs_followup[2] = 27
patient_BMIs_followup
patient_BMIs<jupyter_output><empty_output><jupyter_text>To copy a list through subsetting works ... until it doesn't.When the list contains sublists.The copy module has a deepcopy funtion. Add elements to a list<jupyter_code>patient_BMIs.append(26)
patient_BMIs
patient_BMIs.sort()
patient_BMIs
patient_BMIs.append("test")
patient_BMIs
patient_BMIs.append([35,"text"])
patient_BMIs
patient_BMIs.extend([22,26,33])
patient_BMIs
"""insert an element at a certain position
insert(position, element)"""
patient_BMIs.insert(3,29)
patient_BMIs<jupyter_output><empty_output><jupyter_text>Change list elements<jupyter_code>patient_BMIs[3:5] = [25,25]
patient_BMIs
patient_BMIs[3:6] = [20,20,30,31]
patient_BMIs
patient_BMIs.sort()
patient_BMIs
patient_BMIs.index(20)
patient_BMIs.count(20)
20 in patient_BMIs<jupyter_output><empty_output><jupyter_text>Remove list elements remove() removes the first matching value, not a specific index.<jupyter_code>patient_BMIs.remove(22)
patient_BMIs<jupyter_output><empty_output><jupyter_text>del removes the item at a specific index.<jupyter_code>del patient_BMIs[4]
patient_BMIs<jupyter_output><empty_output><jupyter_text>pop() removes the item at a specific index and returns it.<jupyter_code>patient_BMIs.pop(4)

patient_BMIs<jupyter_output><empty_output><jupyter_text>clear() removes all the elements of a list<jupyter_code>patient_BMIs.clear()
patient_BMIs<jupyter_output><empty_output><jupyter_text>String join()<jupyter_code>",".join(["Make","a","sentence."])<jupyter_output><empty_output><jupyter_text>String split()<jupyter_code>"Get the, words".split(",")<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup