Last number of iterator in python - python-3.x

How to edit the iterator giving also the last number in the sequence, please? I mean in general, not for such an easy sequence. Using < instead of == is not an option.
class P():
def __init__(self, n0):
self.n = n0
def __iter__(self):
return self
def __next__(self):
if self.n == 1:
raise StopIteration
num = self.n
self.n = self.n // 2 if self.n % 2 == 0 else 3 * self.n + 1
return num
nmax = 1000
PP = P(nmax)
PPP = []
for j in PP:
PPP.append(j)
print(PPP)
Current output:
[10, 5, 16, 8, 4, 2]
Desired output:
[10, 5, 16, 8, 4, 2, 1]

Use a local variable in your class to determin how many time you have get a next one:
class P():
i = 0
def __init__(self, n0):
self.i=n0-1
self.n = n0
def __iter__(self):
return self
def __next__(self):
self.i=self.i-1
if self.i == 1:
raise StopIteration
num = self.n
self.n = self.n // 2 if self.n % 2 == 0 else 3 * self.n + 1
return num
nmax = 10
PP = P(nmax)
PPP = []
for j in PP:
PPP.append(j)
print(PPP)
NOTE: Generally it is safer to write: if self.i <= 1: then if self.i == 1:. In some future change you might change the value of i, and start decrementing it with 2, adn then the == variant will fail.
EDIT: When you want to stop when the previous value equals to 1, you can do:
class P():
previous_value = 0
def __init__(self, n0):
self.i=n0-1
self.n = n0
def __iter__(self):
return self
def __next__(self):
if self.previous_value == 1:
raise StopIteration
num = self.n
self.n = self.n // 2 if self.n % 2 == 0 else 3 * self.n + 1
self.previous_value = num
return num
nmax = 20
PP = P(nmax)
PPP = []
for j in PP:
PPP.append(j)
print(PPP)

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)
`

I've tried running the code but it says list index is out of range

from typing import List
# You are given an integer n, denoting the no of people who needs to be seated, and a list of m integer seats, where 0 represents a vacant seat. Find whether all people can be seated, provided that no two people can sit together
When I run this code in geeks for geeks for submission I get a error that List index is out of range.
but seems to work fine when I run it as a script.
class Solution:
def is_possible_to_get_seats(self, n: int, m: int, seats: List[int]) -> bool:
vacant_seats = 0
if len(seats) == 2:
if seats[0] or seats[1] == 1:
print(seats)
return False
else:
print(seats)
return True
else:
for x in range(len(seats)):
if x == 0:
if seats[x] == 0 and seats[x+1] == 0:
seats[x] = 1
vacant_seats += 1
elif x == len(seats)-1:
if seats[x] == 0 and seats[x-1] == 0:
seats[x] = 1
vacant_seats += 1
else:
if seats[x] == 0:
if seats[x+1] == 0 and seats[x-1] == 0:
seats[x] = 1
vacant_seats += 1
if vacant_seats < n:
return False
else:
return True
# {
# Driver Code Starts
class IntArray:
def __init__(self) -> None:
pass
def Input(self, n):
arr = [int(i) for i in input().strip().split()] # array input
return arr
def Print(self, arr):
for i in arr:
print(i, end=" ")
print()
if __name__ == "__main__":
t = int(input())
for _ in range(t):
n = int(input())
m = int(input())
seats = IntArray().Input(m)
obj = Solution()
res = obj.is_possible_to_get_seats(n, m, seats)
result_val = "Yes" if res else "No"
print(result_val)
# } Driver Code Ends

I want find the value of 'e' with Monte Carlo Simulation in Python, I am getting NameError

#Finding the value of 'e' with MonteCarlo Simulation
import random
class FindE:
def __init__(self):
self.s = 0
self.N = 1000000
def random_points(self):
for i in range(1,100000):
x = random.uniform(0, 1)
self.s += x
if self.s > 1.0:
return i
def exceed_dict(self, N):
d = dict()
for _ in range(N):
count = random_points()
if count not in d:
d[count] = 0
d[count] += 1
return d
def calculating_e(self):
d = exceed_dict(N)
print(sum([k*v for k, v in d.items()]) / N)
e = FindE()
print(e.calculating_e())
Your are trying to call variable and methods inside a python class.
Don't forget to use self. before call it.
it should be like this :
import random
class FindE:
def __init__(self):
self.s = 0
self.N = 1000000
def random_points(self):
for i in range(1,100000):
x = random.uniform(0, 1)
self.s += x
if self.s > 1.0:
return i
def exceed_dict(self, N):
d = dict()
for _ in range(N):
count = self.random_points()
if count not in d:
d[count] = 0
d[count] += 1
return d
def calculating_e(self):
d = self.exceed_dict(self.N)
print(sum([k*v for k, v in d.items()]) / self.N)
e = FindE()
print(e.calculating_e())

Return value fail

I am working on a doubly linked list and I am having trouble getting returning the value I remove an item from the middle of the list. I am not really sure why and would appreciate the a second pair of eyes look this through.
If I append three numbers and then remove the number at index 1, it should return the value at index 1.
class Linked_List:
class __Node:
def __init__(self, val):
self.val = val
self.next = None
self.prev = None
return
def __init__(self):
self.__header = self.__Node(None)
self.__trailer = self.__Node(None)
self.__header.next = self.__trailer
self.__trailer.prev = self.__header
self.__size = 0
def __len__(self):
return self.__size
def remove_element_at(self, index):
if index > self.__size or index < 0 or index == self.__size:
raise IndexError
cur = self.__header.next
element_to_return = cur
if index == 0:
self.__header.next = self.__header.next.next
else:
for i in range(0, index):
cur = cur.next
element_to_return = cur.val
cur.next = cur.next.next
self.__size -= 1
return str(element_to_return.val)
I added the addValue() and a debug() method (tip: read How to debug small programs (#1) ).
I modified the start/end node to have a value for clarity. I reduced/restructured (rewrote) your the remove method - it had some unneeded overhead and pointer errors. For double linked lists you have to take care of both the folloing and preceeding element and change all the pointers correctly to keep the integrity of the chain.
class Linked_List:
class __Node:
def __init__(self, val):
self.val = val
self.next = None
self.prev = None
return
def __init__(self):
self.__header = self.__Node('Start') # start node
self.__trailer = self.__Node('End') # end node
self.__header.next = self.__trailer
self.__trailer.prev = self.__header
self.__size = 0
def debug(self):
cur = self.__header
print("prev.val cur.val next.val")
i = 0
while cur:
print(" " * i, f'{cur.prev.val if cur.prev else None} {cur.val} {cur.next.val if cur.next else None}')
i+=1
cur = cur.next
def addValue(self, val):
"""Adds the str of val at the end."""
n = self.__Node(str(val))
n.next = self.__trailer
n.prev = self.__trailer.prev
self.__trailer.prev.next = n
self.__trailer.prev = n
self.__size += 1
def remove_element_at(self, index):
if not (0 <= index < self.__size ): # simplified
# better message on error
raise IndexError (f'Index {index} out of bounds [0,{self.__size-1}]')
cur = self.__header.next # simplified, element_to_return not needed
# there is no need for special cases for 0 or size - this will handle all
for i in range(0, index):
cur = cur.next # go ever deeper, if we are at 0 or self.__size not entering
cur.prev.next = cur.next # repointer prev's next to our next
cur.next.prev = cur.prev # repointer next's prev to our prev
self.__size -= 1 # decrease size
return str(cur.val) # return our value
k = Linked_List()
for n in range(5):
k.addValue(n)
k.debug()
removed = k.remove_element_at(4)
k.debug()
print(f'removed: {removed}')
Output:
prev.val cur.val next.val
None Start 0
Start 0 1
0 1 2
1 2 3
2 3 4
3 4 End
4 End None
None Start 0
Start 0 1
0 1 2
1 2 3
2 3 End
3 End None
removed: 4
Edit:
My add method is self-build. Make sure youres gets the pointers correctly - use the debug method to assure that cur.prev.next points to cur and cur.next.prev is cur as well.

Heap Structure with Key Function in initalizer

I'm basically trying to implement this Heap Structure in Python and I've editing the portions under def heap-iffy and def add but I'm not sure how to how to use the current initialize with a key function. This function will be used to extract a value from each element added to the heap; these values, in turn, will be used to order the elements. f no key function is provided, the default max-heap behavior should be used — the "lambda x:x" default value for the initialize method does just that.
class Heap:
def __init__(self, key=lambda x:x):
self.data = []
self.key = key
#staticmethod
def _parent(idx):
return (idx-1)//2
#staticmethod
def _left(idx):
return idx*2+1
#staticmethod
def _right(idx):
return idx*2+2
def _heapify(self, idx=0):
enter code here
while True:
l = Heap._left(idx)
r = Heap._right(idx)
maxidx = idx
if l < len(self) and self.data[l] > self.data[idx]:
maxidx = l
if r < len(self) and self.data[r] > self.data[maxidx]:
maxidx = r
if maxidx != idx:
self.data[idx], self.data[maxidx] = self.data[maxidx], self.data[idx]
idx = maxidx
else:
break
def add(self, x):
enter code here
self.data.append(x)
i = len(self.data) - 1
p = Heap._parent(i)
while i > 0 and self.data[p] < self.data[i]:
self.data[p], self.data[i] = self.data[i], self.data[p]
i = p
p = Heap._parent(i)
def peek(self):
return self.data[0]
def pop(self):
ret = self.data[0]
self.data[0] = self.data[len(self.data)-1]
del self.data[len(self.data)-1]
self._heapify()
return ret
def __bool__(self):
return len(self.data) > 0
def __len__(self):
return len(self.data)
def __repr__(self):
return repr(self.data)

Resources