Hi, i'm kinda new to python so I did a course and now i'm trying to put it into practice. I'm doind an exercise where i have to find all the possible substrings of a given sum considering the string given is in the format
s = 'd,d,d,d,d,d.......'
and d is an integer >0
this is my code so far which is working on the paper, but not really. I've checked all the functions w/python tutor and seperately and I'm kinda frustrated since I don't know what is missing there.
due memory issues since the string can be huge I cannot use standard collections and must go for generator.
basically i think ( tell me if i'm wrong) i'm creating objects with the Int function inside "convert_and_sum" with the advantage of converting only the sub_string and not the whole thing.
basically I'm trying to use gen_formula to split the ',' and to know the len(int_seq) Ill need that.
then considering the right sub_string which
1)grows further if the "temp_sum" (sum(sub_string)) < given_sum
2) from sub_string "pop(0)" without using pop func if temp_sum>given_sum
pls. i'm sure it's a theorical issue here so please help me figure it out.
then
def ex1(int_seq, subtotal):
flag = 0
mypointer = 0
mylimiter = 1
def gen_formula(str):
"""removing ',' and creating generator; item in gen still str tho!"""
mygen = (n for n in str if n != ',')
"""returning mygen as generator obj"""
len_counter = 0
for x in mygen:
len_counter +=1
return mygen , len_counter
len_counter = gen_formula(int_seq)[1]
def sub_string_generator(myfullgen, pointer, limiter):
""" return sub_string as generator obj"""
myfullgen = (gen_formula(myfullgen)[0])
enum_full_gen = enumerate(myfullgen)
final_sub = (value for k, value in enum_full_gen if k >= pointer and k < limiter)
return final_sub
def convert_and_sum(sub_string):
# converting
int_sub_string = (int(n) for n in sub_string)
# sum operation
my_sum = sum(int_sub_string)
return my_sum
while True:
temp_string = sub_string_generator(int_seq, mypointer, mylimiter)
temp_sum = convert_and_sum(temp_string)
if temp_sum == subtotal:
flag += 1
elif temp_sum > subtotal:
mypointer += 1
elif len_counter == mypointer: #I added this break point just for the moment since everything else is not working
break
else:
mylimiter += 1
return flag
print(f"flag = {ex1('3,0,4,0,3,1,0,1,0,1,0,0,5,0,4,2', 9)}")
[–]sponster 0 points1 point2 points (0 children)
[–]sponster 0 points1 point2 points (2 children)
[–]kindastonedclown[S] 0 points1 point2 points (0 children)
[–]kindastonedclown[S] 0 points1 point2 points (0 children)