Leetcode Medium: Rotate a LinkedList - python-3.x

Here's what I wrote, (yes, it's not the most optimal answer)
But I get a timeout exception sometimes.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if (head != None):
while (k > 0):
cur = head
if (head.next == None):
prev = head
else:
while (head.next != None):
prev = head
head = head.next
prev.next = None
head.next = cur
k -= 1
return head```

We can use Floyd's Tortoise and Hare algorithm for this question, is a bit more efficient:
class Solution:
def rotateRight(self, head, k):
if not head:
return
if not head.next:
return head
curr, length = head, 1
while curr.next:
curr = curr.next
length += 1
k %= length
if k == 0:
return head
slow = fast = head
for _ in range(k):
fast = fast.next
while fast.next:
slow, fast = slow.next, fast.next
temp = slow.next
slow.next = None
fast.next = head
head = temp
return head

Related

AttibuteError when trying to make configs

AttributeError: module 'collections' has no attribute 'Sequence'
i get this error everything i try to run my code but there isn't any information about how to use Mothur except for the the documentation.
`# python3
import sys
import queue
import itertools
from collections import deque
from mothur_py import Mothur
import collections.abc as collections
class KmerIdMgmt:
def __init__(self):
self.id = 0
self.ids_map = {}
self.kmers = {}
def insert(self, kmer):
if kmer not in self.ids_map:
self.ids_map[kmer] = self.id
self.kmers[self.id] = kmer
self.id += 1
return self.ids_map[kmer]
class DeBruijnGraph(object):
def __init__(self, k, reads):
self.k = k
self.threshold = self.k + 1
self.kmer_ids = KmerIdMgmt()
self.coverage = {}
self.graph = {}
self.outgoing_num = lambda k: len(self.graph[k][0])
self.incoming_num = lambda k: self.graph[k][1]
self.make_deBruijn_graph(self.break_reads_into_kmers(reads))
def break_reads_into_kmers(self, reads):
break_read = lambda read: [ read[j:j + self.k] for j in range(len(read) - self.k + 1) ]
return [ kmer for read in reads for kmer in break_read(read) ]
def make_deBruijn_graph(self, kmers):
def add_edge(graph, coverage, left, right):
graph.setdefault(left, [set(), 0])
graph.setdefault(right, [set(), 0])
coverage.setdefault((left, right), 0)
coverage[(left, right)] += 1
if right not in graph[left][0]:
graph[left][0].add(right)
graph[right][1] += 1
for kmer in kmers:
left = self.kmer_ids.insert(kmer[:-1])
right = self.kmer_ids.insert(kmer[1:])
if left != right:
add_edge(self.graph, self.coverage, left, right)
def remove_leaves(self):
removable = [ k for k, v in self.graph.items() if len(v[0]) == 0 ]
for k in removable:
del self.graph[k]
def print_graph(self):
for k, v in self.graph.items():
print(k, v)
class TipRemoval(DeBruijnGraph):
def __init__(self, k, reads):
DeBruijnGraph.__init__(self, k, reads)
def remove_tips(self):
for k, v in self.graph.items():
find_and_remove = None
if self.outgoing_num(k) == 1 and self.incoming_num(k) == 0:
find_and_remove = self.find_and_remove_incoming
elif self.outgoing_num(k) > 1:
find_and_remove = self.find_and_remove_outgoing
else: continue
condition = True
while condition:
condition = False
for edge in v[0]:
if find_and_remove(edge, 0):
v[0].remove(edge)
condition = True
break
def find_and_remove_outgoing(self, current, depth):
if self.outgoing_num(current) > 1 or self.incoming_num(current) > 1:
return False
if depth == self.threshold:
return False
if self.outgoing_num(current) == 0:
return True
if self.find_and_remove_outgoing(next(iter(self.graph[current][0])), depth + 1):
to = next(iter(self.graph[current][0]))
self.graph[current][0].pop()
self.graph[to][1] -= 1
return True
return False
def find_and_remove_incoming(self, current, depth):
if self.outgoing_num(current) == 0 or self.incoming_num(current) > 1:
return True
if depth == self.threshold:
return False
if self.find_and_remove_incoming(next(iter(self.graph[current][0])), depth + 1):
to = next(iter(self.graph[current][0]))
self.graph[current][0].pop()
self.graph[to][1] -= 1
return True
return False
class BubbleRemoval(TipRemoval):
def __init__(self, k, reads):
TipRemoval.__init__(self, k, reads)
self.paths = {}
def remove_bubbles(self):
for k, v in self.graph.items():
if self.outgoing_num(k) > 1:
self.dfs(path=[k], current=k, depth=0)
for pair, candidates_list in self.paths.items():
source, target = pair[0], pair[1]
best_path = max(candidates_list, key=lambda item: item[1])[0]
for path, _ in candidates_list:
if best_path == path or not self.bubble_possible(source, target):
continue
if self.paths_disjoint(best_path, path) and self.path_exists(path):
self.remove_path(path)
def bubble_possible(self, source, target):
return len(self.graph[source][0]) > 1 and self.graph[target][1] > 1
def path_exists(self, path):
for j in range(len(path) -1):
if path[j +1] not in self.graph[path[j]][0]:
return False
return True
def remove_path(self, path):
for j in range(len(path) -1):
self.graph[path[j]][0].remove(path[j +1])
self.graph[path[j +1]][1] -= 1
del self.coverage[(path[j], path[j +1])]
def paths_disjoint(self, a, b):
return len(set(a) & set(b)) == 2
def dfs(self, path, current, depth):
if current != path[0] and self.incoming_num(current) > 1:
weight = sum(self.coverage[(path[i], path[i+1])] for i in range(len(path)-1)) / len(path)
self.paths.setdefault((path[0], current), list()).append((path[:], weight))
if depth == self.threshold:
return
for next_ in self.graph[current][0]:
if next_ not in path:
path.append(next_)
self.dfs(path, next_, depth + 1)
path.remove(next_)
class PhiX174GenomeAssembler(BubbleRemoval):
def __init__(self, k, reads):
BubbleRemoval.__init__(self, k, reads)
def make_Euler_cycle(self):
verteces = deque()
path = []
# line 191
current = next(iter(self.graph))
verteces.append(current)
while verteces:
current = verteces[0]
if len(self.graph[current][0]) != 0:
t = next(iter(self.graph[current][0]))
verteces.append(t)
self.graph[current][0].remove(t)
continue
path.append(current)
verteces.popleft()
return path
def assemble(self):
self.remove_tips()
self.remove_leaves()
self.remove_bubbles()
cycle = self.make_Euler_cycle()
circular_genome = self.kmer_ids.kmers[cycle[0]]
for i in range(1, len(cycle) - (self.k - 1)):
circular_genome += self.kmer_ids.kmers[cycle[i]][-1]
return circular_genome
if __name__ == "__main__":
n_kmers = int(input())
for _ in range(n_kmers):
reads = list(input())
reads = str(reads)
with open('reads.fasta', 'w') as read:
read.write(reads)
k = 100
m = Mothur()
contig = m.make.contigs(ffasta = read)
for x in range(n_kmers):
print(">CONTIG", x)
print(contig)
`

AVL Tree, delete mininum node (Python 3)

I want to implement a huffman coding using AVL tree. I perform some insertion, then I delete some node and everything is fine, but suddenly after another deletion the tree delete every nodes on the right side from root. It happens when the tree looks like this (the right side may be a bit different, but the height is correct):
after deleting the minim node (M) the tree has only nodes (S, R).
I think that it is because of my mistake in rotation function. Could you help me understand where is the mistake.
import random
from collections import Counter
class HuffmanCoding:
def __init__(self, data=None, space=False):
# Transform data to the form of dictionary
if data is None:
data = input("Enter string for coding: ")
self.data = Counter(data)
elif isinstance(data, str):
self.data = Counter(data)
elif isinstance(data, dict):
self.data = data
else:
raise TypeError("Type of data is incorrect!")
# Check whether to delete the space or not
if not space:
self.data.pop(' ', None)
self.my_tree = AVL_Tree()
self.root = None
for k, v in self.data.items():
self.root = self.my_tree.insert(self.root, TreeNode(k, v))
def sth(self):
n1 = self.my_tree.delete_min(self.root)
n2 = self.my_tree.delete_min(self.root)
self._create_new_internal_node(n1, n2)
def _create_new_internal_node(self, n1, n2):
new_node = HuffmanNode(n1, n2)
self.my_tree.insert(self.root, new_node)
class HuffmanNode:
def __init__(self, n1, n2):
self.character = n1.character + n2.character
self.freq = n1.freq + n2.freq
self.left = None
self.right = None
self.height = 1
class TreeNode:
def __init__(self, character, freq):
self.character = character
self.freq = freq
self.left = None
self.right = None
self.height = 1
class AVL_Tree:
def insert(self, root, n):
character = n.character
freq = n.freq
# Normal insert, like in BST
if not root:
return TreeNode(character, freq)
elif freq < root.freq:
root.left = self.insert(root.left, n)
else:
root.right = self.insert(root.right, n)
# Update the height of the ancestor node
root.height = 1 + max(self.get_height(root.left), self.get_height(root.right))
# Get the balance
balance = self.get_balance(root)
# Left left
if balance > 1 and freq < root.left.freq:
return self.right_rotate(root)
# Right right
if balance < -1 and freq > root.right.freq:
return self.left_rotate(root)
# Left right
if balance > 1 and freq > root.left.freq:
root.left = self.left_rotate(root.left)
return self.right_rotate(root)
# Right left
if balance < -1 and freq < root.right.freq:
root.right = self.right_rotate(root.right)
return self.left_rotate(root)
return root
def delete_min(self, root):
if not root:
return root
# Get parent of most left node
min_parent = self.get_parent_of_min_value_node(root)
min_node = min_parent.left
# Check if most left node has a right son
if min_parent.left.right is not None:
min_parent.left = min_parent.left.right
else:
min_parent.left = None
# Update the height
root.height = 1 + max(self.get_height(root.left), self.get_height(root.right))
balance = self.get_balance(root)
# Left left
if balance > 1 and min_parent.freq < root.left.freq:
self.right_rotate(root)
# Right right
if balance < -1 and min_parent.freq > root.right.freq:
self.left_rotate(root)
# Left right
if balance > 1 and min_parent.freq > root.left.freq:
root.left = self.left_rotate(root.left)
self.right_rotate(root)
# Right left
if balance < -1 and min_parent.freq < root.right.freq:
root.right = self.right_rotate(root.right)
self.left_rotate(root)
return min_node
def get_height(self, root):
if not root:
return 0
return root.height
def get_balance(self, root):
if not root:
return 0
return self.get_height(root.left) - self.get_height(root.right)
def right_rotate(self, z):
y = z.left
T3 = y.right
y.right = z
z.left = T3
z.height = 1 + max(self.get_height(z.left), self.get_height(z.right))
y.height = 1 + max(self.get_height(y.left), self.get_height(y.right))
return y
def left_rotate(self, z):
y = z.right
T2 = y.left
# Perform rotation
y.left = z
z.right = T2
# Update heights
z.height = 1 + max(self.get_height(z.left), self.get_height(z.right))
y.height = 1 + max(self.get_height(y.left), self.get_height(y.right))
# Return the new root
return y
def pre_order(self, root):
if not root:
return
print("C: {0}, F: {1}".format(root.character, root.freq))
self.pre_order(root.left)
self.pre_order(root.right)
def in_order(self, root):
if not root:
return
self.in_order(root.left)
print("C: {0}, F: {1}".format(root.character, root.freq))
self.in_order(root.right)
def post_order(self, root):
if not root:
return
self.post_order(root.left)
self.post_order(root.right)
print("C: {0}, F: {1}".format(root.character, root.freq))
def get_min_value_node(self, root):
if root is None or root.left is None:
return root
return self.get_min_value_node(root.left)
def get_parent_of_min_value_node(self, root):
if root.left is None or root.left.left is None:
return root
return self.get_parent_of_min_value_node(root.left)
if __name__ == "__main__":
huffman_coding = HuffmanCoding("Blogoslawieni milosierni")
huffman_coding.my_tree.in_order(huffman_coding.root)
print(huffman_coding.my_tree.delete_min(huffman_coding.root).character)
print(huffman_coding.my_tree.delete_min(huffman_coding.root).character)
print(huffman_coding.my_tree.delete_min(huffman_coding.root).character)
print(huffman_coding.my_tree.delete_min(huffman_coding.root).character)
huffman_coding.my_tree.in_order(huffman_coding.root)
print(huffman_coding.my_tree.delete_min(huffman_coding.root).character)
huffman_coding.my_tree.in_order(huffman_coding.root)
x = huffman_coding.root

Add a node specific counter to a slingly linked list

Did some research, but could only find examples where there was a key - say '5' and they count the occurrences of '5' in the linked list. I want to count each occurrence of each string in a llist. Say I have a linked list with ' a, a, a, b, d, f'. I want the output to say a - 3 b - 1 d -1 f -1.
I have built the list but the only way I can think of doing it is initializing a count variable, however I can't figure out how to reset it as I print the entire list after everything is done so right now my output looks like: a - 3 b -3 d -3 f -3.
Here is the code:
class Linked_List:
def __init__(self):
self.head = None
self.count = 0
def print(self):
p = self.head
while p is not None:
print(p.data, ' -', self.count)
p = p.next
def insert(self, x):
""""""
p = self.head
q = None
done = False
while not done:
if self.head == x:
done = True
elif p == None:
head = Linked_List_node(x)
q.next = head
done = True
elif x == p.data:
# head = Linked_List_node(x)
# self.head = head
self.count += 1
done = True
elif x < p.data:
if self.head == p:
head = Linked_List_node(x)
head.next = p
self.head = head
done = True
else:
head = Linked_List_node(x)
head.next = p
q.next = head
done = True
q = p
if p is not None:
p = p.next
class Linked_List_node:
def __init__(self, value):
self.data = value
self.next = None
Revised Code:
def print(self):
p = self.head
head = Linked_List_node(p.data)
while p is not None:
print(p.data, '-', self.count(p.data))
p = p.next
def count(self, x):
# loop thru list for all x, if find x add 1 to count. Assign final count to that word.
with open('cleaned_test.txt', 'r') as f:
for line in f:
for word in line.split():
if word == x:
self.count += 1
Since you want your count function to be able to count the frequencies of each word, I would create a function similar to print called count in class Linked_List, which iterates through the list, and updates the frequency dictionary.
def count(self):
dct = {}
p = self.head
while p is not None:
if p.data in dct:
dct[p.data] += 1
else:
dct[p.data] = 1
p = p.next
return dct
The output will look like.
head = Linked_List_node('a')
ll = Linked_List()
ll.head = head
for item in ['a', 'a', 'b', 'd', 'f']:
ll.insert(item)
print(ll.count())
#{'a': 3, 'b': 1, 'd': 1, 'f': 1}

Python - 'int' object is not callable

I'm writing a singly linked list that counts the number of words that get imported from a test file.
I initialized count inside of my class.
I defined the print function, that prints out each of the nodes, after they are sorted.
I defined a count class to iterate through the list and count up all the occurences of a word fed to it.
I want to pass in every node into count to count how many times it appears in my text file. When I try to do that I end up with 'int' object is not callable. Here is my code
class Linked_List:
def __init__(self):
self.head = None
self.count = 1
def print(self):
p = self.head
head = Linked_List_node(p.data)
while p is not None:
print(p.data, '-', self.count(p.data)) # This is where the error appears
p = p.next
def count(self, x):
# loop thru list for all x, if find x add 1 to count. Assign final count to that word.
with open('cleaned_test.txt', 'r') as f:
for line in f:
for word in line.split():
if word == x:
self.count += 1
def insert(self, x):
""""""
p = self.head
q = None
done = False
while not done:
if self.head == x:
done = True
elif p == None:
head = Linked_List_node(x)
q.next = head
done = True
elif x == p.data:
#head = Linked_List_node(x)
#head.counter += 1
done = True
elif x < p.data:
if self.head == p:
head = Linked_List_node(x)
head.next = p
self.head = head
done = True
else:
head = Linked_List_node(x)
head.next = p
q.next = head
done = True
q = p
if p is not None:
p = p.next
class Linked_List_node:
def __init__(self, value):
self.data = value
self.next = None
Relevant part from your code is:
class Linked_List:
def __init__(self):
# ...
self.count = 1
def count(self, x):
# ...
The self.count = 1 assignment overwrites the value of self.count for every Linked_List object that's created, so it refers to 1 instead of the method you defined on the class. Rename either the variable or the function.

rewriting Tree like function without recursive

class block(object):
def __init__(self, N):
self.N = N; self.l, self.r, self.u, self.d = [None]*4
def move_lower(self):
res = []
for x in (self.u, self.d, self.l, self.r):
if x != None and x.N < self.N:
res.append(x)
return res
def move_lower_chain(self, res = [], history = []):
temp = self.move_lower()
if len(temp) == 0:
res.append(history + [self.N])
else:
for x in temp:
x.move_lower_chain(res, history + [x.N])
return res
I tried to change the 'move_lower_chain' function to Non-recursive function, but i couldn't and even didn't know how to solve. most difficult part was below:
for x in temp:
x.move_lower_chain(res, history + [x.N])
Is there anyone who can help me?

Resources