简体   繁体   English

Python中子序列递归的总和

[英]Sum of subsequences recursion in Python

Over the weekend I was working on the Ad Infinitum challenge on HackerRank. 上周末,我在HackerRank上进行了广告无限挑战。

One problem was to calculate the sum of all subsequences of a finite sequence, if each subsequence is thought of as an integer. 一个问题是,如果每个子序列被认为是整数,则要计算有限序列的所有子序列的总和。

For example, sequence 4,5,6 would give answer 4 + 5 + 6 + 45 + 46 + 56 + 456 = 618. 例如,序列4,5,6将给出答案4 + 5 + 6 + 45 + 46 + 56 + 456 = 618。

I found a recursion and wrote the Python code below. 我找到了一个递归,并在下面编写了Python代码。 It solved 5/13 test cases. 它解决了5/13个测试用例。

The remaining 8/13 test cases had runtime errors. 其余8/13个测试用例存在运行时错误。

I was hoping someone could spy where in the code the inefficiencies lie, and how they can be sped up. 我希望有人可以监视代码中的低效率之处以及如何加快效率。 Or, help me decide that it must be that my recursion is not the best strategy. 或者,请帮助我确定一定是我的递归不是最佳策略。

# Input is a list, representing the given sequence, e.g. L = [4,5,6]

def T(L): 
    limit = 10**9 + 7  # answer is returned modulo 10**9 + 7
    N = len(L)
    if N == 1: 
        return L[0]
    else:
        last = L[-1] 
        K = L[:N-1]
        ans =  T(K)%limit + 10*T(K)%limit + (last%limit)*pow(2,N-1,limit)
        return ans%limit

Well, you want the combinations: 好吧,您想要组合:

from itertools import combinations

def all_combinations(iterable):
    for r in range(len(digits)):
        yield from combinations(digits, r+1)

And you want to convert them to integers: 您想将它们转换为整数:

def digits_to_int(digits):
    return sum(10**i * digit for i, digit in enumerate(reversed(digits)))

And you want to sum them: 您想总结一下:

sum(map(digits_to_int, all_combinations([4, 5, 6])))

Then focus on speed. 然后专注于速度。

Assuming you mean continuous subsequence. 假设您是指连续的子序列。

test = [4, 5, 6]

def coms(ilist):
    olist = []
    ilist_len = len(ilist)
    for win_size in range(ilist_len, 0, -1):
        for offset in range((ilist_len - win_size) + 1):
            subslice = ilist[offset: offset + win_size]
            sublist  = [value * (10 ** power) for (power, value) in enumerate(reversed(subslice))]
            olist.extend(sublist)
    return olist

print sum(coms(test))

This is my submission for the same problem (Manasa and Sub-sequences). 这是我针对相同问题(Manasa和子序列)提交的。 https://www.hackerrank.com/contests/infinitum-may14/challenges/manasa-and-sub-sequences https://www.hackerrank.com/contests/infinitum-may14/challenges/manasa-and-sub-sequences

I hope this will help you to think of a better way. 希望这可以帮助您想到更好的方法。

ans = 0
count = 0
for item in raw_input():
    temp = (ans * 10 + (count + 1)*(int(item)))%1000000007
    ans = (ans + temp)%1000000007
    count = (count*2 + 1)%1000000007

print ans

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM