1. #Practice Exercises for Logic and Conditionals
  2. # Solve each of the practice exercises below.
  3. # 1.Write a Python function is_even that takes as input the parameter number (an integer) and
  4. # returns True if number is even and False if number is odd.
  5. # Hint: Apply the remainder operator to n (i.e., number % 2) and compare to zero.
  6. def is_even(number):
  7. if number % 2 == 0:
  8. return True
  9. else:
  10. return False
  11. res = is_even(93)
  12. print(res)
  13. print('=====')
  14. # 2.Write a Python function is_cool that takes as input the string name and
  15. # returns True if name is either "Joe", "John" or "Stephen" and returns False otherwise.
  16. # (Let's see if Scott manages to catch this. ☺ )
  17. def is_cool(name):
  18. cool_names = ["Joe", "John", "Stephen"]
  19. if name in cool_names:
  20. return True
  21. else:
  22. return False
  23. res = is_cool("Scott")
  24. print(res)
  25. print('=====')
  26. # 3.Write a Python function is_lunchtime that takes as input the parameters hour
  27. # (an integer in the range [1,12]) and is_am (a Boolean “flag” that represents whether the hour is before noon).
  28. # The function should return True when the input corresponds to 11am or 12pm (noon) and False otherwise.
  29. # If the problem specification is unclear, look at the test cases in the provided template.
  30. # Our solution does not use conditional statements.
  31. def is_lunchtime(hour, is_am):
  32. if hour == 11 and is_am:
  33. return True
  34. else:
  35. return False
  36. res = is_lunchtime(11, True)
  37. print(res)
  38. print('=====')
  39. # 4.Write a Python function is_leap_year that take as input the parameter year and
  40. # returns True if year (an integer) is a leap year according to the Gregorian calendar and False otherwise.
  41. # The Wikipedia entry for leap yearscontains a simple algorithmic rule for
  42. # determining whether a year is a leap year. Your main task will be to translate this rule into Python.
  43. def is_leap_year(year):
  44. if year % 400 == 0:
  45. is_leap = True
  46. elif year % 100 == 0:
  47. is_leap = False
  48. elif year % 4 == 0:
  49. is_leap = True
  50. else:
  51. is_leap = False
  52. return is_leap
  53. res = is_leap_year(2016)
  54. print(res)
  55. print('=====')
  56. # 5.Write a Python function interval_intersect that takes parameters a, b, c, and d and
  57. # returns True if the intervals [a,b] and [c,d] intersect and False otherwise.
  58. # While this test may seem tricky, the solution is actually very simple and consists of one line of Python code.
  59. # (You may assume that a≤b and c≤d.)
  60. def interval_intersect(a, b, c, d):
  61. if a > d or b < c:
  62. return False
  63. else:
  64. return True
  65. res = interval_intersect(1,2,3,4)
  66. print(res)
  67. print('=====')
  68. # 6.Write a Python function name_and_age that take as input the parameters name (a string) and age (a number) and
  69. # returns a string of the form "% is % years old." where the percents are the string forms of name and age.
  70. # The function should include an error check for the case when age is less than zero.
  71. # In this case, the function should return the string "Error: Invalid age".
  72. def name_and_age(name, age):
  73. if age >= 0:
  74. form = "%s is %d years old." % (name, age)
  75. else:
  76. form = "Error: Invalid age"
  77. return form
  78. res = name_and_age("John", -25)
  79. print(res)
  80. print('=====')
  81. # 7.Write a Python function print_digits that takes an integer number in the range [0,100) and
  82. # prints the message "The tens digit is %, and the ones digit is %." where the percents should be replaced
  83. # with the appropriate values. The function should include an error check for the case when number is
  84. # negative or greater than or equal to 100. In those cases,
  85. # the function should instead print "Error: Input is not a two-digit number.".
  86. def print_digits(number):
  87. if number in range(100):
  88. tens, ones = number // 10, number % 10
  89. message = "The tens digit is %d, and the ones digit is %d." % (tens, ones)
  90. else:
  91. message = "Error: Input is not a two-digit number."
  92. print(message)
  93. print_digits(49)
  94. print_digits(-10)
  95. print('=====')
  96. # 8.Write a Python function name_lookup that takes a string first_name that corresponds to
  97. # one of ("Joe", "Scott", "John" or "Stephen") and then
  98. # returns their corresponding last name ("Warren", "Rixner", "Greiner" or "Wong").
  99. # If first_name doesn't match any of those strings, return the string "Error: Not an instructor".
  100. def name_lookup(first_name):
  101. first_names = ("Joe", "Scott", "John", "Stephen")
  102. last_names = ("Warren", "Rixner", "Greiner", "Wong")
  103. if first_name in first_names:
  104. return last_names[first_names.index(first_name)]
  105. else:
  106. return "Error: Not an instructor"
  107. res = name_lookup("Scott")
  108. print(res)
  109. print('=====')
  110. # 9.Pig Latin is a language game that involves altering words via a simple set of rules.
  111. # Write a Python function pig_latin that takes a string word and
  112. # applies the following rules to generate a new word in Pig Latin.
  113. # If the first letter in word is a consonant, append the consonant plus "ay" to the end
  114. # of the remainder of the word. For example, pig_latin("pig") would return "igpay".
  115. # If the first letter in word is a vowel, append "way" to the end of the word.
  116. # For example, pig_latin("owl") returns "owlway". You can assume that word is in lower case.
  117. # The provided template includes code to extract the first letter and the rest of word in Python.
  118. # Note that, in full Pig Latin, the leading consonant cluster is moved to the end of the word.
  119. # However, we don't know enough Python to implement full Pig Latin just yet.
  120. def pig_latin(word):
  121. if word[0] in "aeoui":
  122. return word + "way"
  123. else:
  124. return word[1:] + word[0] + "ay"
  125. res = pig_latin("owl")
  126. print(res)
  127. print('=====')
  128. # 10.Challenge: Given numbers a, b, and c, the quadratic equation ax2+bx+c=0 can
  129. # have zero, one or two real solutions (i.e; values for x that satisfy the equation).
  130. # The quadratic formula x=−b±b2−4ac2a can be used to compute these solutions.
  131. # The expression b2−4ac is the discriminant associated with the equation.
  132. # If the discriminant is positive, the equation has two solutions.
  133. # If the discriminant is zero, the equation has one solution.
  134. # Finally, if the discriminant is negative, the equation has no solutions.
  135. # Write a Python function smaller_root that takes an input the numbers a, b and c and
  136. # returns the smaller solution to this equation if one exists.
  137. # If the equation has no real solution, print the message "Error: No real solutions" and simply return.
  138. # Note that, in this case, the function will actually return the special Python value None.
  139. def smaller_root(a, b, c):
  140. discriminant = b ** 2 - 4 * a * c
  141. if discriminant > 0:
  142. return (-b - math.sqrt(discriminant)) / (2.0 * a)
  143. elif discriminant == 0:
  144. return -b / (2.0 * a)
  145. else:
  146. print("Error: No real solutions")
  147. return
  148. res = smaller_root(1.0, -2.0, 1.0)
  149. print(res)
  150. print('=====')

An Introduction to Interactive Programming in Python (Part 1) -- Week 2_2 练习的更多相关文章

  1. An Introduction to Interactive Programming in Python (Part 1) -- Week 2_3 练习

    Mini-project description - Rock-paper-scissors-lizard-Spock Rock-paper-scissors is a hand game that ...

  2. An Introduction to Interactive Programming in Python

    这是在coursera上面的一门学习pyhton的基础课程,由RICE的四位老师主讲.生动有趣,一共是9周的课程,每一周都会有一个小游戏,经历一遍,对编程会产生很大的兴趣. 所有的程序全部在老师开发的 ...

  3. Mini-project # 1 - Rock-paper-scissors-___An Introduction to Interactive Programming in Python"RICE"

    Mini-project description - Rock-paper-scissors-lizard-Spock Rock-paper-scissors is a hand game that ...

  4. An Introduction to Interactive Programming in Python (Part 1) -- Week 2_1 练习

    # Practice Exercises for Functions # Solve each of the practice exercises below. # 1.Write a Python ...

  5. 【python】An Introduction to Interactive Programming in Python(week two)

    This is a note for https://class.coursera.org/interactivepython-005 In week two, I have learned: 1.e ...

  6. Quiz 6b Question 8————An Introduction to Interactive Programming in Python

     Question 8 We can use loops to simulate natural processes over time. Write a program that calcula ...

  7. Quiz 6b Question 7————An Introduction to Interactive Programming in Python

     Question 7 Convert the following English description into code. Initialize n to be 1000. Initiali ...

  8. Quiz 6a Question 7————An Introduction to Interactive Programming in Python

     First, complete the following class definition: class BankAccount: def __init__(self, initial_bal ...

  9. Mini-project # 4 - "Pong"___An Introduction to Interactive Programming in Python"RICE"

    Mini-project #4 - "Pong" In this project, we will build a version of Pong, one of the firs ...

随机推荐

  1. 【原】自定义UIPageControl的圆点

    在下面的两种情况下会导致圆点贴图刷新: 1.用户调用setCurrentPage:(NSInteger)currentPage时 所以重载这个函数便可拦截 2.点击圆点矩形区域时     这说明,我们 ...

  2. C语言-05-内存分析

    一.进制 1> 内存细节 根据数据类型分配相应大小的内存空间 内存空间由高地址向低地址分配 数据一般按照从高位到低位存储 2> 常用的进制格式 十进制 ① 由0~9十个数字组成 ② 逢10 ...

  3. 从1.5k到18k, 一个程序员的5年成长之路

    昨天收到了心仪企业的口头offer, 回首当初什么都不会开始学编程, 到现在恰好五年. 整天在社区晃悠, 看了不少的总结, 在这个时间点, 我也写一份自己的总结吧. 我一直在社区分享, 所以, 这篇总 ...

  4. Memcache笔记03-php操作Memcached

    通过php程序操作Memcached服务几种形式 Memcache 扩展 Memcached 扩展 Socket套接字操作 memcached-client.php(函数) 对于php扩展来说,dan ...

  5. jQuery Form 表单提交插件-----formSerialize,fieldSerialize,fieldValue,resetForm,clearForm,clearFields的 应用

    一.jQuery Form的其他api  1.  formSerialize 将表单序列化成查询串.这个方法将返回一个形如: name1=value1&name2=value2的字符串.是否可 ...

  6. history介绍及bash命令快速调用

    在日常工作中,能够快速并准确的使用命令是必不可少的,下面为大家介绍一下其中的小技巧. 一.查找命令历史——history 使用history能够快速的找到之前输入过的命令. # history 大家可 ...

  7. SVN同步大坑

    遇到的问题 这两天一直在搞svn的主从备份,使用的方法是svnsync做的主从同步,同步大部分的仓库都没有什么问题很顺利的就同步完成了,不了解svnsync同步的可以看我这篇,但是在在同步2个仓库的时 ...

  8. TC79

    /* INSERT INTO TC79(PatientID,AdmissionDate,DischargeDate,Cost) SELECT * FROM ( SELECT 709,TO_DATE(' ...

  9. [转载]两个半小时学会Perl

    Learn Perl in about 2 hours 30 minutes By Sam Hughes Perl is a dynamic, dynamically-typed, high-leve ...

  10. 详解Webwork中Action 调用的方法

    详解Webwork中Action 调用的方法 从三方面介绍webwork action调用相关知识: 1.Webwork 获取和包装 web 参数 2.这部分框架类关系 3.DefaultAction ...