## Learning Python from the Codeschool

There is a funny women on the Web that give lessons of Python and I really enjoy to see her videos and challenges. It is not the traditional professor with a blackboard in behind. Here are some challenges that I resolved as a Python beginner:

#### 1.2 Happy Birthday

>>>2016 - 1732
284


#### 1.3 Your Age in Dog Years

284/7
40.5714

#### 1.4 Calculating British Money Spent

>>> 200*0.65
130.0
>>> (200-2)*0.65
128.70000000000002
>>> ((200-2)*0.65)-100
28.700000000000017

#### 1.6 Naming Variables

us_currency

#### 1.7 Variable Calculations

70

#### 1.8 Exchange Rate Calculations

x_rate = 0.65
total_usd = 200
fee_usd = 2
total_gbp = (total_usd - fee_usd)*x_rate

#### 1.9 Exchange Rate Calculations 2

>>> total_usd
42.15384615384618
>>> import math
>>> math.ceil(total_usd)
43

#### 2.2 Print Output

G'day

#### 2.3 String Concatenation

greeting = "G'day"
new_string = 'mate'
print (greeting+' '+new_string)

#### 2.4 Cast Number to String

str(number)

#### 2.5 Getting Started With Python Strings

name = "Friends"
description = "a group of friends, lives in NY"
year = 2000
sentence = "My favorite sketch is "+name+" where "+description+"in "+str(year)+"."
print(sentence)

#### 2.6 String Formatting

movie1 = "The planet of apes"
movie2 = "La vita e bela"
print ("My Favorite Movies:\n\t",movie1,"\n\t",movie2)

#### 2.8 Slicing to Create a Substring

sub_word = word[2:6]

#### 2.9 Pythonese

word = 'Python'
first = word[0]
rest = word[1:]
result = rest+"-"+first+"y"
print(result)

#### 3.2 Choosing the Right Conditional Operator

answer = 5 < 10
answer = 5<=10

#### 3.3 Comparison Operators

answer = 5 == 5
print(answer)

#### 3.4 If Else

rain_speed = 7
if rain_speed < 5:
print ("Just a Scotch mist")
else:
print ("It's a real Cow-quaker out there")

#### 3.6 If Elif Else

Hola

#### 3.7 Input

name = input('Enter your name')

#### 3.8 Rock-Paper-Python

computer_choice = 'rock'
user_choice = input("Enter rock, paper, or python:\n")
if computer_choice == user_choice:
print('TIE')
else:
print("You lose :( Computer wins :D")

#### 3.9 Improving Rock-Paper-Python

computer_choice = 'rock'
user_choice = input("Enter rock, paper, or python:\n")
if computer_choice == user_choice:
print('TIE')
elif user_choice == 'rock' and computer_choice == 'python':
print('WIN')
elif user_choice == 'paper' and computer_choice == 'rock':
print('WIN')
elif user_choice == 'python' and computer_choice == 'paper':
print('WIN')
else:
print('You lose :( Computer wins :D')

## Study Drills resolutions from “Learn Python the hard way”

I have been practicing more details relating to Python and this time I want to summarize all the drills or little challenges that the Website provides:

Exercise 1: A Good First Program

1. Make your script print another line.
print "Hello World!"
print "Hello Again"
print "I like typing this"
print "This is fun."
print 'Yay! Printing.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
print 'What about "this new line"'

2. Make your script print only one of the lines.

#print "Hello World!"
#print "Hello Again"
print "I like typing this"
#print "This is fun."
#print 'Yay! Printing.'
#print "I'd much rather you 'not'."
#print 'I "said" do not touch this.'
#print 'What about "this new line"'

3. Put a # (octothorpe) character at the beginning of a line. What did it do? Try to find out what this character does.

#print "Hello World!"
#print "Hello Again"
#print "I like typing this"
#print "This is fun."
#print 'Yay! Printing.'
#print "I'd much rather you 'not'."
#print 'I "said" do not touch this.'
#print 'What about "this new line"'

Exercise 2: Comments and Pound Characters

1. Find out if you were right about what the # character does and make sure you know what it’s called (octothorpe or pound character).
2. Take your ex2.py file and review each line going backward. Start at the last line, and check each word in reverse against what you should have typed.
3. Did you find more mistakes? Fix them.
4. Read what you typed above out loud, including saying each character by its name. Did you find more mistakes? Fix them.
print "This will run."
#print "This won't run."
#You can also use a comment to "disable" or comment out a piece of code:
print "I could have code like this." # and the comment after is ignored
#Anything after the # is ignored by python.
#A comment, this is so you can read your program later.
• The output was different from ex2.py by just switching the order of the sentences.

Exercise 3: Numbers and Math

1. Above each line, use the # to write a comment to yourself explaining what the line does.
#This will print a message to introduce my counting method for chickens
print "I will now count my chickens

2. Remember in Exercise 0 when you started python? Start python this way again and using the math operators, use Python as a calculator.

python
>>> 3 == 3 > 3 == 3
False
>>> print "The square of 5 is",5**2
The square of 5 is 25

3. Find something you need to calculate and write a new .py file that does it.

4. Notice the math seems “wrong”? There are no fractions, only whole numbers. You need to use a “floating point” number, which is a number with a decimal point, as in 10.5, or 0.89, or even 3.0.

5. Rewrite ex3.py to use floating point numbers so it’s more accurate. 20.0 is floating point.

print "Is it greater?", 5.0 > -2
print "Is it greater or equal?", 5.0 >= -2
print "Is it less or equal?", 5.0 <= -2

Exercise 4: Variables And Names

1. I used 4.0 for space_in_a_car, but is that necessary? What happens if it’s just 4?
• The fourth output changed with this message “We can transport 120 people today.”

2. Remember that 4.0 is a floating point number. It’s just a number with a decimal point, and you need 4.0 instead of just 4 so that it is floating point.

3. Write comments above each of the variable assignments.

4. Make sure you know what = is called (equals) and that it’s making names for things.

5. Remember that _ is an underscore character.

6. Try running python from the Terminal as a calculator like you did before and use variable names to do your calculations. Popular variable names are also i, x, and j.

python
Python 2.7.6 (default, Sep  9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
>>> x = 3.0
>>> y = x + 3
>>> print x - y
-3.0

Exercise 5: More Variables and Printing

1. Change all the variables so there is no my_ in front of each one. Make sure you change the name everywhere, not just where you used = to set them.
name = 'Zed A. Shaw'
age = 35 #not a lie
height = 74 #inches
weight = 180 #lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print "Let's talk about %s." % name
print "He's %d inches tall." % height
print "He's %d pounds heavy." % weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (eyes,hair)
print "His teeth are usually %s depending on the coffee" % teeth
#this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." %(age,height,weight,age+height+weight)

2. Try to write some variables that convert the inches and pounds to centimeters and kilograms. Do not just type in the measurements. Work out the math in Python.

name = 'Zed A. Shaw'
age = 35 #not a lie
height = 74 * 2.54 #inches to cm
weight = 180 * 0.4536 #lbs to kg
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print "Let's talk about %s." % name
print "He's %f cm tall." % height
print "He's %f kg heavy." % weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (eyes,hair)
print "His teeth are usually %s depending on the coffee" % teeth
#this line is tricky, try to get it exactly right
print "If I add %d, %f, and %f I get %f." %(age,height,weight,age+height+weight)

3. Search online for all of the Python format characters.

#### The format characters of Python are following by % like %s %f %d and then before variables as %  eyes.

4. Try more format characters. %r is a very useful one. It’s like saying “print this no matter what.”

name = 'Zed A. Shaw'
age = 35 #not a lie
height = 74 * 2.54 #inches to cm
weight = 180 * 0.4536 #lbs to kg
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print "Let's talk about %r." % name
print "He's %r cm tall." % height
print "He's %r kg heavy." % weight
print "Actually that's not too heavy."
print "He's got %r eyes and %r hair." % (eyes,hair)
print "His teeth are usually %r depending on the coffee" % teeth
#this line is tricky, try to get it exactly right
print "If I add %r, %r, and %r I get %r." %(age,height,weight,age+height+weight)

### Exercise 6: Strings and Text

1. Go through this program and write a comment above each line explaining it:
#It's going to print 10 types of people instead of saying 2 in dec
x= "There are %d types of people" % 10
#String variables as binary and do_not are going be stored
binary = "binary"
do_not = "don't"
#This new message is going to be stored in y
y = "Those who know %s and those who %s." % (binary, do_not)
#Printing x and y to show the previous messages with the variables
print x
print y
#x is going to print and use %r instead of %s, y keep its format
print "I said: %r" %x
print "I also said: %s" %y
#hilarious is setting with boolean value
hilarious = False
#Define a variable which contains a sentence and waits for a value
joke_evaluation = "Isn't that joke so funny?! %r"
#Print the call of joke_evaluation with the hilarious value: False
print joke_evaluation % hilarious
#Set two sentences and stored in variables w and e
w = "This is the left side of ... "
e = "a string with a right side"
#Join the two previous sentences stored in w and e, shows together
print w + e

2. Find all the places where a string is put inside a string. There are four places.

y = "Those who know %s and those who %s." % (binary, do_not)
print "I said: %r" %x
print "I also said: %s" %y
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious



3. Are you sure there are only four places? How do you know? Maybe I like lying.

#### I think, there are five sentences inside other sentence.

4. Explain why adding the two strings w and e with + makes a longer string.

### Exercise 7: More Printing

1. Go back through and write a comment on what each line does.
#printing a sentence related to Mary and her little lamb
print "Mary had a little lamb"
print "Its fleece was white as %s " % 'snow'
print "And everywhere that Mary went"
print "."* 10 # this print 10 point, because . is multiplied by 10
#In this case a character is going to be stored in a variable end
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
#A comma at the end allows the next characters be in the same line
print end1 + end2 + end3 + end4 + end5 + end6,
print end7 + end8 + end9 + end10 + end11 + end12

2. Read each one backward or out loud to find your errors.

3. From now on, when you make mistakes, write down on a piece of paper what kind of mistake you made.

#### I missed the ‘ ‘ when I wrote the snow variable in the third line.

4. When you go to the next exercise, look at the mistakes you have made and try not to make them in this new one.

5. Remember that everyone makes mistakes. Programmers are like magicians who fool everyone into thinking they are perfect and never wrong, but it’s all an act. They make mistakes all the time.

Exercise 8: Printing, Printing

formatter = "%r %r %r %r"
print formatter % (1,2,3,4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter %(
"That you could type up right",
"But it didn't sing.",
"So I said goodnight."
)
1. Do your checks, write down your mistakes, and try not to make the same mistakes on the next exercise.  – I missed the last parenthesis at the end of the example

2. Notice that the last line of output uses both single-quotes and double-quotes for individual pieces. Why do you think that is?   – I do not know –        This is my output  –>

1 2 3 4
'one' 'two' 'three' 'four'
True False False True
'I had this thing' 'That you could type up right' "But it didn't sing." 'So I said goodnight.'
• Finally, I was able to accomplish my first little Python challenge in minutes:

## Anagrams

def anagrama(L):
l = []
for i in range(len(L)):
l.append(set(L[i]))
if all( x == l[0] for x in l):
print "It is an anagram"
else:
print "It is not anagram"

anagrama(['naaa','ana','annn','naaan'])

## Resolution of the Challenges/Kata CODEWARS – Python

During my training of Python I also used Codewars Web and these are the blocks I solved:

 def multiply(a,b):
return a * b

Correct this code, so that the greet function returns the expected value:

class Person:
def __init__(self, name):
self.name = name
def greet(self,other_name):
return "Hi {0}, my name is {1}".format(other_name,self.name)

Vampire Numbers

def vampire_test(x,y):
prd = x * y
num_prd= list(str(prd))
num_xy = list(str(x))+list(str(y))
if sorted(num_prd)==sorted(num_xy) and len(num_xy)==len(num_prd):
return True
else:
return False

Making Copies

def copy_list(l):
"Make a copy of a list of numbers"
copy = []
for i in l:
copy.append(i)
return copy

Ghostbusters (whitespace removal)

def ghost(phrase):
for i in list(phrase):
if i != " ":
print i,

Character Counter

def validate_word(word):
match = []
word = word.upper()
if " " not in word and len(word) in range(0,100):
for i in word:
match.append(word.count(i))
if (match[1:] == match[:-1]):
return True
else:
return False
else:
return False

UVB-76 Message Validator

def validate(message):
l = message.split()
if len(l) != 8:
return False
if l[0] != "MDZHB":
return False
if not (l[1].isdigit() and len(l[1]) == 2):
return False
if not (l[2].isdigit() and len(l[2]) == 3):
return False
if not (l[3].isalpha() and l[3].isupper):
return False
for i in l[-4:]:
if not i.isdigit() or len(i)!=2:
return False
return True

Length_of_Line

def length_of_line(array):
from math import sqrt
x1 = array[0][0]
y1 = array[0][1]
x2 = array[1][0]
y2 = array[1][1]
r = range( -20, 21 )
if not( x1 in r and x2 in r and y1 in r and y1 in r ):
return False
return '{0:.{1}f}'.format( sqrt( ( x2 - x1 ) ** 2 + ( y2 - y1 ) ** 2 ), 2)

Alphabetize a list by the nth character

def sort_it(list_, n):
def enesima(s):
return s[n-1]
lista = list_.split(', ')
return ', '.join(sorted( lista, key=enesima))

Checking Groups

def group_check(s):
if s == "":
return True
else:
L = []
L.append(s[0])
for i in range(1,len(s)):
L.append(s[i])
if L[len(L)-2:len(L)] == ['{','}'] or L[len(L)-2:len(L)] == [    '(',')'] or L[len(L)-2:len(L)] == ['[',']']:
L.pop()
L.pop()

if len(L) == 0:
return True
else:
return False


Square(n) Sum

def square_sum(numbers):
sum = 0
for i in numbers:
sum = sum + i * i
return sum

IPv4 to int32

def ip_to_int32(ip):
ip = ip.split(".")
bin_total = []
for i in ip:
bin_total.append(format(int(i), 'b').zfill(8))
a = ''.join(bin_total)
intIP = 0
for i in range(32):
if int(a[i]):
intIP += 2 ** (31-i)
return intIP

Bit Counting

def countBits(n):
n = format(n,'b').zfill(8)
count = 0
for i in str(n):
if int(i):
count += 1
return count

IQ Test

def iq_test(numbers):
numbers = numbers.split(" ")
odd = []
even = []
for i,v in enumerate(numbers):
if int(v) % 2:
odd.append([i,v])
else:
even.append([i,v])
if len(even) == 1:
return (even[0][0])+1
if len(odd) == 1:
return (odd[0][0])+1

Fibonacci, Tribonacci and friends

def Xbonacci(signature,n):
for i in range(n-len(signature)):
signature.append(sum(signature[i:]))
return signature[:n]

Find the Mine!

def mineLocation(field):
result = []
for i,v in enumerate(field):
if 1 in v:
result.append(i)
for j in v:
if j == 1:
result.append(v.index(j))
return result

Valid Phone Number

import re
def validPhoneNumber(phoneNumber):
m = re.search('^$$\d{3}$$\s\d{3}-\d{4}\$',phoneNumber)
if m is None:
return False
elif m.group(0):
return True
else:
return False

Sum of Digits / Digital Root

def digital_root(n):
if len(str(n)) == 1:
return n
else:
sum = 0
for i in str(n):
sum += int(i)
return digital_root(sum)

Format a string of names like ‘Bart, Lisa & Maggie’.

def namelist(names):
if names == []:
return ''
elif len(names) == 1:
return names[0]['name']
elif len(names) > 1:
a = []
for i in names:
a.append(i['name'])
return ', '.join(a[:-1])+" & "+''.join(a[-1])

Evil Autocorrect Prank

import re
def autocorrect(input):
return re.sub(r"\b(\W*)((Yo|yo)u+|u)(\W*)\b", r"\1your sister\4",input)

Unique in order

def unique_in_order(iterable):
if len(iterable) == 0:
return []
else:
result = [iterable[0]]
for i in range(1,len(iterable)):
if iterable[i] != iterable[i-1]:
result.append(iterable[i])
return result

primeFactors

from math import ceil, sqrt
def primeFactors(n):
p = [i for i in range (2,int(ceil(sqrt(n))))]
f = []
i = 0
while n > 1 and i != len(p):
if n % p[i] == 0:
f.append(p[i])
n = n/p[i]
else:
i = i + 1
if n!=1:
f.append(n)
return "".join(["({0}**{1})".format(i,k) if k > 1 else "({0})".format(i) for i,k in zip(sorted(set(f)),[f.count(i) for i in sorted(set(f))])])

Maximun Sequence

def maxSequence(arr):
s = 0
s_max = 0
sl = []
for i in range(1,len(arr)):
for j in range(0,len(arr)-i+1):
s = sum(arr[j:j+i])
if s > s_max:
s_max = s
sl = arr[j:j+i]
return s_max

#### Find the missing term in an Arithmetic Progression

def find_missing(sequence):
l_r = []
for i in range(1,len(sequence)):
r = sequence[i] - sequence[i-1]
l_r.append(r)
l_ratio = [abs(r) for r in l_r]
r_max = max(l_ratio)
i_max = l_ratio.index(r_max)
ratio = l_r[i_max]/2

return int(sequence[i_max]+ratio)

#### Mod4 Regex

import re

class Mod:
mod4 = re.compile(r".*$[+-]?(\d*([02468][048]|[13579][26])|[048])$.*")

def match(self,test):
return self.mod4.match(test)

Number of trailing zeros of N!

from itertools import groupby
def zeros(n):
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

m = str(factorial(n))

p = [list(g) for k,g in groupby(m)]

if '0' in p[-1]:
return len(p[-1])

return 0

## Resolution of Hackerrank – Python exercises

This time I have completed the Easy difficulty exercises from Hackerranck Website:

## Mod Divmod

from __future__ import division
a = int(raw_input())
b = int(raw_input())
print a//b
print a%b
print divmod(a,b)

## Print Function

Without using any string methods, try to print the following:

1,2,3…..N

Note that “…..” represents the values in between.

from __future__ import print_function
n = int(raw_input())
for i in xrange(n):
print (i+1,end="")

## Lists

You have to initialize your list L = [] and follow the N commands given in N lines.

Each command will be 1 of the 8 commands given above. The method extend(L) will not be used. Each command will have its own value(s) separated by a space.

L = []
for i in range(int(raw_input())):
s = raw_input().split()
for i in range(1,len(s)):
s[i] = int(s[i])
if s[0] == "append":
L.append(s[1])
elif s[0] == "extend":
L.extend(s[1:])
elif s[0] == "insert":
L.insert(s[1],s[2])
elif s[0] == "remove":
L.remove(s[1])
elif s[0] == "pop":
L.pop()
elif s[0] == "index":
print L.index(s[1])
elif s[0] == "count":
print L.count(s[1])
elif s[0] == "sort":
L.sort()
elif s[0] == "reverse":
L.reverse()
elif s[0] == "print":
print L

## Interchange two numbers

#input of the elements of the tuple in a and then printing in You are given two integers. Store them into two variables and then exchange them. Rather than using any fancy logic, make sure to use a tuple to do the task. Print the two numbers.

a = (int(raw_input()), int(raw_input()))
print a[1]
print a[0]

## Finding the percentage

You have a record of N students. Each record contains the student’s name, and their percent marks in Maths, Physics and Chemistry. The marks can be floating values. The user enters some integer N followed by the names and marks for N students. You are required to save the record in a dictionary data type. The user then enters a student’s name. Output the average percentage marks obtained by that student, correct to two decimal places.

N = int(raw_input())
record = {}
for i in range(0,N):
student_info = raw_input()
name = student_info.split()
record[name[0]] = [float(name[1]),float(name[2]),float(name[3])]
find_name = raw_input()
if record.has_key(find_name):
print "{0:.2f}".format(sum(record[find_name])/3.0)

## Sets – Symmetric Difference

Let’s learn about a new datatype, sets. You are given 2 sets of integers M and N. You have to print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either M or N but do not exist in both.

raw_input()
set_a = set(raw_input().split())
raw_input()
set_b = set(raw_input().split())

l = list(set_a.difference(set_b).union(set_b.difference(set_a)))
l = list(map(int, l))
l.sort()
for i in l:
print i

## List Comprehensions

Let’s learn about list comprehensions! You are given three integers X,Y and Z representing the dimensions of a cuboid. You have to print a list of all possible coordinates on a 3D grid where the sum of Xi + Yi + Zi is not equal to N. If X=2, the possible values of Xi can be 01 and 2. The same applies to Y and Z.

x = int(raw_input())
y = int(raw_input())
z = int(raw_input())
n = int(raw_input())

print [list([xx,yy,zz]) for xx in range(x+1) for yy in range(y+1) for zz in range(z+1) if xx+yy+zz !=n]

## Find the Second Largest Number

N = raw_input()
if N >= 2 and N >= 10:
A_s = raw_input()
A = set([int(x) for x in A_s.split(" ")])
if all( n >= -100 and n <= 100 for n in A):
A.remove(max(A))
print max(A)

## Nested Lists

N = int(raw_input())
All = []
score = []
if N >=2 and N <=5:
for i in range(N):
All.append([raw_input(), float(raw_input())])
score.append(All[i][1])
firstLowest = []
secondLowest = []
for i in All:
if i[1] == min(score):
firstLowest.append(i)
for x in firstLowest:
del All[All.index(x)]
del score[score.index(x[1])]
for i in All:
if i[1] == min(score):
secondLowest.append(i)
secondLowest.sort()
for i in secondLowest:
print i[0]



## Tuples

N = int(raw_input())
T = raw_input()
T = T.split()
T = map(int,T)
print hash(tuple(T))



## sWAP cASE

from __future__ import print_function
S = list(raw_input())
for s in S:
if s == s.upper():
print (s.lower(),end='')
elif s == s.lower():
print (s.upper(),end='')
else:
print (s,end='')



## String Split and Join

words = raw_input()
words = words.split()
print "-".join(words)



## Mutations

S = raw_input()
n = raw_input().split()
l = list(S)
l[int(n[0])] = n[1]
S = ''.join(l)
print S



## Find a string

a = raw_input()
b = raw_input()
c =0
for i in range(len(a)):
if a[i:].startswith(b):
c += 1
print c

## Text Wrap

import textwrap
S = raw_input()
w = int(raw_input())
print textwrap.fill(S,w)



## Capitalize!

a=[word.capitalize() for word in raw_input().split(' ')]
print ' '.join(a)

## String Validators

s = raw_input()
print any(c.isalnum() for c in s)
print any(c.isalpha() for c in s)
print any(c.isdigit() for c in s)
print any(c.islower() for c in s)
print any(c.isupper() for c in s)

## Text Alignment

#Replace all ______ with rjust, ljust or center.

thickness = int(raw_input()) #This must be an odd number
c = 'H'

#Top Cone
for i in range(thickness):
print (c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1)

#Top Pillars
for i in range(thickness+1):
print (c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)

#Middle Belt
for i in range((thickness+1)/2):
print (c*thickness*5).center(thickness*6)

#Bottom Pillars
for i in range(thickness+1):
print (c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)

#Bottom Cone
for i in range(thickness):
print ((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6)

## String Formatting

N = int(raw_input())
n = len(bin(N))-2
for i in range(1,N+1):
print str(i).rjust(n) + " " + format(i,'o').rjust(n) + " " + format(i,'X').rjust(n) + " " + format(i,'b').rjust(n)



## Introduction to Sets

N = int(raw_input())
L = set(map(int,raw_input().split()))
print float(sum(L)) / len(L)

L = set()
for i in range(int(raw_input())):
print len(L)

## Set .discard(), .remove() & .pop()

n = int(raw_input())
s = set(map(int,raw_input().split()))
for i in range(0,int(raw_input())):
a = raw_input().split(" ")
if a[0]=='pop':
s.pop()
elif a[0]=='remove':
s.remove(int(a[1]))
print sum(s)

## Set .union() Operation

N = int(raw_input())
NL = set(raw_input().split())
M = int(raw_input())
ML = set(raw_input().split())
print len(NL.union(ML))

## Set .intersection() Operation

N = int(raw_input())
N = set(raw_input().split())
M = int(raw_input())
M = set(raw_input().split())
print len(N.intersection(M))

## Set .difference() Operation

N = int(raw_input())
N = set(raw_input().split())
M = int(raw_input())
M = set(raw_input().split())
print len(N.difference(M))

## Set .symmetric_difference() Operation

N = int(raw_input())
NL = set(raw_input().split())
M = int(raw_input())
ML = set(raw_input().split())
print len(NL.symmetric_difference(ML))

## The Minion Game

word = raw_input().upper()
vowels = 'AEIOU'
kevin = 0
stuart = 0
for i in range(len(word)):
if word[i] in vowels:
kevin += len(word) - i
else:
stuart += len(word) - i
if kevin > stuart:
print "Kevin", kevin
elif stuart > kevin:
print "Stuart", stuart
else:
print "Draw"

## Captain’ Room

n = int(raw_input())
nums = raw_input().split()
repeticiones = 0
nums.sort()
for i in range(len(nums)):
if i + 1 < len(nums) and nums[i] == nums[i + 1]:
repeticiones += 1
elif repeticiones == 1:
break
repeticiones = 1
print(nums[i])

## Resolution for CodeAcademy’s Python exercises

This is a general view from what I practiced at Codecademy Website. The first command they train is related to print a message for strings using comillas:

print "Hello World in HD!"

The next topic is focused in variables, in order to set them, just use the equal sign “=” :

HD = 5
anotherHD = 1.45

This means that HD has the value of 5. And you can test it by typing HD in your prompt. Other kind of variable are booleans, in this case we can assign H as yes and D as no:

H = True
D = False

What if I do print hd, do you think that value is 5? well try it!… it is a sensitive code, so use uppercase or lowercase as your convenience. In this case I am going to change the value:

HD = 3

so, if I type print HD, the answer must be 3 and not 5 as it was set before.

Functions

The reserve word to define a function is def, and the rest must be indented with 4 spaces:

def HD():
x = 12
return x

print HD()

Any time you want to add a comment in only one line, use the symbol #; if there are more lines, use ”’ at the beginning and at the ending of the comment. To do math, use the operator as you require:

# Set sum equal to the sum of two big numbers
sum = 2355342342354 + 423435465767868

print sum

#Set eggs equal to 100 using exponentiation on line 3!
expo_use = 10 ** 2

print expo_use

#Set spam equal to 1 using modulo on line 3!
spam = 6 % 5

print spam

# this is my first program
monty = True

python = 1.234

monty_python = python ** 2

In order to pay a meal in a restaurant, we set values as tax and tip to calculate the total:

# Assign the variable total on line 8!
meal = 44.50
tax = 0.0675
tip = 0.15
meal = meal + meal * tax
total = meal + meal * tip
print("%.2f" % total)

Then, the string lesson shows concatenating strings that can set numbers between comillas. In the next lines we can set the variable message twice and the use of ” \ ” before ” ‘ ” because it could be interpreted as comillas that break the message. Or you can use ” ‘ ” between a message which starts with double comillas ” ” “.

number = '6'
message = "Hello" + number
new_message = 'This isn\'t an example with style!'
allowed_message = "It's not bad to use the simple one."

To work with lists or arrays and strings, do not forget the comillas and start to count from zero instead of one, e.g. if somebody ask for the four letter of GNOME, the answer must be

four_letter = "GNOME"[3]
print four_letter

String methods is the next topic covered and the common are len(), lower(), upper(), str().

project = "GNOME"
pi = 3.1416
print len(project)
print project.lower()
print project.upper()
print str(pi)   #explicit string conversion

To string formatting with % can be used after enter a value from a prompt and store as:

name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")

print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, quest, color)

To print the current time of the system, call the library datetime and store in variable like:

from datetime import datetime
now = datetime.now()

print '%s/%s/%s %s:%s:%s' % (now.month, now.day, now.year, now.hour, now.minute, now.second)

Control flow

def guessing():
print "We are going to guess the number you enter"
print "Natural numbers are going to use for this exercises"
answer = raw_input("Type a larger number of one cipher and hit 'Enter'.").lower()
print "Ahhh! the number you typed is nine!"
print "Ahhh! the number you typed is eight!"
else:
print "You didn't pick a big number of one cipher."
guessing()

guessing()

The use of operators and boleeans can be mixed as follow:

bool_one = 2**3 == 108 % 100 or 'Cleese' == 'King Arthur'
bool_two = not not False
bool_three = 100**0.5 >= 50 or False
bool_four = True and True
bool_five = not 1**100 == 100**1 and 3 * 2 * 1 != 3 + 2 + 1

The reserve word “return” is important to return a value from a function as its indentation:

def using_control_once():
if True:
return "Success #1"

def using_control_again():
if True:
return "Success #2"

print using_control_once()
print using_control_again()

More uses of conditionals with strings comparison:

answer = "'Tis but a scratch!"

def black_knight():
if answer == "'Tis but a scratch!":
return True
else:
return False # Make sure this returns False

def french_soldier():
if answer == "Go away, or I shall taunt you a second time!":
return True
else:
return False # Make sure this returns False

More uses of conditionals with number comparison:

def greater_less_equal_5(answer):
return 1
return -1
else:
return 0

print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)

Mor conditional uses:

def the_flying_circus():
if True and True: # Start coding here!
return True
elif 2 > 4:
return False
else:
print "Not 2"

print the_flying_circus()

The answer of Pig Latin is a language game, where you move the first letter of the word to the end and add “ay.” So “Python” becomes “ythonpay.”:

pyg = 'ay'
original = raw_input('Enter a word:')
word = original.lower()
first = word[0]
new_word = word[1:len(new_word)] + first + pyg
if len(original) > 0 and original.isalpha():
print new_word
else:
print 'empty'

Defining parameters in functions:

def power(base, exponent): # Add your parameters here!
result = base**exponent
print "%d to the power of %d is %d." % (base, exponent, result)
power(37,4) # Add your arguments here!

calling function inside another function

def one_good_turn(n):
return n + 1

def deserves_another(n):
return one_good_turn(n) + 2

Defining a function of cube and validation of the number divided by 3:

def cube(number):
return number*number*number

def by_three(number):
if number % 3 == 0:
return cube(number)
else:
return False

Using import

# Ask Python to print sqrt(25) on line 3.
import math
print math.sqrt(25)

just to import function from a module

from math import sqrt
# Import *everything* from the math module on line 3!
from math import *

to see all the functions

import math # Imports the math module
everything = dir(math) # Sets everything to a list of things from math
print everything

maximun

# Set maximum to the max value of any set of numbers on line 3!
maximum = max(4,5,6)
print maximum

absolute

absolute = abs(-42)
print absolute

types

# Print out the types of an integer, a float,
# and a string on separate lines below.
print type(45)
print type(6.7)
print type("hi")

Function that validate shut down message

def shut_down(s):
if s == "yes":
return "Shutting down"
elif s == "no":
return "Shutdown aborted"
else:
return "Sorry"

Using the sort function

from math import sqrt
print sqrt(13689)

from math import *

def distance_from_zero(n):
if type(n) == int or type(n) == float:
return abs(n)
else:
return "Nope"

You can define a function to return a value:

def answer():
return 42

Taking a vacation quiz:

def hotel_cost(nights):
return 140 * nights

def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475

def rental_car_cost(days):
total = 40 * days
if days >= 7:
total = total - 50
elif days >= 3:
total = total - 20

def trip_cost(city,days,spending_money):
return hotel_cost(days) + plane_ride_cost(city) + rental_car_cost(days) + spending_money

print trip_cost("Los Angeles",5,600)

using lists

numbers = [5, 6, 7, 8]
print "Adding the numbers at indices 0 and 2..."
print numbers[0] + numbers[2]
print "Adding the numbers at indices 1 and 3..."
print numbers[1] + numbers[3]

append function to add items at the end of a list

suitcase = []
suitcase.append("sunglasses")
suitcase.append("purse")
suitcase.append("keys")
suitcase.append("money")
list_length = len(suitcase) # Set this to the length of suitcase
print "There are %d items in the suitcase." % (list_length)
print suitcase

accessing to items in a list

suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
first = suitcase[0:2] # The first and second items (index zero and one)
middle = suitcase[2:4] # Third and fourth items (index two and three)
last = suitcase[4:6] # The last two items (index four and five)

Accessing to indexes in a list

animals = "catdogfrog"
cat = animals[:3] # The first three characters of animals
dog = animals[3:6] # The fourth through sixth characters
frog = animals[6:] # From the seventh character to the end

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck")
animals.insert(duck_index,"cobra")
print animals # Observe what prints after the insert operation

Loop and lists:

my_list = [1,2,3,4,5]
for number in my_list:
print 2 * number

Math function, loop and list

start_list = [5, 3, 1, 2, 4]
square_list = []

for number in start_list:
square_list.append(number ** 2)
square_list.sort()
print square_list

The use of a dictionary

# Assigning a dictionary with three key-value pairs to residents:
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
print residents['Puffin'] # Prints Puffin's room number
print residents['Sloth']
print residents['Burmese Python']

deleting a value from a dictionary:

# key - animal_name : value - location
zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}

del zoo_animals['Unicorn']
del zoo_animals['Bengal Tiger']
zoo_animals['Rockhopper Penguin'] = 'Peru'

print zoo_animals

to remove ‘dagger’ from backpack

backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']
backpack.remove('dagger')

using dictionary and lists inside dictionary

inventory = {
'gold' : 500,
'pouch':['flint','twine','gemstone'], # Assigned a new list
}

# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag']=['apple','small ruby','three-toed sloth']

# Sorting the list found under the key 'pouch'
inventory['pouch'].sort()

inventory['pocket'] = ['seashell','strange berry','lint']
inventory['backpack'].sort()
inventory['backpack'].remove('dagger')
inventory['gold'] = 500 +50

Using for loop for printing item in a list:

names = ["Adam","Alex","Mariah","Martine","Columbus"]
for each_name in names:
print each_name

Printing items from a dictionary

webster = {
"Aardvark" : "A star of a popular children's cartoon show.",
"Baa" : "The sound a goat makes.",
"Carpet": "Goes on the floor.",
"Dab": "A small amount."
}
for n in webster:
print webster[n]

To print even numbers:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
for number in a:
if number % 2 == 0:
print number

Counting items in a list defined as an input in a function

def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count = count + 1
return count

fizz_count(["fizz","cat","fizz"])

for letter in "Codecademy":
print letter
# Empty lines to make the output pretty
print
print
word = "Programming is fun!"
for letter in word:
# Only print out the letter i
if letter == "i":
print letter

A Day at the Supermarket resolution:

prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}
total = 0
for key in prices:
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
total = total + prices[key] * stock[key]
print "total %s" % total[key]

Stocking out – A Day at the supermarket

shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def compute_bill(food):
total = 0
for item in food:
if stock[item] > 0:
total += prices[item]
stock[item] -= 1
return total

Put it Together = Student becomes a teacher

lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
def average(numbers):
total = sum(numbers)
return float(total) /len(numbers)

def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
return 0.10 * homework + 0.30 * quizzes + 0.60 * tests

if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"

def get_class_average(students):
results = []
for student in students:
results.append(get_average(student))
return average(results)

students = [lloyd,alice,tyler]
print get_class_average(students)
print get_letter_grade(get_class_average(students))

Defining a function that add numbers

m = 5
n = 13
return x + y
print add_function(m, n)

String in fucntions

n = "Hello"
def string_function(s):
return s+"world"
print string_function(n)

Passing a list as argument in a function

def list_function(x):
return x
n = [3, 5, 7]
print list_function(n)

Using an element from a list in a function

def list_function(x):
return x[1]
n = [3, 5, 7]
print list_function(n)

Modifying an element of a list in a function

def list_function(x):
x[1] = x[1] + 3
return x
n = [3, 5, 7]
list_function(n)
print n

List manipulation in functions

n = [3, 5, 7]
def list_extender(lst):
lst.append(9)
return lst
print list_extender(n)

Printing out a list item by item in a function

n = [3, 5, 7]
def print_list(x):
for i in range(0, len(x)):
print x[i]
print_list(n)

Modifying each element in a list in a function

n = [3, 5, 7]
def double_list(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x # Don't forget to return your new list!
print double_list(n)

Passing a range into a function

def my_function(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x
print my_function(range(0,len(n)))

Iterating over a list in a function

n = [3, 5, 7]
def total(numbers):
result = 0
for number in numbers:
result +=number
return result
print total(n)

Using strings in lists in functions

n = ["Michael", "Lieberman"]
def join_strings(words):
result = ""
for i in words:
result += i
return result
print join_strings(n)

Using two lists as two arguments in a function

m = [1, 2, 3]
n = [4, 5, 6]

def join_lists(x,y):
return x+y

print join_lists(m, n)
# You want this to print [1, 2, 3, 4, 5, 6]

Using a list of lists in a function

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
results = []
for item in lists:
for n in item:
results.append(n)
return results
print flatten(n)

Battleship!

from random import randint

board = []

for x in range(0,5):
board.append(["O"] * 5)

def print_board(board):
for row in board:
print " ".join(row)

def random_row(board):
return randint(0, len(board) - 1)

def random_col(board):
return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)

print ship_row
print ship_col

for turn in range(4):
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))

if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
else:
if (guess_row<0 or guess_row>4)or(guess_col<0 or guess_col>4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
break;
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
print "Turn", turn
print "Turn", turn + 1
if turn == 3:
print "Game Over"
print_board(board)

Loops

“While you’re” prints 1 message from the if condition and 10 from the while-loop:

count = 0
if count < 10:
print "Hello, I am an if statement and count is", count

while count < 10:
print "Hello, I am a while and count is", count
count += 1

Condition.- if it is not compared with something else, it is assumed that is True by default:

loop_condition = True
while loop_condition:
print "I am a loop"
loop_condition = False

“While you’re at it” creates a loop that prints out all the numbers from 1 to 10 squared

num = 1
while num < 11: # Fill in the condition
print num ** 2 # Print num squared
num += 1 # Increment num (make sure to do this!)

“Simple errors” checks user input to see if it is valid

choice = raw_input('Enjoying the course? (y/n)')
while choice not in 'y' and  choice not in 'n':
choice = raw_input("Sorry, I didn't catch that. Enter again: ")

“Infinite loops” usually occurs if the condition never gets False or bad use of the counter

count = 0
while count < 10: # Add a colon
print count
count += 1# Increment count

Break

count = 0
while True:
print count
count += 1
if count >= 10:
break

“While / else”.- the else block will execute anytime the loop condition is evaluated to False

import random
print "Lucky Numbers! 3 numbers will be generated."
print "If one of them is a '5', you lose!"
count = 0
while count < 3:
num = random.randint(1, 6)
print num
if num == 5:
print "Sorry, you lose!"
break
count += 1
else:
print "You win!"

“Your own while / else” allows the user to guess what the number is three times:

from random import randint
# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
guesses_left = 3
while guesses_left > 0:
if guess == random_number:
print "You win"
break
guesses_left -= 1
else:
print "You lose"

“For your health”: Make the loop print the numbers from 0 to 19

print "Counting..."
for i in range(20):
print i

“For your hobbies” asks for three hobbies and store them in a list called hobbies:

hobbies = []
for i in range(3):
hobbies.append(h)
print hobbies

“For your strings” means that “for each character c in thing, print c“.

thing = "spam!"
for c in thing:
print c

word = "eggs!"
for c in word:
print c

“For your A”, if char is an 'A' or char is an 'a'print 'X', instead of char.

phrase = "A bird in the hand..."
for char in phrase:
if char == "A" or char == "a":
print "X" ,
else:
print char ,
#Don't delete this print statement!
print

“For your lists” loops that goes through the numbers list and prints each element squared

numbers = [7, 9, 12, 54, 99]
print "This list contains: "
for num in numbers:
print num
for num in numbers:
print num ** 2

“Looping over a dictionary” prints the key, followed by the value associated with that key.

d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}
for key in d:
print key + " " + d[key]

“Counting as you go”, enumerate works by supplying a corresponding index to each element in the list that you pass it:

choices = ['pizza', 'pasta', 'salad', 'nachos']
for index, item in enumerate(choices):
print index+1, item

“Multiple lists” compares each pair of elements and print the larger of the two.

list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
if a > b:
print a
else:
print b

“For / else” will break when it hits 'tomato', so the else block won’t be executed.

fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
print 'You have...'
for f in fruits:
if f == 'tomato':
print 'A tomato is not a fruit!' # (It actually is.)
break
print 'A', f
else:
print 'A fine selection of fruits!'

“Change it up” will finish to scan the rest of the list until showing the last message:

fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
print 'You have...'
for f in fruits:
if f == 'tomato':
print 'A tomato is not a fruit!' # (It actually is.)
print 'A', f
else:
print 'A fine selection of fruits!'

“Create your own”  builds your for/else statement in the editor.

message = "GNOME is an easy and elegant desktop environment"
for char in message:
if char == 'e' or char == 'E':
print "3",
else:
print char,
else:
print "That's All I Have To Say About That"

“Practice! Practice Practice!” the more you practice, the more you learn

“is_even”, if a number is divided by 2, is an even number:

def is_even(x):
if x % 2 == 0:
return True
else:
return False

“is_int” , a number with a decimal part that is all 0s is also an integer, such as 7.0.

def is_int(x):
if type(x) == int or x == round(x):
print True
else:
print False

“digit_sum” takes a positive integer n as input and returns the sum of all its numbers

def digit_sum(n):
number = str(n)
c = 0
for num in number:
c = c + int(num)
print c

Calculate the factorial of a non-negative integer x multiply all the integers from 1 through x

def factorial(x):
fact = 1
for i in range(x):
fact = fact * (i+1)
print fact

“is_prime” if there is a number between 1 and xthat goes in evenly, then x is not prime.

def is_prime(x):
if x < 2:
return False
else:
for n in range(2,x):
if x % n == 0:
return False
return True

Define a function called "reverse" that takes a string textand returns that string in reverse

def reverse(text):
rev=""
for i in text:
rev=i+rev
print rev

“anti_vowel” prints the original message without any vowel that the message has.

def anti_vowel(text):
newtext = ''
for c in text:
if c.lower() not in "aeiou":
newtext += c
return newtext

“Scrabble” the word "abc" would score 7 points due to the sum of the letters: 3 + 3 + 1:

score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}

def scrabble_score(word):
sum = 0
for i in word.lower():
sum = sum + score[i]
return sum

“censor” takes two strings, text and word, as input. It should return the text with the wordyou chose replaced with asterisks.

def censor(text,word):
words=text.split()
for i in range(len(words)):
if words[i]==word:
words[i]="*" * len(words[i])
return " ".join(words)

“count” returns the number of times the item occurs in the list.

def count(sequence,item):
c = 0
for i in range(len(sequence)):
if sequence[i] == item:
c += 1
return c

“purify” takes in a list of numbers, removes all odd numbers in the list:

def purify(l):
n = []
for i in l:
if i % 2 == 0: n.append(i)
return n

“product” takes a list of integers as input and returns the product of all of the elements

def product(list_int):
prod = 1
for i in list_int:
prod = prod * i
return prod

“remove_duplicates” takes in a list and removes elements of the list that are the same

def remove_duplicates(lists):
comp_list = [ ]
for i in lists:
if i not in comp_list:
comp_list.append(i)
return comp_list

“median” takes a list as an input and returns the median value of the list.

def median(lista):
lista.sort()
if len(lista) % 2 == 0:
print (lista[len(lista)/2]+lista[len(lista)/2 -1])/2.0
else:
print lista[len(lista)/2]

“Exam Statistics”

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

total = 0

return average

variance = 0
for score in scores:
variance = variance + (average - score) ** 2
return variance/len(scores)

return variance ** 0.5

print grades_std_deviation(variance)

keys() and values() returns an array of tuples with each tuple consisting of a key/value pair

my_dict = {
"name": "Sandryta",
"age": 26,
"status": "single"
}
print my_dict.keys()
print my_dict.values()

“List Comprehension Syntax” uses a list comprehension to build a list called even_squares

doubles_by_3 = [x*2 for x in range(1,6) if (x*2) % 3 == 0]
# Complete the following line. Use the line above for help.
even_squares = [x**2 for x in range(1,11) if (x % 2) == 0]
print even_squares

“Now You Try!” uses a list comprehension to create a list, cubes_by_four.

cubes_by_four = [x**3 for x in range(1,11) if (x**3 % 4) == 0]
print cubes_by_four

“Omitting Indices” uses list slicing to print out every odd element from start to finish.

my_list = range(1, 11) # List of numbers 1 - 10
print my_list[::2]

“Reversing a List” A negative stride progresses through the list from right to left.

my_list = range(1, 11)
backwards = my_list[::-1]
print backwards

“Stride Length” shows the result of going backwards through to_one_hundred by tens.

to_one_hundred = range(101)
backwards_by_tens = to_one_hundred[::-10]
print backwards_by_tens

“Practice Makes Perfect” creates a to_21, that’s just the numbers from 1 to 21, inclusive; second list, odds, that contains only the odd numbers in the to_21 list (1, 3, 5, and so on); third list, middle_third, that’s equal to the middle third of to_21, from 8 to 14, inclusive.

to_21 = range(1,22)
odds = to_21[::2]
middle_third = to_21[7:14]

“Lambda Syntax”  The lambdashould ensure that only "Python" is returned by the filter.

languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda x:x=="Python", languages)

“Try It!” prints out only the squares that are between 30 and 70 (inclusive).

squares = [x**2 for x in range(1,11)]
print filter(lambda x: x in range(30,71), squares)

“Iterating Over Dictionaries” calls a method such that it will print out all the items

movies = {
"Monty Python and the Holy Grail": "Great",
"Monty Python's Life of Brian": "Good",
"Monty Python's Meaning of Life": "Okay"
}
print movies.items()

“Comprehending Comprehensions” consists only of the numbers between 1 and 15 (inclusive) that are evenly divisible by 3 or 5.

threes_and_fives=[x for x in range(1,16) if x%3 == 0 or x % 5 == 0]

“List Slicing” our message is backwards, and the letter we want is every other letter than X

garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[::-2]
print message

“Lambda Expressions” Create a variable called message and set it to the result of calling filter() with the appropriate lambda that will filter out the X. The 2nd argument:garbled.

garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
message = filter(lambda x: x!="X", garbled)
print message

“Just a Little BIT” Bitwise operations are operations that directly manipulate bits. I

print 5 >> 4 # Right Shift
print 5 << 1 # Left Shift
print 8 & 5 # Bitwise AND
print 9 | 4 # Bitwise OR
print 12 ^ 42 # Bitwise XOR
print ~88 # Bitwise NOT

We can evaluate the first example by setting 5 as 00000101 and then we have to move four positions to the right and then we have 00000000, so the answer is zero.

“Lesson I0: The Base 2 Number System” we can print binary numbers by starting with 0b:

print 0b1, #1
print 0b10, #2
print 0b11, #3
print 0b100, #4
print 0b101, #5
print 0b110, #6
print 0b111 #7
print "******"
print 0b1 + 0b11
print 0b11 * 0b11

“I Can Count to 1100!” Fill out the numbers with their corresponding binary values up to12

one = 0b1
two = 0b10
three = 0b11
four = 0b100
five = 0b101
six = 0b110
seven = 0b111
eight = 0b1000
nine = 0b1001
ten = 0b1010
eleven = 0b1011
twelve = 0b1100

“The bin() Function” prints out the binary representations of the numbers 2 through 5:

print bin(1)
print bin(2)
print bin(3)
print bin(4)
print bin(5)

“int()’s Second Parameter”  use int to print the base 10 equivalent of the binary number 11001001. The output for the following code is: 1 2 7 4 5 201

print int("1",2)
print int("10",2)
print int("111",2)
print int("0b100",2)
print int(bin(5),2)
# Print out the decimal equivalent of the binary 11001001.
print int("11001001",2)

“Slide to the Left! Slide to the Right!” shifts the variable shift_right to the right twice (>> 2) and shift the variable shift_left to the left twice (<< 2).

shift_right = 0b1100
shift_left = 0b1
shift_right = shift_right >> 2
shift_left = shift_left << 2
print bin(shift_right)
print bin(shift_left)

“A BIT of This AND That” prints ob100

print bin(0b1110 & 0b101)

“A BIT of This OR That” prints out the result of using | on 0b1110 and 0b101 as a binary str

print bin(0b1110|0b101)

“This XOR That?” prints the result of using ^on 0b1110 and 0b101 as a binary string.

print bin(0b1110 ^ 0b101)

See? This is NOT That Hard! it will print the next number as it is the negation of the num

print ~1
print ~2
print ~3
print ~42
print ~123

“The Man Behind the Bit Mask”  check_bit4, with one argument, input, an integer.

def check_bit4(n):
if mask & n != 0:
return "on"
else:
return "off"

“Turn It On” uses a bitmask and the value a in order to achieve a result where the third bit from the right of a is turned on.

a = 0b10111011
print bin(desired)

“Slip and Slide” flips the nth bit (with the ones bit being the first bit) and store it in result

def flip_bit(number,n):
mask = 0b1 << n -1
return bin(result)

“Why Use Classes?”

class Fruit(object):
"""A class that makes various tasty fruits."""
def __init__(self, name, color, flavor, poisonous):
self.name = name
self.color = color
self.flavor = flavor
self.poisonous = poisonous
def description(self):
print "I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor)

def is_edible(self):
if not self.poisonous:
print "Yep! I'm edible."
else:
print "Don't eat me! I am super poisonous."

lemon = Fruit("lemon", "yellow", "sour", False)
lemon.description()
lemon.is_edible()

“Class Animal Syntax” creates a class called Animal in the editor

# Class definition
class Animal(object):
"""Makes cute animals."""
# For initializing our instance objects
def __init__(self, name, age, is_hungry):
self.name = name
self.age = age
self.is_hungry = is_hungry

# Note that self is only used in the __init__()
# function definition; we don't need to pass it
# to our instance objects.

zebra = Animal("Jeffrey", 2, True)
giraffe = Animal("Bruce", 1, False)

print zebra.name, zebra.age, zebra.is_hungry
print giraffe.name, giraffe.age, giraffe.is_hungry
print panda.name, panda.age, panda.is_hungry

“A Methodical Approach” adds a method, description, to your Animal class. Using two separate printstatements, it should print out the nameand age of the animal.

class Animal(object):
"""Makes cute animals."""
is_alive = True
def __init__(self, name, age):
self.name = name
self.age = age
def description(self):
print "%s" %(self.name)
print "%d" %(self.age)
hippo = Animal("Baloo",43)
hippo.description()

“They’re Multiplying!” adds a second member variable called health that contains the string "good"; creates two new Animals: sloth and ocelot; and prints their health:

class Animal(object):

is_alive = True
health ="good"

def __init__(self, name, age):
self.name = name
self.age = age

def description(self):
print "%s" %(self.name)
print "%d" %(self.age)
hippo = Animal("Baloo",43)
sloth = Animal("Mona",34)
ocelot = Animal("Walter",45)

hippo.description()

print hippo.health
print sloth.health
print ocelot.health

“It’s Not All Animals and Fruits” creates an instance of ShoppingCartcalled my_cart. Initialize it with any values you like, then use the add_itemmethod to add it to your cart.

class ShoppingCart(object):
"""Creates shopping cart objects
for users of our fine website."""
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name

if not product in self.items_in_cart:
self.items_in_cart[product] = price
else:
print product + " is already in the cart."

def remove_item(self, product):
"""Remove product from the cart."""
if product in self.items_in_cart:
del self.items_in_cart[product]
print product + " removed."
else:
print product + " is not in the cart."

my_cart = ShoppingCart("Manzana")
print my_cart.add_item("verde",123)

“Warning: Here Be Dragons”

class Customer(object):
"""Produces objects that represent customers."""
def __init__(self, customer_id):
self.customer_id = customer_id
def display_cart(self):
print "I'm a string that stands in for the contents of your shopping cart!"

class ReturningCustomer(Customer):
"""For customers of the repeat variety."""
def display_order_history(self):
print "I'm a string that stands in for your order history!"

monty_python = ReturningCustomer("ID: 12345")
monty_python.display_cart()
monty_python.display_order_history()

“Inheritance Syntax” inside the Triangle class, write an __init__() function that takes four arguments: selfside1side2, and side3.

class Shape(object):
"""Makes shapes!"""
def __init__(self, number_of_sides):
self.number_of_sides = number_of_sides

class Triangle(Shape):
def __init__(self, side1, side2, side3):
self.side1 = side1
self.side2 = side2
self.side3 = side3

“Override!” creates a new class PartTimeEmployee and calculate_wage method that overrides Employee‘s

class Employee(object):
def __init__(self, employee_name):
self.employee_name = employee_name

def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00

class PartTimeEmployee(Employee):
def calculate_wage(self, hours):
self.hours = hours
return hours *12.00

“This Looks Like a Job For…” adds a new method called full_time_wage with the arguments self and hours. That method should return the result of a super call to the calculate_wage method of PartTimeEmployee‘s parent class.

class Employee(object):

def __init__(self, employee_name):
self.employee_name = employee_name

def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00

class PartTimeEmployee(Employee):
def calculate_wage(self, hours):
self.hours = hours
return hours *12.00

def full_time_wage(self, hours):
return super(PartTimeEmployee, self).calculate_wage(hours)

milton = PartTimeEmployee("milton")
print milton.full_time_wage(10)

“Class Basics” Create a class, Triangle. Its __init__()method should take selfangle1angle2, and angle3 as arguments.

class Triangle(object):
number_of_sides = 3
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3

“Class It Up” creates a method named check_angles. The sum of the angles should return True if the sum of self.angle1self.angle2, and self.angle3 is equal 180, or False.

class Triangle(object):
number_of_sides = 3
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3

def check_angles(self):
if self.angle1 + self.angle2 + self.angle3 == 180:
return True
else:
return False

“Instantiate an Object” creates a variable named my_triangleand set it equal to a new instance of your Triangle class. Pass it three angles that sum to 180 (e.g. 90, 30, 60).

class Triangle(object):
number_of_sides = 3
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3

def check_angles(self):
if self.angle1 + self.angle2 + self.angle3 == 180:
return True
else:
return False
my_triangle = Triangle(90,30,60)
print my_triangle.number_of_sides
print my_triangle.check_angles()

“Inheritance” creates a class named Equilateralthat inherits from Triangle.

class Triangle(object):
number_of_sides = 3
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3

def check_angles(self):
if self.angle1 + self.angle2 + self.angle3 == 180:
return True
else:
return False
class Equilateral(Triangle):
angle = 60
def __init__(self):
self.angle1 = self.angle
self.angle2 = self.angle
self.angle3 = self.angle
my_triangle = Triangle(90,30,60)
print my_triangle.number_of_sides
print my_triangle.check_angles()

“Class basics”  defines a new class named “Car” and put something inside the class, pass

class Car(object):
pass

“Create an instance of a class” create a new object named my_car that is an instance of Car.

class Car(object):
pass
my_car = Car()

“Class member variables” creates a new member variable named condition as "new".

class Car(object):
condition = "new"
my_car = Car()

“Calling class member variables” prints statement to display the condition of my_car.

class Car(object):
condition = "new"
my_car = Car()
print my_car.condition

“Initializing a class”

class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg

my_car = Car("DeLorean","silver",88)
print my_car.condition

“Referring to member variables”

class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg

my_car = Car("DeLorean","silver",88)
print my_car.condition
print my_car.color
print my_car.model
print my_car.mpg

“Creating class methods”

class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg

def display_car(self):
return "This is a %s %s with %d MPG." % (self.color,self.model, self.mpg)
my_car = Car("DeLorean", "silver", 88)
print my_car.display_car()

“Modifying member variables”

class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg

def display_car(self):
return "This is a %s %s with %d MPG." % (self.color,self.model, self.mpg)

def drive_car(self):
self.condition = "used"

my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.drive_car()
print my_car.condition

“Inheritance” creates a class ElectricCar that inherits from Car

class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg

def display_car(self):
return "This is a %s %s with %d MPG." % (self.color,self.model, self.mpg)

def drive_car(self):
self.condition = "used"

class ElectricCar(Car):
def __init__(self,model,color,mpg,battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type = battery_type

my_car = ElectricCar("moas", "silver", 88,"molten salt")

“Overriding methods”

class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg

def display_car(self):
return "This is a %s %s with %d MPG." % (self.color,self.model, self.mpg)

def drive_car(self):
self.condition = "used"

class ElectricCar(Car):
def __init__(self,model,color,mpg,battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type = battery_type
def drive_car(self):
self.condition = "like new"

my_car = ElectricCar("moas", "silver", 88,"molten salt")
print my_car.condition
my_car.drive_car()
print my_car.condition

“Building useful classes” defines a Point3D class that inherits from object

class Point3D(object):
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return "(%d, %d, %d)" % (self.x,self.y,self.z)
my_point = Point3D(1,2,3)
print my_point

“See It to Believe It” prints in output.txt the squares of numbers from 1 to 10

my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10
f = open("output.txt", "w")
for item in my_list:
f.write(str(item) + "\n")
f.close()

The open() Function creates a variable, my_file that allow you to read and write to it!

my_list = [i**2 for i in range(1,11)]
my_file = open("output.txt", "w")
for n in my_list:
my_file.write(str(n)+"\n")
my_file.close()

“Reading”  creates my_file, and set it equal to the file open() with both "output.txt" and r

my_file = open("output.txt","r")
my_file.close()

“Reading Between the Lines”, in this particular case, modify the content of text.txt

my_file = open("text.txt","r")
my_file.close()

“PSA: Buffering Data”

# Open the file for reading
# Use a second file handler to open the file for writing
write_file = open("text.txt", "w")
# Write to the file
write_file.write("Not closing files is VERY BAD.")
write_file.close()
# Try to read from the file
read_file.close()

“The ‘with’ and ‘as’ Keywords” we don’t explicitly close() our file, and remember that if we don’t close a file, our data will get stuck in the buffer.

with open("text.txt", "w") as textfile:
textfile.write("Success!")

“Try It Yourself” writes any data you like to the text.txt file using withas

with open("text.txt", "w") as textfile:
textfile.write("Hola mundo!")

“Case Closed?” checks if the file is not .closed

with open("text.txt", "w") as textfile:
textfile.write("Hola mundo!")
if my_file.closed != True:
my_file.close()

print my_file.closed

FINISHED :D :D :D

## First Grammar Class at LSI

I have enrolled in English classes at LSI Berkley and I have met new friends there: Joy from Italy, Zara from Saudi Arabia and Michi and Michiru from Japan. So far, I highly recommend the institution. I have been treated well by Ava, who is in charge of student services, Greg, the School Director, Mackenzie, who is in charge of academic matters and my teacher, who is an angel: Megan.

I think I’d like to share what I learned from Megan’s classes today. We started with an unusual presentation, saying the first thing that came to our minds when the teacher said key words like You, your country, Berkeley, English and science. The last word was related to the first activity: Speaking by interviewing all the classroom with some questions. My question was “Do you think it is acceptable for animals to be used in experiments? Does it make a difference if the experiments are for medical research or for cosmetics testing?. From 9 students I only got one negative answer. It was from Maria, a teacher of English at schools in Italy.

The next activity was about Facts and Myths. I enjoyed this activity because it involved curiosity-piquing topics. Here is the list of the items with their answers:

1. A coin dropped from a very high building can kill someone on the ground (MYTH)
2. We only use ten percent of our brains. (MYTH)
3. There us no part of the moon that is permanently dark. (FACT)
4. Rubber tires protect a car from lighting. (MYTH)
5. Albert Einstein was very bad at math in school. (MYTH)
6. Antibiotics don’t kill viruses. (FACT)… they only kill bacterias.
7. A full moon makes people and animals go crazy. (MYTH) … only in movies
8. Bats are blind. (MYTH) … they also have a good sense of smelling and hearing

The following chart was so helpful, I hope you can learn some intonations like I did!

scientist           scientific               science

chemist            chemical              chemistre

biologist           biological              biology

physicist          physical                physics

geneticist         genetic                 genetics

geographer      geographic         geography

economist        economic            economics

politician         political                politics

After that, we completed some sentences with correct grammar:

1. Scientists carry out experiments in a laboratory.
2. Archimedes made an important in his bathtub.
3. Isaac Newton experiments proved his theory that gravity existed.
4. Before a pharmaceutical company can sell new drugs they have to do tests to make tests to make sure they are safe.
5. Scientists have to do a lot of research into the possible side effects of new drugs.
6. People can volunteer to be guinea pigs in clinical trials.
7. Both Sir Humphry Davy and Thomas Midgley damaged their health as a result of inhaling chemicals.
8. Neither Thomas Midgley nor General Motors were prepared to admit how dangerous lead was.
9. Until 1973, all cars used leaded gas.
10. All the blood Bogdanov used in his experiments might have been contaminated because he never tested any of it.
11. Sir Humphry Davy was fascinated by everything to do with gases.
12. Most of my closest friends live near me.
13. You can come over any time on Saturday. We will be home all day.
14. Everything is ready for the party. We are just waiting for the guests to arrive.
15. Most of people enjoy the summer here, but for some it is too hot.
16. Gina goes dancing every Friday night.
17. We do not have any onions for the soup.
18. Any of us wants to go out tonight. We are all broke.
19. Anybody can go to the festival. It is free.
20. I have two very close friends, but unfortunately neither of them lives near me.
21. I would like to have a bigger table, but there is no room in my kitchen.
22. Both the kitchen and the bathroom needs cleaning.
23. The food was not cheap neither tasty.
24. We can go on vacation either on July or August.
25. Both of the trips were long and boring.
26. It is Jane or Karen birthday today? I cant remember it.
27. My brother has neither the energy nor the stamina to run a marathon.
28. Both her aunt and cousin came to visit me.
29. We can either walk or take the bus.
30. I have two children but neither of them look like me.
31. My parent loves horses and both of them ride every day.
• You can use this help for Either an Neither as Meagen said: Either or + , Neither nor –

From this first day, I learned a couple of idiomatic phrases, such as “as blind as a bat” and “take a toll on”, where is used in sentences like “Your words took a toll on my feelings”.

Goterborg is an amazing city. Everything is in order, neat, modern, safe, well-maintained, with good taste in design. They care so much for the environment and good education for their people. Definitely, it is a place with good quality of life, kind people and the cutiest babies and dogs I have ever seen before.

I have been attended GUADEC since 2011, and I try not to miss it every year. Each opportunity is a new start where I can learn from other GNOME members experiences and in some ways recharge my passion which marks a time-stamp in my life.

As usual, my “GUADEC ritual” starts the moment that I apply for a visa to the embassy of the country where it is due to take place, then I make a request to the GNOME Foundation for sponsorship. To prepare myself for the long journey of traveling between several countries to my final destination, I train my eating and sleeping time. Unfortunately, for this years GUADEC, I struggled with them, even more, some pictures I have taken of this experience, show how my jet lag affected me! Another part of the ritual is packing, wear my jeans with nicer GNOME t-shirts and GUADECs from previous edition to show up. I decided to wear the GNOME PERU FEST t-shirts 2012, 2014 and 2015.

Being asked by migrations with interesting questions like why does Peru not have Sweden Embassy and passing the re-checked bags every transit one and one more time without shoes. All these worth when I am literally in the heaven enjoying the view of cities, islands and oceans from the top. Seeing the dancing of many shapes and colours of the clouds and the sun, is awesome!

Anyway, this time I came up with the idea to post in twitter the phrase of “You know you are in GUADEC when….” because as soon I arrived, I was striving my best to find the hotel that GNOME arrange, I found GNOME people in the way. Same story as previous GUADECs is people discovering the new place in groups, people coding in the lobby until late night and I when you woke up early morning, they are still busy in coding.

Presentations at the conference runs smoothly and they were so interested, OpenCloud, OpenOffice and other projects showed their advances. I hope Boxes can run also one day over MAC and other operative systems since we need to reach more users.

*   My impressions to improve some aspects of GUADEC 2015:

1. Advertising like banners at the main entrance may help to identify the place of the event.
2. The InfoDesk could have at least four lines instead of one. Maybe divided by last names (A-D) (E-H) (I-N) (O-Z), and maybe get another printer or set it in another table for the non-registered people. The distribution and design of the info desk is important as well as the location of different stands of Red Hat, OpenSuse, Igalia and the other sponsors.
3. I really loved the design of the GUADEC 2015 badge, Bastein did a good job using the color turquoise. It would have been so great to have the same design in t-shirts GUADEC 2015.
4. To have some food alternatives in the wiki or in the GUADEC social Webpage would have been helpful, considering prices, menus, locations and time. Some of them were closed at noon.
5. In order to meet new people during the picnic activity, (it seems like it was the first GUADEC of most of them) would have been nice to share some activities together to meet each others.
6. The use of twitter or any other social networks were not encourage to use as before.

There were two innovations this time, Jiri Eischman proposed a new way to stay in contact using a CHAT, it would have been so good if all the participants of GUADEC were added. The other was the gift for volunteers and participants. Florian Muller deserves the price, he is a good developer of GNOME shell and he is cool at the same time!

Besides the bad comments and discouragement of some developers related to the future of GNOME, I have seen the effort of the newbies to improve their projects, the enthusiasm of coala developers and the willing GNOME Asia community members were so admirable.

Many thanks to Fabiana and Andreas Nilsson for organising the event, I know it is a huge responsibility to care any single detail of it. I have met the local organiser Olive Prospt who is truth is his word, and he is a smart guy.

Thanks GUADEC for letting me organize the games called “Sport Hackaton”, it was so great thanks to the coordination of Carlos Soriano, the manager of people Syska from Indonesia and all the participants who surprise me with all the fun, it was definitely a cute unforgettable moment.

Special thanks to Tobias Mueller for encouraging me to do the GNOME America and all GNOME friends who wants to come to Peru like Jana from Republic Czech, Magdalen Berns and others… old GNOME friends like Andre Klapper, Srinivasa and BinLi, and the new ones like Rashi and Nuritzi for being so kind people!

Finally, congratulations to the winner of the pants Emily, she works for GNOME since 2006 and her labor is more than admirable as a profesional and as a person. Congrats to Shaun McCance, the new president of the GNOME Foundation and Kat for the re-election.

Posted in GNOME | | 1 Comment