简体   繁体   中英

Indexing function for a string in python

I am trying to implement a function called say "Function" from scratch that counts how many times each parameter z of letters occurs sequentially in a string.

For example, Function('abcbcb', z=2) should return ab:1, bc:2, cb: 2

or Function('abcbcb', z=3) should return abc: 1, bcb: 2, cbc: 1

I have tried using loops and python string methods but I have not been able to write a working one yet.

Thank you!

First let's call the function another name because this one is confusing. I'll call it times.
iterable[n:k] will return the iterable from index n (inclusive) to index k(exclusive).
here is a code with explanations:

def times(str, z):
  dict ={} # we create an empty dict
  for i in range(len(str)-z+1): #we loop over the string a number of times depending on z so we can check all z length paramters
    if str[i:i+z] in dict.keys(): #if the part of the string is in the keys of the dictionary then we add one
        dict[str[i:i+z]] += 1
    else:
      dict[str[i:i+z]] = 1 # if it wasn't we set it to one
  return dict
times('abcbcb',3)

Sorry for the english, it is a second language for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM