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

#Practice Exercises for Logic and Conditionals

# Solve each of the practice exercises below.

# 1.Write a Python function is_even that takes as input the parameter number (an integer) and
# returns True if number is even and False if number is odd.
# Hint: Apply the remainder operator to n (i.e., number % 2) and compare to zero.
def is_even(number):
    if number % 2 == 0:
        return True
    else:
        return False

res = is_even(93)
print(res)
print('=====')

# 2.Write a Python function is_cool that takes as input the string name and
# returns True if name is either "Joe", "John" or "Stephen" and returns False otherwise.
# (Let's see if Scott manages to catch this.  )
def is_cool(name):
    cool_names = ["Joe", "John", "Stephen"]
    if name in cool_names:
        return True
    else:
        return False

res = is_cool("Scott")
print(res)
print('=====')

# 3.Write a Python function is_lunchtime that takes as input the parameters hour
# (an integer in the range [1,12]) and is_am (a Boolean “flag” that represents whether the hour is before noon).
# The function should return True when the input corresponds to 11am or 12pm (noon) and False otherwise.
# If the problem specification is unclear, look at the test cases in the provided template.
# Our solution does not use conditional statements.
def is_lunchtime(hour, is_am):
    if hour == 11 and is_am:
        return True
    else:
        return False

res = is_lunchtime(11, True)
print(res)
print('=====')

# 4.Write a Python function is_leap_year that take as input the parameter year and
# returns True if year (an integer) is a leap year according to the Gregorian calendar and False otherwise.
# The Wikipedia entry for leap yearscontains a simple algorithmic rule for
# determining whether a year is a leap year. Your main task will be to translate this rule into Python.
def is_leap_year(year):
    if year % 400 == 0:
        is_leap = True
    elif year % 100 == 0:
        is_leap = False
    elif year % 4 == 0:
        is_leap = True
    else:
        is_leap = False
    return is_leap

res = is_leap_year(2016)
print(res)
print('=====')

# 5.Write a Python function interval_intersect that takes parameters a, b, c, and d and
# returns True if the intervals [a,b] and [c,d] intersect and False otherwise.
# While this test may seem tricky, the solution is actually very simple and consists of one line of Python code.
# (You may assume that a≤b and c≤d.)
def interval_intersect(a, b, c, d):
    if a > d or b < c:
        return False
    else:
        return True

res = interval_intersect(1,2,3,4)
print(res)
print('=====')

# 6.Write a Python function name_and_age that take as input the parameters name (a string) and age (a number) and
# returns a string of the form "% is % years old." where the percents are the string forms of name and age.
# The function should include an error check for the case when age is less than zero.
# In this case, the function should return the string "Error: Invalid age".
def name_and_age(name, age):
    if age >= 0:
        form = "%s is %d years old." % (name, age)
    else:
        form = "Error: Invalid age"
    return form

res = name_and_age("John", -25)
print(res)
print('=====')

# 7.Write a Python function print_digits that takes an integer number in the range [0,100) and
# prints the message "The tens digit is %, and the ones digit is %." where the percents should be replaced
# with the appropriate values. The function should include an error check for the case when number is
# negative or greater than or equal to 100. In those cases,
# the function should instead print "Error: Input is not a two-digit number.".
def print_digits(number):
    if number in range(100):
        tens, ones = number // 10, number % 10
        message = "The tens digit is %d, and the ones digit is %d." % (tens, ones)
    else:
        message = "Error: Input is not a two-digit number."
    print(message)

print_digits(49)
print_digits(-10)
print('=====')

# 8.Write a Python function name_lookup that takes a string first_name that corresponds to
# one of ("Joe", "Scott", "John" or "Stephen") and then
# returns their corresponding last name ("Warren", "Rixner", "Greiner" or "Wong").
# If first_name doesn't match any of those strings, return the string "Error: Not an instructor".
def name_lookup(first_name):
    first_names = ("Joe", "Scott", "John", "Stephen")
    last_names = ("Warren", "Rixner", "Greiner", "Wong")
    if first_name in first_names:
        return last_names[first_names.index(first_name)]
    else:
        return "Error: Not an instructor"

res = name_lookup("Scott")
print(res)
print('=====')

# 9.Pig Latin is a language game that involves altering words via a simple set of rules.
# Write a Python function pig_latin that takes a string word and
# applies the following rules to generate a new word in Pig Latin.
# If the first letter in word is a consonant, append the consonant plus "ay" to the end
# of the remainder of the word. For example, pig_latin("pig") would return "igpay".
# If the first letter in word is a vowel, append "way" to the end of the word.
# For example, pig_latin("owl") returns "owlway". You can assume that word is in lower case.
# The provided template includes code to extract the first letter and the rest of word in Python.
# Note that, in full Pig Latin, the leading consonant cluster is moved to the end of the word.
# However, we don't know enough Python to implement full Pig Latin just yet.
def pig_latin(word):
    if word[0] in "aeoui":
        return word + "way"
    else:
        return word[1:] + word[0] + "ay"

res = pig_latin("owl")
print(res)
print('=====')

# 10.Challenge: Given numbers a, b, and c, the quadratic equation ax2+bx+c=0 can
# have zero, one or two real solutions (i.e; values for x that satisfy the equation).
# The quadratic formula x=−b±b2−4ac2a can be used to compute these solutions.
# The expression b2−4ac is the discriminant associated with the equation.
# If the discriminant is positive, the equation has two solutions.
# If the discriminant is zero, the equation has one solution.
# Finally, if the discriminant is negative, the equation has no solutions.
# Write a Python function smaller_root that takes an input the numbers a, b and c and
# returns the smaller solution to this equation if one exists.
# If the equation has no real solution, print the message "Error: No real solutions" and simply return.
# Note that, in this case, the function will actually return the special Python value None.
def smaller_root(a, b, c):
    discriminant = b ** 2 - 4 * a * c
    if discriminant > 0:
        return (-b - math.sqrt(discriminant)) / (2.0 * a)
    elif discriminant == 0:
        return -b / (2.0 * a)
    else:
        print("Error: No real solutions")
        return 

res = smaller_root(1.0, -2.0, 1.0)
print(res)
print('=====')
时间: 2024-09-21 00:08:56

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

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 is played by two people. The players count to three in unison and simultaneously "throw" one of three hand signals that correspond to rock, paper

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 function miles_to_feet that takes a parameter miles and # returns the number of feet in miles miles. def miles_to_feet(miles): feet = miles * 5280 ret

An Introduction to Asynchronous Programming and Twisted (1)

之前看的时候, 总觉得思路不是很清晰, 其实Dave在这个模型问题上没有说清楚, 参考同步和异步, 阻塞和非阻塞, Reactor和Proactor 对于阻塞一定是同步的, 但是反之不一定, 对于多线程本质上也是阻塞的方式, 只不过是多个线程一起阻塞, 适用于CPU密集型的任务, 因为事情总要人做的, 无论什么模型都不能让做事情的实际时间变少.  对于非阻塞, 节省的是等待的时间, 所以适用于I/O密集型任务, 因为I/O往往需要等待  Dave谈的异步就是广义的异步, 其实是非阻塞同步  而T

An Introduction to Asynchronous Programming and Twisted (3)

Part 11: Your Poetry is Served A Twisted Poetry Server Now that we've learned so much about writing clients with Twisted, let's turn around and re-implement our poetry server with Twisted too. And thanks to the generality of Twisted's abstractions, i

An Introduction to Asynchronous Programming and Twisted (2)

Part 6: And Then We Took It Higher Part5中的client2.0, 在封装性上已经做的不错, 用户只需要了解和修改PoetryProtocol, PoetryClientFactory就可以完成一个应用. 其实此处, protocol的逻辑就是接受数据, 接受完以后通知factory处理, 这段逻辑已经可以作为common的框架代码, 用户无需改动. 真正需要用户每次根据上下文修改的是, 当数据接受完后的处理逻辑poem_finished(print? sa

再读《Parallel Programming with Python》并作笔记

并发编程,在哪个语言里都属于高端应用,一定得会了才好意思说懂了这门语言. 在工作中用得并不是很多,忘了一些内容,就慢慢看,慢慢补上. 今天一天看了近三分之一(我看外文越来越快了??:)), 实践一下多线程的threading模块. #coding: utf-8 import logging, threading from Queue import Queue logger = logging.getLogger() logger.setLevel(logging.DEBUG) formatter

Machine and Deep Learning with Python

Machine and Deep Learning with Python Education Tutorials and courses Supervised learning superstitions cheat sheet Introduction to Deep Learning with Python How to implement a neural network How to build and run your first deep learning network Neur

Python图形用户界面

tkinter是Python中可用于构建GUI的众多工具集之一. tkinter模块 # 可以使用import tkinter as tk并通过tk.thing去引用其中的内容 from tkinter import * window = Tk() window.mainloop() 以上代码可以显示一个空白的根窗口.可以将其看成是应用程序的最外层容器,创建其他插件(widget)的时候就需要用到它.如果关闭屏幕上的窗口,则相应的窗口对象就会被销毁.所有的应用程序都只有一个主窗口:此外,还可以通

Awesome Python

    Awesome Python      A curated list of awesome Python frameworks, libraries, software and resources. Inspired by awesome-php. Awesome Python Environment Management Package Management Package Repositories Distribution Build Tools Interactive Interp