Python test Development _ string Practice

Source: Internet
Author: User

Programming Learning is a long, gradual accumulation of complexity, comprehensive difficulty of a project. Need to self-drive, urge yourself to move forward. Python Test development is the key learning goal of the year.


Today comes a string of exercises, heavy on the train of thought, constantly train their own thinking.


Title: Find the most frequently occurring character in a string and output where it appears


Code implementation:

#encoding =utf-8

s = "Aaabbbhhiijk"

letter_count_dict={}

For I in S:

If Letter_count_dict.has_key (i): #判断是否在字典中出现过

Letter_count_dict[i]+=1

else: #没出现过就是1

Letter_count_dict[i] = 1

Print Letter_count_dict


Max_letter_occurrence=max (Letter_count_dict.values ())

#所有出现次数列出来, max function takes maximum value

Print Max_letter_occurrence

Max_occurrence_letters=[]

#空列表用来存储, because there could be 1 or more

For k,v in Letter_count_dict.items ():

If v==max_letter_occurrence:

#值 = When the maximum number of times occurs

Max_occurrence_letters.append (k)

#存到列表中


Print Max_occurrence_letters #遍历


For I in Max_occurrence_letters:

Max_occurrence_letter_positions = []

#存位置的列表

Start_postion=0 #从0开始找

While 1: #死循环

If S.find (i,start_postion)!=-1: #! =-1 said he found it.

Max_occurrence_letter_positions.append (S.find (i,start_postion))

Start_postion=s.find (i,start_postion) +1 #起始位置 +1 Keep your weight back, because find won't find it again.

else: #当已查找不到目标字母来, it means all the letters have been found.

Print "%s positions:%s"% (i,max_occurrence_letter_positions)

Break #死循环需要加break

Output Result:

#{' A ': 3, ' B ': 3, ' I ': 2, ' H ': 2, ' K ': 1, ' J ': 1}

#3

#[' A ', ' B ']

#a positions:[0, 1, 2]

#b positions:[3, 4, 5]


Python test Development _ string Practice

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.