使用RECURSION

时间:2016-03-15 17:02:13

标签: python math recursion count range

新手在这里。我在math.stackoverflow上发现了一个关于如何计算4在范围1到10000(34,340,但也是324,3274)中3次出现的次数的问题。我编写了一个解决它的代码,但我想知道是否有一种更简单,更清晰的方法来编写任何数字作为n 的递归。

def fours_after_threes(n):
    List = []
    for i in range(1,n,1):
        buf = ''
        buf += str(i)
        List.append(buf)

    cn = 0

    for el in List:
        if len(el) < 2:
            pass
        elif len(el) == 2:
            if el[0] == "3" and el[1] == "4":
                cn+=1

        elif len(el) == 3:
            if el[0] == "3" and el[1] == "4":
                cn+=1
            elif el[0] == "3" and el[2] == "4":
                cn+=1
            elif el[1] == "3" and el[2] == "4":
                cn+=1

        elif len(el) == 4:
            if el[0] == "3" and el[1] == "4":
                cn+=1
            elif el[0] == "3" and el[2] == "4":
                cn+=1
            elif el[0] == "3" and el[3] == "4":
                cn+=1
            elif el[1] == "3" and el[3] == "4":
                cn+=1
            elif el[1] == "3" and el[2] == "4":
                cn+=1
            elif el[2] == "3" and el[3] == "4":
                cn+=1

    return cn

print fours_after_threes(10000)


>>> 
523

这就是我坚持的代码。如何使用范围的“其余”?或者你可能更了解如何在任何给定范围和任何给定数字下解决它?

while len(List)>0:
    for el in List:
        if "3" in range(0,len(el)-1) and "4" in **range(1,...**
            cn+=1
            List.remove(List[0])
            return function_name(1000)
        else:
            List.remove(List[0])
            return function_name(1000)

print fours_after_threes(1,10000,3,4)

3 个答案:

答案 0 :(得分:1)

我已经尝试过使用字符串并将字符串拆分为第一次出现的'3'。它并不像正则表达式那样优雅,但它显然比手工比较每个字符串数更好。

def test(lst):
    counter = 0
    # Test every element of the list
    for i in lst:
        # Convert it to a string and split it by the *first* occurence of '3'
        i = str(i).split('3', 1)
        # Check if there was a 3 in it by comparing the length of the result
        if len(i) > 1:
            # Now check if a 4 is in the second part (meaning after the 3)
            if '4' in i[1]:
                counter += 1
    return counter

test(range(10000))
# returns 523

这不是递归而是迭代。基于这个例子,扩展具有不同的“数字”应该很容易。

经过一番思考后,我真的找到了一种递归的方法:

def test(lst, numbers):
    counter = 0
    for i in lst:
        # Start recursion for the current number and the numbers we are looking for
        counter += testnumber(str(i), numbers)
    return counter

def testnumber(number, remainingnumbers):
    if len(remainingnumbers) == 0:
        # No number remaining to look for - valid
        return 1
    if len(number) == 0:
        # Number is exhausted but we haven't found that combination
        return 0
    if number[0] == remainingnumbers[0]:
        # Check the rest of the number without the found first number
        # because we have found a match!
        return testnumber(number[1:], remainingnumbers[1:])
    else:
        # Check for the rest of the number... there was no match this recursion
        return testnumber(number[1:], remainingnumbers)

test(range(10000), ['3', '4'])

它可以检查仲裁组合['1', '2']也是可能的,甚至是['1', '2', '3', '4', '5'],即使后者会导致零计数。

答案 1 :(得分:1)

我想出了这个:

def rec(buffer_list, index, found):
    if index == len(buffer_list):
        return found
    num_str = str(buffer_list[index])
    three_index = -1
    four_index = -1
    if len(num_str) < 2:
        return rec(buffer_list, index+1, found)
    for i in num_str:
        if i == '3':
            three_index = num_str.index(i)
        if i == '4':
            four_index = num_str.index(i)

    if 0 <= three_index < four_index:
        found += 1
        return rec(buffer_list, index+1, found)
    else:
        return rec(buffer_list, index+1, found)


def find_three_four(n):
    found = 0
    numbers = range(1, n, 1)
    total = rec(numbers, 0, 0)
    print total

find_three_four(100)

它不是很优雅,但似乎工作,前100个数字(34)为1,500为22.Python无法处理超过999次调用的递归,因此在制作时请记住这一点递归

答案 2 :(得分:1)

这是一个短函数,如果在4(数字=“34”)之前有3,则返回True,并且数字也作为字符串传递:

def in_string(digits, number):
    if not number:    # no more digits in number?
        return False  # all done
    digit = number[0]     # get the leading digit
    number = number[1:]   # leave the remaining digits in number
    if digit == digits[0]:    # found a digit in the sequence?
        digits = digits[1:]   # leave the remaining digits
        if not digits:        # no more digits in sequence?
            return True       # all done
    return in_string(digits, number)    # recursion

c = 0
for i in range(10000):
    if in_string("34", str(i)):
        c += 1
print c

结果是523