r/learnpython • u/Why-IsItAlreadyTaken • Nov 29 '21
A desperate plea for help (StackOverflow did not help)
We have a list [8,6,7,7,3,4,5,6,6,7,2,3,4,5,3,6,6,5,6,7,7,8,9,1] (this list is just an example of what can be inputted). Using iteration, find specific sequences 1 by 1, comparing their length at the same time, overwriting shorter ones with longer ones.
The sequences we are searching for follow a pattern: starting with a flat(or a single element), then dropping, then growing (e.g. 6 6 3 3 4 5 5 6)
After doing all of the operations, return the first longest sequence. In the given list, that would be [7,7,3,4,5,6,6,7]
This is what I was able to come up with:
https://github.com/Whymyusernametaken/a-problem/commit/c8180423f9c274887c453784a7b3d0dc5384750e
The code should print out [7,7,3,4,5,6,6,7], but it prints out []. Any way how I can make this work? Rewrite my code, if it won't do.
Thanks
edit:issue solved, working code on github link in one sec
45
Nov 29 '21
why you expect StackOverflow to help when there is not clear clarity in your problem? I mean you didn't even mentioned the sequence conditions, why do you expect SO to help on this?
-71
u/Why-IsItAlreadyTaken Nov 29 '21
I would like to see you translate the problem from a different language using terms that are impossible to translate, so I did in the most understandable way possible. If you don’t understand - just upvote so someone who will can see this
60
u/mountainjew Nov 29 '21
Must you be dick to everybody trying to help you?
0
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
4
u/mountainjew Nov 30 '21
Why don't you go apologize to all the gay people you have insulted on Reddit? Oh right, you don't need anything from them. Fuck off kid.
-78
u/Why-IsItAlreadyTaken Nov 29 '21
Being a dick? Don't make me laugh, you haven't seen me being a dick. That is an explanation of why it is hard for me to make a 100% clear request. That is the way I talk in real life (strangers, family, friends, etc.), if you see that as being a dick - it is your problem, not mine.
and please, downvote me as much as you want, freedom of expression
10
u/HappyScholar13 Nov 30 '21 edited Nov 30 '21
Retracted
0
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
2
u/Fulk0 Nov 30 '21
Damn bro, you need to grow up.
2
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
0
Nov 29 '21
[deleted]
-1
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
-42
u/Why-IsItAlreadyTaken Nov 29 '21
Lol, stop, I already solved it myself, just needed some tips which I got hours ago. I just translated the task badly and explained it. Chill, ‘kay?
27
15
u/shiftybyte Nov 29 '21
What's the rules of the sequence we are looking for?
Starting then dropping then growing?
For how long dropping? for how long growing?
In the given example..
[7,7,3,4,5,6,6,7]is 6,6 considered growing? is it allowed to flat at any point?
-5
u/Why-IsItAlreadyTaken Nov 29 '21
it is fine if it flats, it just had to save the flat at that point in case a new sequence starts there. Made it work through enumerate (update on the link)
12
Nov 29 '21 edited Dec 04 '21
def subsquence(S): # find start & end indexes of valid subsequences subseqs = [] for start in range(len(S) - 2): i = start while S[i+1] == S[i]: # repeating start values i += 1 if S[i+1] > S[i]: # next value must be strictly decreasing continue while S[i+1] <= S[i]: # subsequent values decreasing or repeating i += 1 if S[i+1] < S[i]: # next value must be strictly increasing continue while S[i+1] >= S[i]: # subsequent values increasing or repeating i += 1 subseqs.append((start, i)) # found valid subsquence # store the start/end indexes
# Find first longest subsequence and return
# lengths of subsequences
sublengths = [e - s for s, e in subseqs]
# start/end indexes of first longest subsequence
start, end = subseqs[sublengths.index(max(sublengths))]
return S[start:end+1]
S = [8, 6, 7, 7, 3, 4, 5, 6, 6, 7, 2, 3,
4, 5, 3, 6, 6, 5, 6, 7, 7, 8, 9, 1]
print(subsquence(S))Pretty straightforward solution. Feel free to reply with any questions/concerns, I would be happy to address them.
Edit: If I were to do it again I would just store the longest (start, end) pair as we go. Easier than the comparison at the end.
-23
u/Why-IsItAlreadyTaken Nov 29 '21
Thanks for help anyway, but I already solved the problem in a way less confusing way.
13
Nov 29 '21
Let’s see it! Now you have my curiosity :)
-6
u/Why-IsItAlreadyTaken Nov 29 '21
I updated the code on the github link
14
Nov 29 '21
There must be something missing, the github code is incomplete.
-1
u/Why-IsItAlreadyTaken Nov 29 '21
Oops, replace sub_array with array. My bad, this code is half of the project, I copied it from the finished one
edit: changed the github one, should work now
11
Nov 29 '21
Now it returns the empty set [ ].
2
u/Why-IsItAlreadyTaken Nov 29 '21
That's weird, works fine for me. I'll just make a new file for it https://github.com/Whymyusernametaken/working-code/blob/main/code
10
u/Chris_Hemsworth Nov 29 '21 edited Nov 29 '21
There might be a more elegant way of doing this, but only storing indices might be easier:
def subsequence(input_array):
cached_start = cached_end = 0
start_index = end_index = 0
for idx, num in enumerate(input_array):
# Check if the next value is growing or not.
if num >= input_array[end_index]:
end_index = idx
else:
# Sequence ended, check its length.
# If length > cached length, stored new indices.
if (end_index - start_index) > (cached_end - cached_start):
cached_start, cached_end = start_index, end_index
# Find the new start index:
start_index, end_index = idx-1, idx
start_val = input_array[start_index]
# Back track until the number is different.
while start_index > 0 and input_array[start_index - 1] == start_val:
start_index -= 1
return input_array[cached_start:cached_end+1]
array = [8, 6, 7, 7, 3, 4, 5, 6, 6, 7, 2, 3, 4, 5, 3, 6, 6, 5, 6, 7, 7, 8, 9, 1]
print(subsequence(array))-1
u/Why-IsItAlreadyTaken Nov 29 '21
Holy moly, thats just.. wow. I managed to do it using enumerate too (updated on github)
6
u/Chris_Hemsworth Nov 29 '21
I didn't extensively test this, you might want to add a check at the end to ensure the last sequence is also not the longest.
For example, this array probably would fail:
[9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
-3
u/Why-IsItAlreadyTaken Nov 29 '21 edited Nov 29 '21
but just in case, could you help me with adding that to my code? I tried some ideas, but they don’t seem to work
11
u/Chris_Hemsworth Nov 29 '21 edited Nov 29 '21
Your code feels very clunky and unintuitive. There are all sorts of ifs / elifs that might do what you need it to do, but the logic is hard to follow.
Here is an updated version of my solution above that checks at the end of the for loop to see if the last sequence is the longest, as well as a version that removes the while loop to ensure this run in O(n) time.
Notice I simply added the length check after the for loop.
def subsequence(input_array): cached_start = cached_end = 0 start_index = end_index = 0 num_consecutive = 0 for idx, num in enumerate(input_array): # Check if the next value is growing or not. if num >= input_array[end_index]: num_consecutive = num_consecutive + 1 if num == input_array[end_index] else 1 end_index = idx else: # Sequence ended, check its length. # If length > cached length, stored new indices. if (end_index - start_index) > (cached_end - cached_start): cached_start, cached_end = start_index, end_index # Find the new start index: start_index, end_index = idx-num_consecutive, idx start_index = 0 if start_index < 0 else start_index # After all elements have been inspected, check if the current (i.e. last) # start and end indices create a longer sequence than the cached version. if (end_index - start_index) > (cached_end - cached_start): cached_start, cached_end = start_index, end_index return input_array[cached_start:cached_end+1] array = [9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # array = [8, 6, 7, 7, 3, 4, 5, 6, 6, 7, 2, 3, 4, 5, 3, 6, 6, 5, 6, 7, 7, 8, 9, 1] print(subsequence(array))
40
u/joyeusenoelle Nov 29 '21
You're not modifying saved inside subsequence(), so when you return it, it's still got the same value you initialized it with: [].
-85
Nov 29 '21
[removed] — view removed comment
57
u/backdoorman9 Nov 29 '21
Desperate plea for help
Immediately gets sassy and disrespectful. Some people just can't stop shooting themselves in the foot.
1
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
-41
u/Why-IsItAlreadyTaken Nov 29 '21
Why do you even continue with all these comments? I even edited to point out that the issue is closed, and though some advice was helpful, I managed to solve the problem by myself, I saw all the answers afterwards. Why did I post that - 8 hours of coding takes its toll on thinking straight, so I thought I should get some help
2
u/Anon_Legi0n Nov 30 '21
Woah, 8 hours of coding? Watch out we got a hacker over here with his 7 whole commits!
1
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
-79
u/Why-IsItAlreadyTaken Nov 29 '21
Where is disrespect in 'duh'? A normal expression of understanding. 'I know it is you fucking cunt' is desrespect, but 'duh'?
'Ditch that function' is desrespect? Just a normal question.
You are the ones who are making a fuss over nothing, the comment author didn't even say anything on the matter.
43
u/Slendigo Nov 29 '21 edited Nov 30 '21
Nah dude, you're being an ass. Tone it down a bit.
2
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
1
u/Slendigo Nov 30 '21
Apology 100% accepted! You did the right thing apologizing dude, it takes a lot of guts to do that. You're a good person!
-52
u/Why-IsItAlreadyTaken Nov 29 '21
Oh, so if you misinterpret what I said, then I’m an ass? Splendid
12
u/NamasteWager Nov 30 '21
Watch the sass captain sassy pants
1
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
7
Nov 30 '21
1
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
15
u/GamerNumba100 Nov 29 '21
Poor guy is being downvoted because everyone thinks he was saying “duh, you’re stupid,” when in fact he was calling himself stupid.
-2
u/Why-IsItAlreadyTaken Nov 29 '21
Lol, I only meant “duh” as in “yeah”, no offense, but nobody throws to think about different meanings. Then just asked if I should put it without a function, totally adequate question
26
u/el_floppo Nov 29 '21
Saying "duh" instead of "yeah" has different connotations. "Duh" implies that the person who you are speaking to is stupid. "Yeah" is just a casually affirmative.
1
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
8
u/RagingGods Nov 30 '21
Where did you get the idea that duh is "yeah"? A quick google search tells you that duh means either "feign ignorance or stupidity" or "to indicate something is too obvious or evident", both have fairly different meaning to "yeah". Maybe it's used as slang within your clique, maybe you just learnt it somewhere else, but please don't use "why can't everyone just think differently like me" as an excuse for your poor phrasing of your comments (as seen fairly common among most of your replies).
1
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
4
u/JasonDJ Nov 30 '21
I didn’t see the OPs post (it’s deleted now), but I’ve definitely used “duh” in a self-deprecating way, certainly more often that I use it otherwise. Does that get misconstrued?
-19
u/Why-IsItAlreadyTaken Nov 29 '21
okay, did so, it worked, but in an extremely weird way: it printed out [8, 4, 5, 6, 6, 7]. So, it just started counting from the next index. Any way how to make it go from the needed one?
7
u/joyeusenoelle Nov 29 '21
Okay, having stepped through your code (useful trick: you can use the pdb module and
pdb.set_trace()to navigate through your code step-by-step and see what the current state (including variable values) is), I suspect your problem is in the logic of settinglast. You've set yourself up with a demo input that unwittingly exposes this bug: you start with a very high value, so your code never has the opportunity to changelast.When you swap the contents of result into saved, and reset result - instead, consider doing something like setting
resultto[saved[-1]]. (You may need to do some iterating oversaved, backwards, just in case - like in your demo input - the proper output starts with a double or triple value.)I modified the code like so:
elif e < result[-1]: result, saved = _length_comparison(result, saved) last = saved[-1] result = [last] i = -2 while result[0] == saved[i]: result = [saved[i]] + result i -= 1but this still didn't quite work; I got
[7,7,7,7,8,9]as output. Unfortunately, I have to get back to work, but I hope this helps you figure this out.0
u/Why-IsItAlreadyTaken Nov 29 '21
Thanks a lot for your help. Me and my friend had the same thought on the matter, and put
<last=e>at the end of the cycle too, so it fixed the problem 'starting with high number'. We fixed the weird outputs by placing "marks" using enumerate: saving spots where we get flats in case a new sequence starts in there10
u/joyeusenoelle Nov 29 '21 edited Nov 29 '21
To address your initial comment:
saveddoes not get modified in_length_comparison().Python passes arguments to functions by value, not by reference;(this was wrong; see my comment below) the parameters of a function are what the function is going to call those values internally, and have nothing to do with how those names are used outside the function.When you call
_length_comparison(result, saved), what you're really calling (in the first pass) is_length_comparison([8,6,7,7], [])._length_comparison()doesn't care about anything outside_length_comparison(), so if you want to modify the value ofsavedandresult, you have to actually use the return value of_length_comparison()to do it:saved = _length_comparison(result, saved)(You can return a tuple and then unpack it outside the function to return them both:)
def _length_comparison(result, saved): ... return result, saved result, saved = _length_comparison(result, saved)I'll respond to the second comment after I run the script myself.
0
Nov 29 '21
[deleted]
5
u/joyeusenoelle Nov 29 '21
You're correct, my error. The problem is not pass-by-value, it's namespacing. Inside the function,
saved = result result = []makes the name
savedrefer to the list passed in asresult, and makes the nameresultrefer to an empty list. This still doesn't change the values associated with the namessavedandresultoutside the function, though!-37
u/Why-IsItAlreadyTaken Nov 29 '21
lmao, haha, just asked a stupid question about a serious matter - 9 downvotes. r/redditmoment
52
u/MagnitskysGhost Nov 29 '21
Asking a beginner question and responding to someone more knowledgeable than you with a condescending comment is going to get you downvoted. Cope
1
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
-19
u/Why-IsItAlreadyTaken Nov 29 '21
Did I say I was frustrated? Cope with what? I go on hate subs to get banned just to get some fun, a few downvotes are not an issue. The laugh was not sarcastic, it was genuine) Have a nice day, no hate for anyone
I'll even downvote these mine comments myself, just for the meme
24
Nov 29 '21 edited Jan 04 '26
[removed] — view removed comment
3
u/NamasteWager Nov 30 '21
Watch out, this dude has nothing to lose, don't want to cross them
1
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
1
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
8
u/m1ss1ontomars2k4 Nov 29 '21
Using iteration, find specific sequences 1 by 1,
What do you mean "specific sequences"? How do we know the sequence has been found?
Maybe it would be easier if you just posted the question in the original language...
3
u/Why-IsItAlreadyTaken Nov 29 '21
I don’t think that there are many people who read Ukrainian here. And I made examples of what type of sequence I am searching for. A completely dumb and useless task, but it has to be done, 1/5 of a mark is important
Thanks for the effort to help, but problem has already been resolved.
12
u/greendayonfire Nov 30 '21
You could always ask on Russian-speaking forums if you feel uncomfortable translating things. But you decided to be rude to everyone here who tried to help.
20
Nov 29 '21
i don't understand what's the problem...
15
u/bingbestsearchengine Nov 30 '21
seems like the biggest problem is with his attitude towards people trying to actually help out.
0
u/Why-IsItAlreadyTaken Nov 30 '21
I am deeply sorry for being in the wrong, I get my mistake, please forgive me (full apology in a separate comment thread for it and a new post)
1
2
u/HappyScholar13 Nov 30 '21
1.) Your apology and your approach to that apology is really emotionally intelligent and mature of you. I full accept your apology and respect you more because of it.
2.) I also understand the way the whole incident manifested itself better now with the background info provided. Working on a second or third language is an exceptionally challenging endeavor. I’ve spent several years of my life living in Countries where English was not the native language. Your willingness to engage the Reddit community in English also speaks highly of your skill, courage and willingness to learn.
This has been a very impressive and honestly inspiring thread. I’m grateful to have been a part of it.
2
u/Why-IsItAlreadyTaken Nov 30 '21
Thank you a lot for accepting my apology. I've been working on this project for more than a week now, with the deadline closing in and nothing was working out, so I decided to ask on forums, but got a bit full of myself after getting an actual answer. Now nobody is wishing to help me on a post that I made today (the task was badly explained to me, and it only works partially, so I made a new post to explain it in great detail and ask for help), so would you be kind enough to look at it, or at least give it an upvote?
P.S. I just slept on the problem and got to the thought that I was in fact being a dickhead for not accepting my fault straight away.
2
u/HappyScholar13 Nov 30 '21
Yeah. I’ll give it a look, and certainly an upvote. You’ll get there. Don’t beat yourself up over it. I’m also learning Python, but I’ve worked in IT Project Management for several years now. Every professional on this thread has lost their shit sometime or another, and woke up the next day and we’re like, “Damn It! I shouldn’t have said that.” Better you get a chance to learn that lesson on Reddit than in the industry.
2
u/Why-IsItAlreadyTaken Nov 30 '21
first year applied math student with the hardest task out of the whole course here)
1
1
6
u/xelf Elf Nov 29 '21 edited Nov 29 '21
So I wrote a quick version using a "find the current end point", and then a function to "find all the sequences", and it seems to work.
def get_sequence(data, start):
tmp,end=start,start+1
while end<len(data) and data[tmp]>=data[end]: tmp,end=end,end+1
if start==tmp: return start
mid=tmp
while end<len(data) and data[tmp]<=data[end]: tmp,end=end,end+1
return start if mid==tmp else tmp
def find_all(data, i=0):
seq = []
while i<len(data):
end = get_sequence(data,i)
if i==end: i+=1
else:
seq.append( (end-i+1,-i,i,end) )
i=end
while i<len(data) and i>1 and data[i]==data[i-1]: i-=1
return seq
s= [8,6,7,7,3,4,5,6,6,7,2,3,4,5,3,6,6,5,6,7,7,8,9,1]
length, order, start, end = max(find_all(s))
print(length, s[start:end+1])1
u/Why-IsItAlreadyTaken Nov 30 '21
I'd like to apologize for all those people who I was rude to yesterday, replying dispectfully to people who did not get the task, which I had explained poorly. Please, forgive me for my terrible behavior. Hope you guys see this
45
u/GumBall1900 Nov 30 '21
This guy asked for help then starting being rude to everyone that was asking for clarity / trying to help. hahaha