Skip to content

Instantly share code, notes, and snippets.

@rukeba
Last active April 22, 2020 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rukeba/40f7da63de2f1657e6acd0205beade83 to your computer and use it in GitHub Desktop.
Save rukeba/40f7da63de2f1657e6acd0205beade83 to your computer and use it in GitHub Desktop.
#2837 Senior Full-stack Python / Javascript Developer
import random
def generate_seq(length, min, max):
"""
Generate sequence of random integer numbers
:param length: length of sequence
:param min: minimal value of random number
:param max: max value of random number
:return:
"""
return [random.randint(min, max) for _ in range(length)]
def find_duplicate_item(seq):
"""
Fastest way to handle unique (or not unique) values in Python is set().
:param seq: list with values to find first duplicate
:return: tuple with index of duplicate element and element itself
"""
uniq = set()
for i, el in enumerate(seq):
if el not in uniq:
uniq.add(el)
else:
return i, el
return None, None
def main():
seq = generate_seq(10**6, 1, 5*10**5)
index, el = find_duplicate_item(seq)
if index is not None:
print(f'Duplicate item {el} found at position {index}')
else:
print('Duplicate element not found')
if __name__ == '__main__':
main()
import argparse
def main():
parser = argparse.ArgumentParser(description='Reverse input number in bin format')
parser.add_argument('number', help='decimal number', type=int)
args = parser.parse_args()
# check number range
if not(1 <= args.number <= 1000000000):
raise ValueError('number should be from 1 to 1000000000')
bin_str = bin(args.number)
# remove first '0b' marker and reverse order
reverted = bin_str[2:][::-1]
# convert back to int
result1 = int(reverted, 2)
print(result1)
# or one-liner
result2 = int(str(bin(args.number)[2:][::-1]), 2)
print(result2)
if __name__ == '__main__':
main()
import argparse
class Point(object):
"""Represents pair of coordinates in matrix
"""
def __init__(self, y, x):
self.y = y
self.x = x
def move(self, direction) -> 'Point':
return Point(self.y + direction.y, self.x + direction.x)
def to_tuple(self) -> tuple:
return self.y, self.x
def __str__(self):
return str(self.to_tuple())
class Area(object):
"""Represents area of matrix
specified by coordinates of top left point and bottom right point
"""
def __init__(self, top_left: Point, bottom_right: Point):
self._top_left = top_left # type: Point
self._bottom_right = bottom_right # type: Point
def contains(self, point: Point) -> bool:
return self._top_left.y <= point.y <= self._bottom_right.y and self._top_left.x <= point.x <= self._bottom_right.x
def is_collapsed(self) -> bool:
return not(self._bottom_right.y - self._top_left.y > 0 or self._bottom_right.x - self._top_left.x > 0)
def resize(self, direction: Point) -> 'Area':
if direction.x > 0 or direction.y > 0:
return Area(self._top_left.move(direction), self._bottom_right)
if direction.x < 0 or direction.y < 0:
return Area(self._top_left, self._bottom_right.move(direction))
raise Exception('Unexpected direction')
class SpiralWalk(object):
"""Walker by 2D matrix in clock wise direction"""
turn_map = {
(0,1): Point(1,0),
(1,0): Point(0,-1),
(0,-1): Point(-1,0),
(-1,0): Point(0,1)
}
def __init__(self, start_position: Point, area: Area):
self.current = start_position # type: Point
self.area = area # type: Area
self.direction = Point(0, 1) # type: Point
def _turn_direction(self) -> Point:
return self.turn_map[(self.direction.to_tuple())]
def _try_to_move(self):
next_position = self.current.move(self.direction)
if self.area.contains(next_position):
self.current = next_position
return True
return False
def walk(self):
# initial or current position
yield self.current
# try to move with direction
while True:
if self._try_to_move():
yield self.current
else:
break
# try to turn direction if area is not collapsed
if not self.area.is_collapsed():
self.direction = self._turn_direction()
self.area = self.area.resize(self.direction)
if self._try_to_move():
yield from self.walk()
def main():
parser = argparse.ArgumentParser(description='Walk on matrix by spiral')
parser.add_argument('size', help='matrix size in form ROWSxCOLUMNS (3x4)', type=str)
args = parser.parse_args()
y_size, x_size = (int(x) for x in args.size.split('x'))
assert y_size > 0
assert x_size > 0
start_position = Point(0, 0)
# suppose top left corner is 0, 0
area = Area(Point(0, 0), Point(y_size-1, x_size-1))
walker = SpiralWalk(start_position, area)
for node in walker.walk():
print(node)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment