patternpythonMinor
Looking for a pattern in a list
Viewed 0 times
patternlistlookingfor
Problem
I've created this function that looks for sequences in a list. If
Part of the script (the
How can it be improved?
[1,2,3] exists, it will print True. I've tested the code and it works fine.def looking_patt(pattern,cursor,found):
big_s = []
for i in range(1,101):
if i % 10 == 0:
big_s.extend([1,2,3])
else:
big_s.append(i)
# check control
print(big_s)
for i in big_s:
if i == pattern[cursor]:
cursor += 1
if cursor == len(pattern):
found.append(pattern)
print(found)
cursor = 0
else:
cursor = 0
print(len(found) > 0)Part of the script (the
for i in big_s:) has been taken from an answer in this SO question.How can it be improved?
Solution
I guess that the first part of your code is just to initialize the sample data.
Then here are a few things:
This is my attempt at it:
Then here are a few things:
- Separate initialization and main loop. I know this is just an exercise, but always doing it will help you keep the mindset.
- If you only need to count something, just count it. Don't keep track of everything.
- If you only need to check the existence of something, use a boolean value and return as soon as you've found it. Adding elements to a list so that at the end you can count them and return a boolean based on the count is definitely not an efficient way to do it.
- What you call
cursoris actually an integer, not an object, so the nameindexmay be more appropriate
- If you want to give the chance to start searching from a specific index, you may also want to have a default value for that parameter (0 looks like a good choice)
- You don't need the third parameter, that's what you are going to return
This is my attempt at it:
big_s = []
def init_big_s():
for i in range(1,101):
if i % 10 == 0:
big_s.extend([1,2,3])
else:
big_s.append(i)
def looking_patt(pattern, index=0):
for i in big_s:
if i == pattern[index]:
index += 1
if index == len(pattern):
return True
else:
index = 0
return False
init_big_s()
print looking_patt([1, 2, 3])Code Snippets
big_s = []
def init_big_s():
for i in range(1,101):
if i % 10 == 0:
big_s.extend([1,2,3])
else:
big_s.append(i)
def looking_patt(pattern, index=0):
for i in big_s:
if i == pattern[index]:
index += 1
if index == len(pattern):
return True
else:
index = 0
return False
init_big_s()
print looking_patt([1, 2, 3])Context
StackExchange Code Review Q#135374, answer score: 5
Revisions (0)
No revisions yet.