python 17

python 17

0.编一个符合以下要求的函数:
a)计算打印所有参数的和乘以基数(base=3)的结果
b)如果参数中最后一个参数为(base=5),则设定基数为5,基数不参与求和计算。

def jisuan(*pram,base=3):
      sum=0
      n=len(pram)
      while n>0:
            sum=sum+pram[n-1]
            n=n-1
      return sum*base

.寻找水仙花数
如果一个3位数等于其各位数字的立方和,则称这个数为水仙花数,例如153=13+53+3^3,因此153是一个水仙花数,编写一个程序,找出所有的水仙花数。

for i in range(100,1000):
    a=str(i)
    b=0
    for each in a:
        b=b+int(each)**3
    if i==b:
        print(i)

编写一个函数findstr(),该函数统计一个长度为2的子字符串在另一个字符串中出现的次数,例如:假如输入的字符串为:You cannot improve your past,but you can improve your future.Once time is wasted,life is wasted.子字符串为im,该函数执行后打印“子字符串在目标字符串中共常出现3次”。

def findstr(x,y):
      count=0
      for each in x:
            if each==y[0]:
                  if x[(x.index(each))+1]==y[1]: #error because index return the first researched str
                        count+=1
      return count

def findstr(x,y):
      count=0
      for each in range(len(x)-1):
            if x[each]==y[0]:
                  if x[each+1]==y[1]:
                        count+=1
      return count

猜你喜欢

转载自blog.csdn.net/XJTU_Kris/article/details/89646776