Euler_problem_14 for python

Euler 14的不同解法 ----所涉及的知识 1. yield 2.BF 3. decorator 4.cache 5.等等

def euler_problem_14():

    """
        最直接粗暴的解法:就是直接如下所示了
    """
    max_count = 1
    max_value = 1
    for i in xrange(100101, 1, -1):
        this_cycle_count = 1
        status = i
        while status > 1:
            if status % 2 == 0:
                status /= 2
            else:
                status = status * 3 + 1
            this_cycle_count += 1
        this_cycle_count += 1
        if this_cycle_count > max_count:
            max_value = i
            (this_cycle_count, max_count) = (max_count, this_cycle_count)
    print("value: %s    terms: %s" % (max_value, max_count))




def euler_problem_14_1():
    """
        solve this large number using a simple cache to return the numberof terms
        from we already know
    """
    max_count = 1
    max_value = 1
    sequence_cache_1 = dict()
    for i in xrange(1, 1000):
        status = i
        this_cycle_count = 0
        while status > 1:
            try:
                this_cycle_count += sequence_cache_1[status] - 1
                break
            except KeyError:
                pass


            if status % 2 == 0:
                # even
                status /= 2
            else:
                # odd
                status = status * 3 + 1
            this_cycle_count += 1
        this_cycle_count += 1
        sequence_cache_1[i] = this_cycle_count


        if this_cycle_count > max_count:
            max_count = this_cycle_count
            max_value = i
    print("value: %s   term: %s" % (max_value, max_count))




SEQUENCE_CACHE = dict()




def cache_euler_14(func):


    def kicker(value, status=None, n=None):
        try:
            SEQUENCE_CACHE[value] = n - 1 + SEQUENCE_CACHE[status]
            return SEQUENCE_CACHE[value]
        except (KeyError, TypeError):
            pass


        if n is None:
            result = func(value, status)
        else:
            result = func(value, status, n)
        if status <= 1:
            SEQUENCE_CACHE[value] = result
        return result


    return kicker




@cache_euler_14
def euler_problem_14_2(value, status=None, n=1):
    """
        通过decorator 来进行性能的提升
        装饰器 cache_euler14
    """
    if status is None:
        status = value
    if status <= 1:
        return n
    if status % 2 == 0:
        # even
        status /= 2
    else:
        # odd
        status = status * 3 + 1


    return euler_problem_14(value, status, n+1)




def euler_problem_14_3():


    terms = 0
    value = 0
    for x in xrange(100000):
        result = euler_problem_14_2()
        if result > terms:
            value = x
            terms = result

    print("value : %s   terms: %s" % (value, terms))




def ext15(n):
    if n > 1:
        yield n
        if n % 2 == 0:
            n /= 2
            for i in ext15(n):
                yield i
        else:
            n = 3 * n + 1
            for i in ext15(n):
                yield i
    else:
        yield n




def count12():
    count = 0
    count1 = 0
    for i in xrange(200000):
        for k, j in enumerate(ext15(i)):
            count1 = k
        if count1 > count:
            (count1, count) = (count, count1)
    print count

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 以下是使用Python实现Christofides算法的示例代码: ```python import networkx as nx from networkx.utils import pairwise def christofides(G): # Step 1: Find minimum spanning tree of G T = nx.minimum_spanning_tree(G) # Step 2: Find odd-degree vertices in T odd_deg_vertices = [v for v in T.nodes if T.degree(v) % 2 == 1] # Step 3: Find minimum weight matching on the subgraph induced by the odd-degree vertices odd_deg_subgraph = G.subgraph(odd_deg_vertices) matching = nx.algorithms.matching.max_weight_matching(odd_deg_subgraph) # Step 4: Combine minimum spanning tree and minimum weight matching to form a tour tour_nodes = list(T.nodes) for u, v in matching: tour_nodes += nx.shortest_path(G, u, v)[1:-1][::-1] tour = [tour_nodes[0]] for u, v in pairwise(tour_nodes): tour += nx.shortest_path(G, u, v)[1:] return tour ``` 说明: 1. 该算法使用NetworkX库实现。 2. `nx.minimum_spanning_tree(G)` 返回G的最小生成树。 3. `T.degree(v)` 返回节点v的度数。 4. `nx.algorithms.matching.max_weight_matching(G)` 返回G的最大权匹配。 5. `G.subgraph(nodes)` 返回由给定节点集合构成的子图。 6. `nx.shortest_path(G, u, v)` 返回从节点u到节点v的最短路径。 7. `pairwise(iterable)` 返回一个迭代器,每次返回iterable中相邻的两个元素。例如,pairwise([1,2,3,4])返回[(1,2),(2,3),(3,4)]。 8. 该算法返回一个旅行商问题的近似解,即一个经过所有节点的回路,使得总权重尽可能小。 ### 回答2: Christofides算法是一种解决旅行商问题(Traveling Salesman Problem,TSP)的近似算法。 该算法主要包括以下几个步骤: 1. 使用Prim算法计算TSP问题的最小生成树(Minimum Spanning Tree,MST)。 2. 在MST的基础上,找到所有奇度节点。如果不存在奇度节点,则直接返回MST作为解决方案。 3. 构建一个新的完全图,其中只包括上一步中找到的奇度节点。 4. 使用最短路径算法(例如Dijkstra算法)计算新图中所有节点间的最短路径。 5. 构建一个最小权重的完全匹配图,其中每个节点只能匹配一个其他节点。 6. 将MST和完全匹配图的边合并,得到一个新的图。 7. 使用欧拉回路算法(例如Fleury算法)得到新图的欧拉回路,即旅行商的路径。 8. 对欧拉回路进行路径压缩,即去除重复经过的节点,得到最终的近似解。 在Python中,可以使用networkx库来实现Christofides算法。首先,需要导入networkx库,然后使用该库提供的函数来实现上述步骤。具体代码如下所示: ```python import networkx as nx def christofides_tsp(graph): # Step 1: 计算最小生成树 mst = nx.minimum_spanning_tree(graph) # Step 2: 找到所有奇度节点 odd_nodes = [node for node, degree in mst.degree() if degree % 2 == 1] # Step 3: 构建新的完全图 complete_graph = graph.subgraph(odd_nodes) # Step 4: 计算最短路径 shortest_paths = dict(nx.all_pairs_dijkstra_path(complete_graph)) # Step 5: 构建完全匹配图 matching_graph = nx.Graph() for node in odd_nodes: if not matching_graph.has_node(node): matching_graph.add_node(node) for u, paths in shortest_paths.items(): for v, path in paths.items(): if u != v and not matching_graph.has_edge(u, v): matching_graph.add_edge(u, v, weight=len(path)-1) # Step 6: 合并图的边 merged_graph = nx.compose(mst, matching_graph) # Step 7: 计算欧拉回路 euler_circuit = list(nx.eulerian_circuit(merged_graph)) # Step 8: 路径压缩 tsp_path = [euler_circuit[0][0]] for edge in euler_circuit: if edge[0] not in tsp_path: tsp_path.append(edge[0]) return tsp_path ``` 上述代码中,graph表示TSP问题的图,可以使用networkx库或自定义的图数据结构来表示。函数christofides_tsp返回TSP问题的近似解,即旅行商的路径。 需要注意的是,Christofides算法是一种近似算法,不能保证得到最优解。然而,该算法在实践中表现良好,能够在合理的时间内求解很大规模的TSP问题。 ### 回答3: Christofides算法是一种解决带有度量约束的旅行商问题(TSP)的启发式算法。它于1976年由N. Christofides提出。 该算法解决的问题是:给定一系列待访问城市和其之间的距离,如何找到一条回路,使得遍历所有城市一次,且总路径最短。 Christofides算法主要步骤如下: 1. 计算城市之间的最短路径矩阵。可以使用Dijkstra或Floyd-Warshall等算法来计算。 2. 在最短路径矩阵的基础上构建最小生成树(Minimum Spanning Tree,MST),可以使用Prim或Kruskal等算法进行构建。 3. 找出最小生成树中的奇数度顶点,形成一个子图。 4. 计算子图中奇数度顶点之间的最小匹配(Minimum Weight Perfect Matching,MWPM),可以使用Blossom等算法来计算。 5. 将最小生成树和最小匹配合并,形成一个欧拉回路。 6. 在欧拉回路中删除重复访问的城市,得到TSP的近似解。 以下是使用Python实现Christofides算法的一个简单例子: ```python import networkx as nx from networkx.algorithms.approximation import christofides # 构建城市之间的距离矩阵 distances = [ [0, 2, 9, 10], [2, 0, 6, 4], [9, 6, 0, 8], [10, 4, 8, 0] ] # 创建一个无向图 G = nx.Graph() # 添加城市节点和边 for i in range(len(distances)): G.add_node(i) for i in range(len(distances)): for j in range(i + 1, len(distances)): G.add_edge(i, j, weight=distances[i][j]) # 使用Christofides算法求解TSP T = christofides(G) # 输出TSP的近似解 print("TSP近似解:", T) ``` 通过运行上述代码,我们可以得到TSP的近似解。请注意,由于Christofides算法是一种启发式算法,所以它在某些情况下可能无法得到最优解,但通常能够得到较好的近似解。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值