This question already has answers here:
Longest sequence of consecutive duplicates in a python list
(4 answers)
Closed 2 years ago.
Im trying to find the biggest series of digit in a row in a list which i can input. And im doing this way:
list = []
count_max_numbers = 0
while True:
x = int(input('число: '))
if x == 0:
break
list.append(int(x))
max_number = max(list)
for i in list:
if i != max_number:
pass
else:
count_max_numbers += 1
current_result = 0
max_result = 0
last_seen = list[0]
longest_digit = 0
for i in list:
if i == last_seen:
current_result += 1
else:
if current_result > max_result:
max_result = current_result
longest_digit = i
last_seen = i
current_result = 1
if current_result > max_result:
max_result = current_result
longest_digit = i
print(f'{list}')
print(f'max number: {max_number} reapeted{count_max_numbers} times')
print(f'the biggest series: {longest_digit} repeated {max_result} times')
this works only with first digit in a list. But i need to work it with whole list.
For example if input (1,2,3,3,3,3,5,55)
It need to get output: the biggest series: 3 repeated 4 times
I still have a problem with output of {longest_digit} it's incorrect
Try this:
mylist = [1,2,3,3,3,3,5,55]
val_holder = {}
for val in mylist:
if val not in val_holder.keys():
val_holder[val] = 1
else:
val_holder[val] += 1
max_key = max(val_holder, key=val_holder.get)
print(max_key)
My aproach to this will be using dictionary
lst = [1,2,3,3,3,3,5,55]
dict = {}
for val in lst:
if val not in dict.keys():
dict[val] = 1
else:
dict[val] = dict[val] + 1
Once we get the dictionary we sort this using the value
sorted_dict = sorted(dict.items(), key=lambda keyVal: keyVal[1], reverse=True)
print(dict[0][0])
Here's a simple algorithm:
Initialize longest = None, longest_digit = None, current = 0, previous_digit, and current_digit = None.
Then, for each item in the list:
If the item is equal to current_digit, increment current by one.
Otherwise:
(A) If current > longest, set longest = previous_digit and longest_digit = item
(B) Then, reset current to 1 and current_digit to item
Set previous_digit to item
At the end of the list, also do step (A) above.
Now you should have the answer in longest (4) and longest_digit (3)
Related
I’d like to get the string having repetitive substrings consecutively more than x times. The substrings has more than y characters.
For example, when x=4, y=3,
BGGEFGEFGEFGEFFD satisfies the condition (= GEF * 4 consecutively).
On the other hand, when x=2, y=4,
GDCCCGDCCFDCC does not satisfies the condition since there is one C between GDCC.
Any suggestions to check if the given string satisfies the condition without importing packages? Thanks in advance.
This is what I’ve tried
counter = 0
for s in range(0, len(string),y):
if string[s : s+y] == string[s+y :s+y*2]:
counter +=1
if counter >= x:
print(‘TRUE’)
def is_expected_str(str_val, x, y):
match_found = False
split_strs = {}
index = 0
for i in str_val:
subs = str_val[index:(index + y)]
index = index + 1
if len(subs) < y:
continue
sub_count = split_strs.get(subs)
if sub_count is None:
match_count = 1
else:
match_count = split_strs[subs] + 1
split_strs[subs] = match_count
if match_count >= x:
match_found = True
print(split_strs)
return match_found
# print(subs)
rr = "BGGEFGEFGEFGEFFD"
res = is_expected_str(rr, x=4, y=3)
print(res)
Use dictionary to store the count information of sub strings
The first line gives the number of entries. Further, each entry contains the name of the candidate and the number of votes cast for him in one of the states. Summarize the results of the elections: for each candidate, determine the number of votes cast for him. Use dictionaries to complete the tasks.
Input:
Number of voting records (integer number), then pairs <> - <>
Output:
Print the solution of the problem.
Example:
Input:
5
McCain 10
McCain 5
Obama 9
Obama 8
McCain 1
Output:
McCain 16
Obama 17
My problem is at the step when I have to sum keys with same names but different values.
My code is:
cand_n = int(input())
count = 0
countd = 0
cand_list = []
cand_f = []
num = []
surname = []
edict = {}
while count < cand_n:
cand = input()
count += 1
cand_f = cand.split(' ')
cand_list.append(cand_f)
for k in cand_list:
for i in k:
if i.isdigit():
num.append(int(i))
else: surname.append(i)
while countd < cand_n:
edict[surname[countd]] = num[countd]
countd += 1
print(edict)
You can add the name and vote to the dictionary directly instead of using one more for() and while().
If the name does not exist in the dictionary, you add the name and vote. If the name exists in the dictionary, increase the vote.
cand_n = int(input())
count = 0
cand_list = []
cand_f = []
edict = {}
while count < cand_n:
cand = input()
count += 1
cand_f = cand.split(' ')
if cand_f[0] in edict:
edict[cand_f[0]] += int(cand_f[1])
else:
edict[cand_f[0]] = int(cand_f[1])
print(edict)
i have 2 variable
ex :
compt = 9
first = 3
second = 2
then i want to looping based on compnt length and then change status on or off based on variable first and second
Output that i want :
On
On
On
Off
Off
On
On
On
Off
my current code is:
x,y=0,0
for i in range(0,compt):
if x != first:
print("On")
x+=1
elif x == first and y != second:
print("Off")
but the output from code above is
On
On
On
Off
Off
On
On
On
On
can someone help me to solve my problem , thank you
compt = 9
first = 3
second = 2
for i in range(compt):
max_val = first + second
if i % max_val < first:
print("on")
else:
print("off")
Output:
on
on
on
off
off
on
on
on
off
from itertools import cycle, islice
total = 9
first = 3
second = 2
sequence = ["On" for _ in range(first)] + ["Off" for _ in range(second)]
print(sequence)
result = islice(cycle(sequence), 0, total)
for state in result:
print(state)
output :
['On', 'On', 'On', 'Off', 'Off']
On
On
On
Off
Off
On
On
On
Off
Another variation with itertools:
from itertools import cycle, repeat, chain
compt = 9
first = 3
second = 2
on = repeat("On", first) # ["On", "On", ..]
off = repeat("Off", second) # ["Off", "Off", ..]
for status in cycle(chain(on, off)): # combine on and off and repeat
print(status)
# break when compt is exhausted
compt -= 1
if compt <= 0:
break
You can use %. We have a total first + second possibility. If our i is less than first it means that we are looking for on and if it's more than first we want to print off:
compt = 9
first = 3
second = 2
for i in range(compt):
if i % (first + second) < first:
print("ON")
else:
print("OFF")
try it...
compt = 9
first = 3
second = 2
i=0
while i < compt:
for k in range(0,first):
i += 1
print('on')
if i >= compt:
break
for j in range(0,second):
i += 1
print('off')
if i >= compt:
break
Let's say you have a list which only has two types of values and goes something like ['t','r','r','r','t','t','r','r','t'] and you want to find the length of the smallest sequence number of 'r's which have 't's at both ends.
In this case the smallest sequence of 'r' has a length of 2, because there is first t,r,r,r,t and then t,r,r,t, and the latter has the smallest number of 'r's in a row surrounded by 't' and the number of 'r's is 2.
How would I code for finding that number?
This is from a problem of trying of going to a play with your friend, and you want to sit as close as possible with your friend, so you are trying to find the smallest amount of taken seats in between two free seats at a play. "#" is a taken seat and a "." is a free seat. you are given the amount of seats, and the seating arrangement (free seats and taken seats), and they are all in one line.
An example of an input is:
5
#.##.
where there are two taken seats(##) in between two free seats.
Here is my code which is not working for inputs that I don't know, but working for inputs I throw at it.
import sys
seats = int(input())
configuration = input()
seatsArray = []
betweenSeats = 1
betweenSeatsMin = 1
checked = 0
theArray = []
dotCount = 0
for i in configuration:
seatsArray.append(i)
for i in range(len(seatsArray)):
if i == len(seatsArray) - 1:
break
if seatsArray[i] == "." and seatsArray[i+1] == ".":
print(0)
sys.exit()
for i in range(0,len(seatsArray)):
if i > 0:
if checked == seats:
break
checked += 1
if seatsArray[i] == "#":
if i > 0:
if seatsArray[i-1] == "#":
betweenSeats += 1
if seatsArray[i] == ".":
dotCount += 1
if dotCount > 1:
theArray.append(betweenSeats)
betweenSeats = 1
theArray = sorted(theArray)
if theArray.count(1) > 0:
theArray.remove(1)
theArray = list(dict.fromkeys(theArray))
print(theArray[0])
This is a noob and a !optimal approach to your problem using a counter for the minimum and maximum sequence where ew compare both and return the minimum.
''' create a funciton that
will find min sequence
of target char
in a list'''
def finder(a, target):
max_counter = 0
min_counter = 0
''' iterate through our list
and if the element is the target
increase our max counter by 1
'''
for i in x:
if i == target:
max_counter += 1
'''min here is 0
so it will always be less
so we overwrite it's value
with the value of max_counter'''
if min_counter < max_counter:
min_counter = max_counter
'''at last iteration max counter will be less than min counter
so we overwrite it'''
if max_counter < min_counter:
min_counter = max_counter
else:
max_counter = 0
return min_counter
x = ['t','r','r','r','t','t','r','r','t','t','t','r','t']
y = 'r'
print(finder(x,y))
Create a string from list and then search for pattern required and then count r in the found matches and then take min of it
Code:
import re
lst = ['t','r','r','r','t','t','r','r','t']
text = ''.join(lst)
pattern = '(?<=t)r+(?=t)'
smallest_r_seq = min(match.group().count('r') for match in re.finditer(pattern, text))
print(smallest_r_seq)
Output:
2
This is a pretty standard interview question. Find the longest substring without repeating characters. Here are the test cases,
abcabcbb -> 3
bbbbb -> 1
pwwkew -> 3
bpfbhmipx -> 7
tmmzuxt -> 5
Here's my code which uses a pretty simple approach with 2 pointers.
def lengthOfLongestSubstring(s):
checklist = {}
starting_index_of_current_substring = 0
length_of_longest_substring = 0
for i, v in enumerate(s):
if v in checklist:
starting_index_of_current_substring = checklist[v] + 1
else:
length_of_current_substring = i - starting_index_of_current_substring + 1
length_of_longest_substring = max(length_of_current_substring, length_of_longest_substring)
checklist[v] = i
return length_of_longest_substring
My code passes all the test cases except the last one (actual 4, expected 5). Can someone help me modify the code to take care of the last test case. I don't wish to reinvent the algorithm.
Here is a simple tweak in your code with 2 pointers to find the longest sub-string without repeating characters.
Change in your code is instead of calculating the length of longest substring when v is not present in checklist, I am calculating length of longest substring for all cases.
def lengthOfLongestSubstring(s):
checklist = {}
starting_index_of_current_substring = 0
length_of_longest_substring = 0
for i, v in enumerate(s):
if v in checklist:
starting_index_of_current_substring = max(starting_index_of_current_substring, checklist[v] + 1)
checklist[v] = i
length_of_longest_substring = max(length_of_longest_substring, i - starting_index_of_current_substring + 1)
return length_of_longest_substring
## Main
result = {}
for string in ['abcabcbb', 'bbbbb', 'ppwwkew', 'wcabcdeghi', 'bpfbhmipx', 'tmmzuxt', 'AABGAKGIMN', 'stackoverflow']:
result[string] = lengthOfLongestSubstring(string)
print(result)
Sample run:
{'abcabcbb': 3, 'bbbbb': 1, 'ppwwkew': 3, 'wcabcdeghi': 8, 'bpfbhmipx': 7, 'tmmzuxt': 5, 'AABGAKGIMN': 6, 'stackoverflow': 11}
This post is pretty old, but I think my solution fixes the bug in the original code.
def lengthOfLongestSubstring(s):
checklist = {}
starting_index_of_current_substring = 0
length_of_longest_substring = 0
for i, v in enumerate(s):
if v in checklist:
if checklist[v] >= starting_index_of_current_substring:
starting_index_of_current_substring = checklist[v] + 1
length_of_current_substring = i - starting_index_of_current_substring + 1
length_of_longest_substring = max(length_of_current_substring, length_of_longest_substring)
checklist[v] = i
return length_of_longest_substring
This doesnt really iterate upon your solution, but it's a bit simpler approach, just to give you an idea how it could be also solved.
def longest_substr(s):
longest = 0
for start_index in range(len(s)):
contains = set()
for letter in s[start_index:]:
if letter in contains:
break
contains.add(letter)
longest = max(longest, len(contains))
return longest
0
I would prefer this solution>>
Time and Space Management Optimised:
def lengthOfLongestSubstring(self, s: str) -> int:
curlen = maxlen = 0 # curlen saves the max len of substrings ending with current num
for i, num in enumerate(s):
curlen -= s[i-curlen:i].find(num)
maxlen = max(maxlen, curlen)
return maxlen
Find Longest Substring in the string without repeating characters.
def find_non_repeating_substring(input_str):
output_length = 0
longest_sub_str = ''
len_str = len(input_str)
index = 0
while len_str != 1:
l_str = ''
for i in range(index, len(input_str)):
if input_str[i] not in l_str:
l_str = l_str + input_str[i]
else:
break
sub_str_length = len(l_str)
if sub_str_length > output_length:
output_length = sub_str_length
longest_sub_str = l_str
len_str = len_str -1
index = index + 1
return output_length,longest_sub_str
if __name__ == '__main__':
input_str = raw_input("Please enter the string: ")
sub_str_length, sub_str = find_non_repeating_substring(input_str)
print ('Longest Substing lenght is "{0}" and the sub string is "{1}"'.format(sub_str_length, sub_str))```