Python Review

来源:互联网 发布:卫浴行业数据 编辑:程序博客网 时间:2024/06/10 03:13

1.Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number’s digits. For example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4. (Assume that the number you are given will always be positive.)

def digit_sum(x):    total = 0    while x > 0:        total += x % 10        x = x // 10        print x    return total
  • 取余 x//10
  • 取整x%10

2.Define a function is_int that takes a number x as an input.
Have it return True if the number is an integer (as defined above) and False otherwise.
For example:
is_int(7.0) # True
is_int(7.5) # False
is_int(-1) # True

def is_int(x):  absolute=abs(x)  if rounded==round(absolute):    return True  else:    return False

3.Define a function called reverse that takes a string textand returns that string in reverse. For example: reverse(“abcd”) should return “dcba”.
You may not use reversed or [::-1] to help you with this.
You may get a string containing special characters (for example, !, @, or #).

def reverse(text):    word = ""    l = len(text) - 1    while l >= 0:        word = word + text[l]        l -= 1    return word
  • 空string
  • 可以使用reserve()函数和[::-1]形成达到reserve形式

4.Define a function called anti_vowel that takes one string, text, as input and returns the text with all of the vowels removed.

For example: anti_vowel("Hey You!")should return "Hy Y!". Don’t count Y as a vowel. Make sure to remove lowercase and uppercase vowels.

def anti_vowel(text):    t=""    for c in text:        for i in "ieaouIEAOU":            if c==i:                c=""            else:                c=c        t=t+c    return t
  • 空string
  • 双重循环

5.Write a function called censor that takes two strings, text and word, as input. It should return the text with the word you chose replaced with asterisks.
For example:

censor("this hack is wack hack", "hack")

should return:

"this **** is wack ****"

Assume your input strings won’t contain punctuation or upper case letters.
The number of asterisks you put should correspond to the number of letters in the censored word.

```def censor(text, word):    words = text.split()    result =''    stars = '*'* len(word)    count = 0    for i in words:        if i == word:            words[count] = stars        count += 1    result =' '.join(words)    return result```
  • str.split(str=”“, num=string.count(str)),返回分割后的字符串列表:
    str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
    num – 分割次数。
  • You can use

    string.split()" ".join(list)

    Remember: "*" * 4 equals "****"

原创粉丝点击