Recursive articles(递归篇)
Feibo sequence
def fib(number):
if number==0 or number == 1:
return number
else:
return fib(number-1) + fib(number-2)
for i in range(8):
print("fib(%2d) = %2d" % (i,fib(i)))
We can control the time of the function.
def fib(number):
if number==0 or number == 1:
return number
else:
return fib(number-1) + fib(number-2)
while True:
a = int(input("How many do you want?"
"\nThis integer must be > 0"
"Please enter your integer:"))
if a < 0:
print("The integer of you enter is wrong,please enter again!\n")
continue
for i in range(a+1):
print("fib(%d) = %2d" % (i,fib(i)))
print()
List's using methods.
# creating an empty list
list = []
# add new value to the list
for number in range(1,11):
list += [ number ]
print(list)
print()
# len(list) is the method to get the length of the list
print("There are",len(list),"elements in the list")
print()
# print the values in list
i = 0
for item in list:
print("list[%d] is %d"%(i,item))
i += 1
print()
# change the value in list
list[0] = 100
# if the index lower than 0
# it will Count from the right
# this is a logical error that is not serious
# better never use it!!!!!
list[-3] = 999
print(list)
Dictionary
# creating empty dictionary
empty_dictionary={"name":"No"}
# creating another dictionary
grade={"name":"Sabo",
"grade":"Good!",
}
# output the grade
print("grade dictionary is")
print(grade)
print()
# add to our empty dictionary
print("before add grade")
print("empty_dictionary is ")
print(empty_dictionary)
print()
print("after add grade")
print("empty_dictionary is ")
empty_dictionary.update(grade)
print(empty_dictionary)