1. Basic

loops

  • pay attention to infinite loop for while
  • enumerate(): counting index for the listchoices = [‘pizza’, ‘pasta’, ‘salad’, ‘nachos’]
    print ‘Your choices are:’
    for index, item in enumerate(choices):
    print index+1, item
  • zip(): multiple lists,  create pairs of elements when passed two lists, and will stop at the end of the shorter list.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):
    # Add your code here!
    if a>b:
    print a
    else:
    print b

functions

  • string.split()
  • ” “.join(list)
  • string.replace(word, anotherword)
  • string.index(i)
  • integer division:an integer divided by an integer will always return an integer. So 1/2 will return 0 instead of 0.5. To fix this, we’ll need to make use of the float() function. float(x)/y will correctly use normal division and so float(1)/2 will correctly return 0.5. Or use 1/2.0

2. Example

1. Board game

from random import randint

board = []

for x in range(5):
board.append([“O”] * 5)

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

print “Let’s play Battleship!”
print_board(board)

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)

for turn in range(4):
# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
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!”
break
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.”
else:
if turn==3:
print “Game Over”
else:
print “You missed my battleship!”
board[guess_row][guess_col] = “X”

# Print (turn + 1) here!
print turn+1
print_board(board)

2. Guess a number from 1-9

from random import randrange

random_number = randrange(1, 10)

count = 0
# Start your game!
while count<3:
guess = int(raw_input(“Enter a guess:”))
count+=1
if guess==random_number:
print ‘You win.’
break
else:
print ‘You lose!’
print random_number

3. is_even function

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

4. is_int function

def is_int(x):
if x-round(x)==0:
return True
else:
return False

5. digit_sum function

def digit_sum(n):
lst=[]
for i in str(n):
lst.append(int(i))
return sum(lst)

print digit_sum(1234)

6. factorial function

def factorial(x):
if x < 2:
return 1
else:
total = 1
for i in range (2, x+1):
total = total * i
return total

7. is_prime function

def is_prime(x):
if x < 2:
return False

else:
for i in range(2, x):
if x % i == 0:
return False
return True

8. string reverse function

def reverse(text):
word = “”
y = len(text) – 1
for i in range(y, -1, -1):
word += str(text[i])
return word

9. anti-vowel function:

def anti_vowel(text):
store = []
for letter in text:
if letter.lower() not in “aeiou”:
store.append(letter)
return “”.join(store)

text = “Hey look words!”

print anti_vowel(text)

10. add score function

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):
word = word.lower()
total=0
for i in word:
total=total+score[i]
return total

11. replace function

def censor(text, word):
return text.replace(word, ‘*’ * len(word))

print censor(“this hack is wack hack”,”hack”)

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

12. count repetition function

def count(sequence, item):
count=0
for i in sequence:
if i==item:
count+=1
return count

print count([1,2,1,1], 1)

13. remove odd function

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

14. product function

def product(lst):
n=1
for i in range(len(lst)):
n=n*lst[i]
return n

15. remove duplicates function

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

16. median function

def median(lst):
lst=sorted(lst)
if len(lst)%2==0:
return (lst[len(lst)/2-1]+lst[len(lst)/2])/2.0
else:
return lst[(len(lst)+1)/2-1]

Advertisements