Python_12_Codecademy_12_实用的functions

总目录


课程页面:https://www.codecademy.com/
内容包含课程笔记和自己的扩展折腾


is_even

def is_even(n):
    if n % 2 == 0:
        return True
    else: 
        return False
print is_even(16)

Output:
True

is_int

def is_int(n):
    if n == int(n):
        return True
    else: 
        return False
"""
这里之所以不用type(n),
是因为python2中,你问他7.0的type是啥
python会说是float
但是一般人类都默认7.0是integer
"""
print is_int(7.0)

Output:
True

digit_sum

给一个多位的数字,return各个位数之和,eg. 给1234 return 10

def digit_sum(n):
    n = str(n)
    result = 0
    for i in range(len(n)):
        result += int(n[i])
    return result
print digit_sum(666)

Output:
18

factorial

ps 这里的阶乘只针对非负数的整数哦,且0!= 1

def factorial(n):
    result = 1
    if n == 0:
        return 1
    elif n > 0 and int(n) == n:
        for i in range(1, n+1):
            result *= i
        return result
    else:
        return 'null'

print factorial(0)
print factorial(3)
print factorial(3.5)
print factorial(-3.5)
Console:
1
6
null
null

is_prime

A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself. 中文:素数/质数,例如:2,3,5,7...

【方法一:用for loop,比较麻烦】

def is_prime(n):
    if n < 2 or int(n) != n:
        return False
    elif n == 2:
        return True
    else:
        for i in range(2, n):
            if n % i == 0:
                return False
                break
        else:
                return True
print is_prime(1)
print is_prime(2)
print is_prime(3)
print is_prime(5)
print is_prime(222)
print is_prime(-9)
print is_prime(0)
print is_prime(2.5)
Console:
False
True
True
True
False
False
False
False

Process finished with exit code 0

【方法二:用while loop,代码会少一些】

def is_prime(n):
    a = 2
    if n < 2 or int(n) != n:
        return False
    else:
        while a < n-1:
            if n % a == 0:
                return False
                break
            a += 1
        else:
            return True

print is_prime(1)
print is_prime(2)
print is_prime(3)
print is_prime(5)
print is_prime(222)
print is_prime(-9)
print is_prime(0)
print is_prime(2.5)
Console:
False
True
True
True
False
False
False
False

Process finished with exit code 0

Modifying strings

(从我自己的2. Strings & Console Output复制过来的)

【自创练习1:把string中的a/A全部换成*】

def no_a(my_string):
    for i in range(len(my_string)):
        if my_string[i] == "a" or my_string[i] == "A":
            my_string[i] = "*" # error!
    return my_string

print no_a("Happy birthday!")
Output:
Traceback (most recent call last):
  File "/Users/y(***)zhang/PycharmProjects/untitled1/test.py", line 11, in 
    print no_a("Happy birthday!")
  File "/Users/y(***)zhang/PycharmProjects/untitled1/test.py", line 8, in no_a
    my_string[i] = "*"
TypeError: 'str' object does not support item assignment

Process finished with exit code 1

搜了一下发现:strings are immutable... 心碎

看来只能曲线救国了:

【方法一:】strings变成list,至少strings之间能concatenate,不算太差

def no_a(my_string):
    result = []
    for i in range(len(my_string)):
        if my_string[i] != "a" and my_string[i] != "A":
            result.append(my_string[i])
        else:
            result.append("*")
    for i in range(1, len(result)): 
        result[0] = result[0] + result[i]
    return result[0]
"""
上面可以多放个变量,
比如new_string = "", 
然后for loop里面不从1开始从0开始,
最后return new_string.
不过开始写程序的时候我懒了。(结果现在还要多打说明comment...)
"""

print no_a("Happy birthday!")
Console:
H*ppy birthd*y!

Process finished with exit code 0

【方法二:】用自带的.join(list)的功能,更加简单

def no_a(my_string):
    result = []
    for i in range(len(my_string)):
        if my_string[i] != "a" and my_string[i] != "A":
            result.append(my_string[i])
        else:
            result.append("*")
    """
    a = "".join(result)
    print type(a)
    结果是,join之后的格式是string: 
    """
    return "".join(result)
print no_a("Happy birthday!")
Console:
H*ppy birthd*y!

Process finished with exit code 0

reverse

给一个string,譬如"zy",把反过来变成"yz"

【方法一:简单方法】

def reverse(ms):
    result = ""
    for char in ms:
        result = char + result
    return result

print reverse("Happy")

【方法二:用range,复习一下range的step是负数的功能】

def reverse(ms):
    n = len(ms)
    result = ""
    for i in range(n-1, -1, -1):
        result = result + ms[i]
    return result

print reverse("Happy")
Console:
yppaH

Process finished with exit code 0

anti_vowel

anti_vowel("Hey You!") should return "Hy Y!"

【方法一:我的偷懒做法】

def anti_vowel(ms):
    result = ""
    for char in ms:
        if char not in "aeiouAEIOU":
            result += char
    return result
print anti_vowel("Happy birthday") 

Output:
Hppy brthdy

【方法二:codecademy的答案】

def anti_vowel(text):
    vowels = ["a", "e", "i", "o", "u"]
    result = ""
    for char in text:
        test = char.lower()
        if test not in vowels:
            result = result + char
    return result

scrabble_score

给一个dictionary, 里面的tuple是:key-字母,value-数值。然后输入字母,输出这些字母对应的数值。

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):
    result = 0
    word = word.lower()
    for char in word:
        result += score[char]
    return result
print scrabble_score("Abc")

Output:
7

censor

要达到如下效果:
censor("this hack is wack hack", "hack")
输出:"this **** is wack ****"

def censor(text, word):
    text = text.split()
    for i in range(len(text)):
        if text[i] == word:
            text[i] == "*"*len(text[i])
    text = " ".join(text)
    return text
print censor("this hack is wack hack", "hack")

Output:
this hack is wack hack

remove_duplicates

输入[4, 1, 2, 2, 2, 1, 3], 输出[1, 2, 3, 4]

def remove_duplicates(ml):
    result = []
    for i in range(len(ml)):
        if ml[i] not in result:
            result.append(ml[i])
    return sorted(result)
print remove_duplicates([4, 1, 2, 2, 2, 1, 3])

Output:
[1, 2, 3, 4]

median

输入[4, 1, 2, 2, 2, 1, 3] 输出 2
输入[1, 1, 2, 2] 输出 1.5

def median(ml):
    ml = sorted(ml)
    n = len(ml)
    if n % 2 == 0:
        return 0.5*(ml[n/2-1] + ml[n/2+1-1])
    else:
        return ml[(n+1)/2-1]
print median([4, 1, 2, 2, 2, 1, 3])
print median([1, 1, 2, 2])
# 注意,计算机从0开始,统计学从1开始

Output:
2
1.5

你可能感兴趣的:(Python_12_Codecademy_12_实用的functions)