CS101_计算机科学导论_Python_1

Unit 1: How to get started: your first program

1.1 Extract url

# Write Python code that assigns to the 
# variable url a string that is the value 
# of the first URL that appears in a link 
# tag in the string page.
# Your code should print http://abc.com
# Make sure that if page were changed to

# page = 'Hello world'

# that your code still assigns the same value to the variable 'url', 
# and therefore still prints the same thing.

# page = contents of a web page

page =('

➡️http://abc.com

1.2 Highlights

1.2.1 find method
.find(,n)

➡️the position number of the target string from n (else: -1)

1.2.2. index string & selecting sub-sequences
[:]

word = 'assume'
print word[:]

➡️'assume'

1.3 Following quizzes

1.3.1 四舍五入

# Given a variable, x, that stores the 
# value of any decimal number, write Python 
# code that prints out the nearest whole 
# number to x.
# If x is exactly half way between two 
# whole numbers, round up, so
# 3.5 rounds to 4 and 2.5 rounds to 3.
# You may assume x is not negative.

# Hint: The str function can convert any number into a string.
# eg str(89) converts the number 89 to the string '89'

# Along with the str function, this problem can be solved 
# using just the information introduced in unit 1.

# x = 3.14159 
# >>> 3 (not 3.0)
# x = 27.63 
# >>> 28 (not 28.0)
# x = 3.5 
# >>> 4 (not 4.0)

x = 3.64159
num = x + 0.5        ###### key step
target = str(num)        ###### to be 'find'
point = target.find('.')
print target[:point]

1.3.2 回文

###############################################
#       Exercise by Websten from forums       #
###############################################
# A palindrome is a word or a phrase that reads 
# the same backwards as forwards. Make a program 
# that checks if a word is a palindrome. 
# If the word is a palindrome, print 0 to the terminal,
# -1 otherwise. 
# The word contains lowercase letters a-z and 
# will be at least one character long.
#
### HINT! ###
# You can read a string backwards with the following syntax:
# string[::-1] - where the "-1" means one step back.
# This exercise can be solved with only unit 1 knowledge
# (no loops or conditions)

word = "madman"
# test case 2
# word = "madman" # uncomment this to test

###
# YOUR CODE HERE. DO NOT DELETE THIS LINE OR ADD A word DEFINITION BELOW IT.
###
is_palindrome = word.find(word[::-1])        ##### search the word with reversed order  

# TESTING
print is_palindrome
# >>> 0  # outcome if word == "madam"
# >>> -1 # outcome if word == "madman"

1.4 How to solve problems

1.4.1

1.4.2

1.4.3

1.4.4

你可能感兴趣的:(python)