Fred Agbo
April 24, 2024
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
test_array = [64, 34, 25, 12, 22, 11, 90]
sorted_array = bubbleSort(test_array)
print("Sorted array:", sorted_array)
7 / 3 >= 2 and not ord("A") > ord("Z") or 13 % 0 == 2
The general form of a function definition looks like:
def name(parameter_list):
#statements in function body
name
is your chosen name for the
functionparameter_list
is a
comma-separated list of variable names that will hold
each input valueYou can return or output a value from the function by including a return statement in the function body
return expression
expression
is the value you want to
return or outputreturn
statement is included,
Python will by default return None
Function | Description |
---|---|
abs(x) |
The absolute value of x |
max(x,y,...) |
The largest of all the arguments |
min(x,y,...) |
The smallest of all the arguments |
round(x) |
The value of x rounded to the nearest integer |
int(x) |
The value of x truncated to an integer |
float(x) |
The value of x as a decimal |
Python defines two types of operators that work with Boolean data: relational operators and logical operators
Relational operators compare values of other types and produce a
True
/False
result:
== |
Equals | != |
Not equals | |||
< |
Less than | <= |
Less than or equal too | |||
> |
Greater than | >= |
Greater than or equal to |
Be careful! ==
compares two
booleans. A single =
assigns a
variable.
Logical operators act on Boolean pairings
Operator | Description |
---|---|
A and B |
True if both terms True, False otherwise |
A or B |
True if any term is True, False otherwise |
not A |
True if A False, False if A True (opposite) |
Order of operations follows parentheses and then proceeds left to right
Careful that or
is still
True
if both options are
True
not
with and
and
or
True ==1
and
False==0
a,b,c= 2,True, False
print(a + b) # >>>3
range()
iterablerange()
function handles
this and produces the needed iterable objectBe careful, the range
function will stop
one step before the final stop value.
Providing just a stop argument:
for n in range(5):
print(n)
Providing a start and stop:
for n in range(1,11):
print(n)
Providing a start, stop, and step:
for n in range(10,0,-1):
print(n)
Suppose we wanted to write a function to compute the greatest factor of a provided number (not including the number itself)
Algorithm:
def greatest_factor(num):
"""Finds the greatest factor of a number."""
for i in range(num-1,0,-1):
if num % i == 0:
return i
'I am a string'
"I am also a string!"
"I'm sad you've gone"
Both strings and lists are examples of a more general type called a sequence
Sequences are ordered, so we can number off their elements, which we call their index
Python defines operations that work on all sequences
[
]
>>> A = [2, 4, 6, 8]
>>> print(A[1])
4
>>> B = "Spaghetti"
>>> print(B[6])
't'
+
operator concatenates sequences
+
will add two integers,
but will concatenate two strings>>> 'fish' + 'sticks'
'fishsticks'
>>> A = [1, 'fish']
>>> B = [2, 'fish']
>>> print(A + B)
[1, 'fish', 2, 'fish']
The number of elements in a sequence is commonly called its
length, and can be given by the
len( )
function
Simply place the sequence you desire to know the length of between the parentheses:
>>> len("spaghetti")
9
You can have sequences of 0 length as well!
>>> A = ""
>>> B = [ ]
>>> print( len(A) + len(B) )
0
chr
and
ord
chr
takes a base-10 integer and returns
the corresponding Unicode character as a string
chr(65)
gives
"A"
(capital A)chr(960)
gives
"π"
(Greek letter pi)ord
goes the other direction, taking a
single character string and returning the corresponding base-10 integer
of that character in Unicode
ord("B")
gives 66ord(" ")
gives 32ord("π")
gives 960Often, you may want more than a single character
Python allows you to specify a starting and an ending index through an operation known as slicing
The syntax looks like:
string_variable[start : limit]
where start
is the first index to be
included and everything up to but not including the
limit
is included
start
and
limit
are actually optional (but the
:
is not)
start
omitted, the slice will begin
at the start of the stringlimit
omitted, the slice will proceed
to the end of the stringCan add a third component to the slice syntax, called a stride
string_variable[start : limit : stride]
Specifies how large the steps are between each included index
Can also make the stride negative to proceed backwards through a string
>>> s = "spaghetti sauce"
>>> s[4:8]
hett
>>> s[10:]
sauce
>>> s[:10:2]
sahti
+
) in Python to concatenate strings\[5+5+5+5+5+5 = 6 \times 5\]
print("Betelguese, " * 3)
Python lets you use normal comparison operators to compare strings
string1 == string2
is true if string1
and
string2
contain the same characters in the
same order
Comparisons involving greater than or less than are done similar to alphabetical ordering
All comparisons are done according to their Unicode values.
"cat" > "CAT"
Strings are what we call immutable: they can not be modified in place by clients.
You can “look” at different parts of the string, but you can not “change” those parts without making a whole new string
s = "Cats!"
s[0] = "R" # THIS WILL ERROR!!
You can of course create a new string object with the desired traits:
s = "R" + s[1:]
This applies to all methods that act on strings as well: they return a new string, they do not modify the original
Method | Description |
---|---|
string.find(pattern) |
Returns the first index of pattern in
string , or -1 if
it does not appear |
string.find(pattern, k) |
Same as the one-argument version, but starts searching at index
k |
string.rfind(pattern) |
Returns the last index of pattern is
string , or -1 if
missing |
string.rfind(pattern, k) |
Same as the one-argument version, but searches backwards from index
k |
string.startswith(prefix) |
Returns True if the string starts with
prefix |
string.endswith(suffix) |
Returns True if the string ends with
suffix |
Method | Description |
---|---|
string.lower() |
Returns a copy of string with all
letters converted to lowercase |
string.upper() |
Returns a copy of string with all
letters converted to uppercase |
string.capitalize() |
Returns a copy of string with the first
character capitalized and the rest lowercase |
string.strip() |
Returns a copy of string with whitespace
and non-printing characters removed from both ends |
string.replace(old, new) |
Returns a copy of string with all
instances of old replaced by
new |
Method | Description |
---|---|
char.isalpha() |
Returns True if
char is a letter |
char.isdigit() |
Returns True if
char is a digit |
char.isalnum() |
Returns True if
char is letter or a digit |
char.islower() |
Returns True if
char is a lowercase letter |
char.isupper() |
Returns True if
char is an uppercase letter |
char.isspace() |
Returns True if
char is a whitespace character (space, tab,
or newline) |
char.isidentifier() |
Returns True if
char is a legal Python identifier |