4 ** 3 # output is int
2 + 3.4 ** 2 # output is float
(1 + 1j) ** 2 # output is complex
# Define string
a = "Hello, egg world!"
# Find position of 'egg' word
pos = a.index('egg')
# Make new string
new_string = a[:pos] + a[pos+4:]
# Print out to check
print(new_string)
s = "CAGTACCAAGTGAAAGAT"
s.count("A")
a = [1, 2, 3]
b = [4, 5, 6]
a + b
x = 3.7
(x > 3.4 and x <= 6.6) or x == 2
words = {}
words['Table'] = 'Tisch'
words['Chair'] = 'Stuhl'
words['Snake'] = 'Schlange'
words['Chair']
for i in range(2, 51): # just to 50 for this example
# Set is_prime 'flag' to initial value
is_prime = True
# Try and divide i by all values between 2 and i-1, and if none of them
# work, then the value is prime.
for j in range(2, i):
# Check if i is divisible by j
if i % j == 0:
is_prime = False
break
if is_prime:
print(i)
There are other ways of doing this, e.g.:
for i in range(2, 51):
for j in range(2, i):
if i % j == 0:
break
else: # this gets executed if break is not called
print(i)
a = 0
b = 1
while a < 100000:
print(a)
c = a # save a to old variable
a = b
b = c + b
Even simpler:
a, b = 0, 1
while a < 100000:
print(a)
a, b = b, a + b
With a list:
fib = [0, 1]
while fib[-1] + fib[-2] < 100000:
fib.append(fib[-1] + fib[-2])
print(fib)
def is_prime(x):
for j in range(2, x):
if x % j == 0:
return False
return True
is_prime(7)
With loop
def factorial(x):
fact = 1
for i in range(1,x+1):
fact = fact * i
return fact
Without loop
def factorial(x):
if x > 0:
return x * factorial(x - 1)
else:
return 1
def mean(x):
return sum(x) / float(len(x))
mean([1, 3, 4, 5, 6, 7])
import math
math.cos(math.radians(60))
math.sin(math.pi / 6)
import numpy as np
np.logspace(-20, -10, 11)
np.repeat(2, 10)
np.empty(10) # sometimes returns values != 0 because uninitialized
np.zeros(5, dtype=np.float32)
x = np.random.random(10)
x[1:] - x[:-1]
np.diff(x)
filename = "data/vienna_daily_temperatures_with_bad_data.txt"
date, tmin, tmax = np.loadtxt(filename, unpack=True)
keep = np.abs(tmax) < 50
date_good = date[keep]
tmax_good = tmax[keep]
# The following code reads in the file and removes bad values
date, tmin, tmax = np.loadtxt('data/vienna_daily_temperatures_with_bad_data.txt', unpack=True)
keep = np.abs(tmax) < 90
date = date[keep]
tmax = tmax[keep]
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot(date, tmax, '.')
plt.plot(date % 1, tmax, '.')
def gaussian(x, amplitude, offset, sigma):
return 1. / np.sqrt(2 * np.pi) / sigma * np.exp(-0.5 * (x - offset) ** 2 / sigma ** 2)
values = np.random.normal(0, 1, 100000)
h = plt.hist(values, bins=100, normed=True)
x = np.linspace(-5, 5, 100)
plt.plot(x, gaussian(x, 1, 0, 1), color='red', lw=2)
total = np.zeros(10000)
values = np.random.random(10000)
total = total + values
h = plt.hist(total, bins=30)
values = np.random.random(10000)
total = total + values
h = plt.hist(total / 2., bins=30)
for iter in range(8): # already did it twice
values = np.random.random(10000)
total = total + values
h = plt.hist(total / 10., bins=30)