So I want to write a program that read integer until the user enter empty input. Then print the longest increasing number from the input that I recieve.
example 1
#input
enter n: 5
enter n: 4
enter n: 3
enter n: 3
enter n: 2
enter n: 1
enter n:
#output
3 3
example 2
#input
enter n: 5
enter n: 7
enter n: 9
enter n: 6
enter n: 8
enter n: 9
enter n: 12
enter n: 1
enter n: 3
enter n: 7
enter n: 8
enter n: 9
enter n: 9
enter n: 10
enter n: 0
enter n:
#output
1 3 7 8 9 9 10
example 3
#input
enter n: 5
enter n: 4
enter n: 3
enter n: 2
enter n: 1
enter n:
#output
5
Here is my code
numlist = []
while True:
number = input("enter n: ")
if number != "":
numlist.append(int(number))
else:
break
if numlist == []:
print("ERROR: please enter at least one number")
# what I'm trying to do here is that I want to group increasing numbers in the list and find the longest one.
# for example, lst = [[1,2,3,6],[2,6,8],[9,11,14]] then the longest will be [1,2,3,6]
# but I have no idea what to do next so it looks kinda confusing.
def group(p, p2):
lst = []
list2 = []
for i in range(1, len(p)):
if p[i 1] > p[i]:
lst.append(p[i])
else:
list2.append(p[i])
What should I do next? maybe there is a better way to write this program?? (ಥ_ʖಥ)
CodePudding user response:
An example based on my comment:
curlist = []
longest = []
while True:
number = input("enter n: ")
if not number: break
number = int(number)
if curlist and number < curlist[-1]:
if len(curlist) > len(longest):
longest = curlist
curlist = []
curlist.append( number )
if len(curlist) > len(longest):
longest = curlist
print( longest )
CodePudding user response:
Another approach for the same:
numlist = []
while True:
number = input("enter n: ")
if number != "":
numlist.append(int(number))
else:
break
if numlist == []:
print("ERROR: please enter at least one number")
longest = []
interlist = [numlist[0]]
for i in range(1, len(numlist)):
if numlist[i]>=interlist[-1]:
interlist.append(numlist[i])
else:
longest.append(interlist)
interlist = [numlist[i]]
longest.append(interlist)
longest_data = longest[0]
for data in longest:
if len(data) > len(longest_data):
longest_data = data
print (longest_data)
Output:
enter n: 5
enter n: 6
enter n: 7
enter n: 8
enter n: 12
enter n: 1
enter n: 2
enter n: 3
enter n: 4
enter n: 4
enter n: 5
enter n: 6
enter n:
[1, 2, 3, 4, 4, 5, 6]