欢迎光临!
若无相欠,怎会相见

Python练习题之第一天

序言

做毕设工作累了,看微信公众号文章放松一下,发现了这篇文章《2018 热门编程挑战网站 Top10 ,果断收藏!》,个人感觉很不错,一天不练码代码,手生,所以就自己注册了coderbyte.com的账号,练练手。一天练几题也不用多少时间。

题目

该网站的题目都是英文的,不过也很浅显,能看懂!题目如下:

Challenge

Using the Python language, have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it (e.g. if num = 4, return (4 * 3 * 2 * 1)). For the test cases, the range will be between 1 and 18 and the input will always be an integer.

Sample Test Cases

Input:    4
Output: 24

Input:     8
Output:  40320

Hint

Think of how you can create a recursive function that multiplies N by N-1 by N-2 etc.

下一题:

Challenge

Using the Python language, have the function FirstReverse(str) take the str parameter being passed and return the string in reversed order. For example: if the input string is “Hello World and Coders” then your program should return the string sredoC dna dlroW olleH.

Sample Test Cases

Input:"coderbyte"
Output:"etybredoc"

Input:"I Love Code"
Output:"edoC evoL I"

Hint

Think of how you can loop through a string or array of characters backwards to produce a new string.

分析

从英文描述和例子的输入和输出可以知道,第一题基本上就是一个阶乘计算,当然题目中限定了数字范围是1-18,否则代码还需判断数字。

第二题就是字符串的倒序输出,我能想到的有两种方法,

  1. 借用索引
  2. 通过list

代码

第一题:

def FirstFactorial(num): 
    # code goes here 
    if num-1>0:
        num = num*FirstFactorial(num-1) # 递归
    else:
        num = 1
    return num
    
# keep this function call here  
print FirstFactorial(raw_input())

我操作的截图:

我这是又写文章,又写代码,耗得时间比较长,你也可以点击“Redo”重新做题。

第二题:方法一:

def FirstReverse(str): 
    # code goes here 
    str= str[::-1]
    return str
    
# keep this function call here  
print FirstReverse(raw_input())

方法二:

def FirstReverse(str): 
    # code goes here 
    a = []
    for i in str:
        a.append(i) #写入list
    a.reverse() # 反转
    str = ''.join(a) # 转换成字符串
    return str
    
# keep this function call here  
print FirstReverse(raw_input())

结语

本次完成了两道题目,暂时就完成这些。

如有错误,敬请指出,感谢指正!     —2018-05-07  21:51:20

赞(0) 打赏
转载请注明:飘零博客 » Python练习题之第一天
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

欢迎光临