鱼C论坛

 找回密码
 立即注册
查看: 1851|回复: 16

[已解决]第18讲课后练习查找两位字符的提问

[复制链接]
发表于 2019-6-4 00:00:23 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
各位老师好!

第18题
2. 编写一个函数 findstr(),该函数统计一个长度为 2 的子字符串在另一个字符串中出现的次数。例如:假定输入的字符串为“You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.”,子字符串为“im”,函数执行后打印“子字母串在目标字符串中共出现 3 次”。

我在做以上练习的时候,做了以下代码,

  1. def findx(str1,tar):
  2.     a = 0
  3.     s = 0
  4.     while a<(len(str1)-2):
  5.         if str1[a:a+1] == tar:
  6.             s +=1
  7.             a +=1
  8.     return s
  9. str1 = input("请输入文本:")
  10. tar = input("请输入需要查询的两位字符:")

  11. print(findx(str1,tar))
复制代码


str1为输入的字符,tar为需要搜索的字符,用切片的方法进行逐一搜索并记录查询到的次数。
但在运行的时候POWERSHELL,输入了文本和所需要查询的文字,却一直没有输出结果,请问大神是哪里出了问题呢?
盼复,谢谢!



最佳答案
2019-6-5 11:19:55
死循环,所以一直没结果,因为你的a+=1 是在满足if条件后,所以,一开始没满足,a不会自增1,就不会往后面查找了,你可以把a+=1 缩进一个单位,移出到if 外,比如下面
while a<(len(str1)-2):
        if str1[a:a+1] == tar:
            s +=1
        a +=1

18讲课后练习

18讲课后练习
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-6-4 00:11:03 | 显示全部楼层
其实你可以直接先找第一个字符,在if第二个字符,那样效率会更快一些
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-6-4 06:42:06 From FishC Mobile | 显示全部楼层
死循环啊
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-6-4 08:05:23 | 显示全部楼层
  1. import re


  2. def findx(rstr, fstr):
  3.     result = re.findall(fstr, rstr, re.S | re.M)
  4.     if result:
  5.         return len(result)


  6. raw_str = "You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted."
  7. # raw_str =input("请输入文本:")
  8. find_str = input("请输入需要查询的两位字符:")
  9. print(findx(raw_str, find_str))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-6-4 08:06:10 | 显示全部楼层
1.png
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-6-4 08:33:14 From FishC Mobile | 显示全部楼层
本帖最后由 jackz007 于 2019-6-4 08:36 编辑
  1. def findx(str1,tar):
  2.     a , s = 0 , 0
  3.     while (a = str1 . find(tar , a)) != -1:
  4.         a , s = a + 1 , s  + 1
  5.     return s
  6. str1 = input("请输入文本:")
  7. tar = input("请输入需要查询的两位字符:")
  8. print(findx(str1,tar))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-6-4 23:05:33 | 显示全部楼层
My_A 发表于 2019-6-4 00:11
其实你可以直接先找第一个字符,在if第二个字符,那样效率会更快一些

谢谢! 我也这样想过,但还是行不通。。。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-6-4 23:06:04 | 显示全部楼层

多谢!此话怎讲啊? 看不出死循环
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-6-4 23:08:01 | 显示全部楼层

谢谢! 朋友这个走不通啊
显示
PS E:\python ex\MAY> python zhaozifu.py
  File "zhaozifu.py", line 3
    while (a = str1.find(tar,a))!= -1:
             ^
SyntaxError: invalid syntax
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-6-4 23:09:09 | 显示全部楼层

多谢! 若不用 import ,我这样方法可以吗?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-6-5 00:15:27 | 显示全部楼层
My_A 发表于 2019-6-4 00:11
其实你可以直接先找第一个字符,在if第二个字符,那样效率会更快一些

你可以使用下面这个,测试过了比用re的更快

  1. def find_first(string,target):
  2.     range_start = len(string)-2    # 因为len要常用所以保存一下效率会更快
  3.     position = 0
  4.     times = 0
  5.     while position < range_start:
  6.         # 只有第一个条件成立才会比较第二个条件
  7.         if (target[0] == string[position]) and (target[1] == string[position+1]):
  8.             times += 1
  9.             position += 2
  10.         else:
  11.             position += 1

  12.     return times
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-6-5 08:07:34 | 显示全部楼层
1.png


程序运行99999次时,才相差3秒.
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-6-5 08:46:45 | 显示全部楼层
# py 3.7
import re
import datetime
#内容来自:http://english.sina.com/news/2019-06-04/detail-ihvhiqay3419510.shtml
raw_str = '''China steps up defense of rights amid trade tensions
2019-06-04 02:06:33 GMT2019-06-04 10:06:33(Beijing Time) Xinhua English
BEIJING, June 3 (Xinhua) -- China's Ministry of Education on Monday warned students and scholars of the risks of going to study in the United States citing U.S. visa restrictions, urging them to step up risk assessment and make corresponding preparations.
The alert states that the visa applications of some Chinese hoping to study in the United States have recently been restricted, with an extended review process, shortened validity period, and an increased rejection rate, which have affected their plans to study in the United States or the completion of their studies there.
"These actions have hurt the dignity of Chinese students in the United States, and also seriously hurt the feelings of the Chinese people," said Xu Yongji, an official with the ministry.
The previous week has witnessed China take prompt actions defending its rights and interests. The new mechanism of unreliable entities list to protect Chinese national and corporate interests was unveiled, additional tariffs on a list of imported U.S. products went into effect, and FedEx landed in the crosshairs of an official investigation.
FedEx has recently failed to deliver express packages to designated addresses in China, violating laws and regulations governing the express industry in China.
"International delivery firms operating in China are required to comply with Chinese laws and regulations and not to harm the legitimate rights and interests of Chinese clients," Ma Junsheng, head of the State Post Bureau, told Xinhua.
On Friday, the Chinese government decided to establish a list of unreliable entities to safeguard national security, public interests, and the legitimate rights and interests of Chinese enterprises.
The United States has imposed discriminatory measures such as blocking and cutting supplies of Chinese firms in the name of national security, on top of backpedalling and extreme-pressure tactics that derailed biliteral talks.
The decision to establish the list is made in line with international practice with the aim to safeguard the fair and reasonable international economic and trade order, and the rule-based multilateral trading system, said Wang Hejun, director of the treaty and law department with the Ministry of Commerce.
"If the United States attempts to force China into making concessions through extreme pressure and escalation of trade friction, it will never succeed," Vice Commerce Minister Wang Shouwen said Sunday at a news conference regarding a white paper titled "China's Position on the China-U.S. Economic and Trade Consultations."
China will not bow under pressure and will rise to any challenge coming its way, according to the white paper.
"Whatever the future might bring, China is confident of meeting challenges head on, turning risks into opportunities, and opening new chapters," the document read.
China will soon grant 5G licenses for commercial use, the Ministry of Industry and Information Technology (MIIT) said Monday.
The country's 5G industry has built a competitive edge by combining independent innovation and open cooperation, the MIIT said, adding that 5G standards were unified international standards jointly established by global industry players and China now owns more than 30 percent of the standard essential patents for the technology.
China, as always, welcomes enterprises at home and abroad to actively participate in the building, application and promotion of its 5G network and share the sector's development dividends, the MIIT said.



'''
find_str = 'in'
def find_first(string, target):
    range_start = len(string) - 2  # 因为len要常用所以保存一下效率会更快
    position = 0
    times = 0
    while position < range_start:
        # 只有第一个条件成立才会比较第二个条件
        if (target[0] == string[position]) and (target[1] == string[position + 1]):
            times += 1
            position += 2
        else: position += 1
    return times
def find_re(rstr, fstr):
    result = re.findall(fstr, rstr, re.S | re.M)
    if result:  return len(result)

begTime = datetime.datetime.now()

find_re(raw_str, find_str)
endTime = datetime.datetime.now()
print('re方法耗时',endTime-begTime)

begTime1 = datetime.datetime.now()


find_first(raw_str, find_str)
endTime1 = datetime.datetime.now()
print('find_first方法耗时', endTime1-begTime1)
'''
长篇文字时
re方法耗时         0:00:00
find_first方法耗时 0:00:00.001000
'''
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-6-5 11:19:55 | 显示全部楼层    本楼为最佳答案   
死循环,所以一直没结果,因为你的a+=1 是在满足if条件后,所以,一开始没满足,a不会自增1,就不会往后面查找了,你可以把a+=1 缩进一个单位,移出到if 外,比如下面
while a<(len(str1)-2):
        if str1[a:a+1] == tar:
            s +=1
        a +=1
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-6-5 22:43:11 | 显示全部楼层
再次感谢楼上各位大神!谢谢!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-7-1 00:38:58 | 显示全部楼层

re.S | re.M这个是什么意思呢
可以回答一下吗
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-7-1 00:40:01 | 显示全部楼层
yinxiuan 发表于 2019-6-5 11:19
死循环,所以一直没结果,因为你的a+=1 是在满足if条件后,所以,一开始没满足,a不会自增1,就不会往后面查找了, ...

为什么要-2呢?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-4-1 21:10

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表