text stringlengths 37 1.41M |
|---|
# ============================
# Lowest Common Ancestor in BST
# ============================
from BST import *
def findResult (root,a,b):
if root.value > a and root.value < b:
return root
elif root.value <a and root.value < b:
findResult(root.right,a,b)
elif root.value >a and root.value > b:
findResult(root.left,a,b)
else:
return None
print(findResult(root,1,6).value) |
from BST import *
def findMin(root):
'''
Iterates to left most node and returns it's value!
'''
if root is not None:
tmp = root
while(tmp.left!=None):
tmp= tmp.left
return tmp.value
def findMax(root):
'''
Iterates to right most node and returns it's value!
'''
if root is not None:
tmp = root
while(tmp.right!=None):
tmp = tmp.right
return tmp.value
def findHeight(root):
'''
The idea is to find iterate to last node recursively to each side and returns maximum value + 1
A height = max(0,0)+1 => 1
/ \
B C height = max(-1,-1)+1 => 0
'''
if root is None:
return -1
leftHeight = findHeight(root.left)
rightHeight = findHeight(root.right)
return max(leftHeight,rightHeight)+1
def findDepth(root,value,depth=0):
'''
Irritating to all levels with depth = 0 to the target and incrementing depth on each passed level , till we reach target and retun value of depth.
Make point: We're irritating left or right based on current root's value and target value
Target = D
A A> D ,depth = 0
// \
B C B> D , depth = 1
// \
D E Fount D , depth =2
'''
tmp=depth
if root is None:
print("Value not found")
if root.value == value:
print("Depth is",tmp)
elif root.value > value:
tmp+=1
findDepth(root.left,value,depth=tmp)
else:
tmp+=1
findDepth(root.right,value,depth=tmp)
def BFS(root):
'''
BFS => Breath First Search, The concept is that it goes to each level and irritate all nodes on that level, QUEUE is used for that
'''
queue = []
queue.append(root)
while len(queue)!=0:
tmp1 = queue.pop(0)
print(tmp1.value ,end = " ")
if tmp1.left is not None:
queue.append(tmp1.left)
if tmp1.right is not None:
queue.append(tmp1.right)
def DFS(root):
'''
DFS => Depth First Search, we irritate deep first till very end,STACK is used,=.
'''
stack = []
stack.append(root)
while len(stack)!=0:
tmp1 = stack.pop()
print(tmp1.value, end= " ")
if tmp1.right is not None:
stack.append(tmp1.right)
if tmp1.left is not None:
stack.append(tmp1.left)
def isBinarySearchTree(root):
flag = True
if root is not None:
if root.left is not None:
flag = isBinarySearchTree(root.left) if(root.value > root.left.value) else False
if root.right is not None:
flag = isBinarySearchTree(root.left) if (root.value < root.right.value) else False
return flag
def DeleteNode(root, value):
if root is None:
return root
if value < root.value:
root.left = DeleteNode(root.left, value)
elif(value > root.value):
root.right = DeleteNode(root.right, value)
else:
if root.left is None :
temp = root.right
root = None
return temp
elif root.right is None :
temp = root.left
root = None
return temp
temp = findMin(root.right)
root.value = temp.value
root.right = DeleteNode(root.right , temp.value)
return root
root = Node(4)
insert(root,3)
insert(root,5)
insert(root,6)
insert(root,1)
insert(root,10)
root = DeleteNode(root,10)
inorder(root)
# print(findMin(root))
# print(findMax(root))
# print(findHeight(root))
# findDepth(root=root,value=3)
# DFS(root)
# print(isBinarySearchTree(root)) |
x=int(input("enter x"))
y=int(input("enter y"))
if(x>y):
print("x",x,"is greater than y",y)
else:
print("y",y,"is greater than x",y)
|
class User:
def __init__(self, username, password, is_admin):
self.__username = username
self.__password = hash(password)
self.__is_admin = is_admin
self.__roles = set()
def check_password(self, password):
return self.__password == hash(password)
def add_role(self, role_name):
self.__roles.add(role_name)
def remove_role(self, role_name):
self.__roles.discard(role_name)
def get_roles(self):
return self.__roles
def get_username(self):
return self.__username
def is_admin(self):
return self.__is_admin
class UsersManager:
def __init__(self):
self.__users = {}
def username_exists(self, username):
return username in self.__users
def __add_user(self, user):
self.__users[user.get_username()] = user
def register_user(self, username, password, is_admin=False):
if self.username_exists(username):
return False, "username already exist"
user = User(username, password, is_admin)
self.__add_user(user)
return True, "user registered sucessfully"
def get_user(self, username):
return self.__users.get(username, None)
def get_users(self):
return self.__users
def verify_username_password(self, username, password):
if self.username_exists(username):
user = self.get_user(username)
return (True, "Login Successful") if user.check_password(
password) else (False, "Incorrect Password")
return False, "UserName not found"
|
from datatracker import *
class DataPrinter():
'''Prints a DataTracker's data.
Takes a structure containing strings representing data from a DataTracker
(specificaly, the output of DataTracker.get_strings()) and produces a readable
string output.
'''
def __init__(self, name, strings, line_width=60):
'''A helper object for printing a DataTracker.
Args:
name (str): The name of the DataTracker instance.
strings (custom structure): The output of DataTracker.get_strings().
line_width (int, optional): The width of any line.
'''
self.name = name
self.strings = strings
self.line_width = line_width
def print(self):
'''Returns a string representing an entire DataTracker.'''
s = self._make_header()
for i in range(0, len(self.strings)):
s += self.print_entry(i)
return s
def _make_header(self):
title = "Data for " + self.name
padding = ' '
line_width = len(title) + 2 * len(padding) + len('||||||||')
header = (line_width - 2) * '=' + '||\n' + \
'||' + (line_width - 6) * '=' + '||||\n' + \
'||||' + padding + title + padding + '||||\n' + \
'||||' + (line_width - 6) * '=' + '||\n' + \
'||' + (line_width - 2) * '=' + '\n' + \
'\n'
return header
def print_entry(self, i):
'''Returns a string representing a single entry.'''
if i < 0 or i >= len(self.strings):
raise IndexError("Split index must be nonnegative and less than the number of splits.")
s = DataPrinter._make_entry_header(self.strings[i]['name'])
s += self._print_characters(i) + '\n'
s += self._print_zenny(i) + '\n'
s += self._print_skill_ink(i) + '\n'
s += self._print_weapon(i)
return s + '\n\n'
def _make_entry_header(s):
s = s + '\n' + '-' * len(s)
return s + '\n'
#
#
# Character and Weapon printing.
def _print_characters(self, i):
s = ''
w = 0
strings = self.strings[i]['party_levels']
for c in strings['total']:
suf = c.name + ': ' + strings['total'][c]
v = strings['gain'][c]
if int(v) > 0: suf = suf + ' (+' + v + ')'
s, w = self._add_to_lined_string(s, w, suf)
return s + '\n'
def _print_weapon(self, i):
s = 'Weapon:\n'
w = 0
strings_dict = self.strings[i]
amts = strings_dict['weapons']['total']
reqs = strings_dict['weapon_requirements']
printed = False
for c in list(Weapon):
if int(amts[c]) >= int(reqs[c]):
continue
suf = c.name + ': ' + amts[c] + '/' + reqs[c]
s, w = self._add_to_lined_string(s, w, suf)
printed = True
if not printed:
s += 'Completed!'
return s + '\n'
def _add_to_lined_string(self, s, used, suf):
suf_with_space = ' ' * 5 + suf
w = used + len(suf_with_space)
if used == 0:
s += suf
w = len(suf)
elif w <= self.line_width:
s += suf_with_space
else:
s += '\n' + suf
w = len(suf)
return s, w
#
#
# Zenny and SkillInk printing
def _print_zenny(self, i):
return self._print_enum(i, Zenny)
def _print_skill_ink(self, i):
return self._print_enum(i, SkillInk)
def _print_enum(self, i, enum):
if enum == Zenny:
s, key = 'Zenny:\n', 'zenny'
elif enum == SkillInk:
s, key = 'Skill Ink:\n', 'skill_ink'
else:
raise ValueError("enum must be Zenny or SkillInk")
strings = self.strings[i][key]
val1s, val2s, max_val2_length = self._pre_process(strings, enum)
for att in list(enum):
s += self._print_line(att.name, val1s[att], val2s[att], max_val2_length)
return s
def _pre_process(self, strings, enum):
max_val2_length = 0
val1s, val2s = dict(), dict()
for att in list(enum):
v1, v2 = '', ''
if att == enum.CURRENT:
v1 = strings['total'][att]
v2 = strings['gain'][att]
if int(v2) >= 0: v2 = '+' + v2
v2 = ' (' + v2 + ')'
else:
v1 = strings['gain'][att]
v2 = strings['total'][att]
v2 = ' (/' + v2 + ')'
val1s[att], val2s[att] = v1, v2
if len(v2) > max_val2_length: max_val2_length = len(v2)
return val1s, val2s, max_val2_length
def _print_line(self, name, val1, val2, max_val2_length):
title = name + ':'
val2 = (max_val2_length - len(val2)) * ' ' + val2
dots = (self.line_width - len(name) - len(val1) - len(val2)) * '.'
return name + dots + val1 + val2 + '\n'
|
import concurrent.futures
import time
start = time.perf_counter()
def do_something(seconds):
print(f'Sleeping {seconds} seconds(s)...\n')
time.sleep(seconds)
return 'Done Sleeping...'+str(seconds)
#Using concurrent.futures I can create a pool of threads
with concurrent.futures.ThreadPoolExecutor() as executor:
secs=[5,4,1,2,4,7]
results=[executor.submit(do_something,sec) for sec in secs]
for f in concurrent.futures.as_completed(results):
print(f.result())
#using map would be:
#results = executor.map(do_something, secs)
#for result in results:
# print(result)
finish= time.perf_counter()
print(f'Finished in {round(finish-start,2)}seconds(s)')
|
def ispalindrome(word):
#Eliminates spaces
wordNoBlanks=''
for letter in word:
if letter == ' ':
continue
wordNoBlanks+=letter
#Reverse Word
wordlist=list(wordNoBlanks)
wordlist.reverse()
word2="".join(wordlist)
#Compare words
if wordNoBlanks==word2:
return True
else:
return False
if ispalindrome('anita lava la tina') is True:
print('Es palindromo')
else:
print('No es palindromo')
|
#! /usr/bin/env python
def generate(arr, i, s, length,filename):
if (i == 0):
f = open(filename + ".txt", "a")
f.write(s+"\n")
f.close()
return
for j in range(0, length):
appended = s + arr[j]
generate(arr, i - 1, appended, length,filename)
return
def Range(arr, len):
for i in range(1, len + 1):
generate(arr, i, "", len)
def load(option):
lower_case = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
upper_case = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
SYMBOLS = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>', '*', '(', ')', '<']
length = int(input("Enter lenght :"))
filename = str(raw_input("Enter file name to be saved \n"))
if option == 1:
generate(lower_case, length, "", 26,str(filename) )
if option == 2:
generate(upper_case, length, "", 26,filename )
if option == 3:
generate(DIGITS, length, "", 10,filename)
if option == 4:
generate(SYMBOLS, length, "", 16,filename)
if option == 5:
generate(lower_case+upper_case, length, "", 52,filename)
if option == 6:
generate(lower_case+DIGITS, length, "", 36,filename )
if option == 7:
generate(lower_case+SYMBOLS, length, "", 42,filename )
if option == 8:
generate(upper_case+DIGITS, length, "", 36,filename )
if option == 9:
generate(upper_case+SYMBOLS, length, "", 42,filename)
if option == 10:
generate(DIGITS+SYMBOLS, length, "", 26,filename)
if option == 11:
generate(upper_case+SYMBOLS+lower_case, length, "", 68,filename)
if option == 12:
generate(upper_case+DIGITS+lower_case, length, "", 62,filename)
if option == 13:
generate(upper_case+SYMBOLS+DIGITS+lower_case, length, "", 78,filename)
def main():
print('''1 - Lower Case \n2- Upper Case \n3- Digits \n4- Symbols \n5- Lower + Upper \n6- Lower + Digits \n7- Lower + Symbols \n8- Upper + Digits \n9- Upper + Symbols\n10- Digits + Symbols\n11- Upper + Lower + Symbols\n12- Upper + Lower + Digits\n13- Upper + Lower + Digits + Symbols
''')
option = input("Enter Option :")
load(option)
main()
print("[+] Done Successfully")
|
class Table(object):
# t = Table(1,2,3)
# vars(t)
def __init__(self, l, w, h):
print "Init"
self.l = l
self.w = w
self.h = h
# Static variable
# class A(object):
# a = 1
#
# def __init__(self):
# A.a += 1
# print A.a
#
# def f(self):
# print "Class A"
#
#
# a = A()
# b = A()
class B(object):
__slots__ = ('x')
def __init__(self, x):
self.x = x
print "Class B"
a = A()
a.f()
b = B()
# Polymorphism , magic methods
class Cat():
def say(self):
print 'Meow'
def __repr__(self):
return 'I`m a Cat'
def __str__(self):
return 'String representation'
@staticmethod
@classmethod
class A(object):
def __init__(self):
self.a = 42
# def __setattr__(self, name, value):
# if hasattr(self,'a') and name == 'a':
# raise AttributeError('a is read-only')
# print "Set {} = {}".format(name, value)
# super(A, self).__setattr__(name, value)
def __delattr__(self, name):
if name == 'a':
raise AttributeError('a is read-only')
super(A, self).__delattr__(name)
def __getattribute__(self, name):
print "Get attribute " + name
return super(A, self).__getattribute__(name)
def __getattr__(self, name):
print "Get attr" + name
return 44
class Mock(object):
def __getattr__(self, item):
return lambda x: x * x
#
# import whois
# domain = whois.query('google.com')
#
# print(domain.__dict__)
#
# print(domain.name)
#
#
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return "Person({}, {})".format(self.name, self.age)
def __eq__(self, other):
return self.name == other.name and self.age == other.age
def __lt__(self, other):
return self.age < other.age
l = [Person('Bob', 32), Person('John', 43), Person('Bill', 23)]
l.sort()
class ReprMixin(object):
def __repr__(self):
return '{}({})'.format(
self.__class__.__name__,
', '.join(['{}={}'.format(k, v) for k, v in self.__dict__.items()])
)
class EqMixin(object):
def __eq__(self, other):
if not isinstance(other, Person):
return NotImplemented
return self.__dict__ == other.__dict__
# mro
class Person(ReprMixin, EqMixin):
def __init__(self, name, age):
self.name, self.age = name, age
def __getstate__(self):
return {
'name': self.name,
'age': self.age
}
def __setstate__(self, state):
self.__init__(**state)
# >>> Person('John', 10)
# Person(age=10, name=John)
# >>> Person('John', 10) == Person('John', 10)
# True
# >>> Person('John', 10) == Person('John', 11)
# False
# whois UA https://hostmaster.ua/whois.php?domain=lifecell.ua
# to parse all parameters in to dict "<td.*>(?<a>.*)<\/td><td>(?<b>.*)<\/td>"
import re
import urllib2
def get_whois(url):
url = 'https://hostmaster.ua/whois.php?domain=' + url
request = urllib2.Request(url)
response = urllib2.urlopen(request)
html_page = response.read()
r = re.findall(r'<td.*>(.*)<\/td><td>(.*)<\/td>', html_page)
print r
for i in r:
print i[0] + ':' + i[1]
get_whois('lifecell.ua')
class MyList(object):
def __init__(self, l=[]):
self._l = l[:]
def __repr__(self):
return repr(self._l)
def __len__(self):
return len(self._l)
def __contains__(self, item):
return item in self._l
def add(self, value):
self._l.append(value)
def __setitem__(self, key, value):
self._l[key] = value
def __getitem__(self, item):
if isinstance(item, int):
return self._l[item]
elif isinstance(item, tuple):
return [self._l[x] for x in item if 0 <= x < len(self._l) - 1]
elif item == Ellipsis:
return self._l[:]
# def __iter__(self):
# return MyListIterator(self._l)
def __iter__(self):
# returns generator object
for i in self._l:
yield i
class MyListIterator(object):
def __init__(self, l):
self._l = l[:]
self.i = 0
def __iter__(self):
return self
def next(self):
if self.i == len(self._l):
raise StopIteration
self.i += 1
return self._l[self.i - 1]
def f():
print 'a'
import dis
dis.dis(f)
#
# async - coroutine
# await - yield
# lazy calculations
def f(x, y):
if x:
return 2 * x * y
# f (x, g(a,b)) if g(a,b) = > generator
def inf_list():
i = 0
while True:
yield i
i += 1
for i in inf_list():
if i * i > 1000:
break
print i
g = xrange(10)
i = iter(g)
i.next()
import itertools
print list(itertools.takewhile(lambda i: i * i <= 100, itertools.count()))
permutations = itertools.permutations('ABC', 2)
print list(permutations)
[x * x for x in range(10)] # list comprehensions
(x * x for x in range(10)) # generator
# twsited acsync lib
# aiohttp
# coroutine
def coroutine(f):
g = f()
g.next()
return g
@coroutine
def f():
i = yield
print 'f,', i
i = yield i + 1
print 'f,', i
i = yield i + 1
print 'f,', i
i = yield i + 1
def main():
i = f.send(0)
print 'main, ', i
i = f.send(i + 1)
print 'main, ', i
i = f.send(i + 1)
print 'main, ', i
# Constructor / singleton
class A(object):
def __new__(cls, *args, **kwargs):
print "NEW"
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls, *args)
return cls._instance
# return super(A, cls).__new__(cls, *args, **kwargs)
def __init__(self):
print 'init'
class Line(object):
def __init__(self):
self._l = 0
@property
def l(self):
return self._l * 10
@l.setter
def l(self, value):
self._l = value / 10
# Metaclasses
A = type('A', (object,), {'a': 1})
class A(object):
a = 1
class Meta(type):
def __new__(cls, name, parents, attrs):
new_attrs = {name: value
for name, value in attrs.items()
if not name.startswith('unused')}
return type.__new__(cls, name, parents, new_attrs)
class A(object):
__metaclass__ = Meta
a = 1
unused_a = 1
import abc
class Base(object):
__metaclass__ = abc.ABCMeta
def f(self):
print 'Base.f'
@abc.abstractmethod
def g(self):
pass
class Child(Base):
def g(self):
pass
|
"""Implementation of Binary Search Tree."""
from collections import deque
import random
import time
import io
class Node(object):
"""Binary Search Tree."""
def __init__(self, val=None, left=None, right=None, parent=None):
"""Initialize BST."""
self.val = val
self.left = left
self.right = right
self.parent = parent
@property
def left(self):
"""Left property."""
return self._left
@left.setter
def left(self, new_node):
self._left = new_node
if new_node is not None:
new_node.parent = self
@property
def right(self):
"""Right property."""
return self._right
@right.setter
def right(self, new_node):
self._right = new_node
if new_node is not None:
new_node.parent = self
def depth(self):
"""Return depth of the tree."""
if not self.val:
return 0
elif not self.left and not self.right:
return 1
else:
left_depth = self.left.depth() if self.left else 0
right_depth = self.right.depth() if self.right else 0
return max(left_depth, right_depth) + 1
def in_order(self):
"""Yield items by in-order traversal."""
if self.left:
for item in self.left.in_order():
yield item
yield self.val
if self.right:
for item in self.right.in_order():
yield item
def pre_order(self):
"""Yield items by pre-order traversal."""
yield self.val
if self.left:
for item in self.left.pre_order():
yield item
if self.right:
for item in self.right.pre_order():
yield item
def post_order(self):
"""Yeild items by post-ordre traversal."""
if self.left:
for item in self.left.post_order():
yield item
if self.right:
for item in self.right.post_order():
yield item
yield self.val
def check_balance(self):
"""Get balance of current node."""
counter = 0
current = self
while current.left:
counter += 1
current = current.left
current = self
while current.right:
counter -= 1
current = current.right
return counter
# Dot graph stuff
def _get_dot(self):
"""Recursively prepare a dot graph entry for this node."""
if self.left is not None:
yield "\t%s -> %s;" % (self.val, self.left.val)
for i in self.left._get_dot():
yield i
elif self.right is not None:
r = random.randint(0, 1e9)
yield "\tnull%s [shape=point];" % r
yield "\t%s -> null%s;" % (self.val, r)
if self.right is not None:
yield "\t%s -> %s;" % (self.val, self.right.val)
for i in self.right._get_dot():
yield i
elif self.left is not None:
r = random.randint(0, 1e9)
yield "\tnull%s [shape=point];" % r
yield "\t%s -> null%s;" % (self.val, r)
class Bst(object):
"""Binary Search Tree."""
def __init__(self, root=None):
"""Init BST."""
self.root = root
self.size = 0
def tree_climb(self, node):
"""Climb the tree based on parents."""
current = node
while True:
if current.check_balance() >= 2:
self.rotate_right(current)
elif current.check_balance() <= -2:
print('rotate left')
else:
print('balanced')
if current == self.root:
break
else:
current = current.parent
def rotate_right(self, node):
"""Rotate unbalanced node to right side of left child."""
if not node.left.left:
self.straighten_for_rotate_right(node)
if self.root == node:
node.left.right = node
self.root = node.left
else:
node.parent.left = node.left
node.left.right = node
def straighten_for_rotate_right(self, node):
"""Prepare nodes to be rotated right."""
node.left.right.parent = node
node.left.parent = node.left.right
def insert(self, val):
"""Insert into tree."""
try:
int(val)
except ValueError:
print('Please type in a number')
return
node = Node(val)
if self.root is None:
self.root = node
self.size += 1
else:
current = self.root
while True:
if current.val == val:
break
elif val < current.val:
if current.left:
current = current.left
else:
current.left = node
self.tree_climb(node)
self.size += 1
break
else:
if current.right:
current = current.right
else:
current.right = node
self.tree_climb(node)
self.size += 1
break
def contains(self, val):
"""Return if node is contained in bst."""
if not self.root:
return False
current = self.root
while True:
if current.val == val:
return True
elif val < current.val:
if current.left:
current = current.left
else:
return False
else:
if current.right:
current = current.right
else:
return False
def _search(self, val):
"""Return node for delete."""
if not self.root:
return None
elif val == self.root.val:
return self.root
else:
current = self.root
while True:
if current.val == val:
return current
elif val < current.val:
if current.left:
current = current.left
else:
break
else:
if current.right:
current = current.right
else:
break
return None
def tree_size(self):
"""Return size of list."""
return self.size
def depth(self):
"""Return the number of levels in the tree."""
return self.root.depth()
def balance(self):
"""Return how balanced the tree is."""
if not self.root:
return None
counter = 0
current = self.root
while current.left:
counter += 1
current = current.left
current = self.root
while current.right:
counter -= 1
current = current.right
return counter
def in_order(self):
"""Yield items by in-order traversal."""
if not self.root:
return
for item in self.root.in_order():
yield item
def pre_order(self):
"""Yield items by pre-order traversal."""
if not self.root:
return
for item in self.root.pre_order():
yield item
def post_order(self):
"""Yield items by post-order traversal."""
if not self.root:
return
for item in self.root.post_order():
yield item
def breadth_first(self):
"""Yield items by breadth-first traversal."""
if not self.root:
return
queue = deque([self.root])
while queue:
current = queue.pop()
yield current.val
if current.left:
queue.appendleft(current.left)
if current.right:
queue.appendleft(current.right)
def _delete_leaf(self, node):
if self.root == node:
self.root = None
return
parent_node = node.parent
if parent_node.left == node:
parent_node.left = None
else:
parent_node.right = None
def _delete_one_descendant(self, node):
parent = node.parent
if parent.left == node and node.right:
parent.left = node.right
elif parent.left == node and node.left:
parent.left = node.left
elif parent.right == node and node.right:
parent.right = node.right
elif parent.right == node and node.left:
parent.right = node.left
def _multiple_children_delete(self, node):
parent = node.parent
if parent.left == node:
target = node.right
if target.left:
while target.left:
target = target.left
node.val = target.val
target.parent = None
else:
node.val = target.val
node.right = target.right
target.parent = None
else:
target = node.left
if target.right:
while target.right:
target = target.right
node.val = target.val
target.parent = None
else:
node.val = target.val
node.left = target.left
target.parent = None
def delete(self, val):
"""Delete a node from tree."""
if not self.root:
return None
to_delete = self._search(val)
if not to_delete:
return None
elif not to_delete.right and not to_delete.left:
self._delete_leaf(to_delete)
elif not to_delete.right or not to_delete.left:
self._delete_one_descendant(to_delete)
else:
self._multiple_children_delete(to_delete)
self.size -= 1
def get_dot(self):
"""Return the tree with root 'self' as a dot graph for visualization."""
return "digraph G{\n%s}" % ("" if self.root.val is None else (
"\t%s;\n%s\n" % (
self.root.val,
"\n".join(self.root._get_dot())
)
))
if __name__ == "__main__":
import subprocess
vals = random.sample(range(1000), 100)
bst = Bst()
# for val in vals:
# bst.insert(val)
bst.insert(4)
bst.insert(5)
bst.insert(2)
bst.insert(1)
# random_val = random.choice(vals)
# times = []
# for i in range(1000):
# start = time.time()
# bst.contains(random_val)
# time_passed = time.time() - start
# times.append((time_passed, random_val))
# times.sort()
# print("Fastest search: {} seconds for {}".format(times[0][0], times[0][-1]))
# print("Slowest search: {} seconds for {}".format(times[-1][0], times[-1][-1]))
g = bst.get_dot()
g = g.encode('utf-8')
sub = subprocess.Popen(['dot', '-Tpng'], stdin=subprocess.PIPE)
sub.communicate(g)
# bst.breadth_first()
|
# -*- coding: utf-8 -*-
"""Module to test parenthetics of string input."""
import sys
def parenthetics(input_str):
"""Method to test for unmatched parenthesis."""
counter = 0
for i in input_str:
if i is ')':
counter -= 1
elif i is '(':
counter += 1
if counter < 0:
break
if counter > 0:
counter = 1
print(counter)
return counter
if __name__ == '__main__':
parenthetics(sys.argv[1])
|
# _*_ coding:utf-8 _*_
"""A module to create a queue data structure."""
from Node import Node
class Queue(object):
"""Queue data structure object creator."""
def __init__(self, head=None, tail=None):
"""Queue object constructor."""
self.head = head
self.tail = tail
self.length = 0
def enqueue(self, data):
"""Enqueue method for Queue object."""
self.head = Node(data, self.head)
if self.tail is None:
self.tail = self.head
else:
self.head.next_node.prev_node = self.head
self.length += 1
def dequeue(self):
"""Dequeue method for Queue object."""
old_tail = self.tail
self.tail = self.tail.prev_node
self.length -= 1
return old_tail.data
def peek(self):
"""Peek method for Queue object."""
try:
return self.tail.prev_node.data
except AttributeError:
return None
def size(self):
"""Size method for Queue object."""
return self.length
|
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 29 18:15:34 2019
@author: CEC
"""
def isPrime(num):
if num <= 1:
return False
for i in range (2,num):
print(num, i, num%i)
if (num%i == 0):
return False
return True
while True:
x = input("Ingrese un número: ")
if(x=='Q' or x == 'q'):
break
x=int(x)
if (isPrime(x)):
print("El número ", x, "es primo")
else:
print("El número ", x, "no es primo") |
def bigger(a,b):
if a>b:
return a
else:
return b
def biggest(a,b,c):
return bigger(a,b,c)
def median:(a,b,c):
big - biggest(a,b,c)
if big == a:
return bigger(b,c)
if big == b:
return bigger(a,c)
else:
return bigger(a,b)
def lesser(a,b):
if a<b:
return a
else:
return b
def least(a,b,c):
return lesser(a,lesser(b,c))
def set_range(a,b,c):
return biggest(a,b,c) - least(a,b,d)
|
# coding: utf-8
# 一.已经字符串
# s = "i,am,lilei", 请用两种办法取出之间的“am”字符。
s = "i,am,lilei"
print s.split(',')[1]
print s[2:4]
#
# 二.在python中,如何修改字符串?
#
# 三.bool("2012" == 2012)
# 的结果是什么。False
print bool("2012" == 2012)
#
# 四.已知一个文件
# test.txt,内容如下:
#
# ____________
# 2012
# 来了。
# 2012
# 不是世界末日。
# 2012
# 欢乐多。
# _____________
#
# 1.
# 请输出其内容。
fileName = 'test.txt'
txt = open(fileName, 'r')
content = txt.read()
txt.close()
print content
# 2.
# 请计算该文本的原始长度。
print len(content.decode('utf-8'))
# 3.
# 请去除该文本的换行。
contentWithoutReturn = content.replace('\n', '')
print contentWithoutReturn
# 4.
# 请替换其中的字符
# "2012"
# 为
# "2013"。
print contentWithoutReturn.replace('2012', '2013')
# 5.
# 请取出最中间的长度为5的子串。
print '------------------------di5'
decodeContent = contentWithoutReturn.decode('utf-8')
print decodeContent[len(decodeContent)/2:len(decodeContent)/2+5].encode('utf-8')
print '------------------------end'
# 6.
# 请取出最后2个字符。
contentWithoutReturn += '12'
print contentWithoutReturn[-2:]
# 7.
# 请从字符串的最初开始,截断该字符串,使其长度为11.
print contentWithoutReturn[:11]
# 8.
# 请将
# {4}
# 中的字符串保存为test1.py文本.
newFileName = 'test1.py'
o = open(newFileName, 'w')
o.write(contentWithoutReturn.replace('2012', '2013'))
o.close()
#
# 五.请用代码的形式描述python的引用机制。
#
# 六.已知如下代码
#
# ________
#
a = "中文编程"
b = a
c = a
a = "python编程"
# b = u'%s' % a
d = "中文编程"
e = a
c = b
b2 = a.replace("中", "中")
# ________
#
# 1.
# 请给出str对象
# "中文编程"
# 的引用计数
import sys
print sys.getrefcount(a)
# 2.
# 请给出str对象
# "python编程"
# 的引用计数
#
# 七.已知如下变量
# ________
a = "字符串拼接1"
b = "字符串拼接2"
# ________
#
# 1.
# 请用四种以上的方式将a与b拼接成字符串c。并指出每一种方法的优劣。
print a + b
print '%s%s' % (a, b)
print '{a}{b}'.format(a=a, b=b)
print ''.join([a, b])
# 2.
# 请将a与b拼接成字符串c,并用逗号分隔。
ab = a + ',' + b
print ab
# 3.
# 请计算出新拼接出来的字符串长度,并取出其中的第七个字符。
print len(ab.decode('utf-8'))
print ab.decode('utf-8')[7]
#
#
# 八.请阅读string模块,并且,根据string模块的内置方法输出如下几题的答案。
#
# 1.
# 包含0 - 9
# 的数字。
print '123'.isdigit()
# 2.
# 所有小写字母。
print 'abA'.islower()
# 3.
# 所有标点符号。
# 4.
# 所有大写字母和小写字母。
# 5.
# 请使用你认为最好的办法将
# {1} - {4}
# 点中的字符串拼接成一个字符串。
#
# 九.已知字符串
# ________
#
# a = "i,am,a,boy,in,china"
# ________
#
# 1.
# 假设boy和china是随时可能变换的,例boy可能改成girl或者gay,而china可能会改成别的国家,你会如何将上面的字符串,变为可配置的。
a = "i,am,a,{sexy},in,{country}".format(sexy='boy', country='china')
# 2.
# 请使用2种办法取出其间的字符
# "boy"
# 和
# "china"。
# 3.
# 请找出第一个
# "i"
# 出现的位置。
print a.find('i')
# 4.
# 请找出
# "china"
# 中的
# "i"
# 字符在字符串a中的位置。
print a.find('i', a.find('china'))
# 5.
# 请计算该字符串一共有几个逗号。
print a
print a.count('i')
#
#
# 十.请将模块string的帮助文档保存为一个文件。 |
# coding: utf-8
# Author: lee_zix
def test():
for i in range(4):
print 'test1: %d' % i
yield i
print 'test: %d' % i
def fblq_num(num):
"""斐波拉切数列"""
ls = [0, 1]
result = ls[-1] + ls[-2]
while num >= result:
ls.append(result)
result = ls[-1] + ls[-2]
# yield result
return ls
pass
def fibonacci(num):
x, y = 0, 1
f = [x]
while y <= num:
f.append(y)
x, y = y, x+y
else:
return f
pass
def is_zhi(num):
if num == 1:
return False
if num == 2:
return True
if num > 1:
for i in xrange(2, num):
if num % i == 0:
return False
return True
pass
#
if __name__ == '__main__':
#
# t = test()
#
# print t
# print t.next()
# print t.next()
# print fblq_num(13)
# print fibonacci(5)
print [x for x in xrange(0, 100) if is_zhi(x)]
#
|
# coding: utf-8
# Author: lee_zix
import types
# 今天习题:
#
# 1 定义一个方法get_fundoc(func),func参数为任意一个函数对象,返回该函数对象的描述文档,如果该函数没有描述文档,则返回"not found"
def get_fundoc(func):
if isinstance(func, types.FunctionType):
desc = func.__doc__
if isinstance(desc, types.NoneType) or len(desc) == 0:
return 'not found'
return func.__doc__
else:
return 'func %s is not function' % repr(func)
#
# 2 定义一个方法get_cjsum(),求1-100范围内的所有整数的平方和。返回结果为整数类型。
def get_cjsum():
num_sum = 0
for index, item in enumerate(range(1, 101)):
num_sum += item * item
return num_sum
#
# 3 定义一个方法list_info(list), 参数list为列表对象,怎么保证在函数里对列表list进行一些相关的操作,不会影响到原来列表的元素值,比如:
#
# a = [1,2,3]
#
# def list_info(list):
# '''要对list进行相关操作,不能直接只写一句return[1,2,5],这样就没意义了'''
#
# print list_info(a):返回结果:[1,2,5]
#
# print a 输出结果:[1,2,3]
#
# 写出函数体内的操作代码。
def list_info(params):
if not isinstance(params, list):
print 'params: %s is not list' % repr(params)
return
return [x+1 for x in params]
#
#
# 4 定义一个方法get_funcname(func),func参数为任意一个函数对象,需要判断函数是否可以调用,如果可以调用则返回该函数名(
# 类型为str),否则返回 “fun is not function"。
def get_funcname(func):
"""
get function isValidate
:param func: Function
:return: BOOL
"""
if not isinstance(func, types.FunctionType):
print 'params: %s is not function' % repr(func)
return False
print dir(func)
print dir(func.__code__)
print func.func_name
if __name__ == '__main__':
# print get_fundoc('asd')
# print get_cjsum()
# a = [1, 2, 3]
# print list_info(a)
# print a
get_funcname(get_cjsum)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: xxx
def main():
tup = (1,2,3,4)
#取值
print tup[2]#记得这里要打中括号[],和列表一样下标从0开始,不能同时取两个0,1,想要同时取多个值只能用切片
# 切片
print tup[0:1]#切片左边是闭区间,右边是开区间,即右边的实际取值会比写出来的下标少一位
print tup[2:]#右边什么都不写,默认取到最后一位
print tup[:3]#左边什么都不写,默认从第一位开始数
# 是否存在某值
print (1 in tup) #存在,则打印ture
print (5 in tup) #不存在,则打印false
if 1 in tup:
a,b,c,d=(1,2,3,5) #可以利用元祖直接给多个变量赋值
print a,b,c,d
if not 5 in tup:
a,b,c,d=(7,9,3,2)
print a,b,c,d
# 赋值
x,y,z,q=tup
print x+y,y+z,z+q
# 遍历
for item in tup:
print item
print "enumerate-------"
for index,item in enumerate(tup):
print index+item
# 花式报错
# 不支持 1)插入 2)修改 3) 删除
print "---------"
try:
#tup.append(9)#插入失败
#tup[2]=6#修改失败
del tup[0] #删除失败
except Exception, e:
print e
if __name__ == '__main__':
main()
|
import matplotlib.pylab as plot
import numpy as np
n=np.linspace(0,199,200) ; y=np.linspace(0,199,200)
x=eval((input("Write an equation for x(n):")))
i=0
while i in range(0,200):
if i==199:
y[i]=(1.5*x[i])-(2*x[i-1])+(0.5*x[i-2])
elif i==0:
y[i]=(-1.5*x[i])+(2*x[i+1])-(0.5*x[i+2])
else:
y[i]= (0.5*x[i+1])-(0.5*x[i-1])
i+=1
plot.plot(x,color="g")
plot.plot(y,color="r")
plot.suptitle('piecewise of f(n)')
plot.xlabel('n=0 to n=199')
plot.legend(['x(n) Value', 'y(n) Value'],loc=1)
plot.show |
"""
This program uses the trained keras model to predict images and visualize the
output of intermediate layers.
Use the following command to execute the code
python train.py
"""
import numpy as np
import os, glob, cv2
import tensorflow as tf
import tensorflow.keras
from tensorflow.keras.models import Sequential, load_model, Model
from random import shuffle
import matplotlib.pyplot as plt
# Setting this system up for enabling cuda
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
def predict(model_path = 'model.h5',
data_path = 'dataset/test_set/',
image_size = (64,64,3),
n_images = 5,
layer_visu = None):
"""
_func_: Predicts the object in the image using the trained model
Can visualize the models if required
Input:
model: traned model file
path(optional): path to the testing dataset folder
n_images(optional): number of images to be tested
input_size(optional) - input size of the image, defaulted to 64x64x3
layer_visu(optional) - list of network block to visualize; eg [0,2]
Return:
"""
# get a list of all the images in the folder
image_paths = glob.glob(data_path + '*')
shuffle(image_paths)
# Load the saved CNN
model = load_model(model_path)
# Iterate through every image
for image_path in image_paths[:n_images]:
# Read the image from the file
image = cv2.imread(image_path)
# Resize the image to what was used during training
image_predict = cv2.resize(image,(image_size[0],image_size[1]))
# Expand the dimensions as keras adds additional dimension while training
image_predict = np.expand_dims(image_predict, axis=0)
# Predict the passed image using the trained model
model_prediction = model.predict(image_predict)
# Discritize the prediction
if model_prediction[0][0] == 1: predicted_label = 'DOG'
else:predicted_label = 'CAT'
image = cv2.resize(image,(500,500))
print(predicted_label)
# If the user wishes to visualize layers go ahead
if layer_visu:
visualize_activations(model, image_predict, layer_visu)
# Add the prediction text to the image
cv2.putText(image, str(predicted_label), (100, 100), cv2.FONT_HERSHEY_SIMPLEX, 3,(0,0,255),4,cv2.LINE_AA)
# Display the image
cv2.imshow('output', image)
cv2.waitKey(0)
def visualize_activations(model, image, layer_list):
"""
_func_: Visualize the intermediate layer outputs aka feature maps
Input:
model: trained model file
image: image to visualize
layer_list - list of network block to visualize; eg [0,2]
Return:
"""
# An empty list that stores layer name
layer_names = []
# Iterating through the layers and getting the names
for layer in model.layers:
layer_names.append(layer.name)
print(layer.name)
# Extract the output of every layer
layer_outputs = [layer.output for layer in model.layers]
# No of kernels to be displayed in a row
kernels_per_row = 16
# Creates a modified model that will return the layer outputs after activations
activation_model = Model(inputs=model.input, outputs=layer_outputs)
# Extracting the output of the layers
activations = activation_model.predict(image)
# Now let's display our feture maps
for nb_layer in layer_list:
layer_activation = activations[nb_layer]
# This is the number of features in the feature map
n_features = layer_activation.shape[-1]
# The feature map has shape (1, size, size, n_features)
size = layer_activation.shape[1]
# We will tile the activation channels in this matrix
n_cols = n_features // kernels_per_row
display_grid = np.zeros((size * n_cols, kernels_per_row * size))
# We'll tile each filter into this big horizontal grid
for col in range(n_cols):
for row in range(kernels_per_row):
channel_image = layer_activation[0,
:, :,
col * kernels_per_row + row]
# Post-process the feature to make it visually palatable
channel_image -= channel_image.mean()
channel_image /= channel_image.std()
channel_image *= 64
channel_image += 128
channel_image = np.clip(channel_image, 0, 255).astype('uint8')
display_grid[col * size : (col + 1) * size,
row * size : (row + 1) * size] = channel_image
# Display the grid
scale = 1. / size
plt.figure(figsize=(scale * display_grid.shape[1],
scale * display_grid.shape[0]))
plt.title(layer_names[nb_layer])
plt.grid(False)
plt.imshow(display_grid, aspect='auto', cmap='viridis')
plt.show()
# Main function this is where the code begins to execute
if __name__ == "__main__":
# Calling the prediction function
predict(model_path = 'model.h5',
data_path = 'dataset/test_set/',
image_size = (64,64,3),
n_images = 20,
layer_visu = [2,3]) |
n = int(input("Enter the nth term"))
f = []
a = 0
b = 1
f.append(a)
f.append(b)
for i in range(2,n):
c = a + b
f.append(c)
a = b
b = c
print("The nth term is:",f[n-1])
|
import unittest
class TestCalculadora(unittest.TestCase):
def setUp(self):
self.cal = Calculadora()
def test_sumar_2_mas_2(self):
resultado = self.cal.suma(2, 2)
self.assertEqual(4, resultado)
def test_sumar_3_mas_3(self):
resultado = self.cal.suma(3, 3)
self.assertEqual(6, resultado)
class Calculadora():
def suma(self, numero1, numero2):
return numero1 + numero2
if __name__ == '__main__':
unittest. main() |
if __name__ == '__main__':
x = [1, 2, 3];
y = [1, 2, 3];
#创建一个没有重复元素当tuple
print([(xx, yy) for xx in x for yy in y if xx != yy])
# expected output:
# [{'name': 'jason', 'dob': '2000-01-01', 'gender': 'male'},
# {'name': 'mike', 'dob': '1999-01-01', 'gender': 'male'},
# {'name': 'nancy', 'dob': '2001-02-01', 'gender': 'female'}]
attributes = ['name', 'dob', 'gender']
values = [['jason', '2000-01-01', 'male'],
['mike', '1999-01-01', 'male'],
['nancy', '2001-02-01', 'female']
]
result = []
for x in values:
p = {}
result.append(p)
for i,v in enumerate(attributes):
p[v] = x[i]
print(result)
# 一行搞定
print([dict(zip(attributes, value)) for value in values]) |
for a in 'MHMSM':
print('hello')
# بعد از فور ها می توان از esle استفاده کرد
b=[1,2,8,56,100]
for c in b:
print(c)
else:
print('adad tamom shod ')
#break شکستن حلقه
#continue ادامه می دهد
#pass
for c in 'string':
if(c=='i'):
continue#با درسیدن به این جا این قمست فور را انجام نمی دهد
print(c)
#i در مقادیر چاپ شده نیست
list1=[]
for v in 'MHMSM':
list1.append(v)
#/////////////////////////for in list
list2=[ v for v in 'MSM']#مثل شرط گداشتن برای اضافه کردن چیزی به لیست هست
print(list2)
list3= [ s for s in range(20) if s%2 == 0]
print(list3)
#/////////////////////while
g=0
while g!=2:
print('i love you god ')
g+=1
else:
print('tamam shod ')
#/////////////////////////////////fucntion
#def ==defind
def hello():
print('hello MHMSM')
'doc string '#یعنی توضیحاتی درباره تابع
return '86'
hello()#وقتی صداش میزنم کار های داخل تابع را انجام میدهد
print(hello())#اما وقتی این طوری صداش میزنم مقدار return شد را نمایش میدهد 3
#count=? # یعنی خالی
def print_hello(count):
for i in range(count):
print("hello")
'''it is for count'''
print(print_hello.__doc__)
print_hello(int(input('enter count :')))
#//////////////////////////// globall && local
f=2 #globall
def add():
# f=3#local
# در حالت عادی مقدار متغییر محلی تغییر میکند و نمی نتوان از متغییری که در بالا تعریف شده استفاده کرد
#مگر اینکه مشخص کنیم که از کدام متغییر استفاده می کنیم
global f
f+=3
return f
print(add())
#print(locals())#برای متغییر ها محلی
#print(globals())#برای متغییر هاجهانی
#می توان در همان ابتدا به متغیر ها مقدار داد تا در صورت ندادن مقدار به صورت پیش ورز مقدار داشته باشد
#نکته خیلی مهم نمی توان یکی را مقدرا پیش ورز داد و دیگری را نداد چون ارور می دهد
# برای پیش نیامدن ارور متغیری که بهش مقدار پیش ورز نمی دهید را در ابتدا بگدارید
def MHMSM(countr,name_love='MHM' ):
return f'{name_love} {countr} man in ghadr doset darm'
#print(MHMSM('god',10000))به روشی دیگر هم میشود به متغییر ها مقدار داد
#print(MHMSM(name_love='god',countr=100))#به روش می گویند کیبورد ارگمان
print(MHMSM(10))
#در متد نویسی دو تا پارامتر مهم هست
#*args =(1,'ali)= tuple
#**kwargs = {name :"ali"} = dictionary
# از این پارامتر ها موقعی استفاده می شود که ما نمی دانیم کاربر قرار است چند مقدار وارد کند
def name(*arge,**kwargs):
print(arge)
print(kwargs)
#البته برای نام گدازی پارامترها می توان از هر اسمی استفاده کرد ولی بهتر است از
# *args & **kwargs
#name('i am mohammad iam ','developer',age=19,my_love='god')
# اما اگر مغییر بود
list4=['MHMSM','developer']
list5={'age':19,'my_love':'god'}
#name(list4,list5)اما اگر این طوری مقدار دهیم همه را در *arge می گدارد
name(*list4,**list5)
#////////////////////////////////recursive function تابع بازگشتی
#list6=[]
#def zarb(x):
# javab=0
# if i<10:
# javab=x*i
# list6.append(javab)
# i+=1
# zarb(5)
# else:
# return list6
#print(zarb(5))
#///////////////////////////////////lambda
#def number(num):
# return num**2
#print(number(3))
#///////////////////تبدیل به
#lambda
number =lambda num: num**2
print(number(5))
even=lambda enter: enter%2==0
print(even(5))
add= lambda x,y: x+y
print(add(10,10))
|
def run():
my_list = [1, 'Hi', True, 4.5]
my_dicc = {
"firstname": "abraham",
"lastname": "garcia",
"age": 22,
}
super_list = [
{
"firstname": "abraham",
"lastname": "garcia",
"age": 22,
},
{
"firstname": "lupia",
"lastname": "moreno",
"age": 50,
},
{
"firstname": "jazmin",
"lastname": "garcia",
"age": 22,
},
{
"firstname": "paola",
"lastname": "cortez",
"age": 23,
},
]
super_dict = {
"natural_nums" : [1,2,3,4,5],
"integer_nums" : [-1, 0, 1, 2],
"float_nums" : [1.5, 2.5, 3.5],
}
#Imprimir super lista de diccionarios
for values in super_list:
for key, value in values.items():
print(key + " : " + str(value))
#Imprimir super diccionario de listas
for key, value in super_dict.items():
print("La llave es " + key + " el valor es " + str(value))
if __name__ == '__main__':
run() |
#GuessTheWord.py
#Karl Pearson
#10/27/2014
import random
print("Welcome to Guess the Word: Legend of Zelda Edition")
print("You will have 5 tries to guess the word")
tries=7
WORDS=("Link","Hyrule","Zelda","Epona","Ocarina","Triforce")
count=1
answer=random.choice(WORDS)
print("The word has", len(answer),"letters in the word.")
letters=input('Enter a letter: ')
while tries != 2:
if letters in answer:
print("Yes")
letters=input('What letters do you guess? ')
tries=tries-1
else:
print('No')
letters=input('What letter do you guess? ')
tries=tries-1
print("Time to have a guess")
guess=input("What is the word? ")
while guess != answer:
print("That is incorrect, try again")
guess=input("What is the word?: ")
if guess==answer:
print('Good Job!')
print('Hope you enjoyed the game')
input('\n\npress enter to exit')
|
numero = input('Digite um número: ')
if numero.isdigit():
numero = int(numero)
if numero % 2 == 0:
print('Número par')
elif numero % 2 != 0:
print('Numero ímpar')
else:
print('Isso não é um número inteiro')
|
#Tensorflow course
#Chapter 1
#Q1
import constant from TensorFlow
from tensorflow import constant
# Convert the credit_numpy array into a tensorflow constant
credit_constant = constant(credit_numpy)
# Print constant datatype
print('\n The datatype is:', credit_constant.dtype)
# Print constant shape
print('\n The shape is:', credit_constant.shape)
#Q2
# Define tensors A1 and A23 as constants
A1 = constant([1, 2, 3, 4])
A23 = constant([[1, 2, 3], [1, 6, 4]])
# Define B1 and B23 to have the correct shape
B1 = ones_like(A1)
B23 = ones_like(A23)
# Perform element-wise multiplication
C1 = multiply(A1, B1)
C23 = multiply(A23, B23)
# Print the tensors C1 and C23
print('\n C1: {}'.format(C1.numpy()))
print('\n C23: {}'.format(C23.numpy()))
# Define features, params, and bill as constants
features = constant([[2, 24], [2, 26], [2, 57], [1, 37]])
params = constant([[1000], [150]])
bill = constant([[3913], [2682], [8617], [64400]])
# Compute billpred using features and params
billpred = matmul(features, params)
# Compute and print the error
error = bill - billpred
print(error.numpy())
# Reshape the grayscale image tensor into a vector
gray_vector = reshape(gray_tensor, (784, 1))
# Reshape the color image tensor into a vector
color_vector = reshape(color_tensor, (2352, 1))
def compute_gradient(x0):
# Define x as a variable with an initial value of x0
x = Variable(x0)
with GradientTape() as tape:
tape.watch(x)
# Define y using the multiply operation
y = multiply(x,x)
# Return the gradient of y with respect to x
return tape.gradient(y, x).numpy()
# Compute and print gradients at x = -1, 1, and 0
print(compute_gradient(-1.0))
print(compute_gradient(1.0))
print(compute_gradient(0.0))
'''
Working with image data
You are given a black-and-white image of a letter, which has been encoded as a tensor, letter. You want to determine whether the letter is an X or a K. You don't have a trained neural network, but you do have a simple model, model, which can be used to classify letter.
The 3x3 tensor, letter, and the 1x3 tensor, model, are available in the Python shell. You can determine whether letter is a K by multiplying letter by model, summing over the result, and then checking if it is equal to 1. As with more complicated models, such as neural networks, model is a collection of weights, arranged in a tensor.
Note that the functions reshape(), matmul(), and reduce_sum() have been imported from tensorflow and are available for use.
'''
# Reshape model from a 1x3 to a 3x1 tensor
model = reshape(model, (3, 1))
# Multiply letter by model
output = matmul(letter, model)
# Sum over output and print prediction using the numpy method
prediction = reduce_sum(output)
print(prediction.numpy())
|
student_score = int(input())
maximum_score = int(input())
score_percentage = (student_score / maximum_score) * 100
if score_percentage < 60:
print('F')
elif score_percentage < 70:
print('D')
elif score_percentage < 80:
print('C')
elif score_percentage < 90:
print('B')
else:
print('A')
|
from xml.dom.minidom import parse, parseString
import os
class NotTextNodeError:
pass
def getTextFromNode(node):
"""
scans through all children of node and gathers the
text. if node has non-text child-nodes, then
NotTextNodeError is raised.
"""
t = ""
for n in node.childNodes:
if n.nodeType == n.TEXT_NODE:
t += n.nodeValue
else:
raise NotTextNodeError
return t
def nodeToDic(node):
"""
nodeToDic() scans through the children of node and makes a
dictionary from the content.
three cases are differentiated:
- if the node contains no other nodes, it is a text-node
and {nodeName:text} is merged into the dictionary.
- if the node has the attribute "method" set to "true",
then it's children will be appended to a list and this
list is merged to the dictionary in the form: {nodeName:list}.
- else, nodeToDic() will call itself recursively on
the nodes children (merging {nodeName:nodeToDic()} to
the dictionary).
"""
dic = {}
multlist = {} # holds temporary lists where there are multiple children
multiple = False
for n in node.childNodes:
if n.nodeType != n.ELEMENT_NODE:
continue
# find out if there are multiple records
if len(node.getElementsByTagName(n.nodeName)) > 1:
multiple = True
# and set up the list to hold the values
if not multlist.has_key(n.nodeName):
multlist[n.nodeName] = []
else:
multiple = False
try:
# text node
text = getTextFromNode(n)
except NotTextNodeError:
if multiple:
# append to our list
multlist[n.nodeName].append(nodeToDic(n))
dic.update({n.nodeName:multlist[n.nodeName]})
continue
else:
# 'normal' node
dic.update({n.nodeName:nodeToDic(n)})
continue
# text node
if multiple:
multlist[n.nodeName].append(text)
dic.update({n.nodeName:multlist[n.nodeName]})
else:
dic.update({n.nodeName:text})
return dic
def readConfig(filename):
dom = parseString(open(filename).read())
return nodeToDic(dom)
if __name__ == "__main__":
import sys
import pprint
pprint.pprint(readConfig(sys.argv[1]))
|
l1 = [1, 'Two', 3.00, True, False]
l2 = ['a', 'x', 'l', 'b', 'n','a']
print(l1)
print(l2.count('a'))
print(len(l1))
print(l1[1:])
l1.append('FOUR')
print(l1)
print(l1.pop()) # pops last element in the list and prints it. Here by default the index is -1.
print(l1)
l1.pop(2) # pops at index 1 permamently...
l2.sort() # sort is a ind of special inplace method which actualy doesnt returns anything..NOTE LIST SHOULD BE Either Numerics or Alphabetic for sorting
print("L2.sort returntype is {} and type(l2) = {} and type(l2.sort()) is {} ".format(l2.sort(), type(l2),
type(l2.sort())))
print(l1)
print(l2)
'''l1.sort()
#TypeError: '<' not supported between instances of 'str' and 'int'''
print(l2[-1] + "is the element at index -1 before reversing")
l2.reverse() # It reverses the list
print(l2[-1] + "is the element at index -1 after reversing")
nestedlist1 = ['one', [2.1, 2.2, 2.3], 'three', [4, [4.1, 4.2, 4.3]]]
print(nestedlist1[1]) # [2.1, 2.2, 2.3]
print(nestedlist1[1][2]) # 2.3
print(nestedlist1[3][1][2]) # 4.3
# Stack calling of the nested list (here list containing the dictionary).
listofdict = [{'key1': 'val1', 'key2': 'val2'}, {'Bhupi': 150, 'Monty': 200}]
print(listofdict)
print(listofdict[1])
print(listofdict[1]['Bhupi'])
|
d1 = {'k1': 'Val1', "key2": 200}
print(d1)
print(d1["key2"])
# Note that key is always a string
# NESTED DICTIONARIES
d2 = {'k1': 105, 'k2': [105, 106, 109], 'k3': {'innerkey': 1000},'k4':['a','b','c','d']}
print(d2)
print(d2['k2'])
print(d2['k2'][2]) # prints element at 2nd index of the list at key= k2..ALSO .upper() at int list causes error as no upper is there for int
print(d2['k3'])
print(d2['k3']['innerkey']) # prints element at innerkey at k3
print(d2['k4'][2].upper())
d2['k0']='Value0'
print(d2)#Note that the new value added here gets added at the last of the dict.
d2['k1']="Value 1"
print("AFTER UPDATING THE VALUE OF K1 THE DICTIONARY BECAME:")
print(d2) |
d =dict(a=1,b=2,c=3)
for k in d.keys():
print(d[k], end=" ")
print()
for v in d.values():
print(v,end=" ")
print()
for kv in d.items():
print(kv, end=" ")
print()
for k, v in d.items():
print(k, v)
vo = d.items()
for kv in vo:
print(vo,end=" ")
for k, v in vo:
d[k] += 2
print()
for k, v in d.items():
print(k, v)
|
class Account:
def __init__(self, aid, abl):
self.aid = aid
self.abl = abl
def __add__(self, m):
self.abl += m
print("__add__")
def __iadd__(self, m):
self.abl += m
print("__iadd__")
return self
def __sub__(self, m):
self.abl -= m
print("__sub__")
def __isub__(self, m):
self.abl -= m
print("__isub__")
return self
def __call__(self):
print("__call__")
return str(self.aid) + " : " + str(self.abl)
def __str__(self):
return "Account {0} : Balance ={1}".format(self.aid, self.abl)
acnt = Account("James01", 100)
acnt += 100
acnt -= 50
print(acnt)
class Vector:
def __init__(self, x, y):
self.x =x
self.y =y
def __add__(self, o):
return Vector(self.x + o.x , self.y + o.y)
def __call__(self):
return "Vector({0}, {1})".format(self.x, self.y)
def __iadd__(self,o):
self.x += o.x
self.y += o.y
return self
def __str__(self):
return "Vector({0}, {1})".format(self.x, self.y)
v1 = Vector(3,3)
print(v1)
v2 = Vector(7,7)
print(v2)
v1 += v2
print(v1)
class Simple:
def __init__(self, i):
self.i = i
def __str__(self):
return "Simple({0})".format(self.i)
s = Simple(10)
print(s)
print(s.__str__())
|
class Person:
def __init__(self, n, a):
self._name = n
self._age =a
def __str__(self):
return "{0}:{1}".format(self._name, self._age)
def add_age(self, a):
if(a<0):
print("나이 정보 오류")
else:
self._age += a
p = Person("Kavin", 22)
p.len =178
p.adr ="Korea"
print(p.__dict__)
p.__dict__["_name"] ="James"
p.__dict__["_age"] = 40
print(p) |
from collections import namedtuple
Tri = namedtuple("Tiangle", ["bottom","height"])
t = Tri(3,7)
print(t[0], t[1])
print(t.bottom, t.height)
def show(n1, n2):
print(n1, n2)
t = Tri(3,8)
show(*t)
|
# class Course:
# """asd"""
# def __init__(self, code, name, points):
# """asd"""
# self.code = code
# self.name = name
# self.points = points
# def to_dictionary(self):
# """asd"""
# result ={'code': self.code, 'name': self.name, 'points': self.points}
# return result
# def __str__(self):
# """asd"""
# return "{} ({}) {} points".format(self.code, self.name, self.points)
# course = Course('COSC121', 'Introduction to Programming', 15)
# print("{}, {}, {}".format(course.code, course.name, course.points))
# # print(course)
# # print(sorted(course.to_dictionary().items()))
# result = {}
# # # kjhjk
# # result["sdf"] = "sdff"
# # result[12] = "abcd"
# # print(result)
# # result.items()
# # print(result.items())
# # for i, j in result.items():
# # print(i,j)
# # for i in result.keys():
# # print(i,result[i])
# set1 = set()
# set1.add("a")
# print(set1)
def read_data(filename):
file = open(filename, "r")
lines = file.read()
file.close()
# print(lines)
list1 = lines.split()
dict1 = {}
temp = set(list1)
set1 = list(temp)
set1.sort()
for i in set1:
count = list1.count(i)
if count in dict1.keys():
dict1[count].append(i)
else:
dict1[count] = [i]
return dict1, len(list1)
# Question 23
def print_n_most_common(filename, n):
"""asd"""
dict1, list_len = read_data(filename)
keys = list(dict1.keys())
keys.sort()
print( keys)
i = 1
print_num = 0
limit = 0
while print_num < n and limit < 100 and i < len(keys)+1:
limit += 1
for word in dict1[keys[-i]]:
if(print_num < n):
print(word, keys[-i])
print_num += 1
i += 1
#Z:\\Tutor 2021\\CS121\\codes\\revision\\test1.txt
print_n_most_common('test1.txt', 7) |
"""Demonstrate event binding and variable tracing,
this time with a clean OO design.
"""
from tkinter import *
from tkinter.ttk import *
class GreetingGui:
"""The GUI class"""
def __init__(self, window):
"""Setup the label and button on given window"""
self.click_count=0
self.hello_label = Label(window, text='0')
self.hello_label.grid(row=0, column=0)
self.hello_button = Button(window, text="+1", command=self.say_hello)
self.hello_button.grid(row=1, column=0)
self.btn_2 = Button(window, text="-1", command=self.minus_1)
self.btn_2.grid(row=1, column=1)
def say_hello(self):
"""The event handler for clicks on the button"""
self.click_count += 1
self.hello_label['text'] = self.click_count.__str__()
def minus_1(self):
"""The event handler for clicks on the button"""
self.click_count -= 1
self.hello_label['text'] =self.click_count.__str__()
def main():
"""Set up the GUI and run it."""
window = Tk()
greeting_gui = GreetingGui(window)
window.mainloop()
main() |
# Program to add two matrices using nested loop
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
def sum_odd(arg_x):
"""add the odd numbers below arg_x"""
result=0
for i in range(0,arg_x,2):
result += i
#return result
print(sum_odd(100))
5 |
"""File for creating Person objects"""
class Person:
"""Defines a Person class, suitable for use in a hospital context.
Data attributes: name of type str
age of type int
weight (kg) of type float
height (metres) of type float
Methods: bmi()
"""
def __init__(self, name, age, weight, height):
"""Creates a new Person object with the specified name, age, weight
and height"""
self.name = name
self.age = age
self.weight = weight
self.height = height
def bmi(self):
"""Returns the body mass index of the person"""
return self.weight / (self.height * self.height)
# *** YOUR CODE *** Define a status method here.
def status(self):
"""asd"""
bmi_number = self.bmi()
if bmi_number < 18.5:
return "Underweight"
elif bmi_number >= 18.5 and bmi_number < 25:
return "Normal"
elif bmi_number >= 25 and bmi_number < 30:
return "Overweight"
else:
return "Obese"
def __str__(self):
"""Returns the formatted string representation of the Person object"""
template = "{0} ({1}) has a bmi of {2:3.2f}. Their status is {3}."
return template.format(self.name, self.age, self.bmi(), self.status())
def read_people(csv_filename):
"""asd"""
infile = open(csv_filename)
persons = []
for line in infile:
data = line.split(',')
persons.append(Person(data[0], int(data[1]), \
float(data[2]), float(data[3])))
return persons
def filter_people(people, status_string):
"""asd"""
result = []
for person in people:
if person.status() == status_string:
result.append(person)
return result
def age_value(person):
"""asd"""
return person.age
def bmi_value(person):
"""asd"""
return person.bmi()
bods = read_people("Z:\Tutor 2021\cosc212\code\people1.csv")
bods.sort(key=age_value)
for bod in bods:
print(bod)
bods = read_people("Z:\Tutor 2021\cosc212\code\people1.csv")
bods.sort(key=bmi_value)
for bod in bods:
print(bod) |
print("fera")
v= area()
print v
def area(b,h):
a=1/2*b*h
print(a)
#pandas
Machine Learning SMP
Numpy Assignment Questions
Assignment I
1.
2.
3.
4.
5.
Extract the integer part of a random array using 5 different
methods
6.
Write a Python program to check two random arrays are equal or not.
7.
Write a Python program to find the nearest value from a given value in an
array.
8.
Write a Python program to get the n largest values of an array.
9.
How to find the closest value (to a given scalar) in an array?
10.
Write a Python program to create random vector of size 15 and replace
the maximum value by -1.
11.
Consider a random vector with shape (100,2) representing
coordinates, find point by point distances
12.
How to I sort an array by the nth column?
13.
Considering a four dimensions array, how to get sum over the
last two axis at once?
14.
How to find the most frequent value in an array? |
#
# @lc app=leetcode.cn id=20 lang=python
#
# [20] 有效的括号
#
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for i in s:
if len(stack) == 0:
stack.append(i)
continue
if stack[-1] == "(" and i == ")":
stack.pop()
elif stack[-1] == "[" and i == "]":
stack.pop()
elif stack[-1] == "{" and i == "}":
stack.pop()
else:
stack.append(i)
if len(stack) == 0:
return True
else:
return False
|
#Del Castillo, Mary Abigail V.
#2014-23666
#Galois Field Calculator
def pad_poly(poly,len_a,len_b):
pad = len_a - len_b
for x in range(pad):
poly.insert(0,0)
return poly
def pad_poly_str(poly,len_a,len_b):
pad = len_a - len_b
for x in range(pad):
poly.insert(0," ")
return poly
def del_zeroes(a):
new_a=a
if (len(a)>0):
while(new_a[0]==0):
new_a.pop(0)
return new_a
def print_output(poly,a):
ctr = len(a)-1
print poly,
for x in range(0,len(a)):
if (x == len(a)-1):
print str(a[x])
else:
print str(a[x]) + "x^" + str(ctr) + " +",
ctr-=1
def print_terms(a):
for x in range(0,len(a)):
if (x == len(a)-1):
print str(a[x])
else:
print str(a[x]),
def input_check(a):
b = a.split()
for x in b:
if (x.isdigit()==False):
return 0
return 1
#Polynomial Operations
def poly_add2(a,b):
result = []
print "Now, let's perform bitwise xor operation for every term in A(x) and B(x)."
for x in range(len(a)):
xor_value = a[x] ^ b[x]
print "if we perform",str(a[x]),"xor",str(b[x]),", we get",str(xor_value)
result.append(xor_value)
print "Therefore, after joining all the individual xor results, we get,"
print_terms(result)
return result
def poly_subtract2(a,b):
result = []
print "Now, let's perform bitwise xor operation for every term in A(x) and B(x)."
for x in range(len(a)):
xor_value = a[x] ^ b[x]
print "if we perform",str(a[x]),"xor",str(b[x]),", we get",str(xor_value)
result.append(xor_value)
print "Therefore, after joining all the individual xor results, we get,"
print_terms(result)
return result
def poly_add(a,b):
result = []
for x in range(len(a)):
xor_value = a[x] ^ b[x]
result.append(xor_value)
return result
def poly_subtract(a,b):
result = []
for x in range(len(a)):
xor_value = a[x] ^ b[x]
result.append(xor_value)
return result
def s_mult(a,b,c):
a=list(bin(a)[2:])
b=list(bin(b)[2:])
a=[int(n) for n in a]
b=[int(n) for n in b]
#pad binary representation according to the longest number
if len(a)>len(b):
b = pad_poly(b,len(a),len(b))
else:
a = pad_poly(a,len(b),len(a))
temp=[]
#multiply each element of b to a
for x in range(len(b)-1,-1,-1):
prod=[str(b[x]*a[y]) for y in range(len(a))] #temporary storage for current product
prod.extend("0"*((len(b)-1)-x)) #pad-right depending on which place we are multiplying
prod=[int(n) for n in prod]
temp=pad_poly(temp,len(prod),len(temp)) #pad-left temporary depending on the place in preparation for XOR op
temp=poly_add(temp,prod) #add temp and the current product
#mod P(x) as long as the resulting polynomial is longer than P(x)
#delete leading zeroes
temp = int(''.join(map(str,temp)),2)
temp= list(bin(temp)[2:])
temp=[int(n) for n in temp]
temp_c=[int(n) for n in c]
len_c = len(c)
while(len(temp)>=len_c):
temp_c=[int(n) for n in c]
temp_c.extend("0"*(len(temp)-len(temp_c)))
temp_c=[int(n) for n in temp_c]
temp=poly_add(temp,temp_c)
#delete leading zeroes
temp = int(''.join(map(str,temp)),2)
temp= list(bin(temp)[2:])
temp=[int(n) for n in temp]
return int(''.join(map(str,temp)),2)
def poly_multiply(a,b,c):
temp=[]
#multiply each element of b to a
len_ba=len(b)+len(a)
temp_c=[int(n) for n in c]
for x in range(len(b)-1,-1,-1):
temp_c=[int(n) for n in c]
prod=[str(s_mult(a[y],b[x],temp_c)) for y in range(len(a))] #temporary storage for current product
prod.extend("0"*((len(b)-1)-x)) #pad-right depending on which place we are multiplying
prod=[int(n) for n in prod]
temp2 = [str(n) for n in prod]
temp2=pad_poly_str(temp2,len_ba,len(temp2))
print_terms(temp2)
temp=pad_poly(temp,len(prod),len(temp)) #pad-left temporary depending on the place in preparation for XOR op
temp=poly_add(temp,prod) #add temp and the current product
print "---------------------------"
temp3=[str(n) for n in temp]
temp3=pad_poly_str(temp3,len_ba,len(temp3))
print_terms(temp3)
#delete leading zeroes
temp=del_zeroes(temp)
#mod P(x) as long as the resulting polynomial is longer than P(x)
# temp_c=c
# len_c = len(c)
# while(len(temp)>=len_c):
# print len(temp), len_c
# temp_c=c
# temp_c.extend("0"*(len(temp)-len(temp_c)))
# temp_c=[int(n) for n in temp_c]
# temp=poly_add(temp,temp_c)
# print temp
# #delete leading zeroes
# temp=del_zeroes(temp)
return temp
def div_mult(ctr,a,c):
prod=[str(s_mult(a[y],ctr,c)) for y in range(len(a))] #temporary storage for current product
prod=[int(n) for n in prod]
return prod
def poly_divide(a,b,c):
result2=[]
result=[]
ctr = 1
ctr2 = len(a)-len(b)
x = div_mult(ctr,b,c)
len_b = len(b)
len_a = len(a)
for n in range(0,len(a)):
if (n == len(a)-1):
print str(a[n]),"= A"
else:
print str(a[n]),
while (len(a)>=len_b):
while(a[0]!=x[0]):
ctr+=1
x = div_mult(ctr,b,c)
result.append(ctr)
if (len(a) < len(b)):
return result
else:
len_x = len(x)
x.extend("0"*((len(a))-len_x))
x=[int(n) for n in x]
#printing solution
temp1=[str(n) for n in x]
temp1=pad_poly_str(temp1,len_a,len(temp1))
for n in range(0,len(temp1)):
if (n == len(temp1)-1):
print str(temp1[n])+" = B x "+str(ctr)+"x^"+str(ctr2)
else:
print str(temp1[n]),
print "--------------------"
a = poly_add(a,x)
temp2=[str(n) for n in a]
temp2=pad_poly_str(temp2,len_a,len(temp2))
print_terms(temp2)
a = del_zeroes(a)
ctr=1
ctr2-=1
result2.append(result)
result2.append(a)
print "result =",
print_terms(result2[0])
print "remainder =",
print_terms(result2[1])
return result2
'''Main Program'''
#User Input
a_input = raw_input("Enter A(x) separated by spaces: ")
while (input_check(a_input)!=1):
print "You have entered a non-digit in the polynomial."
a_input = raw_input("Enter A(x) separated by spaces: ")
a_input = [int(n) for n in a_input.split()]
a_div = [int(n) for n in a_input]
b_input = raw_input("Enter B(x) separated by spaces: ")
while (input_check(b_input)!=1):
print "You have entered a non-digit in the polynomial."
b_input = raw_input("Enter B(x) separated by spaces: ")
b_input = [int(n) for n in b_input.split()]
b_div = [int(n) for n in b_input]
c_input = raw_input("Enter P(x) separated by spaces: ")
while (input_check(c_input)!=1):
print "You have entered a non-digit in the polynomial."
c_input = raw_input("Enter P(x) separated by spaces: ")
c_input = [int(n) for n in c_input.split()]
#preprocess input
if len(a_input)>len(b_input):
b_input = pad_poly(b_input,len(a_input),len(b_input))
else:
a_input = pad_poly(a_input,len(b_input),len(a_input))
max_value=2**(len(c_input)-1)
for x in a_input:
if (x >= max_value):
f=raw_input("One of the coefficients is greater than the limit set by the P(x)")
exit()
for x in b_input:
if (x >= max_value):
f=raw_input("One of the coefficients is greater than the limit set by the P(x)")
exit()
operation = 0
while(operation<1 or operation>4):
print "Choose an operation you want to perform:"
print "1. A(x) + B(x)"
print "2. A(x) - B(x)"
print "3. A(x) x B(x)"
print "4. A(x) / B(x)"
operation = input("Enter the number of your choice: ")
#operations
result = 0
len_ba = len(b_input)+len(a_input)
if operation == 1:
print "\nDetailed solution for A(x) + B(x) (addition):\n"
print "We can pad the terms to have equal number of terms."
print "After padding, we have"
print "A(x) =",
print_terms(a_input)
print "B(x) =",
print_terms(b_input)
print "\n"
result = poly_add2(a_input,b_input)
print "\nOutput:"
print_output("A(x) =",a_input)
print_output("B(x) =",b_input)
print_output("A(x) + B(x) =",result)
elif operation == 2:
print "\nDetailed solution for A(x) - B(x) (subtraction):\n"
print "We can pad the terms to have equal number of terms."
print "After padding, we have"
print "A(x) =",
print_terms(a_input)
print "B(x) =",
print_terms(b_input)
print "\n"
result = poly_subtract2(a_input,b_input)
print "\nOutput:"
print_output("A(x) =",a_input)
print_output("B(x) =",b_input)
print_output("A(x) - B(x) =",result)
elif operation == 3:
print "\nDetailed solution for A(x) x B(x) (multiplication):\n"
print "1) Using the Galois Field GF(2^" + str(len(c_input)-1)+") based on the primitive P(x) =",
print_terms(c_input)
print "2) Multiply each term by their binary values (with modulo 2 addition) and then the result is computed modulo P(x)"
print "3) After multiplying each term of B(x) with A(x), perform bitwise xor on those terms."
print "4) For the solution itself, please look at the following: "
temp=[str(n) for n in a_input]
temp=pad_poly_str(temp,len_ba,len(temp))
print_terms(temp)
temp2=[str(n) for n in b_input]
temp2=pad_poly_str(temp2,len_ba,len(temp2))
print_terms(temp2)
print "---------------------------"
result = poly_multiply(a_input,b_input,c_input)
print "\nOutput:"
print_output("A(x) =",a_input)
print_output("B(x) =",b_input)
print_output("A(x) x B(x) =",result)
elif operation == 4:
print "\nDetailed solution for A(x) / B(x) (division):\n"
print "1) Try to multiply integers to B(x) starting from 1 until the first term is equal to the dividend's first term."
print "2) Perform xor on the dividend and the product of the integer and B(x)."
print "3) Divide this result to B(x) again and repeat the process from step 1 until the number of terms of the dividend is less than the length of B(x)."
print "4) For a detailed solution, please look at the following."
result = poly_divide(a_div,b_div,c_input)
print "\nOutput:"
print_output("A(x) =",a_input)
print_output("B(x) =",b_input)
print_output("A(x) / B(x) =",result[0])
print_output("remainder =",result[1])
last = raw_input("Press enter to exit the program")
|
import logging
from Heap import BinaryHeap
import Random
import sys
def Djikstra(G, v1, v2=None):
"""
Single Source shortest path
Implement the Djikstras algorithm starting from node v1
Return the edges
"""
minNodes = BinaryHeap()
minNodes.add(0, v1)
for key in G.vertices.keys():
G.vertices[key] = (None, None)
G.vertices[v1] = (0, None)
while not minNodes.empty():
(dist, v) = minNodes.deleteMin()
assert G.vertices[v] != None
for otherv in G.neighbours(v):
weight = G.get_edge_value(v, otherv)
ndist = dist + weight
cdist, cprev = G.vertices[otherv]
if cdist == None or ndist < cdist:
G.vertices[otherv] = (ndist, v)
minNodes.add(ndist, otherv)
return G.vertices
def BellmannFord(G, v1, v2=None):
"""
Single Source shortest path generic case where weights can be negative
This is a O(VE) algorithm
"""
for key in G.vertices.keys():
G.vertices[key] = (sys.float_info.max, None)
G.vertices[v1] = (0, None)
for i in range(len(G.vertices.keys())):
for vkey, edges in G.edges.items():
vw = G.vertices[vkey][0]
if(vw < sys.float_info.max):
for ovkey, weight in edges.items():
ovw = G.vertices[ovkey][0]
if vw + weight < ovw:
G.vertices[ovkey] = (vw + weight, vkey)
for vkey, edges in G.edges.items():
for ovkey, weight in edges.items():
if G.vertices[vkey][0] + weight < G.vertices[ovkey][0]:
assert "Graph with a negative-weight cycle"
return G.vertices
if __name__=="__main__":
#G = Random.path_graph(10)
logger = logging.getLogger(__name__)
logging.basicConfig(filename='ssp.txt', level=logging.INFO)
logger.setLevel(logging.DEBUG)
G = Random.random_skew_graph(50, 0.2)
dj = Djikstra(G, 0)
print("DJIKSTRA:")
print(dj)
bf = BellmannFord(G, 0)
print("BELLMANN-FORD:")
print(bf)
assert bf == dj
|
# Implement a mathod to perform basic string compression using the counts
# of repeated characters. For example, the string aabccccaaa would become
# a2b1c5a3. If the 'compressed' string would not become smaller than the
# original string, your method should return the original string. You can assume
# the string has only uppper and lower case letters (a - z)
import unittest
def compress(s):
# Base case: not compressible
# In other words, given string has only 1 of each letter
if len(s) == len(set(s)):
return s
# Build dictionary for the counts of each letter
counts = dict()
for i in range(len(s)):
if s[i] not in counts:
counts[s[i]] = 1
else:
counts[s[i]] += 1
result = ''
for d in counts:
result += str(d) + str(counts[d])
return result
class Test(unittest.TestCase):
def test_compress(self):
self.assertEqual(compress('abc'),'abc')
self.assertEqual(compress('abbcccdddd'),'a1b2c3d4')
if __name__ == '__main__':
unittest.main()
#
#
#s = 'abbcccdddd'
#counts = dict()
#for i in range(len(s)):
# if s[i] not in counts:
# counts[s[i]] = 1
# else:
# counts[s[i]] += 1
#
#result = ''
#for d in counts:
# result += str(d) + str(counts[d])
#
#print(result)
#
#print(str(counts))
#
#
#result.append('blah').append('hey')
#print(result) |
# Declaring tuple
tup = (2, 4, 6, 8)
# Displaying value
print(tup)
# Displaying Single value
print(tup[2])
# Updating by assigning new value
# tup[2] = 22
# Displaying Single value
# print(tup[2])
# Traceback (most recent call last):
# File "C:/Users/DattatrayaTembare/PycharmProjects/python-examples/src/python_basics/tuple_examples.py", line 10, in <module>
# tup[2] = 22
# TypeError: 'tuple' object does not support item assignment |
import os
print(f"{'*' * 10}Execute the command in a subshell{'*' * 10}")
for i in range(2, 6):
input_string = "python --version " + str(i)
os.system(input_string)
print(f"{'*' * 10}Execute the command in a subshell{'*' * 10}")
print(f"{'*' * 10}Use of format{'*' * 10}")
name = "Datta"
lname = "Tembare"
greeting = "Hello! {} {}"
greet = greeting.format(name, lname)
print(greet) # Hello Datta Tembare
name = "Swara"
greet = greeting.format(name, lname)
print(greet) # Hello Swara Tembare
print(f"{'*' * 10}Use of format{'*' * 10}")
# format
point = {'x': 4, 'y': -5}
print('{x} {y}'.format(**point)) # 4 -5
"""
The only difference is that, the str.format(**mapping) copies the dict whereas str.format_map(mapping)
makes a new dictionary during method call. This can be useful if you are working with a dict subclass.
"""
point = {'x': 4, 'y': -5}
print('{x} {y}'.format_map(point)) # 4 -5
point = {'x': 4, 'y': -5, 'z': 0}
print('{x} {y} {z}'.format_map(point)) # 4 -5 0
# Returns a tuple where the string is parted into three parts
txt = "I could eat bananas all day"
x = txt.partition("bananas")
print(x) # ('I could eat ', 'bananas', ' all day')
# Fills the string with a specified number of 0 values at the beginning
txt = "50"
x = txt.zfill(10)
print(x) # 0000000050
#################
print(f"{'*' * 10}Use of translate{'*' * 10}")
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)
str = "this is string example....wow!!!"
print(str.translate(trantab))
#################
a = 10
# print(f'something {(result:=a+2)}') # python3.8
print(f'something {(a + 2)}')
print(f'something {a + 2}')
print('something {a}'.format(a=10 + 2))
print('something {}'.format(a+2))
|
def sort_array(my_list):
"""sort array or bubble array,"""
for j in range(len(my_list) - 1):
for i in range(len(my_list) - j - 1):
if my_list[i] > my_list[i + 1]:
# temp = my_list[i]
# my_list[i] = my_list[i + 1]
# my_list[i + 1] = temp
my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i] # equivalent to above 3 lines
return my_list
print(sort_array(my_list=[52, 25, 27, 72, 81, 18, 35, 13, 8, 5]))
def sort_array_dec(my_list):
"""sort array or bubble array"""
for j in range(len(my_list) - 1):
for i in range(len(my_list) - j - 1):
if my_list[i] < my_list[i + 1]:
my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i]
return my_list
print(sort_array_dec(my_list=[52, 25, 27, 72, 81, 18, 35, 13, 8, 5]))
def binary_search_iterative(alist, n):
"""
Primarry requirement for binary search engine is provided list should be sorted
Time complexity of binary search tree is O(log (n))
"""
slist = sort_array(alist)
# Alternative sorts
# slist = sorted(alist)
# alist.sort() <- return None
first = 0
last = len(slist) - 1
while first <= last:
middle = (first + last) // 2
if n == slist[middle]:
return True
elif n < slist[middle]:
last = middle - 1
else:
first = middle + 1
return False
def binary_search_with_index(alist, n):
slist = sort_array(alist)
first = 0
last = len(slist) - 1
while first <= last:
middle = (first + last) // 2
if n == slist[middle]:
return True, alist.index(n)
elif n < slist[middle]:
last = middle - 1
else:
first = middle + 1
return False, None
def binary_search_recursive(slist, n, first, last):
if first > last:
return False
else:
middle = (first + last) // 2
if n == slist[middle]:
return True
elif n < slist[middle]:
return binary_search_recursive(slist, n, first=first, last=middle - 1)
else:
return binary_search_recursive(slist, n, first=middle + 1, last=last)
my_list = [52, 25, 27, 72, 81, 18, 35, 13, 8, 5]
print(sorted(my_list))
print(my_list[-1]) # last index
print(f'Number found in list {binary_search_iterative(my_list, 27)}')
print(f'Number found in list {binary_search_iterative(my_list, 72)}')
print(f'Number found in list {binary_search_iterative(my_list, 10)}')
print(f'Number found in list {binary_search_with_index(my_list, 27)}')
print(f'Number found in list {binary_search_with_index(my_list, 72)}')
print(f'Number found in list {binary_search_with_index(my_list, 10)}')
my_list = sorted(my_list)
print(f'Number found in list {binary_search_recursive(my_list, 27, 0, len(my_list) - 1)}')
print(f'Number found in list {binary_search_recursive(my_list, 72, 0, len(my_list) - 1)}')
print(f'Number found in list {binary_search_recursive(my_list, 10, 0, len(my_list) - 1)}')
|
# PYTHON: 3.8.2
# AUTHOR: Alex Moffat
# PURPOSE: Code Challenge
# Requirement: You are given an array of positive numbers from 1 to n, such that all numbers from 1 to n are present except one number (x). You have to find x. The input array is not sorted.
# =============================================================================
def missingNums(arg):
for i in range(len(arg)):
if (i + 1) not in arg:
print("x = {}".format(i + 1))
def missingNum(arg):
direct = (((len(arg)+1) * (len(arg)+2)) / 2) - sum(arg)
print("x = {:n}".format(direct))
# ========== MAIN
if __name__ == '__main__':
missingNums([3, 7, 1, 2, 8, 4, 5])
missingNum([3, 7, 1, 2, 8, 4, 5])
|
import numpy as np
from math import log
from numba import jit
from matplotlib import pyplot
import time
"""
Here is a Numba accelerated implementation of the Gillespie's algorithm that simulates stochastic processes with an example of its use on the SIR epidemiology model.
SIR is a model simulating how many people will be infected and will recovered from an infectious disease. Here is its diagram:
S -> I -> R
With S: susceptible population, I: infected population, R: recovered population <- 3 categories
Propensity/ Transition rate from S to I : alpha * PopulationOfS * PopulationOfI / TotalPopulation
Propensity/ Transition rate from I to R : beta * PopulationOfI
Stoichiometry of the first reaction: -1 to PopulationOfS and +1 to PopulationOfI
Stoichiometry of the second reaction: -1 to PopulationOfI and +1 to PopulationOfR
"""
@jit(nopython=True, cache= True)
def gillespie_direct(data, stoichiometry, iter, timestop=0):
"""
Inputs:
data: preallocated numpy array of size (n+1)xiter with n the number of categories of the stochastic system + 1 for the time. The first column is initialized with initial conditions
stoichiometry: numpy array of the size mxn with m the number of possible transitions and n the number of categories. The array is used to transfer units from one category to another when a transition is chosen
iter: max number of iteration the algorithm can do
timestop: optional, maximum time of the simulation.
propensity(i, d): user defined function which returns a numpy array with the propensities of length m
Output:
res: slice of the data array with the actual number of iterations done (algorithm can stop sooner than iter if no more possible transition),
warning: res refers to the same memory as data
See the example for proper initialisation of data stoichiometry and propensity()
"""
for i in range(iter-1):
if timestop>0:
if data[-1,i]>=timestop:
return data[:,:i]
propensities= propensity(i, data)
partition = np.sum(propensities)
if partition==0.0:
return data[:,:i]
r1=np.random.random()
sojourn = log(1.0 / r1) / partition
data[-1,i+1]= data[-1, i]+sojourn
indexes= np.argsort(propensities)
partition= np.random.random()*partition
for j in indexes:
partition-=propensities[j]
if partition<=0.0:
data[:-1,i+1]=data[:-1,i]+stoichiometry[j]
break
return data
"""
iter: max number of iteration the algorithm will execute
data: preallocated array upon which gillespie will work. Each row (except the last) stores the population of each category at a given time, the last row is used to store the time.
The first column must be initialized with the initial conditions.
Here S= 5480, I= 20, E= 0 and time = 0
"""
iter=20000
data= np.zeros((4,iter), dtype=float)
data[:, 0]=[5480.0,20.0,0.0,0.0] #intialiase data -> s i r time
"""
Array used to know how many units are transferred from one category to another for each reaction/transition
"""
stoichiometry = np.array([# s i r <- same column order than initial conditions and same line order as propensities
[ -1, 1, 0], # First row: S->I thus -1 for S, +1 for I and R not affected
[0, -1, 1],# Second row: I-> R thus -1 for I, +1 for R and S not affected
])
@jit(nopython=True, cache= True)
def propensity(i, d):
"""
user defined function
Input
i: current iteration
d: data array
Output:
1D Numpy array of length m, the number of possible transitions
Help for defining the function: put parameters of the stochastic process here
The order of the rows of the output array must be the same as the stoichiometry array.
Ex: The first reaction/transition is on row 0 of stoichiometry and its propensity (aka its transition rate) must be element 0 of this output array
Warning: this function must be Numba accelerated thus some python functionalities are unavailable
"""
# parameters
alpha = 2.0
beta = 1.0
N = 5500 # do not forget to update this number if you change initial population in data
return np.array([alpha * d[0][i] * d[1][i] / N, #S -> I at transition rate: alpha * S * I / N
beta * d[1][i]]) # I -> R at transition rate: beta * I
pyplot.figure(figsize=(10,10))
# make a subplot for the susceptible, infected and recovered individuals
axes_s = pyplot.subplot(311)
axes_s.set_ylabel("susceptible individuals")
axes_i = pyplot.subplot(312)
axes_i.set_ylabel("infected individuals")
axes_r = pyplot.subplot(313)
axes_r.set_ylabel("recovered individuals")
axes_r.set_xlabel("time (days)")
t1=time.time()
np.random.seed(1235)
timestop=200 #will end at 200 or sooner depending on iter
#execute 100 simulations of our stochastic process
for i in range(100):
res=gillespie_direct(data,stoichiometry, iter, timestop=timestop) # first column of data remains untouched, data can be reused for all simulations
axes_s.plot(res[-1], res[0], color="orange")
axes_i.plot(res[-1], res[1], color="orange")
axes_r.plot(res[-1], res[2], color="orange")
t2=time.time()
print(t2-t1)
pyplot.show()
|
# coding: utf8
'''
奇偶调序:
输入一个整数数组,调整数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。要求时间复杂度为O(n)。
'''
# 设置头尾两个指针, 分别从前往后和从后往前遍历数组, 当遇到头指针为偶数, 尾指针为奇数时交换它们
def odd_even_sort1(nums):
n = len(nums)
if n <= 1:
return nums
left, right = 0, n - 1
while left < right:
while nums[left] & 1 == 1:
left += 1
while nums[right] & 1 == 0:
right -= 1
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
return nums
# 维护两个指针i和j,一个指针指向数组的第一个数的前一个位置,我们称之为后指针i,向右移动;一个指针指向数组第一个数,称之为前指针j,也向右移动,
# 且前指针j先向右移动。如果前指针j指向的数字是奇数,则令i指针向右移动一位,然后交换i和j指针所各自指向的数字。
def odd_even_sort2(nums):
n = len(nums)
if n <= 1:
return nums
front, latter = -1, 0
while latter < n:
if nums[latter] & 1 == 1:
front += 1
nums[front], nums[latter] = nums[latter], nums[front]
latter += 1
return nums
if __name__ == '__main__':
print(odd_even_sort1([2, 44, 3, 6, 87, 1, 3, 5]))
print(odd_even_sort2([2, 44, 3, 6, 87, 1, 3, 5]))
'''
举一反三:
一个未排序整数数组,有正负数,重新排列使负数排在正数前面,并且要求不改变原来的正负数之间相对顺序.
比如: input: 1,7,-5,9,-12,15 ans: -5,-12,1,7,9,15 要求时间复杂度O(n),空间O(1)。
'''
# 详见: http://blog.csdn.net/v_july_v/article/details/7329314 |
'''
LintCode: http://www.lintcode.com/zh-cn/problem/find-minimum-in-rotated-sorted-array-ii/
160. 寻找旋转排序数组中的最小值 II
假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。
你需要找到其中最小的元素。
数组中可能存在重复的元素。
样例:
给出[4,4,5,6,7,0,1,2] 返回 0
'''
# 跟 findMin I 类似
# 因为可能存在重复的元素,所以在判断 num[left] >= num[mid] 之后
# 需要判断 left - mid 之间的元素是否相等,如果相等,那就说明最小元素在后半段
# 如果不相等,则说明最小元素在前半段
class Solution:
# @param num: a rotated sorted array
# @return: the minimum number in the array
def findMin(self, num):
# write your code here
n = len(num)
if n < 1:
return 0
left = 0
right = n - 1
while left < right:
if num[left] < num[right]:
return num[left]
mid = (left + right) / 2
if num[left] < num[mid]:
left = mid + 1
else:
flag = True
for i in range(left, mid + 1):
if num[left] != num[i]:
right = mid
flag = False
if flag:
left = mid + 1
return num[left] |
"""
4.
Hard
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
"""
from typing import List
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
n1, n2 = len(nums1), len(nums2)
if n1 > n2:
return self.findMedianSortedArrays(nums2, nums1)
k = (n1 + n2 + 1) // 2
l, r = 0, n1
while l < r:
m1 = l + (r - l) // 2 # number of elements used
m2 = k - m1
if nums1[m1] < nums2[m2 - 1]:
l = m1 + 1
else:
r = m1
m1 = l
m2 = k - m1
if m1 <= 0:
c11 = -float('inf')
else:
c11 = nums1[m1-1]
if m2 <= 0:
c12 = -float('inf')
else:
c12 = nums2[m2-1]
c1 = max(c11, c12)
if m1 >= n1:
c21 = float('inf')
else:
c21 = nums1[m1]
if m2 >= n2:
c22 = float('inf')
else:
c22 = nums2[m2]
c2 = min(c21, c22)
if (n1+n2) % 2 == 1:
return c1
return (c1 + c2) * 0.5
if __name__ == '__main__':
sol = Solution()
method = sol.findMedianSortedArrays
cases = [
(method, ([1, 3],[2]), 2),
(method, ([1, 2],[3, 4]), 2.5),
]
for i, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(i + 1))
else:
print("Case {:d} Failed; Expected {:s} != {:s}".format(i + 1, str(expected), str(ans))) |
"""
967.
A binary tree is univalued if every node in the tree has the same value.
Return true if and only if the given tree is univalued.
Easy
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isUnivalTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
elif root.left is None and root.right is None:
return True
elif root.left is None and root.right:
if root.val == root.right.val and self.isUnivalTree(root.right):
return True
elif root.left and root.right is None:
if root.val == root.left.val and self.isUnivalTree(root.left):
return True
else:
if root.val == root.left.val == root.right.val and \
self.isUnivalTree(root.left) and self.isUnivalTree(root.right):
return True
return False
if __name__ == '__main__':
# [3,3,3,null,null,2,3]
n1 = TreeNode(2)
n2 = TreeNode(2)
n3 = TreeNode(2)
n4 = TreeNode(2)
n5 = TreeNode(2)
n6 = TreeNode(5)
n1.left, n1.right = n2, n3
# n2.left, n2.right = n6, n4
n3.left, n3.right = n6, n4
sol = Solution()
print(sol.isUnivalTree(n1)) |
"""
946. Validate Stack Sequences
Given two sequences pushed and popped with distinct values, return true
if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Note:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
"""
class Solution:
def validateStackSequences(self, pushed: 'List[int]', popped: 'List[int]') -> 'bool':
"""
:param pushed:
:param popped:
:return:
Time complexity: O(n)
Space complexity: O(n)
"""
stack = []
j = 0
for i, _ in enumerate(pushed):
stack.append(pushed[i])
while stack and stack[-1] == popped[j]:
stack.pop()
j += 1
if j == len(popped):
return True
return False
if __name__=='__main__':
sol = Solution()
cases = [
(sol.validateStackSequences, ([1,2,3,4,5],[4,5,3,2,1]), True),
(sol.validateStackSequences, ([1,2,3,4,5],[4,3,5,1,2]), False),
]
for i, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(i + 1))
else:
print("Case {:d} Failed; Expected {:s} != Output {:s}".format(i+1, str(expected), str(ans)))
|
"""
"""
from math import sqrt
class Solution:
"""
@param n: a integer
@return: return a 2D array
"""
def getFactors(self, n):
def dfs(num, start):
res = []
for f in range(start, int(num)+1):
if f ** 2 > num:
break
if num % f == 0:
sub = dfs(num / f, f)
for s in sub:
res.append([int(f)]+s)
res.append([int(num)])
return res
ans = dfs(n, 2)
ans.pop()
return ans
sol = Solution()
print(sol.getFactors(32)) |
"""
739. Daily Temperatures
Given a list of daily temperatures T, return a list such that, for each day in the input,
tells you how many days you would have to wait until a warmer temperature.
If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73],
your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000].
Each temperature will be an integer in the range [30, 100].
"""
class Solution:
def dailyTemperatures(self, T):
"""
:param T:
:return:
Maintain the hottest and closest temperature up to this day in a stack.
if a day is father and cooler, it is removed since one can find a hotter and closer day
Iterate backwards
"""
ans = [0] * len(T)
stack = [] #indexes from hottest to coldest
for i in range(len(T) - 1, -1, -1):
while stack and T[i] >= T[stack[-1]]:
stack.pop()
if stack:
ans[i] = stack[-1] - i
stack.append(i)
return ans
def dailyTemperatures2(self, T):
days = [0]*len(T)
stack = []
for i, t in enumerate(T):
while stack and t > stack[-1][1]:
top = stack.pop()
days[top[0]] = i - top[0]
stack.append((i, t))
return days
if __name__ == '__main__':
sol = Solution()
method = sol.dailyTemperatures2
cases = [
(method, ([73, 74, 75, 71, 69, 72, 76, 73],), [1, 1, 4, 2, 1, 1, 0, 0]),
]
for i, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(i + 1))
else:
print("Case {:d} Failed; Expected {:s} != Output {:s}".format(i+1, str(expected), str(ans))) |
"""
873. Length of Longest Fibonacci Subsequence
Medium
1st: 2020-08-30
"""
from typing import List
from collections import defaultdict
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
inds = {x:i for i, x in enumerate(A)}
dp = defaultdict(lambda: 2)
ans = 0
for i, num in enumerate(A):
for j in range(i):
prev_elem_ind = inds.get(num - A[j], -1)
if prev_elem_ind >= 0 and prev_elem_ind < j:
dp[(i, j)] = dp[(j, prev_elem_ind)] + 1
ans = max(ans, dp[(i, j)])
return ans if ans >= 3 else 0
if __name__ == "__main__":
sol = Solution()
method = sol.lenLongestFibSubseq
cases = [
(method, ([1,2,3,4,5,6,7,8],), 5),
]
for i, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(i + 1))
else:
print("Case {:d} Failed; Expected {:s} != {:s}".format(i + 1, str(expected), str(ans))) |
"""
841. Keys and Rooms
There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, ..., N-1,
and each room may have some keys to access the next room.
Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1]
where N = rooms.length. A key rooms[i][j] = v opens the room with number v.
Initially, all the rooms start locked (except for room 0).
You can walk back and forth between rooms freely.
Return true if and only if you can enter every room.
Example 1:
Input: [[1],[2],[3],[]]
Output: true
Explanation:
We start in room 0, and pick up key 1.
We then go to room 1, and pick up key 2.
We then go to room 2, and pick up key 3.
We then go to room 3. Since we were able to go to every room, we return true.
Example 2:
Input: [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can't enter the room with number 2.
Note:
1 <= rooms.length <= 1000
0 <= rooms[i].length <= 1000
The number of keys in all rooms combined is at most 3000.
Time: O(n)
Space: O(n)
"""
from typing import List
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
number_of_rooms = len(rooms)
if number_of_rooms == 0:
return False
visited = set()
q = [0]
visited.clear()
visited.add(0)
while q:
top = q.pop(0)
for n in rooms[top]:
if n not in visited:
q.append(n)
visited.add(n)
if len(visited) == number_of_rooms:
return True
if len(visited) == number_of_rooms:
return True
else:
return False
if __name__ == '__main__':
sol = Solution()
cases = [
(sol.canVisitAllRooms, ([[1], [2], [3], []],), True),
(sol.canVisitAllRooms, ([[1, 3], [3, 0, 1], [2], [0]],), False),
(sol.canVisitAllRooms, ([[]],), True),
(sol.canVisitAllRooms, ([[1], [], [0,3], [1]],), False),
]
for k, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(k + 1))
else:
print("Case {:d} Failed; Expected {:s} != Output {:s}".format(k + 1, str(expected), str(ans)))
|
"""
665. Non-decreasing Array
Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.
We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).
Example 1:
Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.
Note: The n belongs to [1, 10,000].
"""
class Solution:
def checkPossibility(self, nums: 'List[int]') -> 'bool':
if len(nums) <= 1:
return True
count, first = 0, -1
for i in range(len(nums)-1):
if nums[i+1] < nums[i]:
if first < 0:
first = i
count += 1
if count > 1:
return False
if 0 < first < len(nums)-2:
if nums[first] > nums[first+2] and nums[first+1] < nums[first-1]:
return False
# elif first >= len(nums)-2:
# if nums[first+1] < nums[first-1]:
# return False
return True
def checkPossibility2(self, nums):
n = len(nums)
pos, pairs = 0, 0
for i, num in enumerate(nums):
if i < n - 1 and num > nums[i+1]:
pairs += 1
if pairs == 1:
pos = i
if pairs >= 2:
return False
if 0 < pos < n - 2 and nums[pos + 1] < nums[pos - 1] and nums[pos] > nums[pos+2]:
return False
return True
if __name__=='__main__':
sol = Solution()
method = sol.checkPossibility2
cases = [
(method, ([4,2,3],), True),
(method, ([4,2,1],), False),
(method, ([1,3,2],), True),
(method, ([1,2,4,5,3],), True),
(method, ([3,4,2,3],), False),
(method, ([-1,4,2,3],), True),
(method, ([2,3,3,2,4],), True),
]
for i, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(i + 1))
else:
print("Case {:d} Failed; Expected {:s} != {:s}".format(i+1, str(expected), str(ans))) |
"""
131. Palindrome Partitioning
Medium
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
from collections import defaultdict
class Solution:
def partition(self, s):
n = len(s)
if n == 1:
return [[s]]
res = []
def is_palindrome(seq):
for i in range(len(seq)):
if seq[i] != seq[len(seq) - i - 1]:
return False
return True
def dfs(start_index, curr):
if start_index == n:
res.append(curr[:])
return
for i in range(start_index+1, n+1):
if is_palindrome(s[start_index:i]):
curr.append(s[start_index:i])
dfs(i, curr)
curr.pop(-1)
dfs(0, [])
return res
def partition_faster(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
res = [[]]
for c in s:
for i in range(len(res)):
l = res[i]
if len(l)>0 and l[-1]==c:
res.append(l[:-1]+[c*2])
if len(l)>1 and l[-2]==c:
res.append(l[:-2]+[c+l[-1]+c])
res[i].append(c)
return res
if __name__ == '__main__':
sol = Solution()
cases = [
(sol.partition_faster, ("aab", ), [["aa","b"], ["a","a","b"]]),
(sol.partition, ("bb", ), [["b","b"], ["bb"]]),
]
for k, (func, case, expected) in enumerate(cases):
ans = func(*case)
if sorted(ans) == sorted(expected):
print("Case {:d} Passed".format(k + 1))
else:
print("Case {:d} Failed; Expected {:s} != Output {:s}".format(k+1, str(expected), str(ans))) |
"""
572.
Easy
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s.
A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
Example 1:
Given tree s:
3
/ \
4 5
/ \
1 2
Given tree t:
4
/ \
1 2
Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
3
/ \
4 5
/ \
1 2
/
0
Given tree t:
4
/ \
1 2
Return false.
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSubtree2(self, s: TreeNode, t: TreeNode) -> bool:
def help(s, t):
if not s and not t:
return True
if not s or not t:
return False
if s.val == t.val:
l = help(s.left, t.left)
r = help(s.right, t.right)
return l and r
if not s:
return False
return help(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
"""
Pre-order traversal to serialize the tree and then compare.
"""
def bfs(node,f,left=True):
if node:
f[0] += '#'+str(node.val)
bfs(node.left,f,True)
bfs(node.right,f,False)
else:
if left:
f[0] += 'ln'
else:
f[0] += 'rn'
finger1 = ['']
finger2 = ['']
bfs(s,finger1)
bfs(t,finger2)
print(finger1,finger2)
return finger2[0] in finger1[0] |
"""
350.
Easy
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
1. What if the given array is already sorted? How would you optimize your algorithm?
Ans: Use the binary search algorithm.
2. What if nums1's size is small compared to nums2's size? Which algorithm is better?
Ans: If arrays are not sorted, use the hash table solution.
3. What if elements of nums2 are stored on disk, and the memory is limited
such that you cannot load all elements into the memory at once?
Ans:
If only nums2 is too big for the memory, the hash table solution still works.
If both arrays are too big for the memory, use external sort to sort both arrays.
Load the arrays by chunk and run the two-pointer algorithm. If one array is exhausted,
load the next chunk from that array.
"""
import bisect
from collections import Counter
class Solution:
def intersect_hashtable(self, nums1, nums2):
"""
hash table solution.
Put nums1 in a hash table and check if each element in nums2 is in the hash table.
Time: O(m+n)
Space: O(m)
"""
m, n = len(nums1), len(nums2)
# assume nums2 is the longer array
if m > n:
return self.intersect(nums2, nums1)
c1 = Counter(nums1)
res = []
for num in nums2:
if num in c1:
# add to the result
res.append(num)
# update the count
c1[num] -= 1
if c1[num] == 0:
c1.pop(num)
return res
def intersect_two_pointer(self, nums1, nums2):
"""
Assume both arrays are sorted
Time: O(m+n)
Space: O(1)
"""
nums1.sort()
nums2.sort()
res = []
p1, p2 = 0, 0
m, n = len(nums1), len(nums2)
while p1 < m and p2 < n:
n1, n2 = nums1[p1], nums2[p2]
if n1 == n2:
res.append(n1)
p1 += 1
p2 += 1
elif n1 < n2:
p1 += 1
else:
p2 += 1
return res
def intersect_binary_search(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""
binary search if both arrays are already sorted.
for each element in the shorter array, find the first appearance in the longer array.
then move the lower bound of the binary search to avoid duplicates
Time: O(mlog(n))
Space: O(1)
"""
m, n = len(nums1), len(nums2)
# assume nums2 is the longer array
if m > n:
return self.intersect(nums2, nums1)
nums1.sort()
nums2.sort()
l2, h2 = 0, n
res = []
for n1 in nums1:
ind = self.find_first_element(nums2, n1, l2, h2)
if ind >= 0:
res.append(n1)
l2 = ind + 1
return res
def find_first_element(self, nums, target, lo, hi):
"""
Find the size of the subarray with value target between lo and hi
"""
l = bisect.bisect_left(nums, target, lo, hi)
if l < len(nums) and nums[l] == target:
return l
return -1 |
"""
211.
"""
class TrieNode:
def __init__(self):
self.children = {}
self.endofword = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
p = self.root
for w in word:
if w not in p.children:
p.children[w] = TrieNode()
p = p.children[w]
p.endofword = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
return self.search_helper(self.root, word)
def search_helper(self, root, word):
if root.endofword and not word:
return True
p = root
for i, w in enumerate(word):
if w == '.':
for key in p.children.keys():
p2 = p.children[key]
if self.search_helper(p2, word[1:]):
return True
else:
if w in p.children:
return self.search_helper(p.children[w], word[1:])
else:
return False
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.trie = Trie()
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
self.trie.insert(word)
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
return self.trie.search(word)
class WordDictionary2:
def __init__(self):
"""
Initialize your data structure here.
"""
self.wordMap = {}
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
currentMap = self.wordMap
for c in word:
if c not in currentMap:
currentMap[c] = {}
currentMap = currentMap[c]
currentMap["end"] = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
return self.searchRecursive(word, self.wordMap)
def searchRecursive(self, word: str, startingMap: dict) -> bool:
currentWordmap = startingMap
for i in range(len(word)):
if word[i] == ".":
for c in currentWordmap:
if c != "end":
if self.searchRecursive(word[i + 1:], currentWordmap[c]):
return True
return False
else:
if word[i] not in currentWordmap:
return False
currentWordmap = currentWordmap[word[i]]
return "end" in currentWordmap
if __name__ == '__main__':
wd = WordDictionary2()
wd.addWord('bad')
wd.addWord('dad')
wd.addWord('mad')
print(wd.search('pad'))
print(wd.search('bad'))
print(wd.search('.ad'))
print(wd.search('b..')) |
"""
20.
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
"""
class Solution:
def isValid(self, s: 'str') -> 'bool':
"""
:param s:
:return:
Time: O(n)
Space: O(n)
"""
stack = []
for c in s:
if c in "([{":
stack.append(c)
else:
if stack and stack[-1]+c in ("()","{}","[]"):
stack.pop()
else:
return False
if stack:
return False
return True
if __name__=='__main__':
sol = Solution()
cases = [
(sol.isValid, ("()[]{}",), True),
(sol.isValid, ("((",), False),
(sol.isValid, ("}}(",), False),
(sol.isValid, ("",), True),
]
for i, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(i + 1))
else:
print("Case {:d} Failed; Expected {:s} != Output {:s}".format(i+1, str(expected), str(ans)))
|
"""
852. Peak Index in a Mountain Array
Easy
Let's call an array A a mountain if the following properties hold:
A.length >= 3
There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
Given an array that is definitely a mountain, return any i such that
A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].
Example 1:
Input: [0,1,0]
Output: 1
Example 2:
Input: [0,2,1,0]
Output: 1
Note:
3 <= A.length <= 10000
0 <= A[i] <= 10^6
A is a mountain, as defined above.
"""
class Solution(object):
def peakIndexInMountainArray(self, A):
"""
:type A: List[int]
:rtype: int
"""
l, r = 0, len(A)-1
while l < r:
mid = int((l+r)/2)
if len(A) - 1 > mid > 0 and A[mid+1] < A[mid] > A[mid-1]: # solution condition
return mid
elif A[mid] < A[mid+1]: # otherwise, eliminate half
l = mid + 1
elif A[mid] < A[mid-1]:
r = mid - 1
return l
def peakIndexInMountainArray2(self, A):
"""
2020.02.23: Binary search.
"""
l, r = 0, len(A)
while l < r:
mid = l + (r - l) // 2
if A[mid-1] < A[mid] > A[mid+1]:
return mid
elif A[mid-1] <= A[mid] <= A[mid+1]:
l = mid
elif A[mid-1] >= A[mid] >= A[mid+1]:
r = mid
return l
if __name__ == '__main__':
sol = Solution()
method = sol.peakIndexInMountainArray2
cases = [
(method, ([0,2,1,0],), 1),
(method, ([0,3,2,1,0],), 1),
(method, ([0,1,0],), 1),
(method, ([0,1,2,3,4,2],), 4),
]
for i, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(i + 1))
else:
print("Case {:d} Failed; Expected {:s} != {:s}".format(i+1, str(expected), str(ans))) |
"""
501. Find Mode in Binary Search Tree
Given a binary search tree (BST) with duplicates, find all the mode(s)
(the most frequently occurred element) in the given BST.
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to the node's key.
The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
Both the left and right subtrees must also be binary search trees.
For example:
Given BST [1,null,2,2],
1
\
2
/
2
return [2].
Note: If a tree has more than one mode, you can return them in any order.
Follow up: Could you do that without using any extra space?
(Assume that the implicit stack space incurred due to recursion does not count).
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def get_num(self, root, value):
if not root:
return [[value], 0]
left = self.get_num(root.left, value)[1]
right = self.get_num(root.right, value)[1]
if root.val == value:
return [[value], left+right+1]
else:
return [[value], left+right]
def traverse(self, root):
if root:
cur = self.get_num(root, root.val)
left = self.traverse(root.left) if root.left else [[0], 0] # find the mode in left
right = self.traverse(root.right) if root.right else [[0], 0] # find the mode in right
# combine mode for root, left, and right
if cur[1] < left[1]:
cur = left
elif cur[1] == left[1]:
cur[0] += left[0]
if cur[1] < right[1]:
cur = right
elif cur[1] == right[1]:
cur[0] += right[0]
return cur
def findMode(self, root):
"""
Time: O(n)
Space: O(1)
Actual runtime is much slower than dfs
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
return self.traverse(root)[0]
def findMode_dfs(self, root):
"""
Time: O(n)
Space: O(n)
:param root:
:return:
use dfs
"""
if not root:
return []
nodes = {}
def dfs(root: TreeNode):
if not root:
return
if root.left:
dfs(root.left)
if root.val in nodes:
nodes[root.val] +=1
else:
nodes[root.val] = 1
if root.right:
dfs(root.right)
dfs(root)
modes, count = [], 0
for k, v in nodes.items():
if v == count:
modes.append(k)
if v > count:
modes.clear()
modes.append(k)
count = v
return modes
if __name__=='__main__':
sol = Solution()
n1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(2)
n4 = TreeNode(0)
n5 = TreeNode(0)
n6 = TreeNode(2147483647)
n1.left, n1.right = n4, n2
n2.left = n3
n4.left = n5
print(sol.findMode(n1))
# print(sol.findMode(n6)) |
"""
695. Max Area of Island
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land)
connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
Note: The length of each dimension in the given grid does not exceed 50.
Time: O(n)
Space: O(n)
"""
from typing import List
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
"""
DFS
Use a mutable to record the recursion depth (number of 1's found).
The return value is the depth. In cycle detection, the return value is bool
to indicate if a cycle is found
"""
if not grid:
return 0
m, n = len(grid), len(grid[0])
max_area = 0
# how to modify recursion depth and return it
def dfs(x, y, area):
if grid[x][y] == 1:
area[0] += 1
grid[x][y] = 0 # mark visited. A seperate matrix could be used if overwriting is not desired
if x + 1 < m and grid[x+1][y] == 1:
dfs(x+1, y, area)
if x - 1 >= 0 and grid[x - 1][y] == 1:
dfs(x - 1, y, area)
if y + 1 < n and grid[x][y+1] == 1:
dfs(x, y+1, area)
if y - 1 >= 0 and grid[x][y-1] == 1:
dfs(x, y-1, area)
return area[0]
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
area = dfs(i, j, [0])
max_area = max(max_area, area)
return max_area
if __name__ == '__main__':
sol = Solution()
cases = [
(sol.maxAreaOfIsland, (
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]],
), 6),
(sol.maxAreaOfIsland, ([[0,0,0,0,0,0,0,0]],), 0),
]
for k, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(k + 1))
else:
print("Case {:d} Failed; Expected {:s} != Output {:s}".format(k + 1, str(expected), str(ans))) |
"""
152.
Medium
Given an integer array nums, find the contiguous subarray within an array (containing at least one number)
which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
2019.08.03
"""
class Solution:
def maxProduct(self, nums: List[int]) -> int:
"""
:param nums:
:return:
dp_max[i]: max subarray product using element i
dp_min[i]: min subarray product using element i
Time: O(n); Space: O(n)
"""
n = len(nums)
min_product, max_product = [0]*n, [0]*n
min_product[0], max_product[0] = nums[0], nums[0]
ans = 0
for j in range(1, n):
max_product[j] = max(nums[j], min_product[j-1]*nums[j], max_product[j-1]*nums[j])
min_product[j] = min(nums[j], max_product[j-1]*nums[j], min_product[j-1]*nums[j])
ans = max(ans, max_product[j])
return ans
|
"""
21. Merge Two Sorted Lists (Easy)
Merge two sorted linked lists and return it as a new list.
The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, self.next) # self.next is converted and it triggers recursive calls
class Solution:
def traverse(self, l):
res = []
while l:
res.append(l.val)
l = l.next
return res
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1 and not l2:
return None
res = ListNode(0)
it1 = l1
it2 = l2
it3 = res
while it1 and it2:
if it1.val < it2.val:
it3.val = it1.val
it1 = it1.next
else:
it3.val = it2.val
it2 = it2.next
it3.next = ListNode(0)
it3 = it3.next
while it1 and it2 is None:
it3.val = it1.val
it1 = it1.next
if it1:
it3.next = ListNode(0)
it3 = it3.next
while it2 and it1 is None:
it3.val = it2.val
it2 = it2.next
if it2:
it3.next = ListNode(0)
it3 = it3.next
return res
def mergeTwoLists2(self, l1, l2):
curr = dummy = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
curr.next = l1 or l2
return dummy.next
if __name__ == "__main__":
sol = Solution()
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(4)
n1.next = n2
n2.next = n3
n4 = ListNode(1)
n5 = ListNode(3)
n6 = ListNode(5)
n4.next = n5
n5.next = n6
print(n1)
print(n4)
print(sol.mergeTwoLists(n1, n4))
print(sol.mergeTwoLists2(n1, n4))
|
"""
220. medium
Given an array of integers, find out whether there are two distinct indices i and j in the array such that
the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j
is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
2019.02.07 Reviewed; Group numbers into ranges with centers at t, 2t, 3t...,
"""
import bisect
class Solution:
def containsNearbyAlmostDuplicate_brute_force(self, nums, k, t):
"""
:type nums: List[int]
:type k: int
:type t: int
:rtype: bool
"""
for i, _ in enumerate(nums):
for d in range(-k, k+1):
if d != 0 and i+d >= 0 and i+d < len(nums):
if abs(nums[i] - nums[i+d]) <=t:
return True
return False
def containsNearbyAlmostDuplicate(self, nums, k, t):
window = []
for i, num in enumerate(nums):
ind = bisect.bisect_left(window, num)
window.insert(ind, num)
if len(window) > k+1:
pop_ind = bisect.bisect_left(window, nums[i-k-1])
window.pop(pop_ind)
if ind > 0:
ind -= 1
if len(window) > 1:
if ind + 1 >= len(window):
if abs(window[ind] - window[ind-1]) <= t:
return True
elif ind - 1 < 0:
if abs(window[ind] - window[ind+1]) <= t:
return True
else:
if abs(window[ind] - window[ind+1]) <= t or abs(window[ind] - window[ind-1]) <= t:
return True
return False
def containsNearbyAlmostDuplicate_solution(self, nums, k: int, t: int) -> bool:
if t == 0 and len(nums) == len(set(nums)):
return False
for i, val in enumerate(nums):
for j in range(i + 1, i + k + 1):
if j >= len(nums):
break
if abs(nums[j] - val) <= t:
return True
return False
if __name__ == '__main__':
# cases = [
# ([1, 2, 3, 1], 3, 0),
# ([1,0,1,1], 1, 2),
# (),
# ([3,6,0,4], 2, 2),
# ]
sol = Solution()
method = sol.containsNearbyAlmostDuplicate
cases = [
# (method, ([1, 2, 3, 1], 3, 0,), True),
# (method, ([1,5,9,1,5,9], 2, 3), False),
(method, ([1, 2, 3, 1], 1, 0,), False),
]
for i, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(i + 1))
else:
print("Case {:d} Failed; Expected {:s} != Output {:s}".format(i+1, str(expected), str(ans))) |
"""
1425.
Hard
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
2020.05.07: TLE then pass with hints
2020.05.31: 2nd attempt
"""
from typing import List
from collections import deque
class MaxWindow:
def __init__(self, k):
self.k = k
self.maxd = deque()
def add(self, x):
while self.maxd and x > self.maxd[-1]:
self.maxd.pop()
self.maxd.append(x)
def remove(self, removed):
if removed is not None and self.maxd[0] == removed:
self.maxd.popleft()
def get_max(self):
return self.maxd[0]
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
m = len(nums)
# dp[i] max. sum of the seq. for array ending at i including element i
dp = [-float('inf') for _ in range(m)]
dp[0] = nums[0]
maxd = deque()
maxd.append(dp[0])
def max_prev_k(new, maxd, remove=None):
while maxd and new > maxd[-1]:
maxd.pop()
maxd.append(new)
if remove is not None:
if maxd[0] == remove:
maxd.popleft()
for i in range(1, m):
dp[i] = nums[i] + max(0, maxd[0])
# get the maximum of the previous k dp values
if i < k:
max_prev_k(dp[i], maxd)
else:
max_prev_k(dp[i], maxd, dp[i-k])
return max(dp)
def constrainedSubsetSum2(self, nums: List[int], k: int) -> int:
"""
dp[i] is the max sum for the elements including i.
state transition: max(dp[i-1], dp[i-2], ... dp[i-k])
use a sliding window to reduce the time complexity to constant time by recording the
max solution before dp[i]
Time complexity: O(n), Space: O(n)
"""
n = len(nums)
dp = [-float('inf') for _ in range(n)]
dp[0] = nums[0]
window = MaxWindow(k+1) # maximum k+1 elements in the window
window.add(dp[0])
for i in range(1, n):
if i > k:
window.remove(removed=dp[i-k-1])
curr_max = window.get_max()
dp[i] = max(dp[i], nums[i], curr_max+nums[i])
window.add(dp[i])
return max(dp)
if __name__ == '__main__':
sol = Solution()
method = sol.constrainedSubsetSum2
cases = [
# (method, ([10,2,-10,5,20],2), 37),
(method, ([10,-2,-10,-5,20],2), 23),
]
for i, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(i + 1))
else:
print("Case {:d} Failed; Expected {:s} != {:s}".format(i + 1, str(expected), str(ans))) |
"""
81. Search in Rotated Sorted Array II
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
Follow up:
This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
Would this affect the run-time complexity? How and why?
"""
from typing import List
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
res = False
if not nums:
return False
pivot = self.find_pivot(nums, 0, len(nums)-1)
if pivot == -1 or pivot == len(nums)-1:
res = self.binary_search(nums, target, 0, len(nums) - 1)
elif nums[pivot] == target:
res = pivot
else:
if nums[0] <= target:
res = self.binary_search(nums, target, 0, pivot)
else:
res = self.binary_search(nums, target, pivot+1, len(nums)-1)
return res >= 0
def binary_search(self, nums, target, low, high):
"""
Standard binary search in an array with distinct elements
:param nums:
:param target:
:param low:
:param high:
:return:
"""
while low <= high:
mid = int((low + high) / 2) # floor
if nums[mid] == target:
return mid
elif nums[mid] > target:
high = mid - 1
else:
low = mid + 1
return -1
def find_pivot(self, nums, low, high):
"""
find the index of the pivot element in the array;
:param nums:
:param low:
:param high:
:return:
for [3, 4, 5, 6, 1, 2]. return 3 (the index of 6)
if it is fully sorted, return the last element
"""
if low > high:
return -1
if low == high:
return low
mid = int((low+high)/2)
if mid < high and nums[mid] > nums[mid+1]:
return mid
elif mid > low and nums[mid] < nums[mid-1]:
return mid-1
elif nums[mid] < nums[low]:
return self.find_pivot(nums, low, mid-1)
elif nums[mid] == nums[low]:
return self.find_pivot(nums, low+1, high)
else:
return self.find_pivot(nums, mid+1, high)
def search2(self, nums: List[int], target: int) -> int:
"""
Binary search. When there are duplicates, the sorted half cannot be identified when nums[0] == nums[mid].
Therefore, the left pointer can only be moved to the right by 1 instead of moving to mid
"""
if not nums:
return False
l, r = 0, len(nums) - 1
while l <= r:
mid = l + (r - l) // 2
if nums[mid] == target:
return True
if nums[l] < nums[mid]:
# left half is the sorted array and right half rotated array
if nums[l] <= target < nums[mid]:
r = mid - 1
else:
l = mid + 1
elif nums[l] > nums[mid]:
if nums[mid] < target <= nums[r]:
l = mid + 1
else:
r = mid - 1
else:
l += 1
return False
if __name__=='__main__':
sol = Solution()
method = sol.search2
cases = [
# (sol.find_pivot, ([3,4,5,6,7,1,2], 0, 6), 4),
# (sol.find_pivot, ([1,2,3,4], 0, 3), 3),
# (sol.find_pivot, ([1,1,3], 0, 2), 2),
# (sol.find_pivot, ([3,3,1], 0, 2), 1),
# (sol.find_pivot, ([3,3,3], 0, 2), 2),
# (sol.find_pivot, ([3,3,1,2,3], 0, 4), 1),
# (sol.binary_search, ([1,2,3,4], 2, 0, 3), 1),
# (sol.binary_search, ([1,2,3,4], 5, 0, 3), -1),
# (sol.binary_search, ([1,2,3,4], 0, 0, 3), -1),
# (sol.binary_search, ([1], 0, 0, 0), -1),
# (sol.binary_search, ([1], 1, 0, 0), 0),
# (sol.binary_search, ([1, 1, 3], 3, 0, 2), 2),
# (method, ([4,5,6,7,0,1,2], 0), True),
# (method, ([4,5,6,7,0,1,2], 3), False),
# (method, ([], 3), False),
# (method, ([1], 1), True),
# (method, ([1,1,3], 3), True),
# (method, ([3,1], 3), True),
# (method, ([2,5,6,0,0,1,2], 0), True),
# (method, ([2,5,6,0,0,1,2], 3), False),
(method, ([1,1,2,1,1,1,1,1,1], 2), True),
# (method, ([1]*4+[2]+[1]*8, 2), True),
]
for i, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(i + 1))
else:
print("Case {:d} Failed; Expected {:s} != {:s}".format(i+1, str(expected), str(ans)))
|
"""
1428.
Medium
1425. Constrained Subsequence Sum
1358. Number of Substrings Containing All Three Characters
1248. Count Number of Nice Subarrays
1234. Replace the Substring for Balanced String
1004. Max Consecutive Ones III
930. Binary Subarrays With Sum
992. Subarrays with K Different Integers
904. Fruit Into Baskets
862. Shortest Subarray with Sum at Least K
239. Sliding window maximum
209. Minimum Size Subarray Sum
"""
import collections
from typing import List
class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
i = 0
maxd = collections.deque() # between i and current, all the possible max for subarrays including current element
mind = collections.deque()
for a in nums:
while len(maxd) and a > maxd[-1]: maxd.pop()
while len(mind) and a < mind[-1]: mind.pop()
maxd.append(a)
mind.append(a)
while maxd[0] - mind[0] > limit:
if maxd[0] == nums[i]: maxd.popleft() # shrink the window and maintain the min and max
if mind[0] == nums[i]: mind.popleft()
i += 1
return len(nums) - i
if __name__ == '__main__':
sol = Solution()
method = sol.longestSubarray
cases = [
(method, ([10,1,2,4,7,2,5],5), 5),
]
for i, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(i + 1))
else:
print("Case {:d} Failed; Expected {:s} != {:s}".format(i + 1, str(expected), str(ans))) |
"""
LC-460
Hard
Design and implement a data structure for Least Frequently Used (LFU) cache.
It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reaches its capacity,
it should invalidate the least frequently used item before inserting a new item. For the purpose of this problem,
when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted.
Note that the number of times an item is used is the number of calls to the get and put functions for that item
since it was inserted. This number is set to zero when the item is removed.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LFUCache cache = new LFUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.get(3); // returns 3.
cache.put(4, 4); // evicts key 1.
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
################ History #####################
Number of Attempts: 1
Most Recent Attenpt: 2021.04
Similar Problems:
LC-146
Concepts:
doubly-linked list
hashtable
"""
class ListNode:
def __init__(self, key=None, value=None, freq=0):
self.key = key
self.value = value
self.freq = freq
self.prev = None
self.next = None
def __repr__(self):
return self.__class__.__name__ + f"(key={self.key}, value={self.value}, freq={self.freq})"
class DoublyLinkedList:
def __init__(self):
self.head = ListNode()
self.tail = ListNode()
self.head.next = self.tail
self.tail.prev = self.head
def insert_front(self, node: ListNode):
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
def remove(self, node):
'''
Remove node from the list from any place
'''
prev_node = node.prev
next_node = node.next
prev_node.next = next_node
next_node.prev = prev_node
def move_to_front(self, node):
'''
Move a node to the front of the linked list
'''
self.remove(node)
self.insert_front(node)
def remove_last_node(self):
'''
Remove the last node and return the removed node
'''
node = self.tail.prev
self.remove(node)
return node
def back(self):
return self.tail.prev
def is_empty(self):
if self.head.next == self.tail:
return True
return False
class LFUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.items = {} # key -> node
self.freq_list = {} # freq: -> a linked list of nodes
self.min_freq = 0
def __len__(self):
return len(self.items)
def get(self, key: int) -> int:
if key not in self.items:
return -1
else:
item = self.items[key]
self.touch(item)
return item.value
def put(self, key: int, value: int) -> None:
if self.capacity == 0:
return
if key not in self.items:
if len(self) == self.capacity:
# remove the least recently used item in the linked list for the min_freq
removed_item = self.freq_list[self.min_freq].remove_last_node()
if self.freq_list[self.min_freq].is_empty():
_ = self.freq_list.pop(self.min_freq)
self.min_freq += 1
self.items.pop(removed_item.key)
item = ListNode(key=key, value=value, freq=1)
self.items[key] = item
self.insert_item_to_freq_list(item)
self.min_freq = 1
else:
item = self.items[key]
item.value = value
self.touch(item)
def insert_item_to_freq_list(self, item:ListNode):
if item.freq not in self.freq_list:
self.freq_list[item.freq] = DoublyLinkedList()
self.freq_list[item.freq].insert_front(item)
def touch(self, item:ListNode):
"""
Increase the freq for the item
"""
prev_freq = item.freq
_ = self.freq_list[prev_freq].remove(item)
if self.freq_list[prev_freq].is_empty() and prev_freq == self.min_freq:
_ = self.freq_list.pop(prev_freq)
self.min_freq += 1
freq = prev_freq + 1
item.freq = freq
self.insert_item_to_freq_list(item)
if __name__ == '__main__':
cache = LFUCache(2)
cache.put(1, 1)
cache.put(2, 2)
print(cache.get(1)) # returns 1
cache.put(3, 3) # evicts key 2
print(cache.get(2)) # returns -1 (not found)
print(cache.get(3)) # returns 3.
cache.put(4, 4) # evicts key 1.
print(cache.get(1)) # returns -1 (not found)
print(cache.get(3)) # returns 3
print(cache.get(4)) # returns 4 |
"""
496
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2.
Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2.
If it does not exist, output -1 for this number.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
Note:
All elements in nums1 and nums2 are unique.
The length of both nums1 and nums2 would not exceed 1000.
"""
class Solution:
def nextGreaterElement(self, nums1: 'List[int]', nums2: 'List[int]') -> 'List[int]':
lookup = {}
stack = []
for n in nums2:
while stack and stack[-1] < n:
lookup[(stack[-1])] = n
stack.pop()
stack.append(n)
return [lookup.get(n, -1) for n in nums1]
if __name__=='__main__':
sol = Solution()
cases = [
(sol.nextGreaterElement, ([2,4],[2,1,5,4]), [5,-1]),
(sol.nextGreaterElement, ([4,1,2], [1,3,4,2]), [-1,3,-1]),
]
for i, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(i + 1))
else:
print("Case {:d} Failed; Expected {:s} != Output {:s}".format(i+1, str(expected), str(ans))) |
"""
973. K Closest Points to Origin
Medium
We have a list of points on the plane. Find the K closest points to the origin (0, 0).
(Here, the distance between two points on a plane is the Euclidean distance.)
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)
Example 1:
Input: points = [[1,3],[-2,2]], K = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].
Example 2:
Input: points = [[3,3],[5,-1],[-2,4]], K = 2
Output: [[3,3],[-2,4]]
(The answer [[-2,4],[3,3]] would also be accepted.)
Note:
1 <= K <= points.length <= 10000
-10000 < points[i][0] < 10000
-10000 < points[i][1] < 10000
"""
from typing import List
import heapq
from math import sqrt
class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
kclosest = []
kclosest.append((self.dist(points[0]), [points[0][0], points[0][1]]))
for k in range(1, len(points)):
if len(kclosest) < K:
d = self.dist(points[k])
kclosest.append((self.dist(points[k]), [points[k][0], points[k][1]]))
heapq._siftup_max(kclosest, -1)
elif abs(points[k][0]) < abs(kclosest[0][1][0]) and abs(points[k][1]) < abs(kclosest[0][1][1]):
d = self.dist(points[k])
heapq._heappop_max(kclosest)
kclosest.append((self.dist(points[k]), [points[k][0], points[k][1]]))
heapq._siftup_max(kclosest, -1)
elif abs(points[k][0]) >= abs(kclosest[0][1][0]) and abs(points[k][1]) >= abs(kclosest[0][1][1]):
continue
else:
d = self.dist(points[k])
if d < kclosest[0][0]:
heapq._heappop_max(kclosest)
kclosest.append((self.dist(points[k]), [points[k][0], points[k][1]]))
heapq._siftup_max(kclosest, -1)
res = []
for p in kclosest:
res.append(p[1])
return res
def dist(self, point):
return sqrt(point[0]**2 + point[1]**2)
def kClosest2(self, points: List[List[int]], K: int) -> List[List[int]]:
pass
if __name__ == '__main__':
sol = Solution()
method = sol.kClosest
cases = [
# (method, ([[1,3],[-2,2]], 1), [[-2,2]]),
(method, ([[-5,4],[-6,-5],[4,6]], 2), [[-5,4],[4,6]]),
]
for i, (func, case, expected) in enumerate(cases):
ans = func(*case)
if ans == expected:
print("Case {:d} Passed".format(i + 1))
else:
print("Case {:d} Failed; Expected {:s} != Output {:s}".format(i + 1, str(expected), str(ans))) |
"""
282.
Given a string that contains only digits 0-9 and a target value,
return all possibilities to add binary operators (not unary) +, -, or *
between the digits so they evaluate to the target value.
Example 1:
Input: num = "123", target = 6
Output: ["1+2+3", "1*2*3"]
Example 2:
Input: num = "232", target = 8
Output: ["2*3+2", "2+3*2"]
Example 3:
Input: num = "105", target = 5
Output: ["1*0+5","10-5"]
Example 4:
Input: num = "00", target = 0
Output: ["0+0", "0-0", "0*0"]
Example 5:
Input: num = "3456237490", target = 9191
Output: []
"""
class Solution:
def addOperators(self, num: 'str', target: 'int') -> 'List[str]':
N = len(num)
answers = []
def recurse(index, prev_operand, current_operand, value, string):
# Done processing all the digits in num
if index == N:
# If the final value == target expected AND
# no operand is left unprocessed
if value == target and current_operand == 0:
answers.append("".join(string[1:]))
return
# Extending the current operand by one digit
current_operand = current_operand*10 + int(num[index])
str_op = str(current_operand)
# To avoid cases where we have 1 + 05 or 1 * 05 since 05 won't be a
# valid operand. Hence this check
if current_operand > 0:
# NO OP recursion
recurse(index + 1, prev_operand, current_operand, value, string)
# ADDITION
string.append('+')
string.append(str_op)
recurse(index + 1, current_operand, 0, value + current_operand, string)
string.pop()
string.pop()
# Can subtract or multiply only if there are some previous operands
if string:
# SUBTRACTION
string.append('-')
string.append(str_op)
recurse(index + 1, -current_operand, 0, value - current_operand, string)
string.pop()
string.pop()
# MULTIPLICATION
string.append('*')
string.append(str_op)
recurse(index + 1, current_operand * prev_operand, 0, value - prev_operand + (current_operand * prev_operand), string)
string.pop()
string.pop()
recurse(0, 0, 0, 0, [])
return answers
if __name__ == '__main__':
sol = Solution()
cases = [
# (sol.addOperators, ("115", 115), ["115"]),
(sol.addOperators, ("1051", 1), ["10+5"]),
]
for k, (func, case, expected) in enumerate(cases):
ans = func(*case)
if sorted(ans) == sorted(expected):
print("Case {:d} Passed".format(k + 1))
else:
print("Case {:d} Failed; Expected {:s} != Output {:s}".format(k+1, str(expected), str(ans)))
|
"""
1286.
Medium
Design an Iterator class, which has:
A constructor that takes a string characters of sorted distinct lowercase English letters and
a number combinationLength as arguments.
A function next() that returns the next combination of length combinationLength in lexicographical order.
A function hasNext() that returns True if and only if there exists a next combination.
Example:
CombinationIterator iterator = new CombinationIterator("abc", 2); // creates the iterator.
iterator.next(); // returns "ab"
iterator.hasNext(); // returns true
iterator.next(); // returns "ac"
iterator.hasNext(); // returns true
iterator.next(); // returns "bc"
iterator.hasNext(); // returns false
Constraints:
1 <= combinationLength <= characters.length <= 15
There will be at most 10^4 function calls per test.
It's guaranteed that all calls of the function next are valid.
2019.04.28: How to use generator in recursion
"""
class CombinationIterator:
def __init__(self, characters: str, combinationLength: int):
self.gen = self.combination(characters, combinationLength)
self.buffer = next(self.gen)
def next(self) -> str:
res = self.buffer
try:
self.buffer = next(self.gen)
except StopIteration:
self.buffer = None
return res
def hasNext(self) -> bool:
return self.buffer is not None
def combination(self, s, n):
if n==1:
for ch in s:
yield ch
else:
for i in range(len(s)-n+1):
for comb in self.combination(s[i+1:],n-1):
yield s[i]+comb |
#!/usr/bin/python3
import re
def main():
with open("./input.txt", 'r') as file:
sum = 0
for line in file:
sum += int(line)
print(sum)
if __name__ == "__main__":
main() |
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
count_odd = 0
count_even = 0
for x in numbers:
if not x % 2:
count_even+=1
else:
count_odd+=1
print("number of even numbers:",count_even)
print("number of odd numbers:",count_odd)
number of even numbers: 0
number of odd numbers: 1
number of even numbers: 1
number of odd numbers: 2
number of even numbers: 2
number of odd numbers: 3
number of even numbers: 3
number of odd numbers: 4
number of even numbers: 4
number of odd numbers: 5 |
# Creating a Sets.
# Normal Set Declaration
farm_animals = {"Cow", "Sheep", "Buffalo"}
print(farm_animals)
for animals in farm_animals:
print(animals)
print("*" * 80)
# Set Constructor Method to Declare Sets
wild_animals = set(["lion", "tiger", "panther", "Deer"]) # We can pass there tuple, tuple and range
print(wild_animals)
for animals2 in wild_animals:
print(animals2)
print()
# Creating Empty Set
empty_set= set()
empty_set.add("Horse")
# empty_set2 = {}
# empty_set2.add("Horse") # This line will cause an error cause when we declared our emptry_set2 it became dict.
# So there is only one way to declare a empty set and that is set constructor method
# Passing tuple and list and range in set constructor method
demo1 = set(("hare","here","hire"))
demo2 = set(("hare","here","hire"))
demo3 = set(range(2,20,8))
print(demo1,demo2,demo3) |
locations = {0: "You are sitting in front of a computer learning Python",
1: "You are standing at the end of a road before a small brick building",
2: "You are at the top of a hill",
3: "You are inside a building, a well house for a small stream",
4: "You are in a valley beside a stream",
5: "You are in the forest"}
exits = [{"Q": 0},
{"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0}, # road
{"N": 5, "Q": 0}, # Hill
{"W": 1, "Q": 0}, # BUilding
{"N": 1, "W": 2, "Q": 0}, # Valley
{"W": 2, "S": 1, "Q": 0}] # Forest
# Explanation : IN the next line it is being writen that loc = 1 .why that is..cz our exits is a list of dictionaries
# and we are using index position 1 for our all available exits . so it is WESNQ
loc = 1 # We are starting from road that's why its =1
while True:
availableExits = ", ".join(exits[loc].keys())
# Here join method is used to join all our available keys as a single string so that we could compare our input entries
print(locations[loc]) # [loc=1]this prints index 1 entries for location
if loc == 0:
break
direction = input("Available exits are " + availableExits + " ").upper()# Upper converts the input in the upper case
print()
if direction in exits[loc]: # if the provided input is in the exits[loc=1] so it will update the value of loc
loc = exits[loc][direction] # here value of loc is being updated using nested indexing technique
#here loc[loc=1][direction = whatever input is being provided] we can use the key and direction to retrieve the next location.
# so there is another doubt arises that may be indexing used in a dict can cause a problem cz it is unordered
# but remember that it is'nt a issue cz it's nested inside a list so it is ordered
else:
print("You cannot go in that direction")
|
import tkinter
from tkinter import *
from tkinter import messagebox
import tkinter.filedialog as tkabrir
import os
import math
global n
def regla_traprecio(h, n, f):
return (h/2) * (f[n-1] + f[n])
def sim38(h, f0, f1, f2, f3):
return (3/8) * h * (f0 + (3 * f1) + (3 * f2) + f3)
def sim13mul(h, n, f):
sum = f[0]
for i in range(1, n-1, 2):
sum = sum + (4 * f[i]) + (2 * f[i+1])
sum = sum + (4 * f[n-1]) + f[n]
return (h/3)*sum
def newton_cotes_equal(x, fx):
n = len(fx) - 1
a = x[0] * 1.0
b = x[n] * 1.0
h = (b-a)/n
sum = 0.0
if n == 1:
sum = regla_traprecio(h, n, fx)
print("trapecio: ", sum)
else:
m = n
odd = math.fmod(n, 2)
if odd > 0 and n > 1:
sum = sum + sim38(h, fx[n-3], fx[n-2], fx[n-1], fx[n])
print("simspon 3/8: ", sum)
m = n-3
if m > 1:
sum = sum + sim13mul(h, m, fx)
print("simspon 1/3: ", sum)
return sum
def newton_cotes_unequal(x, fx):
n = len(x) - 1
current_h = float (x[1] - x[0])
ultima_procesada = 0
pos_actual = 1
res = 0.0
for i in range(1, n+1):
if i < n:
new_h = round(x[i+1] - x[i], 4)
if new_h == current_h:
pos_actual += 1
else:
print("x0 ", x[ultima_procesada], " xi ", x[pos_actual])
res = res + newton_cotes_equal(x[ultima_procesada:(pos_actual+1)], fx[ultima_procesada:(pos_actual+1)])
ultima_procesada = pos_actual
pos_actual += 1
current_h = new_h
else:
print("x0 ", x[ultima_procesada], " xi ", x[pos_actual])
res = res + newton_cotes_equal(x[ultima_procesada:(pos_actual+1)], fx[ultima_procesada:(pos_actual+1)])
return res
def leerArchivo(file,n):
try:
f = open(file, "r")
v = []
row = f.readline().split()
for i in range(n):
v.append(float(row[i]))
# Cerramos el archivo.
f.close()
return v
except ValueError as e:
messagebox.showinfo("ERROR FATAL","Ingresaste un dato no válido, trataste de ingresar un archivo que no era de texto o dejaste vacío el campo de tamaño. Verifica tus datos"), e
except IndexError as e:
messagebox.showinfo("ERROR FATAL","El vector está incompleto, no corresponde a la entrada del tamaño o es un archivo incorrecto. Verifica tus datos."), e
def cargar_vector1():
try:
global x
global n
integer_n = int(n.get())
if (integer_n == 0):
messagebox.showinfo("ERROR FATAL","Error. No pueden haber 0 conjuntos")
raise Exception("Error. No pueden haber 0 conjuntos")
file = tkinter.filedialog.askopenfilename()
x = leerArchivo(file,integer_n)
except:
messagebox.showinfo("ERROR FATAL","No pude abrir el archivo. Intenta de nuevo"), e
def cargar_vector2():
try:
global y
global n
integer_n = int(n.get())
if (integer_n == 0):
messagebox.showinfo("ERROR FATAL","Error. No pueden haber 0 conjuntos")
raise Exception("Error. No pueden haber 0 conjuntos")
file = tkinter.filedialog.askopenfilename()
y = leerArchivo(file,integer_n)
except:
messagebox.showinfo("ERROR FATAL","No pude abrir el archivo. Intenta de nuevo"), e
def boton():
try:
global n
integer_n = int(n.get())
integer_n = int(n.get())
if (integer_n == 0):
messagebox.showinfo("ERROR FATAL","Error. No pueden haber 0 conjuntos")
raise Exception("Error. No pueden haber 0 conjuntos")
resultado = newton_cotes_unequal(x,y)
textito = "El resultado es: " + str(resultado)
messagebox.showinfo("Respuesta",textito)
except:
messagebox.showinfo("ERROR FATAL","Hay un error con los datos o dejaste campos vacíos")
def instrucciones():
top = Toplevel()
top.title("Instrucciones")
top.resizable(False,False)
top.geometry("480x400")
top.config(bg="deepskyblue4")
label = Label(top,text="Instrucciones")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue2", #fondo para todas la GUI
font=("Courier",20)) #tipo de letra
label.place(x=130,y=15)
label = Label(top,text="Para el uso de este método deberás ingresar dos")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=55)
label = Label(top,text="vectores con los valores de los puntos en x y f(x)" )
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=75)
label = Label(top,text="respectivamente en archivos .txt. Las puntos")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=95)
label = Label(top,text=" (x,f(x)) deben estar en la misma posicion en sus")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=115)
label = Label(top,text="respectivos archivos (uno para x y otro para f(x)).")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=135)
label = Label(top,text="Los datos deben estar separados solo por un")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=155)
label = Label(top,text="espacio, de lo contrario podría mostrar errores.")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=175)
label = Label(top,text="En el programa deberás ingresar la cantidad")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=195)
label = Label(top,text="de conjuntos (x,f(x)) que tienes en total. ")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=215)
label = Label(top,text="El uso de este método es para segmentos")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue2", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=245)
label = Label(top,text="separados por diferentes distancias. Verifica")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue2", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=265)
label = Label(top,text="tus datos, de lo contrario, utiliza la sección de")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue2", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=285)
label = Label(top,text="Integración para segmentos iguales")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue2", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=305)
destroy=Button(top,text="Volver", width=7, command=top.destroy)
destroy.place(x=200, y=345)
def integra_des():
global raiz
raiz = Toplevel()
raiz.title("Integración segmentos desiguales")
raiz.resizable(False,False)
raiz.geometry("500x400")
raiz.config(bg="deepskyblue4")
label = Label(raiz,text="Integración de segmentos desiguales")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",17)) #tipo de letra
label.place(x=5,y=15)
label = Label(raiz,text="Métodos de Integración Numérica")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue2", #fondo para todas la GUI
font=("Courier",12)) #tipo de letra
label.place(x=85,y=50)
label = Label(raiz,text="Recomendamos se lean las intrucciones de uso")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",10)) #tipo de letra
label.place(x=65,y=80)
instruccion=Button(raiz,text="Intrucciones", width=10, command=instrucciones)
instruccion.place(x=200, y=110)
label = Label(raiz,text="Ingrese cantidad de puntos a evaluar:")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue3", #fondo para todas la GUI
font=("Courier",10)) #tipo de letra
label.place(x=10,y=170)
global n
n=Entry(raiz)
n.place(x=350,y=173)
label = Label(raiz,text="Carga vector con puntos x:")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue3", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=210)
calcular=Button(raiz,text="Cargar Vector", width=17, command=cargar_vector1)
calcular.place(x=350, y=210)
label = Label(raiz,text="Carga vector con puntos f(x):")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue3", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=240)
calcular=Button(raiz,text="Cargar Vector", width=17, command=cargar_vector2)
calcular.place(x=350, y=240)
calcular=Button(raiz,text="Calcular", width=7, command=boton)
calcular.place(x=100, y=320)
destroy=Button(raiz,text="Volver", width=7, command=raiz.destroy)
destroy.place(x=300, y=320)
if __name__ == "__main__":
integra_des()
|
from tkinter import *
import tkinter
import tkinter.filedialog as tkabrir
from tkinter import messagebox
import os
import math
global n
def sim38(h, f0, f1, f2, f3):
return (3/8) * h * (f0 + (3 * f1) + (3 * f2) + f3)
def sim13mul(h, n, f):
sum = f[0]
for i in range(1, n-1, 2):
sum = sum + (4 * f[i]) + (2 * f[i+1])
sum = sum + (4 * f[n-1]) + f[n]
return (h/3)*sum
def intsim(a, b, f):
n = len(f)-1
h = (b-a)/n
sum = 0
m = n
odd = math.fmod(n, 2)
if odd > 0 and n > 1:
sum = sum + sim38(h, f[n-3], f[n-2], f[n-1], f[n])
print("simspon 3/8: ", sum)
m = n-3
if m > 1:
sum = sum + sim13mul(h, m, f)
print("simspon 1/3: ", sum)
return sum
def leerArchivo(file,n):
try:
f = open(file, "r")
v = []
row = f.readline().split()
for i in range(n):
v.append(float(row[i]))
# Cerramos el archivo.
f.close()
return v
except ValueError as e:
messagebox.showinfo("ERROR FATAL","Ingresaste un dato no válido, trataste de ingresar un archivo que no era de texto o dejaste vacío el campo de tamaño. Verifica tus datos"), e
except IndexError as e:
messagebox.showinfo("ERROR FATAL","El vector está incompleto, no corresponde a la entrada del tamaño o es un archivo incorrecto. Verifica tus datos."), e
def cargar_vector():
try:
global puntos
global n
integer_n = int(n.get())
if (integer_n == 0):
messagebox.showinfo("ERROR FATAL","Error. No pueden haber 0 conjuntos")
raise Exception("Error. No pueden haber 0 conjuntos")
file = tkinter.filedialog.askopenfilename()
puntos = leerArchivo(file,integer_n)
'''
diferencia = math.fabs(puntos[1]) - math.fabs(puntos[0])
for i in range(1, len(puntos)-1):
if ((puntos[i+1] - puntos[i]) != diferencia):
messagebox.showinfo("ERROR FATAL","Los segmentos no son iguales")
raise Exception("Error.Los segmentos no son iguales")
'''
except:
messagebox.showinfo("ERROR FATAL","No pude abrir el archivo. Intenta de nuevo"), e
def instrucciones():
top = Toplevel()
top.title("Instrucciones")
top.resizable(False,False)
top.geometry("480x400")
top.config(bg="deepskyblue4")
label = Label(top,text="Instrucciones")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue2", #fondo para todas la GUI
font=("Courier",20)) #tipo de letra
label.place(x=130,y=15)
label = Label(top,text="Para el uso de este método deberás ingresar un")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=55)
label = Label(top,text="vector con los valores de la evaluación f(x)" )
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=75)
label = Label(top,text="en un archivo .txt. En el programa, deberás")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=95)
label = Label(top,text="ingresar el intervalo entre el que se")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=115)
label = Label(top,text="encuentran las evaluaciones de f(x).")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=135)
label = Label(top,text="Los datos deben estar separados solo por un")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=155)
label = Label(top,text="espacio, de lo contrario podría mostrar errores.")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=175)
label = Label(top,text="En el programa deberás ingresar la cantidad")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=195)
label = Label(top,text="de valores f(x) que tienes en total. ")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=215)
label = Label(top,text="El uso de este método solo es para segmentos")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue2", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=245)
label = Label(top,text="separados por la misma distancia. Verifica")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue2", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=265)
label = Label(top,text="tus datos, de lo contrario, utiliza la sección de")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue2", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=285)
label = Label(top,text="Integración para segmentos desiguales")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue2", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=10,y=305)
destroy=Button(top,text="Volver", width=7, command=top.destroy)
destroy.place(x=200, y=345)
def boton():
try:
global n
global x1
global x2
integer_n = n.get()
x_i = float(x1.get())
x_s = float(x2.get())
if (integer_n == 0):
messagebox.showinfo("ERROR FATAL","Error. No pueden haber 0 conjuntos")
raise Exception("Error. No pueden haber 0 conjuntos")
respuesta = intsim(x_i,x_s,puntos)
textito = "El resultado es: " + str(respuesta)
messagebox.showinfo("Respuesta",textito)
except:
messagebox.showinfo("ERROR FATAL","Hay un error con los datos o dejaste campos vacíos")
def integra_igual():
global raiz
raiz = Toplevel()
raiz.title("Integración segmentos desiguales")
raiz.resizable(False,False)
raiz.geometry("500x400")
raiz.config(bg="deepskyblue4")
label = Label(raiz,text="Integración de segmentos iguales")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",17)) #tipo de letra
label.place(x=17,y=15)
label = Label(raiz,text=" Método de integración numérica")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue2", #fondo para todas la GUI
font=("Courier",12)) #tipo de letra
label.place(x=75,y=50)
label = Label(raiz,text="Recomendamos se lean las intrucciones de uso")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue4", #fondo para todas la GUI
font=("Courier",10)) #tipo de letra
label.place(x=65,y=80)
instruccion=Button(raiz,text="Intrucciones", width=10, command=instrucciones)
instruccion.place(x=200, y=110)
label = Label(raiz,text="Ingrese número de puntos:")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue3", #fondo para todas la GUI
font=("Courier",13)) #tipo de letra
label.place(x=78,y=170)
global n
n=Entry(raiz)
n.place(x=350,y=173)
label = Label(raiz,text="Carga vector:")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue3", #fondo para todas la GUI
font=("Courier",11)) #tipo de letra
label.place(x=213,y=210)
calcular=Button(raiz,text="Cargar Vector", width=17, command=cargar_vector)
calcular.place(x=350, y=210)
label = Label(raiz,text="Ingresa valor menor de x:")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue3", #fondo para todas la GUI
font=("Courier",13)) #tipo de letra
label.place(x=78,y=245)
global x1
x1=Entry(raiz)
x1.place(x=350,y=247)
label = Label(raiz,text="Ingresa valor mayor de x:")
label.pack(anchor=CENTER)
label.config(fg="snow", #color de letra
bg="deepskyblue3", #fondo para todas la GUI
font=("Courier",13)) #tipo de letra
label.place(x=78,y=280)
global x2
x2=Entry(raiz)
x2.place(x=350,y=282)
calcular=Button(raiz,text="Calcular", width=7, command=boton)
calcular.place(x=100, y=330)
destroy=Button(raiz,text="Volver", width=7, command=raiz.destroy)
destroy.place(x=300, y=330)
if __name__ == "__main__":
integra_igual()
|
n = int(input("Enter the number"))
s = 0
num = n
while n > 0:
s += n % 10
n //= 10
if num % s == 0:
print('Harshad no.')
else:
print(" Not Harshad no.")
|
import hashlib
import string
s=input("Enter hash form")
s.encode('utf-8')
g=open(indian-passwords,'r')
line = g.readline( )
wordlist = string.split(line)
for word in wordlist:
if hashlib.md5(word).digest()==s:
print(word)
|
n = int(input("Enter rhe first no."))
num = int(input("Enter the second no."))
s1 = s2 = 0
for i in range(1, n // 2 + 1):
if n % i == 0:
s1 += i
for i in range(1, num // 2 + 1):
if num % i == 0:
s2 += i
if s1 == num and s2 == n:
print("Amicable no.s")
else:
print("Not amicable no.s")
|
import math as m
n = input("Enter the number")
l = int(len(n))
n = int(n)
s, num = 0, n
while n > 0:
s += int(m.pow(n % 10, l))
n //= 10
l = l - 1
if s == num:
print("Disarium no.")
else:
print("Not disarium no.")
|
n = int(input())
a = list()
for i in range(n):
x = int(input())
a.append(x)
a.sort(reverse=True)
print(a.index(x)+1)
|
def binsearch(a, x, l, u):
mid = (l + u) // 2
if l > u:
return False
if a[mid] == x:
return True
if x < a[mid]:
return binsearch(a, x, l, mid - 1)
else:
return binsearch(a, x, mid + 1, u)
a = list(map(int, input("Enter numbers :").split()))
a.sort()
x = int(input("Enter element to be searched : "))
if binsearch(a, x, 0, len(a) - 1):
print("Element found")
else:
print("Element not found")
|
import sys
class Node:
def __init__(self, item, next):
self.item = item
self.next = next
# Note, these are methods "A method is a function that is stored as a class attribute"
class LinkedList:
def __init__(self):
self.head = None
def add(self, item):
self.head = Node(item, self.head)
def remove(self):
if self.is_empty():
return None
else:
item = self.head.item
self.head = self.head.next # remove the item by moving the head pointer
return item
def is_empty(self):
return self.head == None
def largest(self):
return r_largest(self.head)
def r_largest(ptr, largest = -100000):
if ptr == None:
return largest
elif int(ptr.item) > largest:
largest = int(ptr.item)
return r_largest(ptr.next, largest)
else:
return r_largest(ptr.next, largest)
def main():
# Read each set
line = '-14 7495 -237 294 -5893 -285 7421 -921 1441'
items = line.strip().split()
nums = [int(item) for item in items] # Create an array of nums from the strings
ll = LinkedList()
# Add each number to the list
for num in nums:
ll.add(num)
# call the students function
print("Using largest function, {}".format(ll.largest()))
print("Using the built-in max function, {}".format(max(nums)))
if __name__ == "__main__":
main()
|
class nim():
help_text = "Nim is a two player game where the players " \
"take turns removing elements from heaps, the " \
"player to play last loses"
move_explanations = (("Which heap to take from?", int),
("How much to take?", int))
ply = 5
def __init__(self, heaps=[3, 4, 5], active_turn="player"):
self.heaps = heaps
self.active_turn = active_turn
def over(self):
return not any(self.heaps)
def available_moves(self):
""" Move is a tuple (heap_index, take_away) where
heap_index is number of the heap from which to
take pieces and take_away is a number of pieces
to take away"""
heaps = range(len(self.heaps))
return [(h, take) for h in range(len(self.heaps))
for take in range(1, self.heaps[h] + 1)]
def get_new_state(self, move):
heap_index, take = move
if self.heaps[heap_index] < take:
raise BadMoveException("Can't take more that how much there is")
new_heaps = self.heaps[:]
new_heaps[move[0]] -= move[1]
new_player = "player" if self.active_turn == "opponent" else "opponent"
return nim(heaps=new_heaps, active_turn=new_player)
def score(self):
if not self.over():
return 0
if self.active_turn == "player":
return 10
else:
return -10
|
import sys
def main(rotval):
try:
rotval = int(rotval) % 26
except ValueError:
print("ERROR: argument not an integer")
return 1
if rotval < 0:
print("ERROR: Please enter a non-negative integer")
return 1
plaintext = input("plaintext: ")
ciphertext = []
for x in plaintext:
if x >= 'A' and x <= 'Z':
ciphertext.append(chr((((ord(x) - ord('A')) + rotval) % 25) + ord('A')))
elif x >= 'a' and x <= 'z':
ciphertext.append(chr((((ord(x) - ord('a')) + rotval) % 25) + ord('a')))
else:
ciphertext.append(x)
print("ciphertext: {}\n".format(''.join(ciphertext)))
return 0
if __name__ == "__main__":
argc = len(sys.argv)
if argc != 2:
print("ERROR: Please enter precisely one argument")
sys.exit(1)
main(sys.argv[1]) |
a=input()
b=input()
l=list()
if(len(a)!=len(b)):
print(max(len(a),len(b)))
elif(len(a)==len(b)):
if(a!=b):
print(max(len(a),len(b)))
else:
print("-1")
|
from collections import namedtuple
Entry = namedtuple("Entry", ["chrom", "start", "end", "name", "qual", "strand"])
def pair_pair(first, second):
assert first.chrom==second.chrom, (first, second)
assert first.name[:-1]==second.name[:-1], (first, second)
start = min(int(first.start), int(second.start))
end = max(int(first.end), int(second.end))
return (first.chrom, str(start), str(end))
def pair_lines(bed_lines):
entries = (Entry(*line.split()) for line in bed_lines)
while True:
try:
first = next(entries)
except StopIteration:
break
try:
second = next(entries)
except StopIteration:
yield "\t".join(pair_pair(first, first))
break
while first.name[:-1]!=second.name[:-1]:
yield "\t".join(pair_pair(first, first))
try:
first, second = (second, next(entries))
except StopIteration:
yield "\t".join(pair_pair(second, second))
break
if first.chrom == second.chrom:
yield "\t".join(pair_pair(first, second))
#
#
# for first in entries:
# second = next(entries)
# if first.name[:-1]==second.name[:-1], (first, second)
# r = next(entries)
# ... print (x, next(it))
# for line in lines:
return ("\t".join(pair_pair(*pair)) for pair in zip(*[iter(entries)]*2))
|
#The | character is called a pipe. You can use it anywhere you want to match one
#of many expressions.
import re
heroRegex = re.compile(r'Batman|Tina Frey')
#When both Batman and Tina Fey occur in the searched string, the first
#occurrence of matching text will be returned as the Match object.
heroName = heroRegex.search('Batman and Tina Frey')
print(heroName.group())
heroName = heroRegex.search('Tina Frey and Batman')
print(heroName.group())
#You can also use the pipe to match one of several patterns as part of
#your regex
batVehicleRegex = re.compile(r'Bat(man|mobile|copter|bat)')
batVehicle = batVehicleRegex.search('The Batmobile has lost its wheels')
#The method call mo.group() returns the full matched text 'Batmobile',
#while mo.group(1) returns just the part of the matched text inside the first
#parentheses group
print(batVehicle.group())
print(batVehicle.group(1))
#If you need to match an actual pipe character, escape it with a backslash, like \|.
|
import model
import tkinter as tk
window = tk.Tk()
import time
window.geometry("1300x700")
canvas = tk.Canvas(window, width=300, height=600, background="orange")
zvet = [model.siniy] #цвет игрока
def draw():
canvas.delete(tk.ALL) #рисует поле
for i in range(10):
for j in range(10):
if i == model.dx and j == model.dy: #рисует игрока
color = model.siniy
tag = "main"
if i == model.maze[1] and j == model.maze[2]: #рисует квадраты, которые надо ловить
color = model.maze[3]
tag = "nemain"
else:
color = "red"
tag = ""
x = 60
canvas.create_rectangle(i * x, j * x, i * x + x, j * x + x, fill=color, tag=tag) #рисует поле
time.sleep(1) #таймер, позволяющий квадратам падать вниз
for i in range(1):
model.dp = model.dp + 1
if model.dx == model.maze[1] and model.dy == model.maze[2] and zvet == model.maze[3]: #это так называемые уровни, если координаты и цвет совпадают, то цвет игрока меняется
zvet.clear()
zvet.append([model.sheltyy])
else:
print("Проигрыш") #это условно, хочется, чтоб появлялось на экране игры
if model.dx == model.maze[1] and model.dy == model.maze[2] and zvet == model.maze[3]: #это так называемые уровни, если координаты и цвет совпадают, то цвет игрока меняется
zvet.clear()
zvet.append([model.rozoviy])
else:
print("Проигрыш") #это условно, хочется, чтоб появлялось на экране игры
draw()
def go_left(event):
if model.dx > 0:
model.dx -= 1
draw()
def go_right(event):
if model.dx < 4:
model.dx += 1
draw()
window.bind("<a>", go_left)
window.bind("<d>", go_right)
canvas.pack()
window.mainloop() |
class Animal:
def __init__(self,name,color,size,age):
self.name=name
self.color=color
self.size=size
self.age=age
def print_all(self):
print(self.name)
print(self.color)
print(self.size)
print(self.age)
def sleep(self):
print(self.name, "is sleeping")
def eat(self,food):
print(self.name, "is eating",food)
dog=Animal(name="max",color="red",size="huge",age=5)
cat=Animal(name="rex",color="black",size="large",age=8)
dog.print_all()
print("##############")
dog.eat("meat")
cat.eat("fish")
print("##############")
cat.print_all()
|
def inside(x, a, b):
if a == b:
return True
if a < b:
if a < x and x <= b:
return True
else:
return False
else:
if b < x and x <= a:
return False
else:
return True
def inside2(x, a, b, incl=True):
if a == b:
return incl or x != a
if a < b:
if a < x:
if incl:
return x <= b
else:
return x < b
else:
return False
else:
if x <= a:
if incl:
return b >= x
else:
return b > x
else:
return True
def simple_inside(x, a, b, incl=True):
if incl:
if a < b:
return (a < x and x <= b)
else:
return (a < x or x <= b)
else:
if a < b:
return (a < x and x < b)
else:
return (a < x or x < b)
print inside(2, 10, 33)
print inside(2, 33, 10)
print inside(10, 2, 33)
print inside(10, 33, 2)
print inside(33, 2, 10)
print inside(33,33, 2)
print inside(2, 10, 2)
print inside (3, 3, 45)
print inside (3, 45, 45)
print inside (3, 45, 3)
print inside (333, 45, 333)
print "...."
print inside2(2, 10, 33), simple_inside(2, 10, 33)
print inside2(2, 33, 10), simple_inside(2, 33, 10)
print inside2(10, 2, 33), simple_inside(10, 2, 33)
print inside2(10, 33, 2), simple_inside(10, 33, 2)
print inside2(33, 2, 10), simple_inside(33, 2, 10)
print inside2(33,33, 2), simple_inside(33,33, 2)
print inside2(2, 10, 2), simple_inside(2, 10, 2)
print inside2(3, 3, 45), simple_inside(3, 3, 45)
print inside2(3, 45, 45), simple_inside(3, 45, 45)
print inside2(3, 45, 3), simple_inside(3, 45, 3)
print inside2(333, 45, 333), simple_inside(333, 45, 333)
print inside2(333, 333, 333), simple_inside(333, 333, 333)
print inside2(2, 10, 33, False) , simple_inside(2, 10, 33, False)
print inside2(2, 33, 10, False) , simple_inside(2, 33, 10, False)
print inside2(10, 2, 33, False) , simple_inside(10, 2, 33, False)
print inside2(10, 33, 2, False) , simple_inside(10, 33, 2, False)
print inside2(33, 2, 10, False) , simple_inside(33, 2, 10, False)
print inside2(33,33, 2, False) , simple_inside(33,33, 2, False)
print inside2(2, 10, 2, False) , simple_inside(2, 10, 2, False)
print inside2(3, 3, 45, False) , simple_inside(3, 3, 45, False)
print inside2(3, 45, 45, False) , simple_inside(3, 45, 45, False)
print inside2(3, 45, 3, False) , simple_inside(3, 45, 3, False)
print inside2(333, 45, 333, False) , simple_inside(333, 45, 333, False)
print inside2(333, 333, 333, False) , simple_inside(333, 333, 333, False)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.