import math
print(math.pi)
print(math.sqrt(34))
3.141592653589793
5.830951894845301
Python
TypeError: 'str' object does not support item assignment
https://docs.python.org/3/library/stdtypes.html#string-methods
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).
Return a copy of the string with the leading and trailing characters removed.
str.isalnum()
This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9).
abcD1 True
abcD1# False
str.isalpha()
This method checks if all the characters of a string are alphabetical (a-z and A-Z).
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).
str.lower
or str.upper
change whether upper or lower case
captialize the first character
Find the position of a substring within a string
string.find(stringIN)
scan left to right
string.rfind(stringIN)
scan right to left
string.replace(sub_string,string)
replace parts of a string
Put into help( ) to get help on it
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
Create a list with list(XX)
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']
list.append(x)
, add x to end of a list
lista.insert(i,x)
insert x at position i
lista.remove(x)
Remove the first item from the list whose value is equal to x.
lista.pop([i])
Remove the item at the given position in the list, and return it
list.popleft
at left
list.clear()
Remove all items from the list. Equivalent to del a[:].
list.index(x,i)
Return position of x within list starting at position i
lista.count(x)
Return the number of times x appears in the list.
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).
lista.reverse()
Reverse the elements of the list in place.
del lista[0]
remove an item from a list given its index instead of its value
#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']
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.
[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:
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
[[1, 5, 9], [2, 6, 19], [3, 7, 11], [4, 8, 12]]
Convert a list to a string with "".join(lista)
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.
# 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())
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:
Based on Chapter 5 of “Learning Python”, 4th Edition, Mark Lutz, O’Reilly
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 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
Defining a class with a method
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:
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.
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.