Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

source code of Tortoise and hare algorithm in python

nodes = [(1,1,1,3,5,6), (1,2,3,2,4,5), (1,2,2,3,4,5),  (2,4,5,6)]

def next(parent):
  def find(nodes, parent):
    current = nodes[0]
    rest = nodes[1:]

    if current and current[0] == parent:
      return current[1]
    else:
      return find(rest, parent)
  return find(nodes, parent) 

def next_next(x):
  return next(next(x))

def meet(slow, fast, p1, p2, steps):
  p1 = slow(p1)
  p2 = fast(p2)
  steps = steps + 1

  if p1 == p2:
    return (p1, steps)
  else:
    return meet(slow, fast, p1, p2, steps)

def meet_result(slow, fast, p1, p2):
  result = meet(slow, fast, p1, p2, 0)
  return result[0]

def meet_count(slow, fast, p1, p2):
  result = meet(slow, fast, p1, p2, 0)
  return result[1]

def find_cycle(init):
  cycle_meet = meet_result(next, next_next, init, init)
  cycle_root = meet_result(next, next, cycle_meet, init)
  cycle_length = meet_count(lambda x: x, next, cycle_root, cycle_root)
  return (cycle_meet, cycle_root, cycle_length)
Comment

PREVIOUS NEXT
Code Example
Python :: how to make a crosshair in python 
Python :: how to parse dicts in reqparse in flask 
Python :: download a file from kaggle notebook 
Python :: plotly hide trace from hover 
Python :: bar plot fix lenthgy labels matplot 
Python :: python - count number of values without dupicalte in a second column values 
Python :: how to make a complex calculator in python 
Python :: matplotlib transparent line 
Python :: python dataframe get numeric columns 
Python :: show number as 3 digit python 
Python :: rename columns in datarame pandas 
Python :: how to add up everything in a list python 
Python :: selenium python chrome path 
Python :: TypeError: sequence item 0: expected str instance, int found 
Python :: all alphabets 
Python :: add time delta pytohn 
Python :: get all values of a dict python 
Python :: ready command discord.py 
Python :: python join two lists as dictionary 
Python :: how to clear a pickle file 
Python :: plt show 2 images 
Python :: find nth root of m using python 
Python :: my pygame window wont stay open 
Python :: django queryset unique values 
Python :: numpy arrays equality 
Python :: django timezone india 
Python :: python print do not use scientific notation 
Python :: pandas absolute value 
Python :: Find faculty of a number python 
Python :: zlib decompress python 
ADD CONTENT
Topic
Content
Source link
Name
4+1 =