+ 7

Udemy function problem

I have been doing a python course on Udemy to supplement the lessons from Sololearn. The problem below has been the hardest I've come across so far and as a result I was happy to just make it work after playing around with it for several hours. And I neglected to solve the 'empty list' output. My code is much more convoluted than the solution given in the course but I'm intrigued to see how other people would solve this, and how I can clean up the code further. """ SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers. summer_69([1, 3, 5]) --> 9 summer_69([4, 5, 6, 7, 8, 9]) --> 9 summer_69([2, 1, 6, 9, 11]) --> 14 """ def summer_69(arr): for pos, nums in enumerate(arr): # Separate the nums and index positions from the list if 6 not in arr: # if not 6 is in the list, calculate the sum and break print(sum(arr)) break elif nums == 6: six_index = pos elif nums == 9: nine_index = pos idx_lst = arr[six_index: (nine_index +1)] # Slice the list between the 2 indices counter = len(arr[six_index: (nine_index +1)]) # Counter based on the number of values between 6 and 9 for x in idx_lst: arr.remove(x) counter = counter - 1 if counter == 0: print(sum(arr)) else: pass # I tried moving and removing this but the code wouldn't work otherwise (I dont know why)

20th Jul 2018, 8:31 AM
Rob Bailiff
Rob Bailiff - avatar
4 odpowiedzi
+ 7
Thanks Kishalaya. I think this is exactly the sort of thing I was trying to do but I don't yet have a good enough understanding of the language to be able to do it
20th Jul 2018, 10:36 AM
Rob Bailiff
Rob Bailiff - avatar
+ 2
Try this: def so69(a): while 6 in a: del a[a.index(6) : a.index(9)+1] return sum(a) I'm assuming, 1. There could be multiple 6-9 sections. 2. It's okay to alter the list.
20th Jul 2018, 9:29 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 2
You are welcome, Rob! I can see that you were on the right track. Let us know if you need more help. Happy coding :)
20th Jul 2018, 11:38 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 2
# try it..... def summer_69(arr): Sum=0 for n in range(0, len(arr)): if arr[n]<6: Sum+=arr[n] elif arr[n]>9: Sum+=arr[n] else: pass return Sum
22nd Mar 2019, 12:48 AM
Sanower Hossain Shamim