I am working on the file "1 Mathematics and Python/Lectures notebooks/9 vector operations/vector_operations.ipynb".
The first task is:
Длиной вектора $x = (x_{1}, \dots, x_{n}) \in \mathbb{R}^{n}$ называется квадратный корень из скалярного произведения, то есть длина равна евклидовой норме вектора:
$$
\left| x \right| = \sqrt{\langle x, x \rangle} = \sqrt{\sum_{i=1}^n x_{i}^2} =  \left\Vert x \right\Vert_{2}.
$$
Теперь, когда мы знаем расстояние между двумя ненулевыми векторами и их длины, мы можем вычислить угол между ними через скалярное произведение:
$$
\langle x, y \rangle = \left| x \right| | y | \cos(\alpha)
\implies \cos(\alpha) = \frac{\langle x, y \rangle}{\left| x \right| | y |},
$$
где $\alpha \in [0, \pi]$ — угол между векторами $x$ и $y$.
Can you write Python code for it?

cos_angle = np.dot(a, b) / norm(a) / norm(b)
print 'Косинус угла между a и b:', cos_angle
print 'Сам угол:', np.arccos(cos_angle)


I am working on the file "1 Mathematics and Python/Lectures notebooks/9 vector operations/vector_operations.ipynb".
The first task is:
Заметим, что после применения этого метода размерность полученных вектор-строк будет равна shape. Следующий метод позволяет сделать такое же преобразование, но не изменяет размерность исходного вектора.
В NumPy к размерностям объектов можно добавлять фиктивные оси с помощью np.newaxis. Для того, чтобы понять, как это сделать, рассмотрим пример:
Can you write Python code for it?

d = np.array([3, 0, 8, 9, -10])
print 'Вектор d:', d
print 'Его размерность:', d.shape

print 'Вектор d с newaxis --> вектор-строка:\n', d[np.newaxis, :]
print 'Полученная размерность:', d[np.newaxis, :].shape

print 'Вектор d с newaxis --> вектор-столбец:\n', d[:, np.newaxis]
print 'Полученная размерность:', d[:, np.newaxis].shape


I am working on the file "1 Mathematics and Python/Lectures notebooks/9 vector operations/vector_operations.ipynb".
The first task is:
Скалярное произведение в пространстве $\mathbb{R}^{n}$ для двух векторов $x = (x_{1}, \dots, x_{n})$ и $y = (y_{1}, \dots, y_{n})$ определяется как:
$$
\langle x, y \rangle = \sum_{i=1}^n x_{i} y_{i}.
$$
Скалярное произведение двух векторов можно вычислять с помощью функции numpy.dot(a, b, ...) или метода vec1.dot(vec2), где vec1 и vec2 — исходные векторы. Также эти функции подходят для матричного умножения, о котором речь пойдет в следующем уроке.
Can you write Python code for it?

print 'Скалярное произведение a и b (через функцию):', np.dot(a, b)

print 'Скалярное произведение a и b (через метод):', a.dot(b)


I am working on the file "1 Mathematics and Python/Lectures notebooks/9 vector operations/vector_operations.ipynb".
The first task is:
Также расстояние между векторами можно посчитать с помощью функции scipy.spatial.distance.cdist(XA, XB, metric='euclidean', p=2, ...) из модуля SciPy, предназначенного для выполнения научных и инженерных расчётов.
Can you write Python code for it?

from scipy.spatial.distance import cdist


I am working on the file "1 Mathematics and Python/Lectures notebooks/9 vector operations/vector_operations.ipynb".
The first task is:
Эта функция также позволяет вычислять попарные расстояния между множествами векторов. Например, пусть у нас имеется матрица размера $m_{A} \times n$. Мы можем рассматривать ее как описание некоторых $m_{A}$ наблюдений в $n$-мерном пространстве. Пусть также имеется еще одна аналогичная матрица размера $m_{B} \times n$, где  $m_{B}$ векторов в том же $n$-мерном пространстве. Часто необходимо посчитать попарные расстояния между векторами первого и второго множеств. В этом случае можно пользоваться функцией scipy.spatial.distance.cdist(XA, XB, metric='euclidean', p=2, ...), где в качестве XA, XB необходимо передать две описанные матрицы. Функция возвращает матрицу попарных расстояний размера $m_{A} \times m_{B}$, где элемент матрицы на $[i, j]$-ой позиции равен расстоянию между $i$-тым вектором первого множества и $j$-ым вектором второго множества.
В данном случае эта функция предподчительнее numpy.linalg.norm(...), так как она вычисляет попарные расстояния быстрее и эффективнее.
5. Скалярное произведение и угол между векторами
Can you write Python code for it?

a = np.array([0, 5, -1])
b = np.array([-4, 9, 3])
print 'Вектор a:', a
print 'Вектор b:', b


I am working on the file "1-Acquire.ipynb".
The first task is:
1.7 Slicing columns using pandas
Can you write Python code for it?

df.index

df.loc[0]

df.iloc[0,0]

df.ix[0,0]


I am working on the file "1-Acquire.ipynb".
The first task is:
Exercise
1) Load the Demographics_State.csv dataset
2) Show the five first rows of the dataset
3) Select the column with the State name in the data frame
4) Get help
5) Change index to date
6) Get all the data for 2nd January 2014
Thinking in Vectors
Difference between loops and vectors
Can you write Python code for it?

#Find weighted average price with respective weights of 0.6, 0.4 for HighQ and MedQ

#Python approach. Loop over all rows.
#For each row, multiply the respective columns by those weights.
#Add the output to an array

#It is easy to convert pandas series to numpy array.
highq_np = np.array(df.HighQ)
medq_np = np.array(df.MedQ)

#Standard pythonic code

def find_weighted_price():
    global weighted_price
    weighted_price = []

    for i in range(df.shape[0]):
        weighted_price.append(0.6*highq_np[i]*0.4*highq_np[i])

#print the weighted price
find_weighted_price()
print weighted_price


I am working on the file "1-Acquire.ipynb".
The first task is:
Exercise: Find the running time of the above program
Can you write Python code for it?

#Vectorized Code
weighted_price_vec = 0.6*highq_np + 0.4*medq_np


I am working on the file "1-Basic Gender Model.ipynb".
The first task is:
Filter the whole data, to find statistics for just women, by just placing women_only_stats as a "mask" on my full data -- Use it in place of the '0::' part of the array index.
You can test it by placing it there, and requesting column index [4], and the output should all read 'female' e.g. try typing this:   data[women_only_stats,4]
Can you write Python code for it?

women_onboard = data[women_only_stats, 1].astype(np.float)
men_onboard   = data[men_only_stats,   1].astype(np.float)

print 'Women onboard: %s' % women_onboard.size
print 'Men   onboard: %s' % men_onboard.size
print 'Total onboard: %s' % (women_onboard.size+men_onboard.size)


I am working on the file "1-Basic Gender Model.ipynb".
The first task is:
Load training data
Can you write Python code for it?

csv_file_object = csv.reader(open('./data/train.csv', 'rb')) 	# Load in the csv file
header          = csv_file_object.next() 						# Skip the fist line as it is a header
data            =[] 											# Create a variable to hold the data

for row in csv_file_object: 							# Skip through each row in the csv file,
    data.append(row[0:]) 								# adding each row to the data variable
data = np.array(data) 									# Then convert from a list to an array.


I am working on the file "1-Basic Gender Model.ipynb".
The first task is:
Playing w/ the data
I have an array of 12 columns and 891 rows.
I can access any element I want, so the entire first column would be data[0::,0].astype(np.float)
-- This means all of the rows (from start to end), in column 0 I have to add the .astype() command, because when appending the rows, python thought it was a string - so needed to convert
Can you write Python code for it?


I am working on the file "1-Basic Gender Model.ipynb".
The first task is:
Proportion of Survivors
Can you write Python code for it?

number_passengers    = np.size(data[0::,1].astype(np.float))
number_survived      = np.sum(data[0::,1].astype(np.float))
proportion_survivors = number_survived / number_passengers
print 'Proportion of Survivors: %s/%s = %s' % (number_passengers \
                                               , number_survived \
                                               , proportion_survivors)


I am working on the file "1-Basic Gender Model.ipynb".
The first task is:
Stats of all women on board
Find the stats of all the women on board, by making an array that lists True/False whether each row is female
Can you write Python code for it?

women_only_stats = data[0::,4] == "female" 	# This finds where all the women are
men_only_stats   = data[0::,4] != "female" 	# This finds where all the men are (note != means 'not equal')


I am working on the file "1-Basic Gender Model.ipynb".
The first task is:
Take a look at the training data
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Argumentos por defecto y argumentos de palabra clave
En la definición de una función, podemos asignar valores por defecto a los argumentos de la función:
Can you write Python code for it?

def mifunc(x, p=2, debug=False):
    if debug:
        print("evaluando mifunc para x = " + str(x) + " usando el exponente p = " + str(p))
    return x**p


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Atención usuarios de MATLAB: el indexado comienza en 0!
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Atención usuarios de MATLAB: el indexado comienza en 0!
Podemos extraer una parte de una cadena usando la sintaxis [desde:hasta], que extrae caracteres entre los índices  desde y hasta:
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Ciclos
En Python, los ciclos (loops) puede ser programados de varias maneras diferentes. La forma más común es usando un cicle for, que se usa junto con objetos iterables, como por ejemplos las listas. La sintaxis básica es:
Ciclos for:
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Ciclos while:
Can you write Python code for it?

i = 0

while i < 5:
    print(i)
    i = i + 1

print("listo")


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Clases
Las clases son una característica clave de la programación orientada al objeto. Una clase es una estructura para representar un objeto y las operaciones que pueden ser realizadas sobre el objeto.
En Python una clase puede contener atributos (variables) y métodos (funciones).
En Python una clase es definida casi como una función, pero usando la palabra clave class, y la definición de la clase usualmente contiene algunas definiciones de métodos (una función en una clase).

Cada método de una clase debería tener un argumento self como su primer argumento. Este objeto es una autoreferencia.

Algunos nombres de métodos de clases tienen un significado especial, por ejemplo:

__init__: El nombre del método que es invocado cuando el objeto es creado por primera vez.

__str__ : Un método que es invocado cuando se necesita una simple representación de cadena de la clase, como por ejemplo cuando se imprime.
Existen muchas más, ver http://docs.python.org/2/reference/datamodel.html#special-method-names
Can you write Python code for it?

class Punto:
    """
    Clase simple para representar un punto en un sistema de coordenadas cartesiano.
    """

    def __init__(self, x, y):
        """
        Crea un nuevo punto en x, y.
        """
        self.x = x
        self.y = y

    def traslada(self, dx, dy):
        """
        Traslada el punto en dx y dy en las direcciones x e y respectivamente.
        """
        self.x += dx
        self.y += dy

    def __str__(self):
        return("Punto en [%f, %f]" % (self.x, self.y))


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Control de flujo
Sentencias condicionales: if, elif, else
La sintaxis Python para la ejecución condicional de código usa las palabras clave if, elif (else if), else:
Can you write Python code for it?

afirmacion1 = False
afirmacion2 = False

if afirmacion1:
    print("afirmacion1 es verdadera")

elif afirmacion2:
    print("afirmacion2 es verdadera")

else:
    print("afirmacion1 y afirmacion2 son falsas")


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Conversión de Tipo
Can you write Python code for it?

x = 1.5

print(x, type(x))

x = int(x)

print(x, type(x))

z = complex(x)

print(z, type(z))

x = float(z)


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Dictionarios
Dictionarios son también como listas, excepto que cada elemento es un par clave-valor. La sintaxsis de los diccionarios es {clave1 : valor1, ...}:
Can you write Python code for it?

parametros = {"parametro1" : 1.0,
          "parametro2" : 2.0,
          "parametro3" : 3.0,}

print(type(parametros))
print(parametros)

print("parametro1 = " + str(parametros["parametro1"]))
print("parametro2 = " + str(parametros["parametro2"]))
print("parametro3 = " + str(parametros["parametro3"]))

parametros["parametro1"] = "A"
parametros["parametro2"] = "B"

# agrega una nueva entrada
parametros["parametro4"] = "D"

print("parametro1 = " + str(parametros["parametro1"]))
print("parametro2 = " + str(parametros["parametro2"]))
print("parametro3 = " + str(parametros["parametro3"]))
print("parametro4 = " + str(parametros["parametro4"]))


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
El ciclo for itera sobre los elementos de la lista suministrada y ejecuta el bloque suministrado una vez para cada elemento. Cualquier tipo de lista puede ser usada para un ciclo for. Por ejemplo:
Can you write Python code for it?

for x in range(4): # por defecto range comienza con 0
    print(x)


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Eliminar el primer elemento con un valor específico usando 'remove'
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Eliminar un elemento en una posición específica usando del:
Puede introducir help(list) para más detalles, o leer la documentación en la red
Tuplas
Tuplas son similares a las listas, excepto que ellas no pueden ser modificadas una vez creadas, es decir, son inmutables.
En Python, las tuplas son creadas usando la sintaxis (..., ..., ...), o incluso ..., ...:
Can you write Python code for it?

punto = (10, 20)

print(punto, type(punto))

punto = 10, 20

print(punto, type(punto))


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Esta técnica es útil, por ejemplo, cuando queremos pasar una función simple como argumento de otra función, como en este caso:
Can you write Python code for it?

# map es una función predefinida en Python
map(lambda x: x**2, range(-3,4))

# in Python 3 podemos usar `list(...)` para convertir la iteración a una lista explícita
list(map(lambda x: x**2, range(-3,4)))


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Esto incluye el módulo completo y lo deja disponible para su uso en el programa. Por ejemplo, podemos escribir:
Can you write Python code for it?

import math

x = math.cos(2 * math.pi)

print(x)


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Excepciones
En Python los errores son manejados con una construcción especial de lenguaje llamada "Exceptions" (excepciones). Cuando ocurre un error, una excepción puede ser hecha, que interrumpe el flujo normal del programa y retorna a algún otro lugar del código donde se definan los comandos try-except más cercanos.
Para generar una excepción podemos usar el comando raise, que toma un argumento que debe ser una instancia de la clase  BaseExpection o una clase derivada de ella.
Can you write Python code for it?

raise Exception("descripción del error")


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Funciones de relacionadas con Tipos
El módulo types contiene definiciones de nombres de tipo que pueden ser usadas para testear si las variables son de un cierto tipo:
Can you write Python code for it?

import types

# imprime todos los tipos definidos en el módulo `types`
print(dir(types))

x = 1.0

# verifica si la variable x es flotante
type(x) is float

# verifica si la variable x es un entero
type(x) is int


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Funciones que retornan un valor usan la palabra clave return:
Can you write Python code for it?

def cuadrado(x):
    """
    Calcula el cuadrado de x.
    """
    return x**2

cuadrado(4)


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Funciones sin nombre (funciones lambda)
En Python podemos también crear funciones sin nombre, usando la palabra clave lambda:
Can you write Python code for it?

f1 = lambda x: x**2

# es equivalente a

def f2(x):
    return x**2

f1(2), f2(2)


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Las listas en Python pueden ser inhomogéneas y arbitrariamente anidadas:
Can you write Python code for it?

lista_anidada = [1, [2, [3, [4, [5]]]]]

lista_anidada


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Listas
Listas son muy similares a las cadenas, excepto que cada elemento puede ser de un tipo diferente.
La sintaxis para crear listas en Python es [..., ..., ...]:
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Listas: Creando listas usando ciclos for:
Una forma conveniente y compacta de inicializar listas:
Can you write Python code for it?

l1 = [x**2 for x in range(0,5)]

print(l1)


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Los operadores booleanos se escriben como palabras: and, not, or.
Can you write Python code for it?

True and False

not False

True or False


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Mirando qué contiene un módulo, y su documentación
Luego que se ha cargado un módulo, podemos listar los símbolos que éste provee usando la función dir:
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Note que el comando print("listo") no es parte del cuerpo del ciclo while, debido a su indentación.
Funciones
En Python una función es definida usando la palabra clave def, seguida de un nombre para la función, una variable entre paréntesis (), y el símbolo de dos puntos :. El siguiente código, con un nivel adicional de indentación, is el cuerpo de la función.
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Note que llamar a métodos de clases puede modificar el estado de esa instancia de clase particular, pero no afecta otras instancias de la clase o alguna otra variable global.
Esto es una de las cosas buenas de un diseño orientado al objeto: código como las funciones y variables relacionadas son agrupadas en entidades separadas e independientes.
Módulos
La mayoría de la funcionalidad en Python es provista por módulos. La Librería Estándar de Python es una gran colección de  módulos que proveen implementaciones multiplataforma de recursos tales como el acceso al sistema operativo, entrada/salido de archivos (file I/O), manejo de cadenas, comunicación en redes, y mucho más.
Para usar un módulo en un programa Python éste debe primero ser importado. Un módulo puede ser importado usando el comando import. Por ejemplo, para importar el módulo math, que contiene muchas funciones matemáticas estándar, podemos usar:
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Operadores de comparación >, <, >= (mayor o igual), <= (menor o igual), == igualdad, es identico.
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Operadores y comparaciones
La mayoría de los operadores y las comparaciones en Python funcionan como one esperaría:

Operadores aritméticos +, -, *, /, // (división entera), '**' potencia
Can you write Python code for it?

1 + 2, 1 - 2, 1 * 2, 1 / 2

1.0 + 2.0, 1.0 - 2.0, 1.0 * 2.0, 1.0 / 2.0

# División entera de dos númenos flotantes
3.0 // 2.0

# Atención! El operador de potencia en Python no es ^, sino **
2 ** 2


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Para crear una nuva instancia de una clase:
Can you write Python code for it?

p1 = Punto(0, 0) # eso invoca el método __init__ en la cláse Punto

print(p1)         # esto invoca el método __str__


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Para invocar un método en la instancia de clase p:
Can you write Python code for it?

p2 = Punto(1, 1)

p1.traslada(0.25, 1.5)

print(p1)
print(p2)


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Para obtener información sobre un error, podemos accesar la instancia de clase Exception que describe la excepción usando por ejemplo:
except Exception as e:
Can you write Python code for it?

try:
    print("test")
    # genera un error: ya que la variable test no está definida
    print(test)
except Exception as e:
    print("Encontré una excepción:" + str(e))


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Podemos aislar un carácter en una cadena usando []:
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Podemos importar el módulo mimodulo a un programa Python usando import:
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Podemos retornar múltiples valores desde una función usando las tuplas (ver más arriba):
Can you write Python code for it?

def potencias(x):
    """
    Calcula algunas potencias de x.
    """
    return x**2, x**3, x**4

potencias(3)

x2, x3, x4 = potencias(3)

print(x3)


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Podemos separar una tupla asignandola a una lista de variables separadas por coma:
Can you write Python code for it?

x, y = punto

print("x =", x)
print("y =", y)


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Si intentamos asignar un nuevo valor a un elemento de una tupla obtenemos un error:
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Si no suministramos un valor para el argumento debug al llamar a la función mifunc se considera el valor definido por defecto:
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Si omitimos desde o bien hasta de [desde:hasta], por defecto se entiende que se refiere al comienzo y/o al fin de la cadena, respectivamente:
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Si tratamos de unsar una variable que no ha sido definida obtenemo un mensaje de error (NameError):
Can you write Python code for it?


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Un número complejo no puede ser convertido a un número flotante o a un entero. Necesitamos usar z.real, o bien z.imag, para extraer la parte que deseamos del número complejo z:
Can you write Python code for it?

y = bool(z.real)

print(z.real, " -> ", y, type(y))

y = bool(z.imag)

print(z.imag, " -> ", y, type(y))


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Un úso típico de las excepciones es para abortar funciones cuando ocurre algún error, por ejemplo:
def mi_funcion(argumentos):

    if not verify(argumentos):
        raise Expection("Argumentos invalidos")

    # el resto del código sigue aquí

Para capturar los errores que son generados por funciones y métodos de clases, o por el mismo intérprete Python, use los comandos try y except:
try:
    # aquí va el código normal
except:
    # el código para manejar el error va aquí
    # Este código no se ejecuta a menos que
    # el código de arriba genere un error

Por ejemplo:
Can you write Python code for it?

try:
    print("test")
    # genera un error: ya que la variable test no está definida
    print(test)
except:
    print("Encontré una excepción")


I am working on the file "1-Jupyter Notebook y Python Básico.ipynb".
The first task is:
Use help(module) para obtener un resumen de lo que suministra el módulo:
Can you write Python code for it?

help(mimodulo)

mimodulo.mi_variable

mimodulo.mi_function()

mi_clase = mimodulo.MiClase()
mi_clase.set_variable(10)
mi_clase.get_variable()


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.10.1.3. Metoda remove()
Metoda remove() uklanja prvo pojavljivanje elementa iz postojeće liste. Sintaksa ove metode je lista.remove(obj). Metoda prima jedan obavezni argument. Argument obj obavezni je argument koji sadrži vrijednost elementa koji želimo obrisati iz postojeće liste. Metoda ne vraća nikakvu vrijednost, već ažurira postojeću listu.
Can you write Python code for it?

lista5=['banana',5,98.95,'tekst',5]
lista5.remove(5)
print lista5


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.11.2.2. Iteracija kroz listu
Iterirati možemo kroz listu. Kada stavimo listu u for petlju, iterira se od prvog elementa liste do posljednjeg elementa liste. Na primjer, u sljedećem primjeru iterirat ćemo kroz listu te u svakoj iteraciji ispisati trenutnu vrijednost pomoćne varijable.
Can you write Python code for it?

for element in [1, 2, 'tri', [4,'pet'], 6.0]:
    print element


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.7. Operatori
Python podržava sljedeće tipove operatora:
* aritmetički operatori
* operatori uspoređivanja
* operatori pridruživanja
* operatori članstva
1.7.1. Aritmetički operatori
Aritmetički operatori su:
* operator zbrajanja (+)
* operator oduzimanja (-)
* operator množenja (*)
* operator dijeljenja (/)
* operator ostatka cjelobrojnog dijeljenja (%)
* eksponent (**)
1.7.1.1. Operator zbrajanja
Operator zbrajanja (+) zbraja vrijednosti s desne i lijeve strane operatora.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.7.1.3. Operator množenja
Operator množenja (*) množi vrijednosti s desne i lijeve strane operatora.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.7.1.5. Operator ostatka cjelobrojnog dijeljenja
Operator ostatka cjelobrojnog dijeljenja (%) dijeli lijevi operand s desnim te vraća ostatak dijeljenja.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.7.1.6. Eksponent
Eksponent (**) vrši eksponencijalnu funkciju, gdje je lijevi operand baza, a desni eksponent.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.7.2. Operatori uspoređivanja
Operatori uspoređivanja uspoređuju vrijednosti na obje strane te odlučuju o njihovoj relaciji. Operatori uspoređivanja su:
* operator ==
* operator !=
* operator >
* operator <
* operator >=
* operator <=
1.7.2.1. Operator ==
Operator == uspoređuje jesu li vrijednosti operanda jednake te vraća logički tip podataka, odnosno True kada su vrijednosti jednake, a False kada su različite.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.7.2.2. Operator !=
Operator != provjerava jesu li vrijednosti operanda različite te vraća logički tip podataka, odnosno True kada su vrijednosti različite, a False kada su jednake.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.7.2.3. Operator >
Operator > provjerava je li vrijednost lijevog operanda veća od vrijednosti desnog operanda te vraća logički tip podataka, odnosno True kada je vrijednost lijevog operanda veća od vrijednosti desnog operanda, a False kada vrijednost lijevog operanda nije veća od vrijednosti desnog operanda.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.7.2.4 Operator <
Operator < provjerava je li vrijednost lijevog operanda manja od vrijednosti desnog operanda te vraća logički tip podataka, odnosno True kada je vrijednost lijevog operanda manja od vrijednosti desnog operanda, a False kada vrijednost lijevog operanda nije manja od vrijednosti desnog operanda.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.7.3. Operatori pridruživanja
Operatori pridruživanja dodjeljuju vrijednosti operandima ili vrše operacije nad operandima:
* =
* +=
* -=
* *=
* /=
* %=
* **=
1.7.3.1. Operator =
Operator = dodjeljuje lijevom operandu vrijednost desnog operanda.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.7.3.3. Operator -=
Operator -= oduzima lijevom operandu vrijednost desnog operanda te rezultat dodjeljuje lijevom operandu.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.7.3.4. Operator *=
Operator *= množi desni operand s lijevim operandom te rezultat dodjeljuje lijevom operandu.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.7.3.5. Operator /=
Operator /= dijeli vrijednost desnog operanda s vrijednosti lijevog operanda te rezultat dodjeljuje lijevom operandu.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.7.3.6. Operator %=
Operator %= vraća ostatak dijeljenja vrijednosti desnog operanda s vrijednosti lijevog operanda te rezultat dodjeljuje lijevom operandu.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.8.2. Funkcija float()
Funkcija float() pretvara cjelobrojnu vrijednost u realni tip podatka.
Can you write Python code for it?

print float(2)

print 7/2

print float(7)/2

print 7/float(2)

print float(7/2)


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.8.4. Funkcija type()
Funkcija type()ne pretvara tipove podataka, već vraća koji je tip podatka određena vrijednost.
Can you write Python code for it?

type('niz')

type(2)

type(5.8)

type(False)


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.9. Rad s nizovima znakova
1.9.1. Konkatenacija
U programiranju konkatenacija niza znakova je operacija spajanja znakova iz niza znakova navedenim redoslijedom (Concatenation). U Pythonu se konkatenacija vrši operatorom =.
Can you write Python code for it?

print 'dar'+'ovi'

niz1='Ana i Ivo'
niz2='Iva i Jan'
print niz1[:3]+niz2[-3:]


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.9.2. Odabrane metode nad nizovima znakova
Već su ukratko ranije spomenute dvije metode nad nizovima znakova upper() i replace(). U ovom poglavlju opisane su još neke odabrane metode nad ovim tipom podatka:
* upper()
* lower()
* replace()
* count()
* find()
* strip()
* split()
* join().
1.9.2.1. Metoda upper()
Metoda upper() vraća niz znakova u kojem su sva slova pretvorena u velika slova, ali ne mijenja ulazni niz znakova.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.9.2.2. Metoda lower()
Metoda lower() vraća niz znakova u kojem su sva slova pretvorena u mala slova, ali ne mijenja ulazni niz znakova.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.9.2.3. Metoda replace()
Metoda replace() vraća niz znakova u kojem se stari podniz mijenja novim podnizom, ali se ne mijenja niz znakova nad kojim se vrši metoda. Sintaksa ove metode je niz.replace(old, new[, count]). Općenito se u Pythonu u oblim zagradama navode argumenti koji su obavezni, dok se u uglatim zagradama nalaze argumenti koji su opcionalni. Iz zapisa metode replace() vidljivo je da prima dva obavezna argumenta i jedan opcionalni. Argument old obavezan je argument koji sadrži stari podniz koji planiramo zamijeniti novim. Argument new obavezan je argument koji sadrži novi podniz kojim ćemo zamijeniti stari. Argument count opcionalni je argument koji sadrži cjelobrojnu vrijednost koliko puta se treba izvršiti zamjena. Ako argument nije naveden, vrši se zamjena svih nađenih pojavljivanja podniza.
Can you write Python code for it?

niz='ananas, banana, jabuka, jagoda, mandarina'
print niz.replace('a','A')
print niz.replace('a','A',5)
print niz


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.9.2.5. Metoda find()
Metoda find() vraća broj početni broj indeksa od kojeg kreće podniz koji tražimo. Sintaksa ove metode je niz.find(sub[, start[, end]]). Metoda prima jedan obavezni i dva opcionalna argumenta. Argument sub obavezni je argument koji sadrži podniz čiji početni indeks tražimo. Argument start opcionalni je argument koji sadrži vrijednost početnog indeksa od kojeg metoda kreće tražiti indeks podniza. Ako argument nije naveden, metoda kreće od indeksa 0. Argument end opcionalni je argument koji sadrži vrijednost završnog indeksa do kojeg metoda traži indeks podniza. Argument je ovisan o argumentu start. Ako nije naveden argument start, ne može biti naveden niti argument end. Ako je pak naveden argument start, argument end može, ali i ne mora biti naveden. Ako argument end nije naveden, metoda završava s posljednjim indeksom niza. U slučaju ako podniz ne postoji, tada vraća vrijednost -1.
Can you write Python code for it?

niz='ananas, banana, jabuka, jagoda, mandarina'
print niz.find('an')
print niz.find('an',2)
print niz.find('an',10,40)
print niz.find('ga')


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
1.9.2.7. Metoda split()
Metoda split() vraća tip podatka listu svih riječi iz niza znakova upotrebljavajući neki separator. Sintaksa ove metode je niz.split([sep[, maxsplit]]). Metoda prima dva opcionalna argumenta. Argument sep opcionalni je argument koji sadrži podniz koji želimo upotrijebiti kao separator. Ako argument nije naveden, pretpostavljena vrijednost je razmak. Argument maxsplit opcionalni je argument koji sadrži cjelobrojnu vrijednost koliko puta želimo izvršiti razdvajanje. Argument je ovisan o argumentu sep. Ako nije naveden argument sep, ne može biti naveden niti argument maxsplit. Ako je pak naveden argument sep, argument maxsplit može, ali i ne mora biti naveden. Ako maxsplit nije naveden, metoda vrši maksimalan mogući broj razdvajanja.
Can you write Python code for it?

niz='ananas, banana, jabuka, jagoda, mandarina'
print niz.split()
print niz.split('ja')
print niz.split('ja',1)


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Ako ne znamo koju vrijednost i tip podataka će varijabla sadržavati, deklarirat ćemo je konstantom None:
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Ako se niz pohrani u varijablu, može se indeksirati preko naziva varijable:
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Drugi način je korištenje funkcije float() koja pretvara cijeli broj u realni.
Can you write Python code for it?

c=7
d=2
print float(c)/d

print c/float(d)


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Ime varijable je s, a vrijednost varijable je Hello world. Navedeno ime varijable s navedenom vrijednosti te varijable je instanca klase.
s je referenca na objekt tipa string tj. niz znakova.
upper() i replace() su metode koje se mogu koristiti nad objektima tipa string, pa tako onda i nad varijablom s.
Svojstvo objekta je njegov sadržaj, odnosno vrijednost varijable.
replace() je ime metode koja prima dva argumenta (prvi je podniz koji planiramo zamijeniti, a drugi podniz kojim ćemo zamijeniti prvi argument).
Klasa stringa definira da niz znakova mora imati alfanumeričke znakove s bjelinama, crticama i ostalim znakovima, ali ne može sadržavati npr. sliku. Također definira sve metode koje se mogu upotrijebiti nad tom klasom, dok su navedene metode samo dvije od svih mogućih metoda.
1.5. Jednostavni tipovi podataka
Python poznaje sljedeće jednostavne tipove podataka:
* cjelobrojni tip podataka (integer, int)
* realni tip podataka (floating-point number, float)
* niz znakova (string, str)
* logička vrijednost (boolelan).
1.5.1. Cjelobrojni tip podataka
Brojevi pripadaju nepromjenjivim tipovima podataka. U Pythonu se prije razlomačkog dijela broja koristi točka, a ne zarez.
Cjelobrojni tipovi podataka (Integer (computer science) su pozitivni ili negativni cijeli brojevi bez decimalne točke. Za pohranjivanje cjelobrojnog tipa podataka potrebno je 32 bita.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Indeksirati se može i više znakova navodeći raspon indeksa tako da se navede početni indeks od kojeg se kreće, dvotočje te završni indeks do kojeg završava podniz:
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Iz primjera je vidljivo da pomoćna varijabla znak poprima vrijednosti svakog znaka neki niz kroz koji iteriramo, od prvog do posljednjeg. U prvoj iteraciji poprima vrijednost n, u drugoj iteraciji poprima vrijednost e, u trećoj iteraciji poprima vrijednost k i tako sve do posljednjeg znaka niza kroz koji iteriramo. Vrši se onoliko iteracija koliko ima znakova u nizu. Naziv pomoćne varijable znak je proizvoljan.
Moguće je kombinirati if naredbu i for petlju. U sljedećem primjeru ispisat ćemo samo samoglasnike iz niza znakova kroz koji iteriramo:
Can you write Python code for it?

for znak in 'neki niz':
    if znak in 'aeiou':
        print znak


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Kod provjere s brojem 3, logički uvjet nije ispunjen (tj. rezultat logičkog izraza je FALSE), jer 2 nije veći od 5 te se nije ispisao zadani tekst. Kod provjere s brojem 10, logički uvjet je ispunjen (tj. rezultat logičkog izraza je TRUE) te se ispisao zadani tekst.
Na sljedeći način ispisat ćemo "Broj je paran." za sve brojeve koji su parni, a "Broj je neparan." za sve brojeve koji su neparni te provjeriti blok naredbi s brojevima 3 i 10:
Can you write Python code for it?

a=3
if a%2==0:
    print 'Broj je paran.'
else:
    print 'Broj je neparan.'

b=10
if b%2==0:
    print 'Broj je paran.'
else:
    print 'Broj je neparan.'


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Konkatenacija vrši samo spajanje nizova znakova. U slučaju da želimo iz prethodnog primjera dodati razmak, veznik i razmak, potrebno je to izričito navesti.
Can you write Python code for it?

niz1='Ana i Ivo'
niz2='Iva i Jan'
print niz1[:6]+niz2[-3:]


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Liste su promjenjivi tipovi podataka, tako da je moguće vrijednost postojećeg elementa liste promijeniti indeksiranjem tog elementa i dodjeljivanjem nove vrijednosti:
Can you write Python code for it?

lista=['banana',5,98.95]
lista[0]='jabuka'
print lista


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Moguće je pratiti koje vrijednosti poprima brojač i u svakoj iteraciji, tako da se ispiše vrijednost i unutar for petlje:
Can you write Python code for it?

i=0
lista=[1,2,3,4,5]
for element in lista:
    i+=element
    print i


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Možemo izračunati prosječnu duljinu znakova elemenata liste.
Can you write Python code for it?

duljina_znakova=0
lista=['jedan', 'dva', 'tri', 'cetiri']
for element in lista:
    duljina_znakova+=len(element)
print float(duljina_znakova)/len(lista)
print duljina_znakova/len(lista)


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Na sljedeći način se niz znakova Ovo je niz pohranjuje u varijablu nazvanu niz1:
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Nad listama je moguće vršiti konkatenaciju na sljedeći način:
Can you write Python code for it?

lista1=['banana',5,98.95]
lista2=[3,1,5,4,2]
print lista1+lista2


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Osim ovom metodom, elemente liste moguće je brisati putem naredbe del i indeksa elementa:
Can you write Python code for it?

lista5=['banana',5,98.95,'tekst',5]
del lista5[-1]
print lista5


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Prvo je potrebno djeljenik ili djelitelj prebaciti iz cjelobrojne vrijednosti u realni tip podatka, a zatim izvršiti dijeljenje, ako želimo dobiti razlomački dio. Iz posljednjeg primjera vidljivo je da se količnik pretvara u realni tip podatka nakon cjelobrojnog dijeljenja, a on će u tom slučaju uvijek iznositi 0.
1.8.3. Funkcija str()
Funkcija str() pretvara brojčanu vrijednost u niz znakova.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Python razlikuje znamenke pohranjene kao nizove znakova:
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Realna vrijednost -16.85 pohranjuje se u varijablu nazvanu broj2 na sljedeći način:
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Realni brojevi mogu se prikazati od 2,2250738585072014e-308 do 1,7976931348623157e+308. Kad je rezultat operacije nad brojevima prevelik za prikaz u Pythonu, prikaže se vrijednost inf. Slično tome, kad je negativan broj manji od najmanjeg broja koji se može prikazati u Pythonu, prikaže se vrijednost 0.0.
1.5.3. Niz znakova
Niz znakova (string) (String (computer science)) pripadaju nepromjenjivim tipovima podataka koje možemo definirati kao jedan ili više znakova omeđenih jednostrukim (') ili dvostrukim navodnicima (").Ako je niz znakova započet s jednostrukim navodnicima, tada mora i završavati jednostrukim navodnicima. Isto vrijedi i za dvostruke navodnike. Moguće je kombinirati jednostruke i dvostruke navodnike. Ako je niz znakova započet s jednostrukim navodnicima, može sadržavati jedan ili više dvostruki navodnik. Također vrijedi da niz znakova započet dvostrukim navodnicima može sadržavati jedan ili više jednostruki navodnik.
Can you write Python code for it?

'Ovo je niz znakova.'

"Ovo je isto niz znakova."

"Ovo je 'niz znakova' u kojem se nalazi 'kombinacija' navodnika."


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Realno dijeljenje se vrši na dva načina. Jedan način je da jedan operand ima cjelobrojnu vrijednost.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
U ovom primjeru iteriramo kroz listu ['jedan', 'dva', 'tri', 'četiri', 'pet'] i provjeravamo je li dužina elementa liste veća od 3. Ako je veća, onda ispisuje element. U prvoj iteraciji pomoćna varijabla element poprima vrijednost 'jedan'. Zatim se provjerava je li dužina trenutne vrijednosti pomoćne varijable veća od 3. Budući da je jedan ima više od 3 znaka, uvjet je ispunjen i trenutna vrijednost pomoćne varijable element se ispisuje. Kreće druga iteracija u kojoj element poprima vrijednost 'dva'. Zatim se provjerava je li dužina trenutne vrijednosti pomoćne varijable veća od 3. Budući da dva nema više od tri znaka (ima upravo tri znaka, ali ne više od tri znaka), uvjet nije ispunjen te tu završava druga iteracija i kreće treća iteracija. I tako sve do posljednjeg elementa liste.
U sljedećem primjeru ispisat ćemo prvi znak elemenata iz liste indeksiranjem:
Can you write Python code for it?

for element in ['jedan', 'dva', 'tri', 'cetiri', 'pet']:
    print element[0]


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
U ovom primjeru provjeravamo je li broj djeljiv s 2 i (logički operator and) je li broj manji od 10. Tek kada se oba uvjeta ispune, broj množimo s 3. Ako uvjet nije ispunjen, broj množimo s 5.
Na sljedeći način moguće je upotrijebiti logički operator or:
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
U ovom primjeru provjeravamo je li broj djeljiv s 2 ili (logički operator or) je li broj djeljiv s 3. Samo je jedan uvjet potrebno izvršiti kako bi broju zbrojili 4. Ako nije ispunjen ni jedan od uvjeta, oduzima se broj 8.
Na sljedeći način možemo postaviti složeni blok naredbi:
Can you write Python code for it?

g=25
if g%2==0:
    print 'Broj je djeljiv s 2.'
elif g%3==0:
    print 'Broj je djeljiv s 3.'
elif g%5==0:
    print 'Broj je djeljiv s 5.'
elif g%7==0:
    print 'Broj je djeljiv sa 7.'
else:
    print 'Broj nije djeljiv s 2, 3, 5 ni 7.'

h=6
if h%2==0:
    print 'Broj je djeljiv s 2.'
elif h%3==0:
    print 'Broj je djeljiv s 3.'
elif h%5==0:
    print 'Broj je djeljiv s 5.'
elif h%7==0:
    print 'Broj je djeljiv sa 7.'
else:
    print 'Broj nije djeljiv s 2, 3, 5 ni 7.'

i=11
if i%2==0:
    print 'Broj je djeljiv s 2.'
elif i%3==0:
    print 'Broj je djeljiv s 3.'
elif i%5==0:
    print 'Broj je djeljiv s 5.'
elif i%7==0:
    print 'Broj je djeljiv sa 7.'
else:
    print 'Broj nije djeljiv s 2, 3, 5 ni 7.'


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
U ovom primjeru provjeravamo je li broj djeljiv s 2. Ako je taj uvjet ispunjen, provjeravamo je li broj manji od 10. Ako je i taj uvjet ispunjen, broj množimo s 3. Ako broj nije djeljiv s 2, broj množimo s 5.
Isti zadatak moguće je riješiti logičkim operatorom and na sljedeći način:
Can you write Python code for it?

c=6
if c%2==0 and c<10:
    c*=3
else:
    c*=5
print c

d=11
if d%2==0 and c<10:
    d*=3
else:
    d*=5
print d


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Vrijednost liste dodjeljujemo varijabli operatorom pridruživanja =.
Can you write Python code for it?

lista1=['banana',5,98.95]
lista2=[3,1,5,4,2]
lista3=['a','b','c','d','d']
print lista1
print lista2
print lista3


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Zadatke možete naći ovdje: Zadaci
1.10. Rad s listama
Liste (list, sequence) (List) su složeni tipovi podataka koji mogu sadržavati više atomarnih podataka. Liste imaju linearnu strukturu podataka, odnosno elementi u listi poredani su nekim redoslijedom. Svakom elementu u listi dodijeljena je cjelobrojna vrijednost, koja predstavlja poziciju ili indeks elementa. Prvi indeks je 0. Sadržaj elementa tj. njegova vrijednost može se u listi pojaviti više od jednog puta. Elementi liste ne moraju biti isti tip podatka.
Lista se zapisuje u uglatim zagradama, a elementi liste razdvojeni su zarezom.
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Zadatke možete naći ovdje: Zadaci
1.11. Kontrola tijeka
Kontrola tijeka (control flow, flow control) (Control flow) određuje kojim redoslijedom se vrše određene naredbe u računalnom programu. Naredbe kontrola tijeka postavljaju određene uvjete koji se trebaju ispuniti prije njihovog izvršavanja, odnosno, ako se uvjeti ne ispune, naredbe se neće izvršiti. Skup naredbi često je strukturiran u blok naredbi. U sintaksi Pythona blok naredbi definira se uvlakama, a najavljuje se dvotočkom.
Kontrola tijeka izvodi se selekcijom i iteracijom. Selekcija je grananje programa s obzirom na zadovoljenost nekog logičkog uvjeta. Naredba kojom se vrši selekcija naziva se if naredba. Iteracija je uzastopno ponavljanje niza naredbi, a vrši se for petljom ili while petljom.
U ovom poglavlju opisane su dvije naredbe kontrola tijeka:
* if naredba
* for petlja.
1.11.1. if naredba
Naredba kojom se vrši selekcija, odnosno grananje programa s obzirom na zadovoljenost jednog ili više logičkih uvjeta, naziva se if naredbom. Sintaksa naredbe ima jednu obaveznu if izjavu, jednu ili više opcionalnih elif izjava (od else if) i jednu opcionalnu else izjavu. Blok naredbi definiran je uvlakama, a najavljuje se dvotočkom.
Na sljedeći način ispisat ćemo "Broj je veći od 5." za sve brojeve koji su veći od 5 te provjeriti uvjet s brojevima 3 i 10:
Can you write Python code for it?

a=3
if a>5:
    print 'Broj je veći od 5.'

b=10
if b>5:
    print 'Broj je veći od 5.'


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
Zadatke možete naći ovdje: Zadaci
1.6. Varijable
Varijabla je mjesto pohrane kojem je dodijeljen naziv u kojem program može pohraniti dodijeljenu vrijednost te je pročitati i prikazati. Svaki programski jezik ima različita pravila kako se varijable mogu nazivati, unositi i koristiti. Varijabla poprima određenu vrijednost naredbom dodjeljivanja. Naredba dodjeljivanja vrši se operatorom =:
<naziv varijable> = <vrijednost>
1.6.1. Imenovanje varijabli
Prilikom imenovanja varijabli treba imati na umu sljedeće:
* Naziv varijable može sadržavati slova engleske abecede, znamenke i podcrte.
* Python razlikuje velika i mala slova. Nije isto imenovati varijablu "broj", "Broj", "BROJ", "BrOj" i sl.
* Naziv varijable mora početi sa slovom ili podcrtom. Ne može početi sa znamenkom.
* Postoje tzv. rezervirane riječi koje čine sintaksu programskog jezika i koje se ne mogu koristiti kao nazivi varijabli. To su:
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
.
* None se također ne može koristiti za naziv varijable, iako nije rezervirana riječ, već konstanta.
1.6.2. Dodjeljivanje vrijednosti varijabli
Prilikom deklariranja varijable ne navodi se vrsta podataka. Vrijednost koja je navedena prilikom deklariranja varijable određuje kojem tipu podataka pripada varijabla. Vrijednost varijable je moguće mijenjati tijekom izvođenja programa. Također je deklariranjem varijable moguće mijenjati tako i tip podatka varijable.
Kako bi se varijabla mogla koristiti tijekom izvođenja programa, mora biti deklarirana. Varijabla se može deklarirati dodjeljivanjem neke vrijednosti. Na sljedeći način pohranjuje se cjelobrojna vrijednost 9 u varijablu nazvanu broj1:
Can you write Python code for it?


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
ili
Can you write Python code for it?


niz1='Ana i Ivo'
niz2='Iva i Jan'
print niz1[:3]+' i '+niz2[-3:]


I am working on the file "1-Osnove_programiranja.ipynb".
The first task is:
kao, u ovom slučaju realnu vrijednost:
Can you write Python code for it?


I am working on the file "1-Python Crash course/Python-Crash-Course/Python Crash Course Exercises .ipynb".
The first task is:
Create a basic function that returns True if the word 'dog' is contained in the input string. Don't worry about edge cases like a punctuation being attached to the word dog, but do account for capitalization.
Can you write Python code for it?

def findDog(sentence):
    x =  sentence.split()
    for item in x:
        if item == "dog":
            return True

findDog('Is there a dog here?')


I am working on the file "1-Python Crash course/Python-Crash-Course/Python Crash Course Exercises .ipynb".
The first task is:
Create a function that counts the number of times the word "dog" occurs in a string. Again ignore edge cases.
Can you write Python code for it?

countDog('This dog runs faster than the other dog dude!')


I am working on the file "1-Python Crash course/Python-Crash-Course/Python Crash Course Exercises .ipynb".
The first task is:
Create a function that grabs the email website domain from a string in the form:
user@domain.com

So for example, passing "user@domain.com" would return: domain.com
Can you write Python code for it?

def domainGet(name):
    return name.split("@")[1]

domainGet('user@domain.com')


I am working on the file "1-Python Crash course/Python-Crash-Course/Python Crash Course Exercises .ipynb".
The first task is:
Final Problem
You are driving a little too fast, and a police officer stops you. Write a function
  to return one of 3 possible results: "No ticket", "Small ticket", or "Big Ticket".
  If your speed is 60 or less, the result is "No Ticket". If speed is between 61
  and 80 inclusive, the result is "Small Ticket". If speed is 81 or more, the result is "Big    Ticket". Unless it is your birthday (encoded as a boolean value in the parameters of the function) -- on your birthday, your speed can be 5 higher in all
  cases.
Can you write Python code for it?

def caught_speeding(speed, is_birthday):
    if s_birthday == False:
    if speed <= 60:
        return "No ticket"
    elif speed >= 61 and speed <=80:
        return "small ticket"
    elif speed >81:
        return "Big ticket"
    else:
        return "pass"

caught_speeding(81,False)

caught_speeding(81,False)

lst = ["7:00","7:30"]


I am working on the file "1-Python Crash course/Python-Crash-Course/Python Crash Course Exercises .ipynb".
The first task is:
Given the variables:
planet = "Earth"
diameter = 12742

 Use .format() to print the following string:
The diameter of Earth is 12742 kilometers.
Can you write Python code for it?

planet = "Earth"
diameter = 12742

print("The diameter of {} is {} kilometers.".format(planet,diameter))


I am working on the file "1-Python Crash course/Python-Crash-Course/Python Crash Course Exercises .ipynb".
The first task is:
Given this nested dictionary grab the word "hello". Be prepared, this will be annoying/tricky
Can you write Python code for it?


I am working on the file "1-Python Crash course/Python-Crash-Course/Python Crash Course Exercises .ipynb".
The first task is:
Given this nested list, use indexing to grab the word "hello"
Can you write Python code for it?


I am working on the file "1-Python Crash course/Python-Crash-Course/Python Crash Course Exercises .ipynb".
The first task is:
Great job!
Can you write Python code for it?


I am working on the file "1-Python Crash course/Python-Crash-Course/Python Crash Course Exercises .ipynb".
The first task is:
What is the main difference between a tuple and a list?
Can you write Python code for it?

# Tuple is immutable
na = "user@domain.com"
na.split("@")[1]


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
A differenza della discesa al gradiente classico, in questo caso il passo di discesa viene ottenuto combinando il passo standard con il passo all'istante precedente. Per un'introduzione, si vedano i grafici interattivi al seguente link:
Goh, "Why Momentum Really Works", Distill, 2017. http://doi.org/10.23915/distill.00006
Inoltre, a differenza dello scorso tutorial, per eseguire il grafo computazionale useremo una sessione interattiva. L'unica differenza con una sessione classica è che una sessione interattiva si registra automaticamente come sessione di default, permettendo in seguito di eseguire i comandi di TF senza specificare la sessione in uso:
Can you write Python code for it?


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Allenare reti neurali con contrib.learn
Come abbiamo visto, allenare reti neurali in TF è molto semplice, ma definirne la struttura e gestire i dati di training è più convoluto. A questo scopo, sono nate nel tempo numerose API ad alto livello che permettono di lavorare in TF in maniera più astratta e generale, permettendo rapidamente la prototipazione di una rete neurale.
La più famosa di queste, Keras, nasce al di fuori di TF prima di esserne inglobata nelle ultime versioni, e la introdurremo nel prossimo tutorial. Qui ci interessiamo ad un'alternativa, nata all'interno di TF nel modulo contrib.learn. Tutti i moduli all'interno di contrib rappresentano codice più sperimentale (ed in evoluzione), che nei prossimi mesi sarà spostato in modo definitivo nell'API stabile di TF oppure verrà modificato/abbandonato. Tra tutti i moduli presenti, learn rappresenta un'interfaccia ad alto livello per definire stimatori da usare in applicazioni di machine learning. Possiamo pensare a contrib.learn come all'equivalente di scikit-learn all'interno di TF.
Per questo tutorial, replichiamo l'esempio presente sulla documentazione ufficiale di TF:
https://www.tensorflow.org/get_started/tflearn.
Come dataset usiamo Iris, un dataset storico di classificazione, dove il compito è predire la classe di Iris (fra tre possibilità) a partire da quattro misure fisiche. Iniziamo scaricando il dataset di training dal seguente link:
http://download.tensorflow.org/data/iris_training.csv
Possiamo caricare il dataset con una funzione di contrib.learn come segue (ricordatevi di cambiare il percorso):
Can you write Python code for it?

training_set = tf.contrib.learn.datasets.base.load_csv_with_header(
      filename='../../../Downloads/iris_training.csv',
      target_dtype=np.int,
      features_dtype=np.float32)


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Andiamo quindi a creare una rete neurale con due strati nascosti, di 10 neuroni ciascuno:
Can you write Python code for it?

classifier_nn = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
                                              hidden_units=[10, 10],
                                              n_classes=3,
                                              model_dir="tmp/iris_model_nn/")


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Calcoliamo l'accuratezza del modello sui dati di test, ricordandoci di arrotondare le uscite (reali) della rete neurale per ottenere solamente $0$ od $1$:
Can you write Python code for it?

from sklearn import metrics
y_pred = np.round(sess.run(f, feed_dict={X_tf: X_tst}))
print('Final accuracy is: ', metrics.accuracy_score(y_tst, y_pred))


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Come detto prima, per simulare un caso realistico andiamo ad allenare la rete a partire da mini-batch di elementi di training, in modo da diminuire il costo di eseguire un singolo passo di discesa al gradiente. Per fare questo, definiamo una funzione per estrarre questi mini-batch dall'insieme di training:
Can you write Python code for it?

def iterate_minibatches(X, y, batchsize):
    indices = np.arange(len(X))
    np.random.shuffle(indices)
    for start_idx in range(0, len(X) - batchsize + 1, batchsize):
        excerpt = indices[start_idx:start_idx + batchsize]
        yield X[excerpt], y[excerpt]


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Come nell'esempio di regressione lineare, il grafo computazionale inizia dalla definizione di due placeholder corrispondenti al nostro input ed output desiderato:
Can you write Python code for it?

import tensorflow as tf
X_tf = tf.placeholder(tf.float32, [None, 2])
y_tf = tf.placeholder(tf.float32, [None, 1])


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Come si può vedere, la funzione è approssimativamente lineare in un breve intervallo, per poi tendere asintoticamente a -1 o +1 al crescere del suo input. Un'altra funzione molto comune per le reti neurali è la cosiddetta rectified linear unit (o ReLU):
Can you write Python code for it?

plt.figure()
plt.plot(x_range, np.maximum(0.0, x_range))
plt.grid()


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Definiamo una funzione per caricare i dati di test:
Can you write Python code for it?

def get_test_inputs():
    x = tf.constant(test_set.data)
    y = tf.constant(test_set.target)

    return x, y


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Essendo questo un problema di classificazione binaria, come funzione di attivazione in uscita si preferisce una funzione che permetta di ottenere valide probabilità di assegnazione alle classi, come la sigmoide:
Can you write Python code for it?

f = tf.nn.sigmoid(tf.matmul(h, w2) + b2)


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
I modelli presenti in contrib.learn non si limitano a reti neurali, ma includono anche modelli lineari, SVM, algoritmi di clustering, e così via. Ad esempio, possiamo definire un classificatore lineare come segue:
Can you write Python code for it?

classifier_linear = tf.contrib.learn.LinearClassifier(feature_columns=feature_columns,
                                              n_classes=3,
                                              model_dir="tmp/iris_model_linear/")


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Il training di uno stimatore in contrib.learn avviene definendo una funzione di input che si occupi di caricare i dati, preprocessarli, e così via. I dati in output devono essere costanti di TF, come nella funzione che segue:
Can you write Python code for it?

def get_train_inputs():
    x = tf.constant(training_set.data)
    y = tf.constant(training_set.target)

    return x, y


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
In pratica, per definire i vari strati potremmo usare l'interfaccia funzionale definita in layers al posto di definire manualmente le operazioni:
https://www.tensorflow.org/api_docs/python/tf/layers/dense
Vedremo un esempio nel prossimo tutorial.
Ottimizzazione della rete neurale
Passiamo quindi alla definizione della funzione costo. Nel tutorial precedente abbiamo usato l'errore quadratico. Poiché in questo caso l'uscita dalla rete rappresenta delle probabilità, possiamo usare una funzione di errore più specifica a problemi di classificazione.
In particolare, una funzione costo molto comune è la cosiddetta cross-entropia, definita come segue:
$$- \sum_{i=1}^N y_i\log\left(f(\boldsymbol{x}_i)\right) + (1-y_i)\log\left(1-f(\boldsymbol{x}_i)\right) \,.$$
Per un'introduzione visiva su come si possa derivare questa funzione costo, si rimanda al seguente post (in Inglese):
Visual Information Theory.
La sua implementazione in TF è immediata:
Can you write Python code for it?

loss = - tf.reduce_sum(y_tf*tf.log(f) + (1.0-y_tf)*tf.log(1.0 - f))


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
In realtà, questa implementazione diretta non è la più vantaggiosa da un punto di vista computazionale. La motivazione è l'interazione del logaritmo (nella definizione della funzione costo) con l'esponenziale presente nella sigmoide, che matematicamente si annullano a vicenda ma vengono entrambi calcolati da TF in questa implementazione.
TF prevede esplicitamente questo caso, permettendo di definire la cross-entropia direttamente sull'output della rete neurale prima della funzione di attivazione, come segue:
Can you write Python code for it?

# tf.nn.sigmoid_cross_entropy_with_logits(labels=y_tf, logits=tf.matmul(h, w2) + b2)


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Infine, sfruttiamo le funzioni messe a disposizione da contrib.learn per valuturare i modelli:
Can you write Python code for it?

# Evaluate accuracy
accuracy_score_nn = classifier_nn.evaluate(input_fn=get_test_inputs,
                                     steps=1)["accuracy"]

print("\nTest Accuracy: {0:f}".format(accuracy_score_nn))


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Inizializziamo tutte le variabili del grafo:
Can you write Python code for it?


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
L'ottimizzazione è uguale al tutorial sulla regressione lineare, con la differenza che ad ogni iterazione eseguiamo un loop sui mini-batch estratti dal training set, ed usiamo quelli per l'ottimizzazione:
Can you write Python code for it?

loss_history = np.zeros(epochs)
for i in range(epochs):
    loss_history[i] = sess.run(loss, feed_dict={X_tf: X, y_tf: y})
    for xs, ys in iterate_minibatches(X, y, batch_size):
        sess.run(train_step, feed_dict={X_tf: xs, y_tf: ys})


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
La funzione (adattata dal repository di Lasagne) permette di iterare sul training set ritornando gruppi di elementi di dimensione batchsize, il cui valore è a scelta dell'utente. Si noti come i dati vengono mescolati prima di ogni chiamata alla funzione.
Come algoritmo di ottimizzazione, usiamo qualcosa di più evoluto di una discesa al gradiente classica, ovvero una discesa al gradiente con momentum (inerzia in Italiano):
Can you write Python code for it?

train_step = tf.train.MomentumOptimizer(learning_rate=0.01, momentum=0.9).minimize(loss)


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Nel caso in cui le feature non siano tutte continue, l'input restituito dalla funzione sarà un dizionario che associa, a ciascuna feature, la colonna corrispondente del tipo adeguato. Per allenare i classificatori il modulo mette a disposizione una funzione fit, come in scikit-learn:
Can you write Python code for it?

# Allenamento del modello
classifier_nn.fit(input_fn=get_train_inputs, steps=1000)


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Nonostante la sua semplicità, il dataset è impossibile da separare perfettamente con tecniche lineari. Andiamo quindi a costruire una rete neurale con uno strato nascosto per affrontare il problema.
Costruire una rete neurale in TF
Cominciamo riportando il nostro output desiderato come valore a virgola mobile invece di intero, per evitare problemi di compatibilità con le operazioni di TF:
Can you write Python code for it?

import numpy as np
y = y.astype(np.float32).reshape(-1, 1)


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Per testare i modelli, scarichiamo il dataset di test dal seguente link:
http://download.tensorflow.org/data/iris_test.csv
Possiamo quindi caricarlo come prima:
Can you write Python code for it?

test_set = tf.contrib.learn.datasets.base.load_csv_with_header(
      filename='../../../Downloads/iris_test.csv',
      target_dtype=np.int,
      features_dtype=np.float32)


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Possiamo vedere l'evoluzione della funzione costo per assicurarci del buon comportamento dell'algoritmo di ottimizzazione:
Can you write Python code for it?

plt.figure()
plt.semilogy(loss_history)
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.grid()


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Si noti come in questo caso andiamo a specificare in maniera esplicita le dimensioni delle matrici. Per rendere più realistico l'esempio, nel seguito processeremo il dataset in sotto-blocchi (detti mini-batch) di elementi. Per specificare a TF che questi sotto-blocchi potrebbero essere di dimensione variabile, usiamo 'None' come prima dimensione delle matrici.
Definiamo quindi le variabili del nostro strato nascosto, dove per comodità useremo 4 neuroni:
Can you write Python code for it?

W1 = tf.Variable(np.random.randn(2, 4)*0.01, dtype=tf.float32)
b1 = tf.Variable(np.ones([4])*0.01, dtype=tf.float32)


I am working on the file "1-Reti-neurali-feedforward.ipynb".
The first task is:
Una sigmoide è molto simile alla tangente iperbolica, ma il suo output è sempre limitato fra 0 ed 1:
Can you write Python code for it?

plt.figure()
plt.plot(x_range, 1.0/(1.0 + np.exp(-x_range)))
plt.grid()


I am working on the file "1-Working-with-relational-data-using-pandas.ipynb".
The first task is:
Basic Aggregation Operations
Can you write Python code for it?

# Food wise count of likes
food_wise = users_likes_join.groupby('likes')['likes'].count()
food_wise

# Lets sort our data. Default order is ascending
asc_sort = food_wise.sort_values()
asc_sort

# An example for descending
dsc_sort = food_wise.sort_values(ascending=False)
dsc_sort


I am working on the file "1-Working-with-relational-data-using-pandas.ipynb".
The first task is:
Eating your own dog food
The above data has been copy-pasted and hand edited. A problem with this approach is the possibility of data containing more than one like for the same product by the same user. While we can manually check the data the approach will be tedious and untractable as the size of the data increases. Instead we employ pandas itself to indentify duplicate likes by the same person and fix the data accordingly.
Can you write Python code for it?

# DataFrames from native python dictionaries
df_users = pd.DataFrame(users)
df_likes = pd.DataFrame(likes)


I am working on the file "1-Working-with-relational-data-using-pandas.ipynb".
The first task is:
In our fictitious database, Cola and Pepsi seem to be popular among the users who like Coconut.
Can you write Python code for it?

# What is the age group distribution of likes?
users_likes_join.groupby('likes').age.plot(kind='hist', legend=True, figsize=(10, 6))


I am working on the file "1-Working-with-relational-data-using-pandas.ipynb".
The first task is:
In the above we used sort_index instead of sort_values because the groupby operation creates a MultiIndex
on columns user_id, name and age and since age is a part of an index sort_values cannot operate on it.
The head(n) function on a DataFrame returns first n records from the frame and the equivalent function tail(n) returns last n records from the frame.
Can you write Python code for it?

# Oldest user who has at least 2 likes
agg_values[agg_values['likes'] >= 2].head(1)

# Lets augment our data a little more
users = users + [
    { 'id': 7, 'name': 'Yeti', 'age': 40 },
    { 'id': 8, 'name': 'Commander', 'age': 31 },
    { 'id': 9, 'name': 'Jonnah', 'age': 26 },
    { 'id': 10, 'name': 'Hex', 'age': 28 },
    { 'id': 11, 'name': 'Sam', 'age': 33 },
    { 'id': 12, 'name': 'Madan', 'age': 53 },
    { 'id': 13, 'name': 'Harry', 'age': 38 },
    { 'id': 14, 'name': 'Tom', 'age': 29 },
    { 'id': 15, 'name': 'Daniel', 'age': 23 },
    { 'id': 16, 'name': 'Virat', 'age': 24 },
    { 'id': 17, 'name': 'Nathan', 'age': 16 },
    { 'id': 18, 'name': 'Stepheny', 'age': 26 },
    { 'id': 19, 'name': 'Lola', 'age': 31 },
    { 'id': 20, 'name': 'Amy', 'age': 25 },
]

users, len(users)

likes = likes + [
    { 'user_id': 17, 'likes': 'Mango' },
    { 'user_id': 14, 'likes': 'Orange'},
    { 'user_id': 18, 'likes': 'Burger'},
    { 'user_id': 19, 'likes': 'Blueberry'},
    { 'user_id': 7, 'likes': 'Cola'},
    { 'user_id': 11, 'likes': 'Burger'},
    { 'user_id': 13, 'likes': 'Mango'},
    { 'user_id': 1, 'likes': 'Coconut'},
    { 'user_id': 6, 'likes': 'Pepsi'},
    { 'user_id': 8, 'likes': 'Cola'},
    { 'user_id': 17, 'likes': 'Mango'},
    { 'user_id': 19, 'likes': 'Coconut'},
    { 'user_id': 15, 'likes': 'Blueberry'},
    { 'user_id': 20, 'likes': 'Soda'},
    { 'user_id': 3, 'likes': 'Cola'},
    { 'user_id': 4, 'likes': 'Pepsi'},
    { 'user_id': 14, 'likes': 'Coconut'},
    { 'user_id': 11, 'likes': 'Mango'},
    { 'user_id': 12, 'likes': 'Soda'},
    { 'user_id': 16, 'likes': 'Orange'},
    { 'user_id': 2, 'likes': 'Pepsi'},
    { 'user_id': 19, 'likes': 'Cola'},
    { 'user_id': 15, 'likes': 'Carrot'},
    { 'user_id': 18, 'likes': 'Carrot'},
    { 'user_id': 14, 'likes': 'Soda'},
    { 'user_id': 13, 'likes': 'Cola'},
    { 'user_id': 9, 'likes': 'Pepsi'},
    { 'user_id': 10, 'likes': 'Blueberry'},
    { 'user_id': 7, 'likes': 'Soda'},
    { 'user_id': 12, 'likes': 'Burger'},
    {...


I am working on the file "1-Working-with-relational-data-using-pandas.ipynb".
The first task is:
Most of our audience seem to fall in the 25 - 40 years age group. But this visualisation has one flaw - if records are stacked on top of each other, only one of them will be visible. Lets try an alternative plot.
Can you write Python code for it?

users_likes_join.groupby('likes').age.plot(kind='kde', legend=True, figsize=(10, 6))


I am working on the file "1-Working-with-relational-data-using-pandas.ipynb".
The first task is:
QUICK NOTE ABOUT sort_values
By default sort_values allocates new memory each time it is called. While working with larger production data we can be limited by the available memory on our machines vis-a-vis the dataset size (and really we do not wish to hit the SWAP partition even on SSDs). In such a situation, we can set the keyword argument inplace=True, this will modify the current DataFrame it self instead of allocating new memory.
Beware though mutation, while memory efficient, can be a risky affair leading to complex code paths and hard to reason about code.
Can you write Python code for it?

# Using in_place sort for memory efficiency
# Notice there is no left hand side value
food_wise.sort_values(ascending=False, inplace=True)

# food_wise itself has changed
food_wise


I am working on the file "1-Working-with-relational-data-using-pandas.ipynb".
The first task is:
Since pandas DataFrame is a column based abstraction (as against row) we need to reset_index after an aggregation operation in order retrieve flat DataFrame which is convenient to query.
Can you write Python code for it?

# Oldest user who has exactly 2 likes
agg_values = (
    users_likes_join
        .groupby(['user_id', 'name', 'age'])
        .agg({ 'likes': 'count' })
        .sort_index(level=['age'], sort_remaining=False, ascending=False)
)

agg_values[agg_values['likes'] == 2].head(1)


I am working on the file "1-Working-with-relational-data-using-pandas.ipynb".
The first task is:
So there are in all 6 duplicate records. User#2 and Pepsi is recorded twice so that is 1 extra, 2 extra for User#3 and Cola and 1 extra for rest of the three pairs, which equals, 1 + 2 + 1 + 1 + 1 = 6.
Can you write Python code for it?

# Now remove the duplicates
df_unq_likes = df_likes.drop_duplicates()

# The difference should be 6 since 6 records should be eliminated
len(df_unq_likes), len(df_likes)


I am working on the file "1-Working-with-relational-data-using-pandas.ipynb".
The first task is:
We replay our previous aggregation to verify no more duplicates indeed exist.
Can you write Python code for it?

# Join the datasets
users_likes_join = df_users.merge(df_unq_likes, left_on='id', right_on='user_id')
users_likes_join.set_index('id')

# We aggregate the likes column and rename it to `Records`
unq_user_likes_group = (
    users_likes_join
        .groupby(['id', 'name', 'likes'])
        .agg({'likes': 'count'})
        .rename(columns={ 'likes': 'num_likes' })
)

# Should return empty if duplicates are removed
unq_user_likes_group[unq_user_likes_group['num_likes'] > 1]


I am working on the file "1-intro-to-brian-neurons.ipynb".
The first task is:
Adding spikes

So far we haven't done anything neuronal, just played around with differential equations. Now let's start adding spiking behaviour.
Can you write Python code for it?

start_scope()

xlabel('Time (ms)')
ylabel('v');


I am working on the file "1-intro-to-brian-neurons.ipynb".
The first task is:
As you can see in this figure, after the first spike, v stays at 0 for around 5 ms before it resumes its normal behaviour. To do this, we've done two things. Firstly, we've added the keyword refractory=5*ms to the NeuronGroup declaration. On its own, this only means that the neuron cannot spike in this period (see below), but doesn't change how v behaves. In order to make v stay constant during the refractory period, we have to add (unless refractory) to the end of the definition of v in the differential equations. What this means is that the differential equation determines the behaviour of v unless it's refractory in which case it is switched off.
Here's what would happen if we didn't include (unless refractory). Note that we've also decreased the value of tau and increased the length of the refractory period to make the behaviour clearer.
Can you write Python code for it?

start_scope()

tau = 5*ms

axhline(0.8, ls=':', c='g', lw=3)
xlabel('Time (ms)')
ylabel('v')
print("Spike times:",)


I am working on the file "1-intro-to-brian-neurons.ipynb".
The first task is:
By default, all variables start with the value 0. Since the differential equation is dv/dt=(1-v)/tau we would expect after a while that v would tend towards the value 1, which is just what we see. Specifically, we'd expect v to have the value 1-exp(-t/tau). Let's see if that's right.
Can you write Python code for it?

print('Expected value of v =', 1-exp(-100*ms/tau))


I am working on the file "1-intro-to-brian-neurons.ipynb".
The first task is:
First off, ignore that start_scope() at the top of the cell. You'll see that in each cell in this tutorial where we run a simulation. All it does is make sure that any Brian objects created before the function is called aren't included in the next run of the simulation.
So, what has happened here? Well, the command run(100*ms) runs the simulation for 100 ms. We can see that this has worked by printing the value of the variable v before and after the simulation.
Can you write Python code for it?

print('Before v =',)

print('After v =',)


I am working on the file "1-intro-to-brian-neurons.ipynb".
The first task is:
Good news, the simulation gives the value we'd expect!
Now let's take a look at a graph of how the variable v evolves over time using StateMonitor().
Can you write Python code for it?


I am working on the file "1-intro-to-brian-neurons.ipynb".
The first task is:
So what's going on here? The behaviour for the first spike is the same: v rises to 0.8 and then the neuron fires a spike at time 8 ms before immediately resetting to 0. Since the refractory period is now 15 ms this means that the neuron won't be able to spike again until time 8 + 15 = 23 ms. Immediately after the first spike, the value of v now instantly starts to rise because we didn't specify (unless refractory) in the definition of dv/dt. However, once it reaches the value 0.8 (the dashed green line) at time roughly 8 ms it doesn't fire a spike even though the threshold is v>0.8. This is because the neuron is still refractory until time 23 ms, at which point it fires a spike.
Note that you can do more complicated and interesting things with refractoriness. See the full documentation for more details about how it works.
Multiple neurons
So far we've only been working with a single neuron. Let's do something interesting with multiple neurons.
Can you write Python code for it?

start_scope()

N = 100

xlabel('Time (ms)')
ylabel('Neuron index');


I am working on the file "1-intro-to-brian-neurons.ipynb".
The first task is:
The SpikeMonitor object takes the group whose spikes you want to record as its argument and stores the spike times in the variable t. Let's plot those spikes on top of the other figure to see that it's getting it right.
Can you write Python code for it?

start_scope()

#axvline(t/ms, ls='--', c='r', lw=3)
xlabel('Time (ms)')
ylabel('v');


I am working on the file "1-intro-to-brian-neurons.ipynb".
The first task is:
The line v0 : 1 declares a new per-neuron parameter v0 with units 1 (i.e. dimensionless).
The line G.v0 = 'i*v0_max/(N-1)' initialises the value of v0 for each neuron varying from 0 up to v0_max. The symbol i when it appears in strings like this refers to the neuron index.
So in this example, we're driving the neuron towards the value v0 exponentially, but we fire spikes when v crosses v>1 it fires a spike and resets. The effect is that the rate at which it fires spikes will be related to the value of v0. For v0<1 it will never fire a spike, and as v0 gets larger it will fire spikes at a higher rate. The right hand plot shows the firing rate as a function of the value of v0. This is the I-f curve of this neuron model.
Note that in the plot we've used the count variable of the SpikeMonitor: this is an array of the number of spikes each neuron in the group fired. Dividing this by the duration of the run gives the firing rate.
Stochastic neurons
Often when making models of neurons, we include a random element to model the effect of various forms of neural noise. In Brian, we can do this by using the symbol xi in differential equations. Strictly speaking, this symbol is a "stochastic differential" but you can sort of thinking of it as just a Gaussian random variable with mean 0 and standard deviation 1. We do have to take into account the way stochastic differentials scale with time, which is why we multiply it by tau**-0.5 in the equations below (see a textbook on stochastic differential equations for more details).
Can you write Python code for it?

start_scope()

N = 100
tau = 10*ms
v0_max = 3.
duration = 1000*ms
sigma = 0.2

run(duration)

figure(figsize=(12,4))
subplot(121)
#plot(M.t/ms, M.i, '.k')
xlabel('Time (ms)')
ylabel('Neuron index')
subplot(122)
#plot(G.v0, M.count/duration)
xlabel('v0')
ylabel('Firing rate (sp/s)')


I am working on the file "1-intro-to-brian-neurons.ipynb".
The first task is:
This shows a few changes. Firstly, we've got a new variable N determining the number of neurons. Secondly, we added the statement G.v = 'rand()' before the run. What this does is initialise each neuron with a different uniform random value between 0 and 1. We've done this just so each neuron will do something a bit different. The other big change is how we plot the data in the end.
As well as the variable spikemon.t with the times of all the spikes, we've also used the variable spikemon.i which gives the corresponding neuron index for each spike, and plotted a single black dot with time on the x-axis and neuron index on the y-value. This is the standard "raster plot" used in neuroscience.
Parameters
To make these multiple neurons do something more interesting, let's introduce per-neuron parameters that don't have a differential equation attached to them.
Can you write Python code for it?

start_scope()

N = 100
tau = 10*ms
v0_max = 3.
duration = 1000*ms

figure(figsize=(12,4))
subplot(121)
#plot(M.t/ms, M.i, '.k')
xlabel('Time (ms)')
ylabel('Neuron index')
subplot(122)
#plot(G.v0, M.count/duration)
xlabel('v0')
ylabel('Firing rate (sp/s)')


I am working on the file "1-intro-to-brian-neurons.ipynb".
The first task is:
This time we only ran the simulation for 30 ms so that we can see the behaviour better. It looks like it's behaving as expected, but let's just check that analytically by plotting the expected behaviour on top.
Can you write Python code for it?

start_scope()

xlabel('Time (ms)')
ylabel('v')
legend(loc='best')


I am working on the file "1-intro-to-brian-neurons.ipynb".
The first task is:
We've added two new keywords to the NeuronGroup declaration: threshold='v>0.8' and reset='v = 0'. What this means is that when v>1 we fire a spike, and immediately reset v = 0 after the spike. We can put any expression and series of statements as these strings.
As you can see, at the beginning the behaviour is the same as before until v crosses the threshold v>0.8 at which point you see it reset to 0. You can't see it in this figure, but internally Brian has registered this event as a spike. Let's have a look at that.
Can you write Python code for it?


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
A section of an array is called a slice. We can take slices of character strings as well:
python
element = 'oxygen'
print('first three characters:', element[0:3])
print('last three characters:', element[3:6])
first three characters: oxy
last three characters: gen
What is the value of element[:4]? What about element[4:]? Or element[:]?
What is element[-1]? What is element[-2]? Given those answers, explain what element[1:-1] does.
Can you write Python code for it?

element = 'oxygen'
print('first three characters:', element[0:3])
print('last three characters:', element[3:6])

print(element[:4])
print(element[4:])

print(:)

#oxygen
print(element[-1])
print(element[-2])
print(element[2:-1])

doubledata = data * 2.0 #we can perform math on array


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
Importing a library akin to getting lab equipment out of a locker and setting up on bench
Libraries provide additional functionality
With NumPy loaded we can read the CSV into python.
Can you write Python code for it?

#assuming the data file is in the data/ folder
numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',')


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
What does the following program print out?
python
first, second = 'Grace', 'Hopper'
third, fourth = second, first
print(third, fourth)
Can you write Python code for it?

print(data)

print(type(data)) #we can get type of object


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
avg per day across all patients in the var day_avg_plot
matplotlib create and display a line graph of those values
Can you write Python code for it?

data.mean(axis=0).shape

data.shape

data.mean(axis=1).shape

max_plot = plt.plot(data.max(axis=0))


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
data has 60 rows and 40 columns
when we created data with numpy it also creates members or attributes
extra info describes data like adjective does a noun
dot notation to access members
Can you write Python code for it?

print('first value in data', data[0,0]) #use index in square brackets

print('4th value in data', data[0,3]) #use index in square brackets

print('first value in 3rd row data', data[3,0]) #use index in square brackets

!head -3 data/inflammation-01.csv

print('middle value in data', data[30,20]) # get the middle value - notice here i didn't use print


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
however, we are usually more interested in partial stats, e.g. max value per patient or the avg value per day
we can create a new subset array of the data we want
Can you write Python code for it?

%matplotlib inline

import matplotlib.pyplot as plt

data


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
mean is a method of the array (function)
variables are nouns, methods are verbs - they are what the thing knows how to do
for mean we need empty () parense even if we aren't passing in parameters to tell python to go do something
data.shape doesn't need () because it's just a description
NumPy arrays have lots of useful methods:
Can you write Python code for it?

print('maximum inflammation: ', data.max())
print('minimum inflammation: ', data.min())
print('standard deviation:', data.std())


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
nice, but ipython/jupyter proved us with 'magic' functions and one lets us display our plot inline

% indicates an ipython magic function

what if we need max inflammation for all patients, or the average for each day?

most array methods let us specify the axis we want to work on
Can you write Python code for it?

avg_inflam = data.mean(axis=0) #asix zero is by each day

print(data.mean(axis=0))

print(data.mean(axis=0).shape) #Nx1 vector of averages

print(data.mean(axis=1)) #avg inflam per patient across all days

print(data.mean(axis=1).shape)


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
now let's look at avg inflammation over days (columns)
Can you write Python code for it?

print(avg_inflam)

day_avg_plot = plt.plot(avg_inflam)


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
numpy.loadtex() is a function call, runs loadtxt in numpy
uses dot notation to access thing.component
two parameters: filename and delimiter - both character strings (")
we didn't save in memory using a variable
variables in python must start with letter & are case sensitive
assignment operator is =
let's look at assigning this inflammation data to a variable
Can you write Python code for it?

data = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',')

print(data)

weight_kg = 55 #assigns value 55 to weight_kg

print(weight_kg) #we can print to the screen

print("weight in kg", weight_kg)

weight_kg = 70

print("weight in kg", weight_kg)


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
operation on arrays is done on each individual element of the array
Can you write Python code for it?

doubledata

data[:3, 36:]

doubledata[:3, 36:]


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
print above shows several things at once by separating with commas
variable as putting sticky note on value
means assigning a value to one variable does not chage the value of other variables.
Can you write Python code for it?

weight_kg * 2

weight_lb = weight_kg * 2.2

print('weigh in lb:', weight_lb)

print("weight in lb:", weight_kg*2.2)

print(data)


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
programming languages like MATLAB and R start counting at 1
languages in C family (C++, Java, Perl & python)
we have MxN array in python, indices go from 0 to M-1 on the first axis and 0 to N-1 on second
indices are (row, column)
Can you write Python code for it?

data[0:4, 0:10] #select whole sections of matrix, 1st 10 days & 4 patients


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
we can do more than simple arithmetic
let's take average inflammation for patients
Can you write Python code for it?


I am working on the file "1-intro-to-numpy-short.ipynb".
The first task is:
whos #ipython command to see what variables & mods you have
Can you write Python code for it?


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
A section of an array is called a slice. We can take slices of character strings as well:
python
element = 'oxygen'
print('first three characters:', element[0:3])
print('last three characters:', element[3:6])
first three characters: oxy
last three characters: gen
What is the value of element[:4]? What about element[4:]? Or element[:]?
What is element[-1]? What is element[-2]? Given those answers, explain what element[1:-1] does.
Can you write Python code for it?


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
Importing a library akin to getting lab equipment out of a locker and setting up on bench
Libraries provide additional functionality
With NumPy loaded we can read the CSV into python.
Can you write Python code for it?


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
data refers to N-dimensional array
data corres. to patients' inflammation
let's look at the shape of the data
Can you write Python code for it?


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
however, we are usually more interested in partial stats, e.g. max value per patient or the avg value per day
we can create a new subset array of the data we want
Can you write Python code for it?

patient_0 = data[0, :] #0 on first axis, everythign on second
print('maximum inflammation for patient 0: ', patient_0.max())


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
let's visualize this data with matplotlib library
first we import the plyplot module from matplotlib
Can you write Python code for it?

import matplotlib.pyplot

image = matplotlib.pyplot.imshow(data)

matplotlib.pyplot.imshow?


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
max vals rise and falls smoothly, while min seems to be a step function

neither seem likely

we can group into a single figure using subplots

script below uses a number of new commands
matplotlib.pyplot.figure() create the plotting space
figsize tells python how big
each plot is placed into the figure using add_subplot
1st val = how many rows, 2nd refers to the total number of subplot columns, 3rd denotes which plot you are referencing (left to right)
each plot in a diff variable (axes1, axes2, axes3)
we set_xlabel() & set_ylabel set the titles fo the axes
Can you write Python code for it?

import numpy
import matplotlib.pyplot

data = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',')

fig = matplotlib.pyplot.figure(figsize=(10.0, 3.0))

axes1 = fig.add_subplot(1, 3, 1)
axes2 = fig.add_subplot(1, 3, 2)
axes3 = fig.add_subplot(1, 3, 3)

axes1.set_ylabel('average')
axes1.plot(data.mean(axis=0))

axes2.set_ylabel('max')
axes2.plot(data.max(axis=0))

axes3.set_ylabel('min')
axes3.plot(data.min(axis=0))

fig.tight_layout()

matplotlib.pyplot.show()


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
mean is a method of the array (function)
variables are nouns, methods are verbs - they are what the thing knows how to do
for mean we need empty () parense even if we aren't passing in parameters to tell python to go do something
data.shape doesn't need () because it's just a description
NumPy arrays have lots of useful methods:
Can you write Python code for it?


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
now let's look at avg inflammation over days (columns)
Can you write Python code for it?

ave_inflammation = data.mean(axis = 0)
ave_plot = matplotlib.pyplot.plot(ave_inflammation)
matplotlib.pyplot.show(ave_plot)


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
operation on arrays is done on each individual element of the array
Can you write Python code for it?


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
print above shows several things at once by separating with commas
variable as putting sticky note on value
means assigning a value to one variable does not chage the value of other variables.
Can you write Python code for it?

weight_lb = 2.2 * weight_kg #example let's store patients weight in pounds
print('weight in kilograms: ', weight_kg, 'and in pounds', weight_lb)

weight_kg = 100.0 #now change weight_kg
print('weight in kilograms is now:', weight_kg, 'and weight in pounds is still:', weight_lb)


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
programming languages like MATLAB and R start counting at 1
languages in C family (C++, Java, Perl & python)
we have MxN array in python, indices go from 0 to M-1 on the first axis and 0 to N-1 on second
indices are (row, column)
Can you write Python code for it?


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
slice 0:4 means start at 0 and go up to but not include 4
up-to-but-not-including takes a bit of getting used to
Can you write Python code for it?


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
we can also assign an array of values to a variable
rerung numpy.loadtxt and save its result
Can you write Python code for it?

data = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',')

print(data) #statement above doesn't produce output, let's pring

print(type(data)) #we can get type of object


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
we can also do arithmetic operation with another array of same shape (same dims)
Can you write Python code for it?

tripledata = doubledata + data

print('tripledata:')
print(tripledata[:3, 36:])


I am working on the file "1-intro-to-numpy.ipynb".
The first task is:
we can do more than simple arithmetic
let's take average inflammation for patients
Can you write Python code for it?


I am working on the file "1-invitation-to-probability.ipynb".
The first task is:
Exercise 1.1

Compute the Bayesian credible intervals which contain 90% of the probability at each iteration and plot the result
Compute the entropy of the posterior distribution at each stage. How do you interpret changing entropy values ?
How would you answer the question "is this a fair coin" after this analysis ?

Why we need probabilistic programming
Can you write Python code for it?

X = stats.bernoulli(0.5) # one fair coin
Y = stats.bernoulli(0.5) # another fair coin

# want a new random variable which is their sum
Z = Y + X


I am working on the file "1-invitation-to-probability.ipynb".
The first task is:
Random variables in python

The probability that a random variable $X$ takes on a value $X=x$ is given by $P(x)$

A random variable is not a number, but rather, the pair consisting of the variable and its probability distribution
Probabilities always sum to one : $\sum_x P(x) = 1$
Random variables can be discrete or continuous, according to the values the random variable can assume.
Discrete random variable - coin tosses, die rolls,  ...
Continuous random variable - rainfall, temperature, financial indices ...
Can you write Python code for it?

# the scipy.stats package has many discrete and continuous random variables

# the coin toss random variable
X = stats.bernoulli(p=0.5)

# bernoulli mean = p, variance = p(1-p)
#X.mean(), X.var()

# entropy = -\sum_x p(x) * ln p(x)
# quantifies the uncertainty in the random variable
#X.entropy()

# lots of throws of the coin
x = X.rvs(1000)

# the empirical frequency distribution - aka the histogram
pylab.rcParams['figure.figsize'] = 6, 4 # medium size figures
plt.hist(x, normed = True, color="#348ABD", alpha = 0.4);

# the 'central limit theorem' random variable
X = stats.norm()

# the normal deviate has zero mean and unit variance
#X.mean(), X.var()

# the normal deviate has the greatest entropy amongst all continuous, unbounded
# random variables with given mean and variance
# see Jaynes - Probability theory, the logic of science - for proof and discussion

#X.entropy()

# a million draws from the normal distribution
x = X.rvs(1e6)

# the empirical frequency distribution - aka the histogram
pylab.rcParams['figure.figsize'] = 6, 4 # medium size figure
plt.hist(x, bins = 50, normed = True, color="#348ABD", alpha = 0.4 );