I need this function to tell me the longest sequence of positive numbers in a list.
def longestSequencePos(nums):
index = 0
list = []
integ = 0
for obj in nums:
if obj > 0:
index = index +1
else:
list.append(index)
index = 0
return max(list)
list should contain all of the lengths of the sequences of positives, but the max function is not working.
you are not appending anything to your list when you are exiting the loop and nums only has positive integers, you will need to do something like:
def longestSequencePos(nums):
index = 0
list = []
integ = 0
for obj in nums:
if obj > 0:
index = index +1
else:
list.append(index)
index = 0
list.append(index)
return max(list)
which will append the last count of index if the list is empty at the end of the loop.
also, you have called your list, well, list, which is actually a constructor for a list, although this is not the problem it is something to watch out for as a do not do
You don't need a list to do this:
count = maxc = 0
for obj in nums:
if obj > 0:
count += 1
else:
maxc = max(count, maxc)
count = 0
maxc = max(count, maxc)
The problem might be that you aren't adding index to the list when nums is exhausted, so if the list ends in the longest sequence, it won't return the correct value:
def longestSequencePos(nums):
index = 0
list = []
integ = 0
for obj in nums:
if obj > 0:
index = index +1
else:
list.append(index)
index = 0
list.append(index)
return max(list)
This fixed version works for me in the normal python interpreter. I haven't tried it on jython.
Related
In this problem, I'm given an array(list) strarr of strings and an integer k. My task is to return the first longest string consisting of k consecutive strings taken in the array. My code passed all the sample tests from CodeWars but can't seem to pass the random tests.
Here's the link to the problem.
I did it in two days. I found the max consecutively combined string first. Here's the code for that.
strarr = []
def longest_consec(strarr, k):
strarr.append('')
length = len(strarr)
cons_list = []
end = k
start = 0
freq = -length/2
final_string = []
largest = max(strarr, key=len, default='')
if k == 1:
return largest
elif 1 < k < length:
while(freq <= 1):
cons_list.append(strarr[start:end])
start += k-1
end += k-1
freq += 1
for index in cons_list:
final_string.append(''.join(index))
return max(final_string, key=len, default='')
else:
return ""
Since that didn't pass all the random tests, I compared the combined k strings on both sides of the single largest string. But, this way, the code doesn't account for the case when the single largest string is in the middle. Please help.
strarr = []
def longest_consec(strarr, k):
strarr.append('')
length = len(strarr)
largest = max(strarr, key=len, default='')
pos = int(strarr.index(largest))
if k == 1:
return largest
elif 1 < k < length:
prev_string = ''.join(strarr[pos+1-k:pos+1])
next_string = ''.join(strarr[pos:pos+k])
if len(prev_string) >= len(next_string):
res = prev_string
else:
res = next_string
return res
else:
return ""
print(longest_consec(["zone", "abigail", "theta", "form", "libe"], 2))
Let's start from the first statement of your function:
if k == 1:
while(p <= 1):
b.append(strarr[j:i])
j += 1
i += 1
p += 1
for w in b:
q.append(''.join(w))
return max(q, key=len)
Here q is finally equal strarr so you can shorten this code to:
if k == 1:
return max(strarr, key=len)
I see that second statement's condition checks if k value is between 1 and length of string array inclusive:
elif k > 1 and k <= 2*a:
...
If you want no errors remove equality symbol, last element of every array has index lesser than its length (equal exactly length of it minus 1).
Ceiling and division is not necessary in a definition, so you can shorten this:
a = ceil(len(strarr)/2)
into this:
a = len(strarr)
then your elif statement may look like below:
elif 1 < k < a: # Same as (k > 1 and k < a)
...
again, I see you want to concatenate (add) the longest string to k next strings using this code:
while(p <= 1):
b.append(strarr[j:i])
j += k-1
i += k-1
p += 1
for w in b:
q.append(''.join(w))
return max(q, key=len)
the more clearer way of doing this:
longest = max(strarr, key=len) # Longest string in array.
index = 0 # Index of the current item.
for string in strarr:
# If current string is equal the longest one ...
if string == longest:
# Join 'k' strings from current index (longest string index).
return ''.join(strarr[index:index + k])
index += 1 # Increase current index.
And the last statement which is:
elif k > 2*a or k<1:
return ""
if all previous statements failed then value is invalid so you can instead write:
return "" # Same as with else.
Now everything should work. I advice you learning the basics (especially lists, strings and slices), and please name your variables wisely so they are more readable.
You can try this as well
this has passed all the test cases on the platform you suggested.
def longest_consec(strarr, k):
i = 0
max_ = ""
res = ""
if (k<=0) or (k>len(strarr)):
return ""
while i<=(len(strarr)-k):
start = "".join(strarr[i:i+k])
max_ = max(max_, start, key=len)
if max_==start:
res=strarr[i:i+k]
i+=1
return max_
#output: ["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2 -> abigailtheta
#output: ["zones", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"],2 -> zonesabigail
I wrote the following code. It should return to me the length of the longest subscript in a string without a repeat in letters.
def lengthOfLongestSubstring(s):
lst = []
y = 0
final = 0
count = len(s)
while len(s) > 0:
s = s[y:]
for i in range(len(s)):
if s[i] in lst:
y += 1
count = len(lst)
lst =[]
break
else:
lst.append(s[i])
if count > final:
final=count
return(final)
when entering the string "tmmzuxt" i expect to get an output of 5 (length of "mzuxt") but instead get 4. I have debugged to figure out the problem seems to be that my function skips over the second 'm' when indexing but I can't figure out why. Any suggestions?
Realized I somehow missed a line. Hope this makes more sense.
Your issue here is that you are modifying s while you are running your code.
Consider that in the first iteration, you are getting s = s[0:], so s will now be 'tmmzuxt'. In your next iteration, you are getting s = s[1:], from the modified s. This is still not a problem, because you just get 'mmzuxt'. However, in your third iteration, you are getting s = s[2:], which is now 'zuxt'.
So you need a different variable than s to hold the substring of s that you are actually testing.
here, in your code(line 7) you are updating your string value inside function, everytime your for loop iterates.
for e.g., after every break inside for loop. you string(which is "tmmzuxt") is becoming short and short.
i created a new variable which contains your original string.
def lengthOfLongestSubstring(s):
lst = []
y = 0
final = 0
count = len(s)
main_string = s;#change done here
while len(s) > 0:
s = main_string[y:] #change done here
for i in range(len(s)):
if s[i] in lst:
y += 1
count = len(lst)
lst =[]
break
else:
lst.append(s[i])
if count > final:
final =count
print(final)
return(final)
lengthOfLongestSubstring("tmmzuxt")
The main problem with your code is that you incremented y, even though it should only ever remove the first character. There is no need for a variable y. Try this:
def lengthOfLongestSubstring(s):
final = 0
while len(s) > 0:
count = len(s)
lst = []
for i in range(len(s)):
if s[i] in lst:
count = i - 1
break
lst.append(s[i])
if count > final:
final = count
s = s[1:]
return final
print(lengthOfLongestSubstring("tmmzuxt"))
Here is an edited code. removing #lst =[] and #break lines.
[Code]
def lengthOfLongestSubstring(s):
lst = []
y = 0
final = 0
count = len(s)
while len(s) > 0:
s = s[y:]
for i in range(len(s)):
if s[i] in lst:
y += 1
count = len(lst)
#lst =[]
#break
else:
lst.append(s[i])
if count > final:
final=count
return(final)
s="tmmzuxt"
print(lengthOfLongestSubstring(s))
[Output]
5
I'm not sure if I understand your code, or if the while loop is needed here, actually. Try this instead:
def lengthOfLongestSubstring(s):
max_length = 0
length = 0
previous = ''
for thisCharacter in s:
if thisCharacter != previous:
length += 1
else:
max_length = max(length, max_length)
length = 1
return max_length
Given a list of lists, I would like to find the longest list, as well as the overall max value from all of the lists. Being restricted to not use max(), how can I go about doing this?
My attempt is shown below:
def newMax(table):
a=-1
if len(table) == 0:
print("The list is empty")
for i in range(len(table)*2):
a+=1
if i+1 >= len(table):
print("Big number")
break
else:
if len(table[a]) < len(table[a+1]):
maxs=a+1
if maxs < len(table[a+2]):
maxs = a + 2
print("test",table[maxs])
if maxs < len(table[a + 3]):
maxs = a + 3
print("test", table[maxs])
newMax([[1,3,1,5,1,51,15],[0,3,5,4,5],[1,2,3],[1,3,1,5]])
To find
the largest value in all the lists, and
the longest list,
simply iterate through all the lists while keeping track of the max encountered so far.
def newMax(table):
maxValue = table[0][0]
longestList = table[0]
longestListLen = len(table[0])
This sets the largest value encountered so far to the first element of the first list, and sets the longest list to to be the first list. We then iterate through the rest of the lists to see if there are larger values / longer lists.
for row in table: # iterate through all lists
for val in row: # iterate through each value in each list
if val > maxValue: # encountered a greater value
maxValue = val # let's save the new biggest value
rowLen = len(row) # get this list's length
if len(row) > longestListLen: # encountered a longer list
longestListLen = rowLen # save this list as the longest list
longestList = row
Now you have the max value of all lists in maxValue and the longest list in longestList.
Put all entries in a single collection, then take the max of that. This way, all the looping happens on the C-side, so efficient:
def newMax(table):
s = set()
for l in table:
s.update(l)
return max(s)
Based on the comments above and below, to get all the individual maxes and not use the builtin max(), while staying linear in time and not writing a super-nested function:
import heapq
def newMax(table):
maxvalues = list()
for l in table:
heapq.heapify(l)
maxvalues.append(heapq.nlargest(1, l)[0])
mv2 = maxvalues[:]
heapq.heapify(mv2)
return heapq.nlargest(1, mv2)[0], maxvalues
One more as the goal/requirements seems to have changed again in the comments:
def newMax(table):
length_max = -1
max_length_list = None
value_max = -2**31
for l in table:
if len(l) > length_max:
length_max = len(l)
max_length_list = l
for i in l:
if i > value_max:
value_max = i
return value_max, max_length_list
Not sure have you learn recursion yet , which this is an recursion based solution, since I`m not sure how many level could have in your input list
input = [[1,3,1,5,1,51,15],[0,3,5,4,5],[1,2,3],[1,3,1,5]]
def findMaxRec(input):
max = -999999999
for i in input:
if isinstance(i,list):
temp = findMaxRec(i)
if temp > max:
max = temp
else:
if i > max:
max = i
return max
print(findMaxRec(input))
I wrote this code. It's like len() function.
def length_itr_for(list):
total = 0
for i in list:
total += 1
return total
print length_itr_for([1,2,3,4,5,6,7,8])
output is; 8. because in this list, there are 8 value. so len is of this list is 8.
but I don't know how can I write this code with while loop?
while list[i]: etc... I though a few things but I don't know what should I write it here.
edit:
actually I tried this code too. but It's not good code. just tried and it didn't work.
def length_itr_whl(list):
total = 0
i = 0
while list[i]:
total = total + 1
i = i + 1
return total
print length_itr_whl([1,2,3,4,5])
You can write a function that tests whether an index is in range for a list:
def validIndex(l, i):
try:
_ = l[i]
except IndexError:
return False
return True
I got this code from If list index exists, do X
Then you can use this in your loop:
def length_itr_whl(list):
total = 0
index = 0
while validIndex(list, index):
total += 1
index += 1
return total
You could also use while True: and catch the index error in the loop.
def length_itr_whl(list):
total = 0
index = 0
try:
while True:
_ = list[index]
total += 1
index += 1
except IndexError:
pass
return total
If you really want to convert this code to a while-loop, you could always do something like this:
def length_itr_whl(list):
total = 0
i = 0
while list[i:i+1]:
total = total + 1
i = i + 1
return total
print length_itr_whl([1,2,3,4,5]) # prints 5
print length_itr_whl([]) # prints 0
This uses the list-slicing mechanism in Python and it does not require any try-block. When the indices are out of range the result will be [] (an empty list), which evaluates to False in Python.
However, why don't you just use the built-in len-function in Python?
def length(items) :
idx = 0
try:
while True:
_ = items[idx]
idx += 1
except IndexError:
return idx
Try this:
list=[1,2,3,4,5]
total = 0
while total != len(list):
total +=1
In my program I need to put a while function which sums this list until a particular number is found:
[5,8,1,999,7,5]
The output is supposed to be 14, because it sums 5+8+1 and stops when it finds 999.
My idea looks like:
def mentre(llista):
while llista != 999:
solution = sum(llista)
return solution
Use the iter-function:
>>> l = [5,8,1,999,7,5]
>>> sum(iter(iter(l).next, 999))
14
iter calls the first argument, until the second argument is found. So all numbers are summed up, till 999 is found.
Since you mention using a while loop, you could try a generator-based approach using itertools.takewhile:
>>> from itertools import takewhile
>>> l = [5,8,1,999,7,5]
>>> sum(takewhile(lambda a: a != 999, l))
14
The generator consumes from the list l as long as the predicate (a != 999) is true, and these values are summed. The predicate can be anything you like here (like a normal while loop), e.g. you could sum the list while the values are less than 500.
An example of explicitly using a while loop would be as follows:
def sum_until_found(lst, num):
index = 0
res = 0
if num in lst:
while index < lst.index(num):
res += lst[index]
index += 1
else:
return "The number is not in the list!"
return res
Another possible way is:
def sum_until_found(lst, num):
index = 0
res = 0
found = False
if num in lst:
while not found:
res += lst[index]
index += 1
if lst[index] == num:
found = True
else:
return "The number is not in the list!"
return res
There's many ways of doing this without using a while loop, one of which is using recursion:
def sum_until_found_3(lst, num, res=0):
if num in lst:
if lst[0] == num:
return res
else:
return sum_until_found_3(lst[1:], num, res + lst[0])
else:
return "The number is not in the list!"
Finally, an even simpler solution:
def sum_until_found(lst, num):
if num in lst:
return sum(lst[:lst.index(num)])
else:
return "The number is not in the list!"
Use index and slice
def mentre(llista):
solution = sum(lista[:lista.index(999)])
return solution
Demo
>>> lista = [5,8,1,999,7,5]
>>> sum(lista[:lista.index(999)])
14