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...
#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('=====')
目录
相关文章
|
5月前
|
移动开发 Python
Python3 notes
Python3 notes
|
18天前
|
弹性计算 人工智能 架构师
阿里云携手Altair共拓云上工业仿真新机遇
2024年9月12日,「2024 Altair 技术大会杭州站」成功召开,阿里云弹性计算产品运营与生态负责人何川,与Altair中国技术总监赵阳在会上联合发布了最新的“云上CAE一体机”。
阿里云携手Altair共拓云上工业仿真新机遇
|
15天前
|
机器学习/深度学习 算法 大数据
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
2024“华为杯”数学建模竞赛,对ABCDEF每个题进行详细的分析,涵盖风电场功率优化、WLAN网络吞吐量、磁性元件损耗建模、地理环境问题、高速公路应急车道启用和X射线脉冲星建模等多领域问题,解析了问题类型、专业和技能的需要。
2554 20
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
|
10天前
|
存储 关系型数据库 分布式数据库
GraphRAG:基于PolarDB+通义千问+LangChain的知识图谱+大模型最佳实践
本文介绍了如何使用PolarDB、通义千问和LangChain搭建GraphRAG系统,结合知识图谱和向量检索提升问答质量。通过实例展示了单独使用向量检索和图检索的局限性,并通过图+向量联合搜索增强了问答准确性。PolarDB支持AGE图引擎和pgvector插件,实现图数据和向量数据的统一存储与检索,提升了RAG系统的性能和效果。
|
14天前
|
机器学习/深度学习 算法 数据可视化
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
2024年中国研究生数学建模竞赛C题聚焦磁性元件磁芯损耗建模。题目背景介绍了电能变换技术的发展与应用,强调磁性元件在功率变换器中的重要性。磁芯损耗受多种因素影响,现有模型难以精确预测。题目要求通过数据分析建立高精度磁芯损耗模型。具体任务包括励磁波形分类、修正斯坦麦茨方程、分析影响因素、构建预测模型及优化设计条件。涉及数据预处理、特征提取、机器学习及优化算法等技术。适合电气、材料、计算机等多个专业学生参与。
1545 16
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
|
12天前
|
人工智能 IDE 程序员
期盼已久!通义灵码 AI 程序员开启邀测,全流程开发仅用几分钟
在云栖大会上,阿里云云原生应用平台负责人丁宇宣布,「通义灵码」完成全面升级,并正式发布 AI 程序员。
|
16天前
|
编解码 JSON 自然语言处理
通义千问重磅开源Qwen2.5,性能超越Llama
击败Meta,阿里Qwen2.5再登全球开源大模型王座
735 14
|
11天前
|
人工智能 开发框架 Java
重磅发布!AI 驱动的 Java 开发框架:Spring AI Alibaba
随着生成式 AI 的快速发展,基于 AI 开发框架构建 AI 应用的诉求迅速增长,涌现出了包括 LangChain、LlamaIndex 等开发框架,但大部分框架只提供了 Python 语言的实现。但这些开发框架对于国内习惯了 Spring 开发范式的 Java 开发者而言,并非十分友好和丝滑。因此,我们基于 Spring AI 发布并快速演进 Spring AI Alibaba,通过提供一种方便的 API 抽象,帮助 Java 开发者简化 AI 应用的开发。同时,提供了完整的开源配套,包括可观测、网关、消息队列、配置中心等。
557 8
|
5天前
|
Docker 容器
Docker操作 (五)
Docker操作 (五)
151 68
|
5天前
|
Docker 容器
Docker操作 (三)
Docker操作 (三)
138 69
下一篇
无影云桌面