Some Python Basics

Python

  • toc: true
  • badges: true
  • comments: true
  • categories: [Python, lists, strings, print,maths,variables]

Some maths

import math
print(math.pi)
print(math.sqrt(34))
3.141592653589793
5.830951894845301
import random
print(random.random())

print(random.choice([1,2,3,4]))
print(random.choice([1,2,3,4]))
0.7617615023592539
4
2

Indexing

S='Spam'

print(S[1:3])
print(S[:-1])
print(S[1:])
print(S[:])
print(S*3)
pa
Spa
pam
Spam
SpamSpamSpam

Immutability


# strings are not immutable
S[0]='p' ##error
TypeError: 'str' object does not support item assignment
# but we can create a new string
S = 'z' +S[1:]
print(S)
#or use replaces
zpam

String specific methods

https://docs.python.org/3/library/stdtypes.html#string-methods

Split

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

stra='xsxhu csjoaij jsaijaio j dijoi'
stra1=stra.split()
print(stra1)
stra1=stra.split('j',maxsplit=2)
print(stra1)
['xsxhu', 'csjoaij', 'jsaijaio', 'j', 'dijoi']
['xsxhu cs', 'oai', ' jsaijaio j dijoi']
line='aaa,bbb,cccc,dd d\n'

#split based on something
print(line.split(','))
#creates a list
print(type(line.split(',')))

# strip out whitespace on rhs
print(line.rstrip())

Strip

Return a copy of the string with the leading and trailing characters removed.

'   spacious   '.strip()
'spacious'

Check nature of string

str.isalnum()

This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9).

stra='abcD1'
print(stra,stra.isalnum())
stra='abcD1#'
print(stra,stra.isalnum())
abcD1 True
abcD1# False

str.isalpha()

This method checks if all the characters of a string are alphabetical (a-z and A-Z).

stra='abcD1'
print(stra,stra.isalpha())
stra='abcD'
print(stra,stra.isalpha())
abcD1 False
abcD True

str.isdigit()

This method checks if all the characters of a string are digits (0-9)

stra=‘abcD1’ print(stra,stra.isdigit()) stra=‘190’ print(stra,stra.isdigit())

str.islower()

This method checks if all the characters of a string are lowercase characters (a-z).

stra='abcD1'
print(stra,stra.islower())
stra='190'
print(stra,stra.islower())
abcD1 False
190 False

str.lower or str.upper change whether upper or lower case

stra='abcD1'
print(stra,stra.lower(),stra.upper())
abcD1 abcd1 ABCD1

captialize the first character

print(stra.capitalize())
Abcd1

Find

Find the position of a substring within a string

string.find(stringIN) scan left to right

string.rfind(stringIN) scan right to left

stra='ABCDCDC'
straa='BCD'
stra.find('CD'),stra.rfind('CD')
(2, 4)

Replace

string.replace(sub_string,string) replace parts of a string

S='oke doke karaoke'

#replace parts of a string
print(S)
print(S.replace('karaoke','noke'))
oke doke karaoke
oke doke noke

Formatting


print('%s, eggs, and %s' % ('spam', 'SPAM!'))

print('{0}, eggs, and {1}'.format('spam', 'SPAM!'))

Help

Put into help( ) to get help on it

help(S.format)

Lists

https://docs.python.org/3/tutorial/datastructures.html?highlight=tuple

The Python list object is the most general sequence provided by the language. Lists are positionally ordered collections of arbitrarily typed objects, and they have no fixed size. They are also mutable—unlike strings, lists can be modified in-place by assignment to offsets as well as a variety of list method calls

New List

Create a list with list(XX)

a='1 2 3 4 5 6 7'
lista = list(a)
print(lista)
['1', ' ', '2', ' ', '3', ' ', '4', ' ', '5', ' ', '6', ' ', '7']

Copy

list.copy

lista =a.split(' ')
lista=lista[0:3]
print('Original a=\n',lista)
listb=lista
listc=lista.copy()
listd=lista[:]

listb[1]='po'

print('list b, where b=a and b[1] modified, b=\n',listb,
    '\nJust using equals b=a after mods, a=\n',lista,
      '\n Using a copy c=a.copy(), c=\n',listc,
      '\n Using d=a[:] to create a copy, d=\n',listd)
Original a=
 ['1', '2', '3']
list b, where b=a and b[1] modified, b=
 ['1', 'po', '3'] 
Just using equals b=a after mods, a=
 ['1', 'po', '3'] 
 Using a copy c=a.copy(), c=
 ['1', '2', '3'] 
 Using d=a[:] to create a copy, d=
 ['1', '2', '3']

Append

list.append(x), add x to end of a list

print(lista)
lista.append('ok')
print(lista)
['1', 'po', '3']
['1', 'po', '3', 'ok']

Insert

lista.insert(i,x) insert x at position i

lista.insert(2,'two')
print(lista)
['1', 'po', 'two', '3', 'ok']

Remove

lista.remove(x) Remove the first item from the list whose value is equal to x.

lista.remove('two')
print(lista)
['1', 'po', '3', 'ok']

Pop

lista.pop([i]) Remove the item at the given position in the list, and return it

list.popleft at left

print(lista.pop(1))
po

Remove

list.clear() Remove all items from the list. Equivalent to del a[:].

print(lista.clear())
print(lista)
None
[]

Index

list.index(x,i) Return position of x within list starting at position i

listc.append('1')
print(listc)
print(listc.index('1'),2)
['1', '2', '3', '1']
0 2

Count

lista.count(x) Return the number of times x appears in the list.

print(listc.count('1'))
2

Sort

lista.sort(*, key=None, reverse=False) Sort the items of the list in place (the arguments can be used for sort customization, see sorted() (https://docs.python.org/3/library/functions.html#sorted) for their explanation).

listc.sort()
print(listc)
['1', '1', '2', '3']

Reverse

lista.reverse() Reverse the elements of the list in place.

Del

del lista[0] remove an item from a list given its index instead of its value

print(listc)
del listc[2]
print(listc)
['1', '1', '2', '3']
['1', '1', '3']

#list of different types
L =[123, 'spam',1.23]
print(L)

#access
print(L[2])

#append
L.append('NI')
print(L)

#get rid of one pop!
L.pop(0)
print(L)

M=['aa','jeji','boio','popo','gsss','zulu','ccc']
#sort
M.sort()
print(M)
M.reverse()
print(M)
[123, 'spam', 1.23]
1.23
[123, 'spam', 1.23, 'NI']
['spam', 1.23, 'NI']
['aa', 'boio', 'ccc', 'gsss', 'jeji', 'popo', 'zulu']
['zulu', 'popo', 'jeji', 'gsss', 'ccc', 'boio', 'aa']

Comprehensions

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

squares=[]
for x in range(10):
    squares.append(x**2)
print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# the comprehension version

print([x**2 for x in range(10)])
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:

[(x,y) for x in [1,2,3] for y in [3, 1, 4] if x!=y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
vec = [[1,2,3], [4,5,6], [7,8,9]]
[num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
matrix=[[1,2,3,4],
       [5,6,7,8],
       [9,19,11,12]]
[[col[i] for col in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 19], [3, 7, 11], [4, 8, 12]]

List to string

Convert a list to a string with "".join(lista)

stra = "".join(listd)
print(stra,'-',stra[1:])
123 - 23

Dictionaries

Python dictionaries are something completely different (Monty Python reference intended)—they are not sequences at all, but are instead known as mappings. Mappings are also collections of other objects, but they store objects by key instead of by relative position. In fact, mappings don’t maintain any reliable left-to-right order; they simply map keys to associated values. Dictionaries, the only mapping type in Python’s core objects set, are also mutable: they may be changed in-place and can grow and shrink on demand, like lists.

#create dict

D = {'food':'Spam','quality':4, 'color':'pink'}
print(D)

#or create by key assignment 
D={}
D['food']='Spam'
D['quality']=4
D['color']='pink'
print(D)

#index it
print(D['food'])
# Nesting
#what if the info is more complex? Nest

rec = {'name':{'first':'Bob','last':'Smith'},
        'job':['dev','mgr'],
        'age':40.5}

#index them
print(rec['name'])

print(rec['name']['last'])

print(rec['job'][0])

#or add more NB job is a list
rec['job'].append('janitor')

print(rec)

#keys are 1st bit
print(rec.keys())

Tuples

roughly like a list that cannot be changed—tuples are sequences, like lists, but they are immutable, like strings. Syntactically, they are coded in parentheses instead of square brackets, and they support arbitrary types, arbitrary nesting, and the usual sequence operations:

T=(1,2,3,4)
print(len(T))

#concatenation
print(T+(5,6))

#indexing
print(T[0])

## or
T = ('spam', 3.0, [11, 22, 33])
print(T)

Numeric Types

Based on Chapter 5 of “Learning Python”, 4th Edition, Mark Lutz, O’Reilly

print(type(3))
print(type(3.0))
# integer division or floor
print(102.2//3.2)
#normal division
print(102.2/3.2)

#to the power
print(3**2)

#remainder
print(100%3)

#complex numbers j or J
print((1j +2)*3J)
(52-6)*5*7.5*10*.89
10*.89*5*7.5

Class Methods

Classes and Instances

  • Classes define the behavior of all instances of a specific class.

  • Each variable of a specific class is an instance or object.

  • Objects can have attributes, which store information about the object.

  • You can make objects do work by calling their methods.

  • The first parameter of the methods (self) represents the current instance.

  • Methods are just like functions, but they can only be used through a class.

Special methods

  • Special methods start and end with __. (two underscores)

  • Special methods have specific names, like init for the constructor or str for the conversion to string.

Defining a class

class ClassName:
    def method_name(self, other_parameters):
        body_of_method

Defining a class with a method

class ClassName:
    """Documentation for the class."""
    def method_name(self, other_parameters):
        """Documentation for the method."""
        body_of_method

Object Composition

You can have a situation where two different classes are related, but there is no inheritance going on. This is referred to as composition – where one class makes use of code contained in another class. For example, imagine we have a Package class which represents a software package. It contains attributes about the software package, like name, version, and size. We also have a Repository class which represents all the packages available for installation. While there’s no inheritance relationship between the two classes, they are related. The Repository class will contain a dictionary or list of Packages that are contained in the repository. Let’s take a look at an example Repository class definition:

class Repository:
    def __init__(self):
        self.packages = {}
    def add_package(self, package):
        self.packages[package.name] = package
    def total_size(self):
        result = 0
        for package in self.packages.values():
            result += package.size
        return result

In the constructor method, we initialize the packages dictionary, which will contain the package objects available in this repository instance. We initialize the dictionary in the constructor to ensure that every instance of the Repository class has its own dictionary.

We then define the add_package method, which takes a Package object as a parameter, and then adds it to our dictionary, using the package name attribute as the key.

Finally, we define a total_size method which computes the total size of all packages contained in our repository. This method iterates through the values in our repository dictionary and adds together the size attributes from each package object contained in the dictionary, returning the total at the end. In this example, we’re making use of Package attributes within our Repository class. We’re also calling the values() method on our packages dictionary instance. Composition allows us to use objects as attributes, as well as access all their attributes and methods.

Print

# to so many decimal places

x=30.5557889

print('{:.5f}'.format(x))
30.55579
# add additional characters to string

width = 20
print('HackerRank'.ljust(width,'-'))#or rjust
HackerRank----------
width = 20
print('HackerRank'.center(width,'-'))
-----HackerRank-----

https://docs.python.org/3/library/stdtypes.html#string-methods

Conversion……………………… Meaning

d………………………………. Signed integer decimal.

i………………………………. Signed integer decimal.

o………………………………. Signed octal value.

u………………………………. Obsolete type – it is identical to ‘d’.

x………………………………. Signed hexadecimal (lowercase).

X………………………………. Signed hexadecimal (uppercase).

e ………………………………. Floating point exponential format (lowercase).

E………………………………. Floating point exponential format (uppercase).

f………………………………. Floating point decimal format.

F………………………………. Floating point decimal format.

g………………………………. Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.

G ………………………………. Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.

c………………………………. Single character (accepts integer or single character string).

r………………………………. String (converts any Python object using repr()).

s………………………………. String (converts any Python object using str()).

a………………………………. String (converts any Python object using ascii()).

%………………………………. No argument is converted, results in a ‘%’ character in the result.