Skip to content Skip to sidebar Skip to footer

More Efficient Method Of Dealing With Large Numbers In Python?

I have a question in Python which I have created an answer for it, but I am trying to achieve better efficiency for the answer. I cant use functions, recursions, only basic stuff..

Solution 1:

well, you can have more efficient way of summing the 12 sequential numbers. you can keep track of 12 sequential numbers, pop/subtract the oldest(leftmost) one from the subset's sum, push/add the newest(rightmost) one.

also, sum(iterable) is a built-in function.

my new code with only basic list and for-loop:

x = 5 ** 36
num_list = [int(i) for i instr(x)]
sumOfBig = last_sum = sum(num_list[:12])
maximal_index = 0for i, n inenumerate(num_list[12:]):
   last_sum = last_sum + n - num_list[i]
   if last_sum > sumOfBig:
      maximal_index = i+1
      sumOfBig = last_sum


print num_list[maximal_index:maximal_index+12] #[8, 3, 6, 6, 8, 5, 1, 8, 0, 6, 6, 4]

Solution 2:

x = 5**36
str_x = [int(i) for i instr(x)]


curBestIndex = 0
curBestSum = sum(str_x[:12])
curSum = curBestSum

for i inrange(len(str_x) - 11):
    delta = str_x[i + 11] - str_x[i]
    curSum += delta
    if curSum > curBestSum:
        curBestSum = curSum
        curBestIndex = i

big = str(x)[curBestIndex : curBestIndex + 12]
print(big)
print(curBestSum)

Solution 3:

Here's a method that helps factor out all the occurrences of 11/12, etc.

MAX_LENGTH = 12
x = 5 ** 36

sequence = []
d = []

for i instr(x):
    d.append(int(i))
    iflen(d) > MAX_LENGTH:
        d.pop(0)
    ifsum(d) >= sum(sequence):
        sequence = list(d)

print sequence, sum(sequence)

RETURNS:

>>> 
[8, 3, 6, 6, 8, 5, 1, 8, 0, 6, 6, 4] 61

In accordance with the Zen of Python, "Readability Counts", and I think that single line actions presented here are much more straightforward than slicing operations, especially when considering off-by-one mistakes that come from multiple instances of hardcoding the sequence length.

Post a Comment for "More Efficient Method Of Dealing With Large Numbers In Python?"