CS105
LAB 6- Python 2

 

Objectives
  1. Answer to the Leap Year problem
  2. Strings


Answer to the Leap Year problem

 

>>> def leap(year):

if year%100==0:

if year%400==0:

print"True"

else : print "False"

else :

if year%4==0 :

print "True"

 


Strings

1.

>>> x[:4]
'I am'
>>> x[5:]
'you are'

What is x?

Given x provide a way to access x[5:7] (="you") with negative indices (Hint: use len( ))

 

2.

>>>"base" in "datacase"

What is the type of this?

 

3.

>>>mine=raw_input("My favorite number: ")

>>>yours=raw_input("Your favorite number: ")

Write a program that prints the sum of our (mine and yours) favorite numbers!

 

4.

Provide a line of code that assigns 100 "-" followed by 100 "?" to a variable named "manyDashesAndQuestionmarks"

 

5.

Define a function that has an argument named word and prints each letter of the word twice in the same line and then breaks the line.

Example:

>>>weird("CS")

C C

S S

def weird(word):

for i in word:

print i,i

 

6.

A bunch of people voted their favorite Queen song. The results were gathered in this Python list of the form [song1, votes1, song2, votes2,...]

Define a function that takes one argument ( this list..) and performs a for loop. In the end it outputs two things. The sum of the votes and the songs!

Example (and test case):

>>>myList = [35, "bicycle race", 40, "bohemian rhapsody", 50, " under pressure"]

>>>songsAndVotes(myList)

Votes: 135

Songs: bicycle race, bohemian rhapsody, under pressure

def queen(list):

votes=0

songs=""

for i in list:

if type(i)==int:

votes=votes + i

else: songs = songs +" ," + i

print "Votes:",votes

songs = songs[2:]

print songs

7.

Useful stuff!!!

>>>import string

>>>temp= "There's four new colors in the rainbow, an old man's taking polaroids"

>>>parts1=string.split(temp)

>>>parts2=string.split(temp,",")

>>>temp1=string.join(parts1)

>>>temp2=string.join(parts2)

Is temp1==temp?

What about temp2==temp?

8.

>>>replace(temp, " ", ";")

find(s,substring) returns the index of the first occurence of substring in string s. Discuss how can we use find to find the k-th occurence!


 

CS105