Python 入门练习 - 图1
© getcodify.com

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

Notation: Those Challenges come from Rosalind

Introduction

Function:

  1. def run(a, b):
  2. Result = a + b
  3. print("hello function")
  4. return Result

Function test:

  1. C = run(1 , 5)
  2. print(C)
  1. hello function
  2. 6

Let the fun begin!

Calculate

Link
Given: Two positive integers a and b, each less than 1000.
Return: The integer corresponding to the square of the hypotenuse of the right triangle whose legs have lengths a and b.

  1. in: 3 5
  2. out: 34
  1. def run(a, b):
  2. Result = (a+b)**2 - 2ab
  3. print(Result)
  4. run(3, 4)

String splice

Link
Given: A string s of length at most 200 letters and four integers a, b, c and d.
Return: The slice of this string from indices a through b and c through d (with space in between), inclusively. In other words, we should include elements s[b] and s[d] in our slice.

  1. in:
  2. HumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheKingsmenCouldntputHumptyDumptyinhisplaceagain.
  3. 22 27 97 102
  4. out:
  5. Humpty Dumpty
  1. def run(Str, a, b, c, d):
  2. Result = Str[a:b+1] + " " Str[c:d+1]
  3. print(Result)
  4. Str = "HumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheKingsmenCouldntputHumptyDumptyinhisplaceagain."
  5. a = 22; b = 27; c = 97; d = 102
  6. run(Str, a, b, c, d)

loop

Link
Given: Two positive integers a and b (a Return: The sum of all odd integers from a through b, inclusively.

  1. in:
  2. 100 200
  3. out:
  4. 7500
  1. def run(a, b):
  2. List = [a, b]
  3. List.sort()
  4. Result = 0
  5. for i in range(List[0], List[1]+1):
  6. if i % 2 == 1:
  7. Result += i
  8. print(Result)
  9. run(100, 200)

Reading and writing

Link
Given: A file containing at most 1000 lines.
Return: A file containing all the even-numbered lines from the original file. Assume 1-based numbering of lines.

  1. def run(INPUT, OUTPUT):
  2. In = open(INPUT, 'r').readlines()
  3. Num = 0
  4. Result = ""
  5. for i in In:
  6. if Num % 2 == 1:
  7. Result += i
  8. Num += 1
  9. print(Result)
  10. F = open(OUTPUT, 'w')
  11. F.write(Result)
  12. F.close()

Words count

Link
Given: A string s of length at most 10000 letters.
Return: The number of occurrences of each word in s, where words are separated by spaces. Words are case-sensitive, and the lines in the output can be in any order.

  1. In:
  2. We tried list and we tried dicts also we tried Zen
  3. Out:
  4. and 1
  5. We 1
  6. tried 3
  7. dicts 1
  8. list 1
  9. we 2
  10. also 1
  11. Zen 1
  1. def run(Str):
  2. List = Str.split(" ")
  3. Index = list(set(List))
  4. Result = ""
  5. for i in Index:
  6. if i != "":
  7. Result += i +" " + str(List.count(i)) +"\n"
  8. print(Result)

Enjoy~

本文由Python腳本GitHub/語雀自動更新

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

GitHub: Karobben
Blog:Karobben
BiliBili:史上最不正經的生物狗