2020-04
16

循环,循环

By xrspook @ 19:58:07 归类于: 扮IT

觉得自己虽然见过递归,但几乎不用,不逼着我我都不用,循环用得越来越遛。前两题我和参考答案得出的结论一致,最后一题,我觉得参考答案有问题。下面的都是我的脚本。下面要用到的words.txt在这里

Exercise 7:This question is based on a Puzzler that was broadcast on the radio program Car Talk: Give me a word with three consecutive double letters. I’ll give you a couple of words that almost qualify, but don’t. For example, the word committee, c-o-m-m-i-t-t-e-e. It would be great except for the ‘i’ that sneaks in there. Or Mississippi: M-i-s-s-i-s-s-i-p-p-i. If you could take out those i’s it would work. But there is a word that has three consecutive pairs of letters and to the best of my knowledge this may be the only word. Of course there are probably 500 more but I can only think of one. What is the word? Write a program to find it. Solution: http://thinkpython2.com/code/cartalk1.py.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def double_letter(word):
    num = 0
    i = 0
    if len(word) >= 6:
        while i < len(word)-1:
            if word[i] == word[i+1]: 
                num = num + 1
                i = i + 2
            elif i > 2 and word[i-2] != word[i-3]:
                break
            else:
                i = i + 1
        if num == 3:
            print(word)
fin = open('words.txt')
n = 0
for line in fin:
    word = line.strip()
    double_letter(word)
# bookkeeper
# bookkeepers
# bookkeeping
# bookkeepings

Exercise 8: Here’s another Car Talk Puzzler: “I was driving on the highway the other day and I happened to notice my odometer. Like most odometers, it shows six digits, in whole miles only. So, if my car had 300,000 miles, for example, I’d see 3-0-0-0-0-0. “Now, what I saw that day was very interesting. I noticed that the last 4 digits were palindromic; that is, they read the same forward as backward. For example, 5-4-4-5 is a palindrome, so my odometer could have read 3-1-5-4-4-5. “One mile later, the last 5 numbers were palindromic. For example, it could have read 3-6-5-4-5-6. One mile after that, the middle 4 out of 6 numbers were palindromic. And you ready for this? One mile later, all 6 were palindromic! “The question is, what was on the odometer when I first looked?” Write a Python program that tests all the six-digit numbers and prints any numbers that satisfy these requirements. Solution: http://thinkpython2.com/code/cartalk2.py.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def is_palindrome(word):
    if word[::-1] == word:
        return True 
def test_palindrome(number):
    if is_palindrome(str(number)[2:]):
        if is_palindrome(str(number+1)[1:]):
            if is_palindrome(str(number+2)[1:1]):
                if is_palindrome(str(number+3)):
                    return True
for number in range(100000, 999999):
    if test_palindrome(number):
        print(number)
# 198888
# 199999

Exercise 9: Here’s another Car Talk Puzzler you can solve with a search: “Recently I had a visit with my mom and we realized that the two digits that make up my age when reversed resulted in her age. For example, if she’s 73, I’m 37. We wondered how often this has happened over the years but we got sidetracked with other topics and we never came up with an answer. “When I got home I figured out that the digits of our ages have been reversible six times so far. I also figured out that if we’re lucky it would happen again in a few years, and if we’re really lucky it would happen one more time after that. In other words, it would have happened 8 times over all. So the question is, how old am I now?” Write a Python program that searches for solutions to this Puzzler. Hint: you might find the string method zfill useful. Solution: http://thinkpython2.com/code/cartalk3.py.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
year = 99
meet = int(input('how many times have we met?(1-8): '))
print('mom born me at', '\t','my age', '\t',"mon's age")
for i in range(10, 80): # 假设你妈生你的最低年龄是10,最高年龄是80
    n = 0
    for age in range(1, year):
        if age < int(str(age).zfill(2)[::-1]) and int(str(age).zfill(2)[::-1]) - age == i:            
            # print(i, '\t\t', age, '\t\t', str(age).zfill(2)[::-1])             
            n = n + 1
            if n == meet:
                print(i, '\t\t', age, '\t\t', str(age).zfill(2)[::-1])
 
# how many times have we met?(1-8): 6
# mom born me at   my age          mon's age
# 18               57              75
# 27               58              85
# 36               59              95
 
# how many times have we met?(1-8): 8
# mom born me at   my age          mon's age
# 18               79              97
 
# mom born me at   my age          mon's age
# 18               2               20
# 18               13              31
# 18               24              42
# 18               35              53
# 18               46              64
# 18               57              75
# 18               68              86
# 18               79              97
# 27               3               30
# 27               14              41
# 27               25              52
# 27               36              63
# 27               47              74
# 27               58              85
# 27               69              96
# 36               4               40
# 36               15              51
# 36               26              62
# 36               37              73
# 36               48              84
# 36               59              95
# 45               5               50
# 45               16              61
# 45               27              72
# 45               38              83
# 45               49              94
# 54               6               60
# 54               17              71
# 54               28              82
# 54               39              93
# 63               7               70
# 63               18              81
# 63               29              92
# 72               8               80
# 72               19              91
2020-04
15

反正这是我的答案

By xrspook @ 19:44:55 归类于: 扮IT

题目摆在这里,没有确切的答案,下面是我的解答,对不对不知道。words.txt资源在这里。

There are solutions to these exercises in the next section. You should at least attempt each one before you read the solutions.

Exercise 1: Write a program that reads words.txt and prints only the words with more than 20 characters (not counting whitespace).

Exercise 2: In 1939 Ernest Vincent Wright published a 50,000 word novel called Gadsby that does not contain the letter “e”. Since “e” is the most common letter in English, that’s not easy to do. In fact, it is difficult to construct a solitary thought without using that most common symbol. It is slow going at first, but with caution and hours of training you can gradually gain facility. All right, I’ll stop now. Write a function called has_no_e that returns True if the given word doesn’t have the letter “e” in it. Write a program that reads words.txt and prints only the words that have no “e”. Compute the percentage of words in the list that have no “e”.

Exercise 3: Write a function named avoids that takes a word and a string of forbidden letters, and that returns True if the word doesn’t use any of the forbidden letters. Write a program that prompts the user to enter a string of forbidden letters and then prints the number of words that don’t contain any of them. Can you find a combination of 5 forbidden letters that excludes the smallest number of words?

Exercise 4: Write a function named uses_only that takes a word and a string of letters, and that returns True if the word contains only letters in the list. Can you make a sentence using only the letters acefhlo? Other than “Hoe alfalfa”?

Exercise 5: Write a function named uses_all that takes a word and a string of required letters, and that returns True if the word uses all the required letters at least once. How many words are there that use all the vowels aeiou? How about aeiouy?

Exercise 6: Write a function called is_abecedarian that returns True if the letters in a word appear in alphabetical order (double letters are ok). How many abecedarian words are there?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
fin = open('words.txt') # 第1小问
for line in fin:
    if len(line) >= (20+2):
        word = line.strip()
        print(word)
# counterdemonstrations
# hyperaggressivenesses
# microminiaturizations
 
def has_no_e(word): # 第2小问
    for letter in word:
        if letter == 'e':
            return False
    return True
fin = open('words.txt')
all = 0
count = 0
for line in fin:
    word = line.strip()
    all = all + 1
    if has_no_e(word):
        print(word)
        count = count + 1
print(count, 'words without e')
print('{:.0%}'.format(count/all), 'words without e')
# ...
# zymosis
# zymotic
# zymurgy
# 37641 words without e
# 33% words without e
 
def avoids(word, x): # 第3小问,最后一个问题举手投降
    for letterw in word:
        for letterx in x:
            if letterw == letterx:
                return False
    return True
fin = open('words.txt')
x = input('withtout: ')
num = 0
# word = 'jwrojgre' # input('word is ')
# print(avoids(word, x))
for line in fin:
    word = line.strip()
    if avoids(word, x):
        num = num + 1
print(num, 'words without', x)
# withtout: aeiou
# 107 words without aeiou
# count = 0
# import itertools
# for i in itertools.combinations('abcdefghijklmnopqrstuvwxyz', 5):
#     print(''.join(i))
#     count = count + 1
# print(count) # 65780个排列组合的可能性啊啊啊啊啊啊
 
 
def uses_only(word, x): # 第4小问
    for letter in word:
        if letter not in x:
            return False
    return True
word = input('word is ')
x = input('uses is ')
print(uses_only(word, x))
# word is abc
# uses is efg
# False
 
def uses_all(word, x): # 第5小问
    for letter in x:
        if letter not in word:
            return False
    return True
fin = open('words.txt')
x = input('must use: ' )
num = 0
for line in fin:
    word = line.strip()
    if uses_all(word, x):
        num = num + 1
print(num, 'words with', x)
# must use: aeiou
# 598 words with aeiou
# must use: aeiouy
# 42 words with aeiouy
 
def is_abecedarian(word): # 第6小问
    index = 1
    while index < len(word) - 1:
        if ord(word[index-1]) > ord(word[index]):
            return False
        index = index + 1
    return True
fin = open('words.txt')
num = 0
for line in fin:
    word = line.strip()
    if is_abecedarian(word):
        num = num + 1
print(num, 'words is abecedarian')
# 1573 words is abecedarian
2020-04
15

字符偏移加密

By xrspook @ 13:28:09 归类于: 扮IT

本来我根本没考虑字母以外的那些怎么办,测试过参考答案以后,发现原来字母以外的东西原始输出,于是我也这般弄了,等于再加一个是否字母的判断,折腾。不告诉人家怎么把字符合并成字符串,我就只好准备两个对象二人转连接。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def rotate_word(something, n): # a-z: 97-122, A-Z: 65-90
    newletter1 = ''
    for letter in something:
        if ord(letter) < ord('A') or ord('Z') < ord(letter) < ord('a') or ord('z') < ord(letter):
            newletter2 = newletter1 + letter
        else:
            if ord(letter) + n > ord('z'):
                newletter2 = newletter1 + chr(ord(letter) + n - 26)
            elif ord('a') > ord(letter) + n > ord('Z'):
                newletter2 = newletter1 + chr(ord(letter) + n - 26)
            else:
                newletter2 = newletter1 + chr(ord(letter) + n)
        newletter1 = newletter2
    return newletter2
something = input('please write something: ')
n = int(input('how many shifts do you want: '))
print('before:', something)
print('after :', rotate_word(something, n))
# please write something: IBM
# how many shifts do you want: -1
# before: IBM
# after : HAL
# please write something: g858^h{O
# how many shifts do you want: 6
# before: g858^h{O
# after : m858^n{U
2020-04
14

一句秒杀一段话

By xrspook @ 19:52:09 归类于: 扮IT

还记得初中的时候数学老师跟我说初等数学比高等数学难多了,幸好,我这辈子暂时只学过高等数学,而且几乎都还给大学老师了……

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# def first(word):
#     return word[0]
# def last(word):
#     return word[-1]
# def middle(word):
#     return word[1:-1]
# def is_palindrome(word):
#     if len(word) <= 1:
#         return True
#     elif first(word) != last(word):
#         return False
#     else:
#         return is_palindrome(middle(word))
def is_palindrome(word):
    return word[::-1] == word
word = input('word is ')
print(is_palindrome(word))
# word is qwerreq
# False
# word is poiuuiop
# True
2020-04
13

制表符

By xrspook @ 19:14:09 归类于: 扮IT

题目本身很简单,对我这种新手难就难在完全靠自己去摸索格式。这本书之前根本没说过要怎么输出制表符,一个制表符不能解决问题的时候要连续用2个,幸好这里两个就够了,如果超过16个字符,还得3个或以上制表符。于是明明很简单的print输出里面除了套个必须有的while以外还得来一对if-else分开整除了和有尾数的情况。为什么出题的人就这么喜欢超纲呢?????

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import math
def mysqrt(a):
    x  = 10
    while True:
        y = (x + a/x) / 2
        if abs(y - x) < 1e-11:
            break
        x = y
    return y
def test_squre_root():
    print('a\tmysqrt(a)\tmath.sqrt(a)\tdiff')
    print('-\t---------\t------------\t----')
    a = 1
    while a < 10:
        if mysqrt(a)%1 == 0:
            print(str(float(a))+'\t'+str(float('%.11f'% mysqrt(a)))+'\t\t'+str(float('%.11f'% math.sqrt(a)))+'\t\t'+str(float('%.11e'% abs(mysqrt(a)-math.sqrt(a)))))
        else:
            print(str(float(a))+'\t'+str(float('%.11f'% mysqrt(a)))+'\t'+str(float('%.11f'% math.sqrt(a)))+'\t'+str(float('%.11e'% abs(mysqrt(a)-math.sqrt(a)))))
        a = a + 1
test_squre_root()
© 2004 - 2024 我的天 | Theme by xrspook | Power by WordPress