Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 1. Counting substrings.
- # https://www.tutorialspoint.com/python3/string_count.htm
- def count_substrings(haystack, needle):
- return haystack.count(needle)
- print(count_substrings("This is a test string", "is"))
- print(count_substrings("babababa", "baba"))
- print(count_substrings("Python is an awesome language to program in!", "o"))
- print(count_substrings("We have nothing in common!", "really?"))
- print(count_substrings("This is this and that is this", "this"))
- # 2. Sum numbers in matrix
- # http://www.u.arizona.edu/~erdmann/mse350/topics/list_comprehensions.html
- def sum_matrix(m):
- return sum(map(sum, m))
- m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- print(sum_matrix(m))
- m = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
- print(sum_matrix(m))
- m = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
- print(sum_matrix(m))
- # 3. NaN Expand
- def nan_expand(times):
- return "{}{}".format("Not a " * times, "NaN" if times != 0 else "")
- print(nan_expand(0))
- print(nan_expand(1))
- print(nan_expand(2))
- print(nan_expand(3))
- # 4. Integer prime factorization
- def prime_factors(n):
- prfac = []
- d = 2
- times = 0
- while d * d <= n:
- if n % d == 0:
- while (n % d) == 0:
- times += 1
- n //= d
- prfac.append((d, times))
- d += 1
- times = 0
- if n > 1:
- prfac.append((n, 1))
- return prfac
- print(prime_factors(1000))
- # 5. https://docs.python.org/3/library/itertools.html
- def max_concecutive(items):
- from itertools import groupby
- return max(sum(1 for i in g) for k, g in groupby(items))
- print(max_concecutive([1, 2, 3, 3, 3, 3, 4, 3, 3]))
- # 6. https://docs.python.org/3/library/itertools.html
- def group(elem):
- from itertools import groupby
- return [list(grp) for k, grp in groupby(elem)]
- print(group([1, 1, 1, 2, 3, 1, 1]))
- # 7.
- def first_max(curr, rest, tank_size):
- for x in rest:
- if tank_size < x - curr:
- return rest.index(x) - 1
- def gas_stations(distance, tank_size, stations):
- stations.insert(0, 0)
- currentst = 0
- st = []
- current = 0
- while current >= stations[-1]:
- x = first_max(current, stations[currentst:], tank_size)
- print((stations[x + current]))
- return st
- print(gas_stations(320, 90, [50, 80, 140, 180, 220, 290]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement