diff options
| author | Lubos Kolouch <lubos@kolouch.net> | 2020-04-19 12:58:39 +0200 |
|---|---|---|
| committer | Lubos Kolouch <lubos@kolouch.net> | 2020-04-19 12:58:39 +0200 |
| commit | 96b4cee89c0ad477ad9035465246002ee21076ca (patch) | |
| tree | cbf1ab00228262b0cce5d307803800c3f445e7a2 | |
| parent | 06c2d2a7d1696a513a6830c3904d0ed8868c8444 (diff) | |
| download | perlweeklychallenge-club-96b4cee89c0ad477ad9035465246002ee21076ca.tar.gz perlweeklychallenge-club-96b4cee89c0ad477ad9035465246002ee21076ca.tar.bz2 perlweeklychallenge-club-96b4cee89c0ad477ad9035465246002ee21076ca.zip | |
Python solutions LK
| -rw-r--r-- | challenge-056/lubos-kolouch/python/ch-1.py | 32 | ||||
| -rw-r--r-- | challenge-056/lubos-kolouch/python/ch-2.py | 28 |
2 files changed, 60 insertions, 0 deletions
diff --git a/challenge-056/lubos-kolouch/python/ch-1.py b/challenge-056/lubos-kolouch/python/ch-1.py new file mode 100644 index 0000000000..1ed9d35cdf --- /dev/null +++ b/challenge-056/lubos-kolouch/python/ch-1.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +""" + https://perlweeklychallenge.org/blog/perl-weekly-challenge-056/ + Task 1 + + You are given an array @N of positive integers (sorted) and another non negative integer k. + Write a script to find if there exists 2 indices i and j such that A[i] - A[j] = k and i != j. + It should print the pairs of indices, if any such pairs exist. +""" + + +def get_valid_pairs(k: int, arr: list): + """ get all valid pairs""" + + answer = '' + + for i in range(0, len(arr)-1): + j = i + 1 + + while (arr[j] - arr[i] < k) and (j < len(arr) - 1): + j += 1 + + if arr[j] - arr[i] == k: + answer += f"({j},{i})" + + return answer + + +# TESTS +assert get_valid_pairs(2, (2, 7, 9)) == "(2,1)" +assert get_valid_pairs(2, (2, 4, 6)) == "(1,0)(2,1)" +assert get_valid_pairs(2, (2, 8, 9)) == '' diff --git a/challenge-056/lubos-kolouch/python/ch-2.py b/challenge-056/lubos-kolouch/python/ch-2.py new file mode 100644 index 0000000000..4f7c9aeeda --- /dev/null +++ b/challenge-056/lubos-kolouch/python/ch-2.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +""" https://perlweeklychallenge.org/blog/perl-weekly-challenge-056/ + Task 2 + You are given a binary tree and a sum, write a script to find if the tree has a path such that adding up all the values along the path equals the given sum. Only complete paths (from root to leaf node) may be considered for a sum. +""" + +import networkx as nx + +g = nx.DiGraph() + +g.add_edge(5, 4) +g.add_edge(4, 11) +g.add_edge(11, 7) +g.add_edge(11, 2) +g.add_edge(5, 8) +g.add_edge(8, 13) +g.add_edge(8, 9) +g.add_edge(9, 1) + +start = 5 +my_sum = 22 + +external_vertices = (x for x in g.nodes() if g.out_degree(x)==0 and g.in_degree(x)==1) + +for vert in external_vertices: + path = nx.shortest_path(g, start, vert) + if sum(path) == my_sum: + print(path) |
