ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python语言程序设计Y.Daniel Liang练习题Chapter8

2021-11-24 12:30:00  阅读:188  来源: 互联网

标签:练习题 __ .__ Python self Daniel print s1 def


ckp8.1

s1 = "Welcome to python"
s2 = s1
s3 = "Welcome to Python"
s4 = "to"

a = (s1 == s2)
b = (s2.count('o'))
c = (id(s1) == id(s2))
d = (id(s1) == id(s3))
e = (s1 <= s4)
f = (s2 >= s4)
g = (s1 != s4)
h = (s1.upper())
i = (s1.find(s4))
j = (s1[4])
k = (s1[4 : 8])

l = (4 * s4)
m = (len(s1))
n = (max(s1))
o = (min(s1))
p = (s1[-4])
q = (s1.lower())
r = (s1.rfind('o'))
s = (s1.startswith('o'))
t = (s1.endswith('o'))
u = (s1.isalpha())
v = (s1 + s2)
print("a=", a)
print("b=", b)
print("c=", c)
print("d=", d)
print("e=", e)
print("f=", f)
print("g=", g)
print("h=", h)
print("i=", i)
print("j=", j)
print("k=", k)
print("l=", l)
print("m=", m)
print("n=", n)
print("o=", o)
print("p=", p)
print("q=", q)
print("r=", r)
print("s=", s)
print("t=", t)
print("u=", u)
print("v=", v)

ckp8.2

s1 = "programming 101"
s2 = "programming is fun"

s3 = s1 + s2 # Correct
# s3 = s1 - s2 Wrong
s1 == s2 # correct
s1 >= s2 # correct
i = len(s1) # correct
c = s1[0] # correct
t1 = s1[ : 5] # correct
t2 = s1[5 : ] # correct

print(i, c, t1, t2)

ckp8.3

s1 = "Welcome to Python"
s2 = s1.replace("o", "abc")
print(s1)
print(s2)

ckp8.4

x2 = s1[ : 1]

s3_g = s1 + s2

h = s1[1 : ]
i = s1[1 : 5]

s3_j = s1.lower()
s3_k = s1.upper()
s3_i = s1.strip()

m = s1.replace('e', 'E')

x3 = s1.find('e')
x4 = s1.rfind("abc")

print(isEqual1)
print(isEqual2)
print(b1)
print(b2)
print(x1)
print(x2)
print(s3_g)
print(h)
print(i)
print(s3_j)
print(s3_k)
print(s3_i)
print(m)
print(x3)
print(x4)

ckp8.5

'''
As stated earlier, a string is immutable. None of the methods in the str class changes
the contents of the string; instead, these methods create new strings. As shown in the
preceding script, s is still New England (lines 21–22) after applying the methods
s.lower(), s.upper(), s.swapcase(), and s.replace("England","Haven").

不会改变对象的值,他只不过是创建了一个新的对象罢了
'''

ckp8.6-8.8

# ckp8.6
s = str()
print(len(s))

# ckp8.7
# isupper() and islower()

# ckp8.8
# isalpha()

ckp8.9

'''
ckp8.9
The operators are actually methods defined in the str class. Defining methods for operators
is called operator overloading. Operator overloading allows the programmer to use the
built-in operators for user-defined methods. Table 8.1 lists the mapping between the operators
and methods. You name these methods with two starting and ending underscores so Python
will recognize the association. For example, to use the + operator as a method, you would
define a method named _ _add_ _. Note that these methods are not private, because they have
two ending underscores in addition to the two starting underscores. Recall that the initializer
in a class is named _ _init_ _, which is a special method for initializing an object.
'''

exe8.1

s = input("please input SSN:")
if len(s) == 11:
    a = s[0 : 3]
    b = s[4 : 6]
    c = s[7 : 11]
    if a.isdigit() and b.isdigit() and c.isdigit():
        s1 = s[3 : 5]
        s2 = s[6 : 8]
        if s1 == s2 and s1 == '-':
            print("Valid SSN")
        else:
            print("Invalid SSN")
    else:
        print("Invalid SSN")
else:
    print("Invalid SSN")

exe8.11

def reverse(s):
    newS = ""
    m = len(s)
    for i in range(m, -1, -1):
        newS = newS + s[i : i+1]
    print(newS)

def main():
    s = input("please input a string:")
    reverse(s)

main()

exe8.12

s = input("please input a genome:")
length = len(s)
msg = ""

s1 = s.replace("ATG", "0")
end1 = s1.replace("TAG", "1")
end2 = end1.replace("TAA", "2")
end3 = end2.replace("TGA", "3")
print(end3)
print()

for i in range(length+1):
    if end3[i: i+1] == "0":
        for j in range(i, length+1):
            if end3[j: j+1] == "1" or end3[j: j+1] == "2" or end3[j: j+1] == "3":
                m = j
                break
        msg = end3[i+1: m]
        print(msg)
    else:
        msg = ""

exe8.17

import Point

def main():
    #p1 = Point.Point(2.1, 2.3)
    #p2 = Point.Point(19.1, 19.2)

    a, b, c, d = eval(input("Enter two points:"))
    p1 = Point.Point(a, b)
    p2 = Point.Point(c, d)
    #print("p1=", p1)
    #print("p2=", p2)

    long = p1.__distance__(p2)
    print("The distance between the two points is ", long)
    p1.__isNearBy__(long)

main()

 

list8.1

def main():
    # Prompt the user to enter a string
    s = input("Enter a string: ").strip()
    if isPalindrome(s):
        print(s, "is a palindrome")
    else:
        print(s, " is not a palindrome")

# Check if a string is a palindrome
def isPalindrome(s):
    # The index of the first character in the string
    low = 0

    # The index of the last character in the string
    high = len(s) - 1

    while low < high:
        if s[low] != s[high]:
            return False # Not a palindrome

        low += 1
        high -= 1

    return True # The string is a palindrome

main() # Call the main function

list8.3

import Rational

# Create and initialize two rational numbers r1 and r2.
r1 = Rational.Rational(4, 2)
r2 = Rational.Rational(2, 3)

# Display results
print(r1, "+", r2, "=", r1 + r2)
print(r1, "-", r2, "=", r1 - r2)
print(r1, "*", r2, "=", r1 * r2)
print(r1, "/", r2, "=", r1 / r2)

print(r1, ">", r2, "is", r1 > r2)
print(r1, ">=", r2, "is", r1 >= r2)
print(r1, "<", r2, "is", r1 < r2)
print(r1, "<=", r2, "is", r1 <= r2)
print(r1, "==", r2, "is", r1 == r2)
print(r1, "!=", r2, "is", r1 != r2)

print("int(r2) is", int(r2))
print("float(r2) is", float(r2))

print("r2[0] is", r2[0])
print("r2[1] is", r2[1])

Point.py

import math

class Point:
    def __init__(self, x=0, y=0):
        self.__x = x
        self.__y = y

    def __str__(self):
        return "(" + str(self.__x) + "," + str(self.__y) + ")"

    def __distance__(self, secondPoint):
        long = math.sqrt((self.__x - secondPoint[0]) ** 2 + (self.__y - secondPoint[1]) ** 2)
        return format(long, ".2f")

    def __getitem__(self, index):
        if index == 0:
            return self.__x
        else:
            return self.__y

    def __isNearBy__(self, p1):
        if float(p1) <= 5:
            print("The two points are near each other")
        else:
            print("The two points are not near each other")

Rational.py

class Rational:
    def __init__(self, numerator=1, denominator=0):
        divisor = gcd(numerator, denominator)
        self.__numerator = (1 if denominator > 0 else -1) \
                           * int(numerator / divisor)
        self.__denominator = int(abs(denominator) / divisor)

    # Add a rational number to this rational number
    def __add__(self, secondRational):
        n = self.__numerator * secondRational[1] + \
            self.__denominator * secondRational[0]
        d = self.__denominator * secondRational[1]
        return Rational(n, d)

    # Subtract a rational number from this rational number
    def __sub__(self, secondRational):
        n = self.__numerator * secondRational[1] - \
            self.__denominator * secondRational[0]
        d = self.__denominator * secondRational[1]
        return Rational(n, d)

    # Multiply a rational number by this rational number
    def __mul__(self, secondRational):
        n = self.__numerator * secondRational[0]
        d = self.__denominator * secondRational[1]
        return Rational(n, d)

    # Divide a rational number by this rational number
    def __truediv__(self, secondRational):
        n = self.__numerator * secondRational[1]
        d = self.__denominator * secondRational[0]
        return Rational(n, d)

    # Return a float for the rational number
    def __float__(self):
        return self.__numerator / self.__denominator

    # Return an integer for the rational number
    def __int__(self):
        return int(self.__float__())

    # Return a string representation
    def __str__(self):
        if self.__denominator == 1:
            return str(self.__numerator)
        else:
            return str(self.__numerator) + "/" + str(self.__denominator)

    def __lt__(self, secondRational):
            return self.__cmp__(secondRational) < 0

    def __le__(self, secondRational):
            return self.__cmp__(secondRational) <= 0

    def __gt__(self, secondRational):
            return self.__cmp__(secondRational) > 0

    def __ge__(self, secondRational):
            return self.__cmp__(secondRational) >= 0

    # Compare two numbers
    def __cmp__(self, secondRational):
            temp = self.__sub__(secondRational)
            if temp[0] > 0:
                return 1
            elif temp[0] < 0:
                return -1
            else:
                return 0

    # Return numerator and denominator using an index operator
    def __getitem__(self, index):
            if index == 0:
                return self.__numerator
            else:
                return self.__denominator

def gcd(n, d):
        n1 = abs(n)
        n2 = abs(d)
        gcd = 1

        k = 1
        while k <= n1 and k <= n2:
            if n1 % k == 0 and n2 % k == 0:
                gcd = k
            k += 1

        return gcd

标签:练习题,__,.__,Python,self,Daniel,print,s1,def
来源: https://blog.csdn.net/qq_57569878/article/details/121512511

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有