I am very new to Python and have been going through multiple tutorials to get better.
I have straggled with one difficult problem and found a solution. But it feels, works very newbie like. I think that I have tailored it to answer the specific question.
So the question is:
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
My code to solve this is:
def summer_69(arr):
list1 = arr
summ = int()
for i in range(0, len(arr)):
if 6 in list1:
listOfRange = range(list1.index(6), list1.index(9) + 1)
for index in listOfRange:
print(listOfRange)
arr[index] = 0
if 6 != arr[i]:
summ += arr[i]
else:
continue
else:
summ += arr[i]
return summ
It is a very basic problem and I am very alerted that I have struggled with something like this already.
Short O(n) solution using an iterator and the in operator to search for (and thereby skip to) the 9 following each 6:
def summer_69(lst):
it = iter(lst)
return sum(x for x in it
if x != 6 or 9 not in it)
Less dense version:
def summer_69(lst):
it = iter(lst)
total = 0
for x in it:
if x == 6:
9 in it
else:
total += x
return total
Correctness check (random test cases) and benchmark (with [1] * 5000 + [6, 9] * 2500) along with the accepted answer's solution (which takes O(n2)):
30 out of 30 tests correct
303045 us 303714 us 304335 us 306007 us 309986 us summer_69_Accepted
444 us 446 us 464 us 478 us 527 us summer_69_Kelly1
442 us 448 us 453 us 465 us 500 us summer_69_Kelly2
Code (Try it online!):
from timeit import repeat
def summer_69_Accepted(lst):
copyoflist = lst[:] # makes shallow copy of list
while True:
if 6 not in copyoflist:
return sum(copyoflist)
indexof6 = copyoflist.index(6)
indexof9 = copyoflist.index(9, indexof6+1) # begin search for 9 after 6
del copyoflist[indexof6:indexof9+1]
def summer_69_Kelly1(lst):
it = iter(lst)
return sum(x for x in it
if x != 6 or 9 not in it)
def summer_69_Kelly2(lst):
it = iter(lst)
total = 0
for x in it:
if x == 6:
9 in it
else:
total += x
return total
funcs = summer_69_Accepted, summer_69_Kelly1, summer_69_Kelly2
from random import randrange, choices
def testcase():
def others():
return choices([0, 1, 2, 3, 4, 5, 7, 8], k=randrange(10))
lst = others()
for _ in range(10):
lst += [6, *others(), 9, *others()]
return lst
tests = correct = 0
for _ in range(10):
lst = testcase()
expect = funcs[0](lst.copy())
for func in funcs:
result = func(lst.copy())
correct += result == expect
tests += 1
print(correct, 'out of', tests, 'tests correct')
print()
lst = [1] * 5000 + [6, 9] * 2500
for func in funcs:
times = repeat(lambda: func(lst), number=1)
print(*('%6d us ' % (t * 1e6) for t in sorted(times)), func.__name__)
Here's how I'd do it, as a first cut:
def summer_69(series):
in_summer = False
cur_sum = 0
for v in series:
if in_summer:
if v == 9:
in_summer = False
else:
if v == 6:
in_summer = True
else:
cur_sum += v
return cur_sum
Here's a version that uses a more reusable pythonic idiom, a generator function, and is a little more compact (at the slight cost of an extra comparison):
def yield_non_summer(series):
in_summer = False
def stateful_summer_predicate(v):
nonlocal in_summer
if in_summer and v == 9:
in_summer = False
return True # 9 is still in summer
elif not in_summer and v == 6:
in_summer = True
return in_summer
return (v for v in series if not stateful_summer_predicate(v))
def summer_69(series):
return sum(yield_non_summer(series))
Or, in fewer lines:
def yield_non_summer(series):
in_summer = False
def stateful_summer_predicate(v):
nonlocal in_summer
in_summer = (in_summer or v == 6) and v != 9
return in_summer
return (v for v in series if not stateful_summer_predicate(v))
def summer_69(series):
return sum(yield_non_summer(series))
def summer_69(arr):
sum = 0
Flag = False
if 6 not in arr:
for num in arr:
sum = sum + num
return sum
else:
for num in arr:
if num != 6 and Flag == False:
sum = sum + num
elif num == 6:
Flag = True
continue
elif Flag == True and num != 9:
continue
elif num == 9:
Flag = False
return sum
A simple approach is to make a filter and sum the results.
Code
def filter_substring(seq, start, end):
"""Yield values outside a given substring."""
release = True
for x in seq:
if x == start:
release = False
elif x == end:
release = True
elif release:
yield x
def summer(seq):
"""Return the sum of certain values."""
return sum(filter_substring(seq, 6, 9))
Demo
assert 0 == summer([])
assert 6 == summer([1, 2, 3])
assert 6 == summer([1, 2, 3, 6, 8, 7, 9])
assert 9 == summer([1, 3, 5])
assert 8 == summer([3, 5, 6, 7, 8, 9])
assert 15 == summer([2, 1, 6, 9, 12])
assert 16 == summer([2, 1, 6, 9, 1, 6, 6, 120, 9, 9, 12])
Details
filter_substring()+
This is a generator function. It iterates the input sequence and only yields a value if the conditions are appropriate, i.e. when the release remains True.
>>> list(filter_substring("abcde", "c", "d"))
['a', 'b', 'e']
>>> list(filter_substring([0, 1, 2, 3, 10], 1, 3))
[0, 10]
summer()
Here we simply sum whatever filter_range() yields.
+Note: a substring is a contiguous subsequence; this may or may not include strings in Python.
Will work with indexes:
def summer_69(arr):
y = []
for x in arr:
if 6 in arr:
a = arr.index(6)
b = arr.index(9)
del arr[a:b+1]
y = arr
elif arr == []:
return "0"
else:
return sum(arr)
return sum(y)
print(summer_69([])) #0
print(summer_69([1, 3, 5])) #9
print(summer_69([4, 5, 6, 7, 8, 9])) #9
print(summer_69([2, 1, 6, 9, 11])) #14
print(summer_69([2, 1, 6, 9, 6, 11, 25, 36, 11, 9, 4, 6, 4, 6, 3, 9, 15])) #22
Something like this:
def summer_69(lst):
"""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
"""
if not lst:
return 0
else:
_sum = 0
active = True
for x in lst:
if active:
if x != 6:
_sum += x
else:
active = False
else:
if x == 9:
active = True
return _sum
print(summer_69([1, 3, 5]))
print(summer_69([4, 5, 6, 7, 8, 9]))
print(summer_69([2, 1, 6, 9, 11]))
output
9
9
14
def summer_69(arr):
if 6 in arr:
c=arr[arr.index(6):arr.index(9)+1]
for i in c:
arr.remove(i)
print(arr)
return sum(arr)
else:
return sum(arr)
summer_69([1,2,3,4,5,6,7,8,9,10,11,12])
This will work:
def summer_69(arr):
total = 0
add = True
for num in arr:
while add:
if num != 6:
total += num
break
else:
add = False
while not add:
if num != 9:
break
else:
add = True
break
return total
def summer_69(arr):
a = 0
for nums in arr:
if nums == 6:
for items in arr[arr.index(6):]:
a = a+ items
if items == 9:
break
return sum(arr)-a
def summer_69(arr):
x = arr.count(6)
y = arr.count(9)
# to decide number of iteration required for loop
z = min(x,y)
k = 0
while k < (z) :
m = arr.index(6)
n = arr.index(9)
del arr[m:(n+1)]
k = k + 1
print(arr)
return sum(arr)
This will work for summer_69 problem as well for filtering substring
def filter_substring(seq, start, end):
flag = False
for char in seq:
if char == start:
flag = True
continue
elif flag:
if char == end:
flag = False
else:
continue
else:
yield char
def summer_69(seq, start, end):
return sum(filter_substring(seq, start, end))
def print_substring(string, start, end):
return list(filter_substring(string, start, end))
Example ::
seq = [4, 5, 9, 6, 2, 9, 5, 6, 1, 9, 2]
print(summer_69(seq, start=6, end=9))
string = "abcdef"
print(print_substring(string, start='c', end='e'))
This is the probably best answer if you are a newbie. I have simplified it as much as i can. you only need to know enumerate, function, for loops , tuple unpacking,if/else statements and break function.So lets go straight to the answer.
def myfunc(a):
mylist=[]
sum1 = 0
for b,c in enumerate(a):
if c==6:
for d in a[:b]:
mylist.append(d)
for e,f in enumerate(a):
if f==9:
for j in a[e+1:]:
mylist.append(j)
for y in a:
if y==6:
break
else:
mylist.append(y)
for k in mylist:
sum1 = sum1+k
print(sum1)
myfunc([1,3,5])
For those interested, here is my solution for this problem:
def summer_69(arr):
skate = arr
guitar = []
for i in range(len(arr)):
if 6 in arr:
guitar = skate[skate.index(6):skate.index(9)+1]
return abs(sum(skate) - sum(guitar))
else:
return sum(skate)
Replace
list1.index(9)+1
by
list1.index(9,list1.index(6)+1)+1
in line 6.
This will start searching for a 9 after 6.
This is taken from a Udemy course.
Here is the official answer . . .
def summer_69(arr):
total = 0
add = True
for num in arr:
while add:
if num != 6:
total += num
break
else:
add = False
while not add:
if num != 9:
break
else:
add = True
break
return total
Jose Periera has this on Python 'zero to hero' course.
My own particular approach was this . . .
def summer_69(arr):
#first find out if 6 or 9 are in the list
if 6 in arr and 9 in arr:
#Then create a variable that stores the index location of the number 6
#and the number 9
sixer = arr.index(6)
niner = arr.index(9)
#now return the sum of the array minus the sum of the values between
#index of 6 and index of 9 inclusive (hence the plus 1)
#This way will ignore the case of a 9 appearring before a 6 too.
return sum(arr) - sum(arr[sixer:niner+1])
#Otherwise just return the sum of the array.
else:
return sum(arr)
Happy to accept criticism here. I'm learning Python myself and I'm undergoing an Msc in computer science and hoping to apply for jobs in the field soon, so your comments will help me :)
My approach was to sum the whole list and the part of the list that we want to ignore and subtract them at the end.
def summer_69(arr):
result=0
reduction =0
for i in range(0,len(arr)):
result+=arr[i]
if arr[i] == 6:
temp = arr[arr.index(6):arr.index(9)+1]
reduction = sum(temp)
return result - reduction
def summer69(a):
for z in a:
if z==6 and 9 in a:
x=a.index(6)
y=a.index(9)
del a[x:y+1]
t= sum(a)
else:
t=sum(a)
return t
Will always prefer short , clear and easy understandable solution.
def summer_69(arr):
if 9 in arr :
sum = 0
y = arr.index(9)
for i , l in enumerate(arr):
if l == 6:
del arr[i:y+1]
for i in range(len(arr)):
sum = sum + arr[i]
return sum
elif 9 not in arr:
sum = 0
for i in range(len(arr)):
sum = sum + arr[i]
return sum
def summer_69(mylist):
if 6 in mylist:
return sum(mylist) - sum(mylist[mylist.index(6):mylist.index(9)+1])
else:
return sum(mylist)
def summer_69(arr):
returner = []
if 6 and 9 in arr:
a = arr.index(6)
b = arr.index(9)
if a < b:
seq = arr[a:(b+1)]
for i in arr:
if i not in seq:
returner.append(i)
return (sum(returner))
elif a > b:
seq = arr[b:(a+1)]
for i in arr:
if i not in seq:
returner.append(i)
return (sum(returner))
elif 6 in arr:
a = arr.index(6)
seq = arr[a:]
for i in arr:
if i not in slicer:
returner.append(i)
return(sum(returner))
elif 9 in arr:
a = arr.index(9)
seq = arr[a:]
for i in arr:
if i not in slicer:
returner.append(i)
return(sum(returner))
elif arr == []:
return 0
else:
return (sum(arr))
Just learning Python too and this was what I came up with for it:
def myfunc(arr):
ignore_list = []
newlist = []
for i,v in enumerate(arr):
if v >= 6 and v <= 9:
ignore_list.append(i)
if i in ignore_list:
newlist.append(0)
else:
newlist.append(v)
return sum(newlist)
Related
I am trying to find the summation of integer in list with elements that are divisible by 3 or 7 excluded
def SumSkip37(numList,sum = 0):
if numList:
i = numList.pop()
if i % 3 == 0 or i % 7 == 0:
return sum
else:
sum += i
return SumSkip37(numList, sum=sum)
numList = [1, 3, 5, 7, 9]
print(f'The result is {SumSkip37(numList)}.')
Pls help me figure out
You can update your code to:
def SumSkip37(numList, my_sum = 0): # avoid using sum
if numList:
i = numList.pop()
if i % 3 == 0 or i % 7 == 0:
return SumSkip37(numList, my_sum=my_sum) # pass the unchanged sum
else:
return SumSkip37(numList, my_sum=my_sum+i) # pass the sum + i
else:
return my_sum
NB. I tried to stay as close as possible to the original, but you can simplify greatly!
To avoid mutating the input:
def SumSkip37(numList, my_sum = 0):
if numList:
if numList[0] % 3 != 0 and numList[0] % 7 != 0:
my_sum += numList[0]
return SumSkip37(numList[1:], my_sum=my_sum)
return my_sum
print(f'The result is {SumSkip37(numList)}.')
Better approach than the alternative above suggested by #Stef to run in linear time:
def SumSkip37(numList, my_sum=0, idx=0):
if idx >= len(numList):
return my_sum
elif numList[idx] % 3 != 0 and numList[idx] % 7 != 0:
return SumSkip37(numList, my_sum + numList[idx], idx + 1)
return SumSkip37(numList, my_sum, idx + 1)
Also, recursion is overkill here, better use a short generator expression:
sum(i for i in numList if i%7!=0 and i%3!=0)
You are on the right track. You just weren't iterating through the whole list:
def SumSkip37(numList, total=0):
if numList:
i = numList.pop()
if i % 3 != 0 and i % 7 != 0:
total += i
return SumSkip37(numList, total=total)
return total
I flipped the comparison to remove the unnecessary else branch. It doesn't matter if the current number is divisible with 3 or 7 or not, you always want to continue the recursion until the list runs out.
Without Recursive function:
def SumSkip37(list):
sum = 0
for i in list:
if i % 3 == 0 or i % 7 == 0:
continue
else:
sum += i
return sum
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(SumSkip37(list))
With Recursive Function:
def SumSkip37(lst):
if len(lst) == 0:
return 0
else:
if lst[0] % 3 == 0 or lst[0] % 7 == 0:
return SumSkip37(lst[1:])
else:
return lst[0] + SumSkip37(lst[1:])
print(SumSkip37([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
On relatively clean way:
def SumSkip37(numList):
if not numList:
return 0
head, *tail = numList
return head * bool(head % 3 and head % 7) + SumSkip37(tail)
If either i or j reach the end of their list range, how i copy the remainder of the other
list to the merge list
https://ibb.co/m9JzBYp
go to link if not get the question
def list_merge (x, y):
merge = []
i = 0
j = 0
total = len (x) + len(y)
while != total :
if x[i] < y[j]:
merge.append(x[i])
i += 1
if i >= len (x):
#how i copy the reminder
else :
merge.append(y[j])
j += 1
if j >= len (y):
#how i copy the reminder
return merge
EDIT - OP wanted the code in some specific way.. Please see second snippet.
Don't try to complicate your code.. just go with how you would do it manually and write the code.
def list_merge (x, y):
merged_list = []
i = 0
j = 0
# when one of them is empty, break out
while i < len(x) and j < len(y):
if x[i] <= y[j]:
merged_list.append(x[i])
i +=1
else:
merged_list.append(y[j])
j +=1
# if you are here, that means either one of the list is done
# so check the bounds of both lists and append the one which is not traversed
# x has some elements to add
# check how extend works... makes your code clean
if i != len(x):
merged_list.extend(x[i:])
else:
merged_list.extend(y[j:])
return merged_list
a = [1,3,5,7,10]
b = [2,4,6,8,100]
print(list_merge(a,b))
Output
[1, 2, 3, 4, 5, 6, 7, 8, 10, 100]
What OP needed
def list_merge (x, y):
merge = []
i = 0
j = 0
total = len (x) + len(y)
while len(merge) != total :
if x[i] < y[j]:
merge.append(x[i])
i += 1
if i >= len (x):
merge.extend(y[j:])
else:
merge.append(y[j])
j += 1
if j >= len (y):
merge.extend(x[i:])
return merge
a quite simple form:
def merge(*lists_in):
list_in = []
for l in lists_in:
list_in += l
i = 0
while True:
if i == list_in.__len__() -1:
break
if list_in[i] > list_in[i+1]:
temp = list_in[i]
list_in[i] = list_in[i+1]
list_in[i+1] = temp
i = 0
else:
i += 1
return list_in
Testing it:
list1 = [1,4]
list2 = [1,5,6]
list3 = [3,7,9,10]
print(merge(list1, list2, list3))
Out:
[1, 1, 3, 4, 5, 6, 7, 9, 10]
This can be solved rather nicely using deques, which allow you to efficiently look at and remove the first element.
from collections import deque
# A generator function that interleaves two sorted deques
# into a single sorted sequence.
def merge_deques(x, y):
while x and y:
yield (x if x[0] <= y[0] else y).popleft()
# When we reach this point, one of x or y is empty,
# so one of these doesn't yield any values.
yield from x
yield from y
# Makes a list by consuming the merged sequence of two deques.
def list_merge(x, y):
return list(merge_deques(deque(x), deque(y))
from perms import perms
def dfac(n):
potential_factors = [9, 8, 7, 6, 4, 3, 2, 1]
factors = [9, 8]
n //= 72
while n != 1:
for f in potential_factors:
if n % f == 0 and f != 1:
factors.append(f)
n //= f
break
elif f != 1:
potential_factors = potential_factors[1:]
break
else:
return ['f']
return factors[::-1]
##############################################################################
version = 1
perms_length = len(perms)
index = 17701
def search(start: int):
for ones in range(start, index + 9144 * version, 9): # ignore this weird range
i = 1
for p in perms:
if len(dfac(int('1' * ones + p))) == 1:
print(f'{ones} ({i} / {perms_length})')
else:
cool = f'\n\n\nOnes: {ones}\nPerm: {p}\n\n\n'
print(cool)
exit()
i += 1
search(20077)
perms is a list of 113600 permutations of a number (as strings). I'm appending a bunch of ones to the beginning of each permutation and trying to factor each into single-digit factors (dfac). dfac returns fail string in list ['f'] if it fails to factor the number into any combination of [9, 8, 7, 6, 4, 3, 2]. How could I split this up with multiprocessing to make this go faster?
def perfect(number):
lst = []
sum = 0
for i in range(1,number):
if number % i == 0:
lst.append(i)
sum += i
return sum == number
for k in range(1,1000):
if perfect(k):
print(k)
The code works well except one thing. It finds perfect numbers(ie: 6 = 1+2+3). However, I want to print those dividing numbers in a list(ie: Perfect Number:6, dividing numbers: [1,2,3]). I've tried to use append method but couldn't print it anyways.
Just insert your list and the input number as an output of function:
def perfect(number):
lst = []
sum = 0
for i in range(1,number):
if number % i == 0:
lst.append(i)
sum += i
return (sum == number, lst, number)
Then you can print it assign the list to any variable you want using unpacking:
(result, printList, nr) = perfect(6)
print(f"Perfect Number: {nr}, Dividing numbers: {printList}")
Output
Perfect Number: 6, Dividing numbers: [1, 2, 3]
You'll need to return the list:
def perfect(number):
lst = []
sum = 0
for i in range(1,number):
if number % i == 0:
lst.append(i)
sum += i
if sum == number:
return lst
else:
return False
# Now the function can return either a list or False
for k in range(1,1000):
if isinstance(perfect(k), list):
print(k)
See this solution
def perfect(number):
sum = 0
lst = []
for i in range(1,number):
if number % i == 0:
lst.append(i)
sum += i
return ((sum == number),lst)
for k in range(1,1000):
res,lst = perfect(k)
if res:
print("{:<4} {}".format(k ,lst) )
Output
6 [1, 2, 3]
28 [1, 2, 4, 7, 14]
496 [1, 2, 4, 8, 16, 31, 62, 124, 248]
I am trying to implement the merge sort algorithm described in these notes by Jeff Erickson on page 3. but even though the algorithm is correct and my implementation seems correct, I am getting the input list as output without any change. Can someone point out the anomalies, if any, in it.
def merge(appnd_lst, m):
result = []
n = len(appnd_lst)
i, j = 0, m
for k in range(0, n):
if j < n:
result.append(appnd_lst[i])
i += 1
elif i > m:
result.append(appnd_lst[j])
j += 1
elif appnd_lst[i] < appnd_lst[j]:
result.append(appnd_lst[i])
i += 1
else:
result.append(appnd_lst[j])
j += 1
return result
def mergesort(lst):
n = len(lst)
if n > 1:
m = int(n / 2)
left = mergesort(lst[:m])
right = mergesort(lst[m:])
appnd_lst = left
appnd_lst.extend(right)
return merge(appnd_lst, m)
else:
return lst
if __name__ == "__main__":
print mergesort([3, 4, 8, 0, 6, 7, 4, 2, 1, 9, 4, 5])
There are three errors in your merge function a couple of indexing errors and using the wrong comparison operator. Remember python list indices go from 0 .. len(list)-1.
* ...
6 if j > n-1: # operator wrong and off by 1
* ...
9 elif i > m-1: # off by 1
* ...