如何用python编写简单的代码?

0
Python C/C++ python编码 3470 次浏览

这篇文章包括用Python编写的斐波那契数列,三位数的水仙花数和百钱买百鸡的基础代码

  一、斐波那契数列:

  '''
  def hanshu(n):
  n_1 = 1
  n_2 = 1
  m = n
  sumn = 0
  for a in range(1,m+1):
  if m == 1:
  return n_1
  if m== 2:
  return n_2
  sumn = n_1 + n_2
  n_2 = n_1
  n_1 = sumn
  print(sumn,end = " ")
  hanshu(20)
  '''

 

  二、找出1-1000之内的水仙花数: 

 def hanshu(n):
  sumn = 0
  m = n
  for dix in range(1,4):
  m = m % 10
  sumn = sumn + m ** 3
  m = n // 10
  if sumn == n:
  print(n,end = " ")
  def hanshu1():
  for b in range(1,1000):
  hanshu(b)
  hanshu1()

 

  三、百钱买百鸡:公鸡5元一只,母鸡3元一只,小鸡0.5元一只,100块钱买100只鸡

  问:应该买多少只公鸡母鸡和小鸡,一共有几种买法

  设:公鸡为x只,母鸡为y只,小鸡为z只  

   x = 0
  while x <= 100:
  y = 0
  while y <= 100:
  z = 0
  while z <= 100:
  if x + y + z == 100 and 5 * x +3 * y +0.5 * z == 100:
  print(x,y,z)
  z += 1
  y += 1
  x += 1

文章为博为峰网校(www.atstudy.com)原创

请尽量让自己的答案能够对别人有帮助

35个答案

默认排序 按投票排序
1 2