I need to find a longest sequence of 5's in a list user_scores = [1, 5, 5, 1, 5, 5, 5, 2, 5, 5, 1, 5]
without using any libraries or built in functions (like max
)
My solution is
key = 5
max_sequence = 0
current_sequence = 0
new_sequence = 0
for score in user_scores:
if score == key:
current_sequence = 1
current_sequence = max_sequence
elif score != key:
current_sequence = 0
else:
print(max_sequence)
Obviously it doesn't work at all. Trying my best to learn algorithms so i would appreciate an explanation with a code.
CodePudding user response:
Hope the explanation in comment will make it clear, if not please ask I'll make a more detailed answer :)
user_scores = [1, 5, 5, 1, 5, 5, 5, 2, 5, 5, 1, 5]
key = 5
max_sequence = 0
current_sequence = 0
for score in user_scores:
if score == key:
#If it's the right key then you found another one in the sequence
current_sequence = 1
else:
#Otherwise you'r not in a sequence so current_sequence size is empty
current_sequence = 0
if current_sequence > max_sequence:
#If the current sequence size is bigger than the max then it's the new max
max_sequence = current_sequence
print(max_sequence)
CodePudding user response:
You can try this:
- If you reach to different num reset long_seq.
- If updating long_seq save this update in max_seq (if larger than previous longest sequense).
like below:
user_scores = [1, 5, 5, 1, 5, 5, 5, 2, 5, 5, 1, 5]
def find_long_seq(arr, key):
long_seq = 0
max_seq = 0
for num in arr:
if num == key:
long_seq = 1
if long_seq > max_seq:
max_seq = long_seq
elif num != key:
long_seq = 0
return max_seq
print(find_long_seq(user_scores, 5))
Output:
3
CodePudding user response:
l = [1, 5, 5, 1, 5, 5, 5, 2, 5, 5, 1, 5]
MAX, counter = 0, 0
for i in l:
if i != 5:
if counter > MAX:
MAX = counter
counter = 0 # reset
else:
counter = 1 # increment if 5 is matched
# final fix
if counter > MAX:
MAX = counter
print(MAX)
If lists are allowed:
l = [1, 5, 5, 1, 5, 5, 5, 2, 5, 5, 1, 5]
a = []
for i in l:
if i != 5:
a.append(0)
else:
a[-1] = 1
MAX = 0
for i in a:
if i > MAX:
MAX = i
print(MAX)
CodePudding user response:
You don't need to add an elif
and current_sequence
.Try this.
user_scores = [1, 5, 5, 1, 5, 5, 5, 2, 5, 5, 1, 5]
key= 5
max_sequence = 0
new_sequence = 0
for score in user_scores:
if score ==key:
if new_sequence==max_sequence:
new_sequence = 1
max_sequence =new_sequence
else:
new_squence = 1
else:
new_sequence = 0
print(max_secquence)
output
3