Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
junhuanchen edited this page Nov 18, 2018 · 4 revisions

Document

5. 实现基础算法

上章我们学会了一些基础的硬件控制后,就来补补我们的软件基础课程吧。

1. 输入年份判断闰年

  • 闰年是公历中的名词。普通年:能被4整除但不能被100整除的年份为普通闰年。(如2004年就是闰年,1999年不是闰年);世纪年:能被400整除的为世纪闰年

  • 则有如下代码:(可以放在 main.py 中)

    def is_leap_year(year):
    	if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0:
    		print("{0} is leap year".format(year))
    	else:
    		print("{0} not is leap year".format(year))
  • 先使用runfile main.py 将其运行到解释器中,再到 repl 中调用 is_leap_year(int(input("input a leap year ")))

  • mpfshell17

    • 可以看到 2004 is leap year,说明 2004 年是闰年。
    • 可以看到 1999 not is leap year,说明 1999 年不是闰年。
    • 可以看到 2000 is leap year,说明 2000 年是闰年。
    • 你也可以继续输入更多,让它回答你哪一年是闰年。
  • 当在 REPL 时输入命令后,会提示你输入一个数值,输入后并按下确定键确认输入。

2. 生成斐波那契数列

  • 什么是斐波那契数列?它指的是,有这样一个数列 0, 1, 1, 2, 3, 5, 8, 13,特别指出:第0项是0,第1项是第一个1。从第三项开始,每一项都等于前两项之和。

  • 则有如下代码:(可以放在 main.py 中)

    def fab(n):
    	if n == 1:
    		return 0
    	if n == 2:
    		return 1
    	if n > 2:
    		return fab(n-1) + fab(n-2)
    def printfablist(n):
    	for i in range(1, n+1):
    		print(fab(i),end = ' ')
    	print('')
  • 先使用runfile main.py 将其运行到解释器中,再到 repl 中调用 printfablist(int(input('please input a number:')))

  • mpfshell16

    • 可以自己试着运算 第一项 和 第二项 的关系。
  • 当在 REPL 时输入命令后,会提示你输入一个数值,并按下确定输入,比如我输入了的 5,则依次输出 五个项的 斐波那契数列(0 1 1 2 3)。

logo

Clone this wiki locally

AltStyle によって変換されたページ (->オリジナル) /