text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 15:10:56 2019
@author: jinyanliu
"""
class intDict(object):
"""A dictionary with integer keys"""
def __init__(self, numBuckets):
"""Create an empty dictionary"""
self.buckets = []
self.numBuckets = numBuckets
for i in range (numBuckets):
self.buckets.append([])
def addEntry(self, key, dictVal):
"""Assumes key an int. Adds an entry."""
hashBucket = self.buckets[key%self.numBuckets]
for i in range(len(hashBucket)):
if hashBucket[i][0] == key:
hashBucket[i] = (key, dictVal)
return
hashBucket.append((key, dictVal))
def getValue(self, key):
"""Assumes key an int.
Returns value associated with key"""
hashBucket = self.buckets[key%self.numBuckets]
for e in hashBucket:
if e[0] ==key:
return e[1]
return None
def __str__(self):
result = '{'
for b in self.buckets:
for e in b :
result = result+str(e[0]) +':'+str(e[1])+','
return result[:-1] + '}' #result[:-1] omits the last comma
dict = intDict(4)
dict.addEntry(5,"five")
dict.addEntry(7,"seven")
print(dict.getValue(5))
print(dict)
import random
D = intDict(17)
for i in range(20):
#choose a random int in the range 0 to 10**5 -1
key = random.choice(range(10**5))
D.addEntry(key,i)
print('The value of the intDict is:')
print(D)
print('\n', 'The buckets are:')
for hashBucket in D.buckets: #violates abstraction barrier
print(' ', hashBucket) |
x,y=raw_input('Enter balance ane interest rate:').split()
balance=float(x)
rate=float(y)
lixi=balance*(rate/1200)
print('The interest is '+str(lixi))
|
def eliminateDuplicates(lst):
s=[]
for i in lst:
if i not in s:
s.append(i)
print(s)
if __name__ == '__main__':
a=raw_input('Enter ten number:')
l=a.split()
eliminateDuplicates(l)
|
import math
def distance(x1,y1,x2,y2):
return math.sqrt((x2-x1)**2+(y2-y1)**2)
x,y,n,m=eval(raw_input('>>'))
print(distance(x,y,n,m))
|
import math
x,y=raw_input('Enter the radius and length of a cylinder:').split()
radius=float(x)
length=float(y)
area=radius*radius*math.pi
volume=area*length
print('The area is '+str(area)+'\n'+'The volume is '+str(volume))
|
import random
def shuffle(lst):
l= len(lst)
s=[]
for i in range(l):
n=random.randint(0,len(lst)-1)
s.append(lst[n])
lst.pop(n)
print(s)
if __name__ == '__main__':
a=raw_input('>>')
b=a.split()
print(b)
shuffle(b)
|
def indexOfSmallestElement(lst):
m=min(l)
print(m)
for i in range(len(l)):
if l[i]==m:
print(str(i)+' ',end="")
print()
if __name__ == '__main__':
a=input('>>')
l=a.split()
indexOfSmallestElement(l)
|
# -- coding: utf-8 --
#1
print("-[Задание 1]-")
print("Введите число 1: ")
a = int(input())
print("Введите число 2: ")
b = int(input())
print("Введите число 3: ")
c = int(input())
print("Сумма введённых чисел: ",a+b+c)
#2
print("-[Задание 2]-")
print("Введите катет А: ")
a = int(input())
print("Введите катет Б: ")
b = int(input())
print("Площадь прямоугольного треугольника: ", 1/2*(a*b))
#3
print("-[Задание 3]-")
print("Введите число N: ")
n = int(input())
minute = (n % 60)
chas = ((n//60)%24)
print("Количество часов: ",chas)
print("Количество минут: ",minute)
#4 - mb переделать
def dlina_shnura(a,b,l,n):
otv = (2 * l + (2 * n - 1) * a + 2 * (n - 1) * b)
return otv
print("-[Задание 4]-")
print("Введите расстояние между рядами (a): ")
v1 = int(input())
print("Введите расстояние между дырочками (b): ")
v2 = int(input())
print("Введите количество дырочек (n): ")
v3 = int(input())
print("Введите длину свободного конца шнурка (l): ")
v4 = int(input())
print("Искомая длина шнура: ",dlina_shnura(v1,v2,v4,v3))
#5
def naumenshie(a,b,c):
if b >= a <= c:
buf = (a)
elif a >= b <= c:
buf = (b)
else:
buf = (c)
return buf
print("-[Задание 5]-")
print("Введите число 1: ")
a = int(input())
print("Введите число 2: ")
b = int(input())
print("Введите число 3: ")
c = int(input())
print("Наименьший из 3 чисел: ",naumenshie(a,b,c))
#6
print("-[Задание 6]- \nВведите первую клетку(X,Y) и потом вторую (X,Y)")
a, b = ((int(input()) + int(input()) - 1) % 2 for _ in range(2))
print("Да, это чёрные клетки" if a == b else "Они различаются")
#7
print("-[Задание 7]- \nВведите Год")
year = int(input())
if (year % 4 == 0) :
if (not (year % 100 == 0)) or (year % 400 == 0):
print("Это високосный год")
else:
print("Это обычный год")
#8
print("-[Задание 8]- \nВведите 3 числа")
a = int(input())
b = int(input())
c = int(input())
rez = 0
if a == b == c:
rez = 3
elif a == b or b == c or a == c:
rez = 2
else:
rez = 0
print("Количество совпадений: ",rez)
#9
print("-[Задание 9]- \nВведите n*m долек шоколада и отлом от шоколадки на k долей")
n = int(input())
m = int(input())
k = int(input())
if k < n * m:
if ((k % n == 0) or (k % m == 0)):
print('Да, можно отломить от шоколадки часть')
else:
print('Нет, можно отломить от шоколадки часть')
|
import sys
cols = """name,age,gender,raceethnicity,month,day,year,streetaddress,city,state,latitude,longitude,state_fp,county_fp,tract_ce,geo_id,county_id,namelsad,lawenforcementagency,cause,armed,pop,share_white,share_black,share_hispanic,p_income,h_income,county_i""".split(",")
def max():
for line in sys.stdin:
row = dict(zip(cols, line.split(',')))
print(row)
print(int(row['age']))
max() |
import sqlite3
from db import *
ranks = ['Новичок ☕', 'Любитель ①', 'Опытный Кликер ②', 'Профессиональный Кликер③', 'Мастер ⋆', 'Гранд-Мастер ⋆⋆⋆', 'Величайший Кликер ㉨㉨㉨', 'Элита ╰☆╮']
def get_price(id):
sql = f"SELECT * FROM users WHERE uid={id}"
cursor.execute(sql)
info = cursor.fetchone()
price = int(info[4])
price_text = f'Цена улучшения: {price}'
return price_text
def buy_click(id):
sql = f"SELECT * FROM users WHERE uid={id}"
cursor.execute(sql)
info = cursor.fetchone()
print(info)
if int(info[1])>int(info[4]):
cursor.execute(f"""
UPDATE users
SET money = money - {info[4]},
click_price = click_price*2,
per_click = per_click + 1
WHERE uid={id}
""")
return 'success'
else:
return 'none'
def get_price_rank(id):
sql = f"SELECT * FROM users WHERE uid={id}"
cursor.execute(sql)
info = cursor.fetchone()
rank = int(info[3])
price = rank * 300 * 2
if rank == 0:
price = 250
price_text = f'Цена улучшения: {price}'
return price_text
def buy_rank(id):
sql = f"SELECT * FROM users WHERE uid={id}"
cursor.execute(sql)
info = cursor.fetchone()
print(len(ranks)-1)
rank = int(info[3])
print(rank)
rank_price = rank*300*2
if rank == 0:
rank_price = 250
if int(info[1])>rank_price and rank < len(ranks)-1:
cursor.execute(f"""
UPDATE users
SET money = money - {rank_price},
rank = rank +1,
per_click = per_click +4
WHERE uid={id}
""")
return 'success'
else:
return 'none'
def buy_status(id):
sql = f"SELECT * FROM users WHERE uid={id}"
cursor.execute(sql)
info = cursor.fetchone()
print(info)
if int(info[1]) > 500:
cursor.execute(f"""
UPDATE users
SET money = money - 500
WHERE uid={id}
""")
return 'success'
else:
return 'none'
#get_price('142901911') |
# Convert a flat sequence of numbered list labels such as
# 1 2 a b 3 4
# into a hierarchical structure like
# 1, 2, [a, b] 3, 4
#
# Works on the sorts of symbols found in the DC Code, which
# get quite interesting like QQ-i (which is between PP and
# either QQ-ii or RR).
#
# Try:
# 1 2 2A 2B A B 3 A B C D E F G H I J K L M N i ii iii iv O P Q R S T U V W X Y Z AA BB BB-i BB-ii CC
# which gives:
# 1 2 2A 2B [A B] 3 [A B C D E F G H I J K L M N [i ii iii iv] O P Q R S T U V W X Y Z AA BB BB-i BB-ii CC
import re
def default_symbol_comparer(a, b):
# Compares two symbols a and b and returns 0 if b is an appropriate
# symbol to follow a, or a positive score indicating how bad it is
# for b to follow a. In the special case when a is None, test whether
# b is an appropriate initial symbol for a new list.
if a == None:
# Check initial symbols.
if b in ("1", "a", "A", "i", "I"):
return True
return False
# Check for all valid continuations.
# 1, 2 or 1A, 2
m = re.match("^(\d+)(\D.*)?$", a)
if m and re.match("^\d+$", b):
if int(b) == int(m.group(1)) + 1:
return True
# A, B or a, b
if (re.match("^[A-Z]$", a) and re.match("^[A-Z]$", b)) or (re.match("^[a-z]$", a) and re.match("^[a-z]$", b)):
if ord(b) == ord(a) + 1:
return True
# I, II or i, ii
roman_numeral_letters = 'MDCLXVI'
if (re.match("^[%s]+$" % roman_numeral_letters, a) and re.match("^[%s]+$" % roman_numeral_letters, b)) or \
(re.match("^[%s]+$" % roman_numeral_letters.lower(), a) and re.match("^[%s]+$" % roman_numeral_letters.lower(), b)):
if parse_roman_numeral(b) == parse_roman_numeral(a) + 1:
return True
# 5, 5A
m = re.match("^(\d+)(\D.*)$", b)
if m and m.group(1) == a:
if default_symbol_comparer(None, m.group(2)):
return True
# 5A, 5B
m = re.match("^(\d+)(\D.*)$", a)
if m and b.startswith(m.group(1)):
if default_symbol_comparer(m.group(2), b[len(m.group(1)):]):
return True
# Z, AA
if a == "Z" and b == "AA": return True
if a == "ZZ" and b == "AAA": return True
# AA, BB
def all_same_char(s):
if len(s) == 0: raise ValueError()
for i in range(1, len(s)):
if s[i] != s[0]:
return False
return True
if re.match("^[A-Za-z]{2,}$", a) and re.match("^[A-Za-z]{2,}$", b) and len(a) == len(b) and all_same_char(a) and all_same_char(b):
if default_symbol_comparer(a[0], b[0]):
return True
# ??, ??-i
b1 = b.split("-", 1)
if len(b1) == 2 and b1[0] == a:
if default_symbol_comparer(None, b1[1]):
return True
# ??-i, ??-ii
a1 = a.split("-", 1)
b1 = b.split("-", 1)
if len(a1) == 2 and len(b1) == 2 and a1[0] == b1[0]:
if default_symbol_comparer(a1[1], b1[1]):
return True
# AA-i, BB
a1 = a.split("-", 1)
if len(a1) == 2:
if default_symbol_comparer(a1[0], b):
return True
return False
def infer_list_indentation(
symbol_list,
symbol_comparer=default_symbol_comparer,
):
# Work from left-to-right.
stack = [ [symbol_list[0]] ]
for s in symbol_list[1:]:
# Let the user put None's in the list and we'll just put those at
# their own indent levels.
if s is None:
stack.append([s])
continue
# Does this continue any symbol on the stack?
ok_levels = []
for i in range(len(stack)):
if stack[i][-1] is not None and symbol_comparer(stack[i][-1], s):
ok_levels.append(i)
if len(ok_levels) == 0:
# Symbol doesn't continue from any symbol on the stack, so this must be an indentation.
if not symbol_comparer(None, s):
# It also doesn't appear to be an indentation because it's not an initial
# symbol.
#raise ValueError("%s does not continue from any symbol on the stack and is not an initial symbol: %s" % (s, [ss[-1] for ss in stack]) )
pass
stack.append([s])
#elif len(ok_levels) > 1:
# raise ValueError("%s continues from multiple symbols on the stack: %s" % (s, [ss[-1] for ss in stack]) )
else:
lvl = ok_levels[-1]
while len(stack) > lvl+1:
q = stack.pop(-1)
stack[-1].append(q)
stack[-1].append(s)
while len(stack) > 1:
q = stack.pop(-1)
stack[-1].append(q)
return stack[0]
# via http://code.activestate.com/recipes/81611-roman-numerals/
roman_numeral_map = tuple(zip(
(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1),
('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I')
))
def parse_roman_numeral(n):
n = n.upper()
i = result = 0
for value, symbol in roman_numeral_map:
while n[i:(i + len(symbol))] == symbol:
result += value
i += len(symbol)
if i != len(n): raise ValueError("Not a roman numeral: %s (parsed up to '%s')" % (n, n[0:i]))
return result
if __name__ == "__main__":
#ret = infer_list_indentation(['a', '1', '2'])
#ret = infer_list_indentation(['a', '1', '2', 'A', 'B', 'C', 'D', '3', 'A', 'B', 'C', 'D', 'E', 'F', '4', '5', '6', 'b', '1', 'A', 'B', 'i', 'ii', 'iii', 'iv', '2', 'A', 'B', 'C', 'D', 'E', 'c', '1', '2', 'd', '1', '2', '3', '4', '5', 'A', 'B', '6', '7', 'A', 'B', 'C', 'D', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', 'A', 'B', 'C', 'e', '1', 'A', 'B', 'C', 'D', 'i', 'ii', 'iii', 'iv', 'v', 'I', 'II', 'III', 'E', 'i', 'ii', 'iii', 'iv', 'v', '2', 'f', '1', '2', '3'])
#ret = infer_list_indentation(['1', '2', '3', '4', '5', '5A', '5B', '5C', 'A', 'B', '6', 'A', 'B', 'C', 'D', 'E', 'F', '7', '8', '8A', '9', '9A', '10', '10A', '11', '12', '13', '13A', '13B', '13C', '14', '14A', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', '15', '15A', '16', '17', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'i', 'ii', 'iii', 'iv', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'BB', 'CC', 'DD', 'EE', 'FF', 'GG', 'HH', 'II', 'JJ', 'KK', 'LL', 'MM', 'NN', 'OO', 'PP', 'QQ', 'QQ-i', 'RR', 'SS', 'TT', 'UU', 'VV', 'WW', 'XX', 'YY', 'ZZ', 'AAA', 'BBB', 'CCC', 'DDD', 'EEE'])
ret = infer_list_indentation(['1', '2', '3', '4', '5', '5A', '6', '7', '7A', '7B', '8', '9', '10', '11', '11A', '11B', '12', '12A', '12A-i', '12B', '12C', '12D', '13', '14', '14A', '15', '16', '17', '18', '19', '20', 'A', 'i', 'ii', 'iii', 'B', '21', '22', '23', '24', 'A', 'B', 'C', '25', '26', '27', '28', '29', '30', '31'])
def dump(symbols, indent=0):
for symbol in symbols:
if isinstance(symbol, list):
dump(symbol, indent=indent+1)
else:
print(" "*indent + symbol)
dump(ret) |
# NO IMPORTS!
##############
# Problem 01 #
##############
def find_triple(ilist):
""" If the list ilist contains three values x, y, and z such that x + y = z
return a tuple with x and y. Otherwise return None. """
s = set(ilist)
for i in range(len(ilist)):
for j in range(i+1,len(ilist)):
x = ilist[i]
y = ilist[j]
if (x+y) in s:
# make sure third elements differs from first two!
z = ilist.index(x+y)
if z == i or z == j: continue
return (x,y)
return None
##############
# Problem 02 #
##############
def is_palindrome(s):
return s == s[::-1]
def is_quasidrome(s):
"""Check whether s is a quasidrome."""
if is_palindrome(s):
return True
return any(is_palindrome(s[:cut] + s[cut+1:]) for cut in range(len(s)))
##############
# Problem 03 #
##############
def max_subsequence(ilist, is_circular = False):
""" Return the start and end indices as a tuple of the maximum subsequence
in the list. If is_circular = True, imagine the list is circular.
That is, after the end index comes the start index. """
n = len(ilist)
if is_circular: ilist = ilist + ilist
maxsum = None
result = None
for start in range(n):
for slen in range(1,n+1):
if start + slen <= len(ilist):
test = sum(ilist[start:start+slen])
if maxsum is None or test > maxsum:
maxsum = test
result = (start,(start+slen-1) % n)
return result
##############
# Problem 04 #
##############
# This problem is trickier. Here are three solutions (they all
# assume that there are no duplicate edges). We'd left a few
# questions (as comments) here and there; they are a good way to
# test your understanding!
# The first solution is much like in the Bacon lab in that
# we first build a useful mapping of a vertex to its neighbors
def count_triangles(edges):
"""Count the number of triangles in edges."""
# build adjaceny dict: vertex => set of immediate neighbor vertices
neighbors = {}
for source, destination in edges:
neighbors.setdefault(source,set()).add(destination)
neighbors.setdefault(destination,set()).add(source)
count = 0
for v1 in neighbors:
for v2 in neighbors[v1]:
for v3 in neighbors[v2]:
if v1 in neighbors[v3]:
count += 1
return count // 6 # Think about this part: why do we divide by 6?
# The second solution can be a bit less efficient, but it's
# still reasonable. Bonus question to think about: in which
# cases is solution 1 much faster than solution 1? In which
# cases is it about the same? Can it be slower?
def count_triangles_2(edges):
"""Count the number of triangles in edges."""
edgeset, vertexset = set(), set()
for v1, v2 in edges:
vertexset.add(v1)
vertexset.add(v2)
edgeset.add((v1, v2))
edgeset.add((v2, v1))
vertices = list(vertexset)
def is_triangle(edges, v1, v2, v3):
return (v1, v2) in edges and (v2, v3) in edges and (v3, v1) in edges
count = 0
for idx1 in range(len(vertices)):
for idx2 in range(idx1 + 1, len(vertices)):
for idx3 in range(idx2 + 1, len(vertices)):
if is_triangle(edgeset, vertices[idx1], vertices[idx2], vertices[idx3]):
count += 1
return count # Why don't we divide by 6 here?
# The third one is much less efficient. The idea here is to
# iterate over all *edges*, instead of all *vertices*. In the
# quiz, such a solution would pass almost everything, but on
# examples with many edges it might fail.
def is_triangle_3(e1, e2, e3):
# Why is it enough to test just this sequence?
return e1[1] == e2[0] and e2[1] == e3[0] and e3[1] == e1[0]
def all_triangles_3(edges):
triangles = set()
for e1 in edges:
for e2 in edges:
for e3 in edges:
if is_triangle_3(e1, e2, e3):
# Why do we use tuple() here?
triangles.add(tuple(sorted((e1[0], e2[0], e3[0]))))
return triangles
def count_triangles_3( edges ):
"""Count the number of triangles in edges."""
all_edges = []
all_edges.extend(edges)
all_edges.extend([y, x] for [x, y] in edges)
return len(all_triangles_3(all_edges)) # Why don't we divide by 6 here?
##############
# Problem 05 #
##############
def is_unique( A ):
""" return True if no repeated element in list A. """
A.sort()
return all(A[i] != A[i-1] for i in range(1,len(A)))
##############
# Problem 06 #
##############
def matrix_product( A, B, m, n, k ):
""" compute m-by-k product of m-by-n matrix A with n-by-k matrix B. """
return [sum(A[i + n*r] * B[c + i*k] for i in range(n))
for r in range(m)
for c in range(k)]
##############
# Problem 07 #
##############
def mode( A ):
""" return the most common value in list A. """
currMode = None
maxCount = 0
for a in A:
count = A.count(a) # count occurrences of a in A
if count > maxCount:
currMode = a
maxCount = count
return currMode
##############
# Problem 08 #
##############
def transpose( A, m, n ):
""" return n-by-m transpose of m-by-n matrix A. """
# each row of the output is a column of the input
return [A[c*n + r]
for r in range(n)
for c in range(m)]
##############
# Problem 09 #
##############
def check_valid_paren(s):
"""return True if each left parenthesis is closed by exactly one
right parenthesis later in the string and each right parenthesis
closes exactly one left parenthesis earlier in the string."""
diff = 0
for ch in s:
diff = diff + 1 if ch == "(" else diff - 1
if diff < 0:
# if at any point we've seen more ) than (
return False
# if we saw the same number of ( and )
return diff == 0
##############
# Problem 10 #
##############
def get_all_elements(root):
""" Return a list of all numbers stored in root, in any order. """
# generator recursively walks the tree yielding values
def walk_tree(node):
if node is not None:
yield from walk_tree(node["left"])
yield node["value"]
yield from walk_tree(node["right"])
# call to list ensure an actual list as the result
return list(walk_tree(root))
# here's a straight-forward recursive solution
def get_all_elements_recursive(root):
""" Return a list of all numbers stored in root, in any order. """
elements = [root["value"]]
if root["left"] != None:
elements.extend(get_all_elements(root["left"]))
if root["right"] != None:
elements.extend(get_all_elements(root["right"]))
return elements
##############
# Problem 11 #
##############
def find_path(grid):
""" Given a two dimensional n by m grid, with a 0 or a 1 in each cell,
find a path from the top row (0) to the bottom row (n-1) consisting of
only ones. Return the path as a list of coordinate tuples (row, column).
If there is no path return None. """
n = len(grid)
m = len(grid[0])
def helper(row,col,path):
if row == n:
return path
for i in range(col-1,col+2):
if 0 <= i < m and grid[row][i]:
result = helper(row+1,i,path + [(row,i)])
if result is not None:
return result
return None
for c in range(0,m):
if grid[0][c]:
result = helper(1,c,[(0,c)])
if result is not None:
return result
return None
##############
# Problem 12 #
##############
def longest_sequence(s):
""" find sequences of a single repeated character in string s.
Return the length of the longest such sequence. """
max_len = 0 # length of longest sequence seen so far
cur_len = 0 # length of current sequence
last_ch = None # previous character
for ch in s:
cur_len = cur_len + 1 if ch == last_ch else 1
max_len = max(cur_len,max_len)
last_ch = ch
return max_len
##############
# Problem 13 #
##############
# straightforward enumeration
def integer_right_triangles(p):
"""Let p be the perimeter of a right triangle with integral, non-zero
length sides of length a, b, and c. Return a sorted list of solutions with perimeter p. """
return [[a,b,p-a-b]
for a in range(1,p)
for b in range(a,p)
if a**2 + b**2 == (p-a-b)**2]
# a mathematician's solution
# this is very fast, but we wouldn't expect you to find this solution
def integer_right_triangles_at_the_speed_of_list(p):
solutions = []
# one side will always be shorter than p//2
for x in range(1, p // 2):
# we know x^2 + y^2 = z^2 and x + y + z = p
# so (p - x - y)^2 = x^2 + y^2
# so p^2 - 2px - 2py + 2xy = 0
# now solve for y given x and p
y, r = divmod(p*p - 2*p*x, 2*(p - x))
if r == 0 and x < y:
z = p - x - y
solutions.append([x, y, z])
return solutions
##############
# Problem 14 #
##############
def encode_nested_list(seq):
"""Encode a sequence of nested lists as a flat list."""
# use recursive generator to avoid creating a zillion intermediate-level lists
def encode(L):
if not isinstance(L, list):
yield L
else:
yield "up"
for y in L:
yield from encode(y)
yield "down"
return list(encode(seq))
def encode_nested_list_recursive(seq):
"""Encode a sequence of nested lists as a flat list."""
if not isinstance(seq, list):
return [seq]
return ["up"] + [x for y in seq for x in encode_nested_list(y)] + ["down"]
|
# coding: utf-8
# # Tent Packing
# In[ ]:
from instrument import instrument
# In[ ]:
# Pack a tent with different sleeping bag shapes leaving no empty squares
#
# INPUTS:
# tent_size = (rows, cols) for tent grid
# missing_squares = set of (r, c) tuples giving location of rocks
# bag_list = list of sets, each decribing a sleeping bag shape
# Each set contains (r, c) tuples enumerating contiguous grid
# squares occupied by the bag, coords are relative to the upper-
# left corner of the bag. You can assume every bag occupies
# at least the grid (0,0).
#
# Example bag_list entries:
# vertical 3x1 bag: { (0,0), (1,0), (2,0) }
# horizontal 1x3 bag: { (0,0), (0,1), (0,2) }
# square bag: { (0,0), (0,1), (1,0), (1,1) }
# L-shaped bag: { (0,0), (1,0), (1,1) }
# C-shaped bag: { (0,0), (0,1), (1,0), (2,0), (2,1) }
# reverse-C-shaped bag: { (0,0), (0,1), (1,1), (2,0), (2,1) }
#
# OUTPUT:
# None if no packing can be found; otherwise a list giving the
# placement and type for each placed bag expressed as a dictionary
# with keys
# "anchor": (r, c) for upper-left corner of bag
# "shape": index of bag on bag list
# ### Recursive Backtracking Pattern: build on result of sub-problem
# In[ ]:
def pack(tent_size, missing_squares, bag_list):
all_squares = set((r, c) for r in range(tent_size[0])
for c in range(tent_size[1]))
def first_empty(covered_squares):
""" returns (r, c) for first empty square, else None if no empty squares """
return 'todo'
def helper(covered_squares):
""" input: set of covered squares (covered by rocks or bags)
output: None if no packing can be found, else a list of placed bags"""
return 'todo'
# get things started
return helper(missing_squares)
# In[ ]:
bag_list = [
{ (0,0), (1,0), (2,0) }, # vertical 3x1 bag
{ (0,0), (0,1), (0,2) }, # horizontal 1x3 bag
{ (0,0), (0,1), (1,0), (1,1) }, # square bag
{ (0,0), (1,0), (1,1) }, # L-shaped bag
{ (0,0), (0,1), (1,0), (2,0), (2,1) }, # C-shaped bag
{ (0,0), (0,1), (1,1), (2,0), (2,1) }, # reverse C-shaped bag
]
# horizontal bag in 1x3 tent, no rocks => fits, no backtracking (case 1)
tent_size = (1,3)
rocks = set()
print(pack(tent_size, rocks, bag_list))
# In[ ]:
# C-shaped bag in 3x2 tent, one rock => fits, one backtrack (case 6)
tent_size = (3,2)
rocks = {(1,1)}
print(pack(tent_size, rocks, bag_list))
# In[ ]:
# 5x5 tent with three rocks => fits, backtracking (case 13)
tent_size = (5,5)
rocks = {(1,1),(1,3),(3,1)}
print(pack(tent_size, rocks, bag_list))
# In[ ]:
# 5x5 tent with 4 rocks => fails; lots of backtracking to try every possibility (case 12)
tent_size = (5,5)
rocks = {(1,1),(1,3),(3,1),(3,3)}
print(pack(tent_size, rocks, bag_list))
# ### Recursive Backtracking Pattern: do/undo on success/fail
# In[ ]:
def pack(tent_size, missing_squares, bag_list):
all_squares = set((r, c) for r in range(tent_size[0])
for c in range(tent_size[1]))
def first_empty(covered_squares):
""" returns (r, c) for first empty square, else None if no empty squares """
return 'todo'
def helper(result_so_far, covered_squares):
""" result_so_far: list of placed bags
covered_squares: set of squares covered by rocks or bags (will be mutated)
output: boolean indicating if packing successfully completed """
return 'todo'
# get things started
result = []
covered_squares = set(missing_squares)
success = helper(result, covered_squares)
return result if success else None
# In[ ]:
# horizontal bag in 1x3 tent, no rocks => fits, no backtracking (case 1)
tent_size = (1,3)
rocks = set()
print(pack(tent_size, rocks, bag_list))
# In[ ]:
# C-shaped bag in 3x2 tent, one rock => fits, one backtrack (case 6)
tent_size = (3,2)
rocks = {(1,1)}
print(pack(tent_size, rocks, bag_list))
# In[ ]:
# 5x5 tent with three rocks => fits, backtracking (case 13)
tent_size = (5,5)
rocks = {(1,1),(1,3),(3,1)}
print(pack(tent_size, rocks, bag_list))
# In[ ]:
# 5x5 tent with 4 rocks => fails; lots of backtracking to try every possibility (case 12)
tent_size = (5,5)
rocks = {(1,1),(1,3),(3,1),(3,3)}
print(pack(tent_size, rocks, bag_list))
# ### What if we want *all* packings?
# In[ ]:
def all_packings(tent_size, missing_squares, bag_list):
all_squares = set((r, c) for r in range(tent_size[0])
for c in range(tent_size[1]))
def first_empty(covered_squares):
""" returns (r, c) for first empty square, else None if no empty squares """
return 'todo'
def helper(covered_squares):
""" input: set of covered squares (covered by rocks or bags)
output: None if no packing can be found, else a list of packings,
each packing being a list of placed bags
"""
return 'todo'
# get things started
return helper(missing_squares)
# In[ ]:
# Succeeds; more than one packing possible
tent_size = (3,3)
rocks = set()
res = all_packings(tent_size, rocks, bag_list)
print("NUMBER PACKINGS:", len(res) if res is not None else 0)
print(res)
# In[ ]:
# More packings... (case 5)
tent_size = (4,4)
rocks = set()
res = all_packings(tent_size, rocks, bag_list)
print("NUMBER PACKINGS:", len(res) if res is not None else 0)
# In[ ]:
# 9x7 tent with scattered rocks -- Lots of possibilities (case 15)
tent_size = (9,7)
rocks = {(0,2), (2,2), (2,4), (3,4), (7,4), (5,4), (5,5), (8,6), (7,1)}
res = all_packings(tent_size, rocks, bag_list)
print("NUMBER PACKINGS:", len(res) if res is not None else 0)
|
''' Write a Python program to get a string from a given string where all occurrences of its first char
have been changed to '$', except the first char itself ?'''
import time
n=str(input("Please enter the string :"))
print("Changing all the occurrences of first char of the string to $ ...")
time.sleep(1)
str_1=n.replace(n[0],'$')
print(str_1)
|
# Write a Python function that takes a list of words and returns the length of the longest one?
import time
list_1=[]
max_list=[]
i=0
n=int(input("Please enter the n of elements you want to put in the list :"))
while i<n:
ele_list=input("Please enter the elemnt :")
list_1.append(ele_list)
i+=1
print("Preparing lists ...")
time.sleep(1)
print(list_1)
for i in list_1:
max_list.append(len(i))
print("Calculating length of the elements of the list ...")
time.sleep(1)
print(max_list)
time.sleep(1)
print("Largest length :",max(max_list)) |
# Unittest for simple calculator
# author: Muztrizen
import unittest
import calculator
class TestCalculator(unittest.TestCase):
def test_add(self):
"""
Test case: Normal case of addition
"""
expected_answer = 1
actual_answer = calculator.add(1, 0)
self.assertEqual(expected_answer, actual_answer)
def test_subtract(self):
"""
Test case: Normal case of subtraction
"""
expected_answer = 1
actual_answer = calculator.subtract(2, 1)
self.assertEqual(expected_answer, actual_answer)
def test_multiply(self):
"""
Test case: Normal case of multiplication
"""
expected_answer = 1
actual_answer = calculator.multiply(1, 1)
self.assertEqual(expected_answer, actual_answer)
def test_divide(self):
"""
Test case: Normal case of division
"""
expected_answer = 1
actual_answer = calculator.divide(2, 2)
self.assertEqual(expected_answer, actual_answer)
"""
Test case: Raise ValueError when y ==0
"""
with self.assertRaises(ValueError):
calculator.divide(1, 0)
|
class BST:
class Node:
def __init__(self, key, data, parent = None):
self.quantity = 1
self.key = key
self.data = data
self.parent = parent
self.left = None
self.right = None
def __init__(self, lambda_key):
self.lambda_key = lambda_key
self.root = None;
def add(self, data):
if self.root is None:
self.root = self.Node(self.lambda_key(data), data)
return
new_key = self.lambda_key(data)
current = self.root
while True:
if current.key < new_key:
if current.right is None:
current.right = self.Node(new_key, data, current)
break
else:
current = current.right
elif current.key > new_key:
if current.left is None:
current.left = self.Node(new_key, data, current)
break
else:
current = current.left
else:
current.quantity += 1
break
def get_and_remove_min_element(self):
current = self.root
while True:
if current.left is None:
min_element = current
break
current = current.left
if min_element.quantity == 1:
if min_element.right is not None:
if min_element == self.root:
min_element.right.parent = None
self.root = min_element.right
min_element.right = None
else:
min_element.parent.left = min_element.right
min_element.right.parent = min_element.parent
else:
if min_element == self.root:
self.root = None
else:
min_element.parent.left = None
min_element.parent = None
else:
min_element.quantity -= 1
return min_element
|
"""
Controller is the one class to rule them all! It's responsible for the communication of model and view
"""
from Conect4_View import View
from Conect4_Model import Model
from itertools import product
class Controller:
""" Creates logic for communication model and view. """
def __init__(self):
""" Init's controller"""
self.winner = False
self.view = View()
self.model = Model()
self.board = self.model.grid
def get_board_status(self):
""" Takes input from grid and updates view for display. """
self.view.show_board(self.board)
def get_move(self):
"""
Get's the input from the view and stores it in the update_board in the model.
"""
move_needed = True
while move_needed:
move = self.view.show_turn(self.model.playing_player)
move_needed = self.model.update_board(move)
def check_tie(self):
"""
Loops through the board and looks for a empty space. If it does find a space it print's that it was a tie.
"""
for x in self.board: # loop through each inner list
if x[0] == " ":
return False
self.view.show_tie()
return True
def check_winner(self):
"""
Checks to see if four in a row exists horizontally, vertically, or diagonally."""
#checks columns
for x in self.board:
if self.model.playing_player[1] * 4 in "".join(x):
return True
#Checks the rows
for each_row in range(6):
if self.model.playing_player[1] * 4 in "".join(column[each_row] for column in self.board):
return True
#Get's diagonals(cartesian product of a series of lists)
#checks diagonal
for row, column in product(range(5,2, -1), range(4)):
if self.model.playing_player[1] * 4 in "".join(self.board[column + i][row - i] for i in range(4)):
return True
#checks the other diagonal
for row, column in product(range(3), range(4)):
if self.model.playing_player[1] * 4 in "".join(self.board[column + i][row + i] for i in range(4)):
return True
return False
def main(self):
"""
Starts game and calls all helper functions to control the flow of the game.
"""
winner = False
self.view.starting_print()
while winner == False:
self.view.show_board(self.board)
self.get_move()
winner = self.check_winner()
if winner:
self.view.show_board(self.board)
self.view.show_winner(self.model.playing_player[0])
break
winner = self.check_tie()
if winner:
self.view.show_board(self.board)
self.view.show_tie()
self.model.swap_player()
if __name__ == '__main__':
game = Controller()
game.main()
|
"""
Monte Carlo Tic-Tac-Toe Player
"""
import random
import poc_ttt_gui
import poc_ttt_provided as provided
# Constants for Monte Carlo simulator
# Change as desired
NTRIALS = 100 # Number of trials to run
MCMATCH = 1.0 # Score for squares played by the machine player
MCOTHER = 1.0 # Score for squares played by the other player
def mc_trial(board, player):
"""
mc_trial
"""
while board.check_win() == None:
empty_squares = board.get_empty_squares()
if len(empty_squares) == 0:
break
empty_squares = board.get_empty_squares()
square = random.choice(empty_squares)
board.move(square[0],square[1],player)
if player == provided.PLAYERX:
player = provided.PLAYERO
else:
player = provided.PLAYERX
def mc_update_scores(scores, board, player):
"""
mc_update_scores
"""
#print "-----------------------------------"
#print scores
winner = board.check_win()
if winner == provided.DRAW:
return
dim = board.get_dim()
for dummy_i in range(dim):
for dummy_j in range(dim):
square = board.square(dummy_i,dummy_j)
if square == provided.EMPTY:
continue
if winner == player and square == player:
scores[dummy_i][dummy_j] += MCMATCH
if winner == player and square != player and square != provided.EMPTY:
scores[dummy_i][dummy_j] -= MCOTHER
if winner != player and square == player:
scores[dummy_i][dummy_j] -= MCMATCH
if winner != player and square != player and square != provided.EMPTY:
scores[dummy_i][dummy_j] += MCOTHER
#print scores
#print "-----------------------------------"
def get_best_move(board, scores):
"""
get_best_move
"""
empty_squares = board.get_empty_squares()
max_score = float("-inf")
result = (0,0)
for dummy_square in empty_squares:
if scores[dummy_square[0]][dummy_square[1]] > max_score:
max_score = scores[dummy_square[0]][dummy_square[1]]
result = dummy_square
return result
def mc_move(board, player, trials):
"""
mc_move
"""
dim = board.get_dim()
scores = [ [0 for dummy_col in range(dim)] for dummy_row in range(dim)]
for dummy in range(trials):
board_clone = board.clone()
current_player = player
mc_trial(board_clone, current_player)
mc_update_scores(scores, board_clone, player)
for dummy_i in range(dim):
for dummy_j in range(dim):
scores[dummy_i][dummy_j] = scores[dummy_i][dummy_j]/trials
print scores
return get_best_move(board, scores)
# Test game with the console or the GUI.
# Uncomment whichever you prefer.
# Both should be commented out when you submit for
# testing to save time.
provided.play_game(mc_move, NTRIALS, False)
poc_ttt_gui.run_gui(3, provided.PLAYERX, mc_move, NTRIALS, False)
|
# Generator for the prime number sequence
def prime(n):
counter = 1
primes = []
candidate = 2
while counter <= n:
hasDivisor = False
for prime in primes:
hasDivisor = (candidate % prime == 0)
if hasDivisor or prime > candidate**(.5):
break
if not hasDivisor:
counter += 1
primes.append(candidate)
yield candidate
candidate += 1
val = 600851475143
maxPrimeDivisor = 0
for primeNum in prime(val):
print primeNum
if val % primeNum == 0:
maxPrimeDivisor = primeNum
if primeNum > val**(.5):
break
print maxPrimeDivisor |
# Define a generator of the fibonacci sequence; want to evaluate this in lazy and space efficient fashion
def fib(n):
last = 0
penult = 0
current = 0
counter = 1
while counter <= n:
if counter > 1:
penult = last
last = current
current = last + penult
else:
current = 1
yield current
counter += 1
evenSum = 0
for fibNum in fib(4000000):
if fibNum > 4000000:
break
elif fibNum % 2 == 0:
evenSum += fibNum
print evenSum |
def word_count(filename):
file = open(filename)
word_list = []
for line in file:
line = line.rstrip()
words = line.split(" ")
word_list.extend(words)
words_in_file = {}
for word in word_list:
words_in_file[word] = words_in_file.get(word, 0) + 1
for word, number in words_in_file.items():
print("{} {}".format(word, number))
file.close()
# word_count("test.txt")
word_count("twain.txt")
|
import turtle
from Pong_Build_Game import *
# Functions
def paddle_a_up():
y = paddle_a.ycor()
y += 20
paddle_a.sety(y)
def paddle_a_down():
y = paddle_a.ycor()
y -= 20
paddle_a.sety(y)
def paddle_b_up():
y = paddle_b.ycor()
y += 20
paddle_b.sety(y)
def paddle_b_down():
y = paddle_b.ycor()
y -= 20
paddle_b.sety(y)
# Keyboard binding
wn.listen()
wn.onkeypress(paddle_a_up, "w")
wn.onkeypress(paddle_a_down, "s")
wn.onkeypress(paddle_b_up, "Up")
wn.onkeypress(paddle_b_down, "Down") |
class A:
def __init__(self):
self.var1=4
print (self.var1)
def add(self,x,y):
print (self.var1)
return x+y
class B(A):
def __init__(self):
self.var1 = 5
print (self.var1)
a = A()
b = B()
b.add(3,3)
|
class Printer:
def __init__(self, extruders, price, has_misp):
self.extruders = extruders
self.price = price
self.has_misp = has_misp
@property
def extruders(self):
print("Get extruders")
return self._extruders
@extruders.setter
def extruders(self, value):
if not isinstance(value, int):
raise TypeError("No integer!")
if value < 1:
raise ValueError("Need at least one extruder!")
print("Set extruders", value)
self._extruders = value
@property
def price(self):
print("Get price")
return self._price
@price.setter
def price(self, value):
if not isinstance(value, int):
raise TypeError("No integer!")
if value < 2000:
raise ValueError("Too cheap!")
print("Set price", value)
self._price = value
@property
def has_misp(self):
print("Get has_misp")
return self._has_misp
@has_misp.setter
def has_misp(self, value):
if not isinstance(value, bool):
raise TypeError("Must be boolean!")
print("Set has_misp", value)
self._has_misp = value |
#econtactbook.py
#
#Tyler Clark
#23 Dec 2012
#
#a text based contact book that can store, update, and retrieve a
#contact's name, address, phone number, and email by using an xml file
#
#
import xml.etree.ElementTree as ET
#xml parser
class Tree:
#returns root of existing ebook xml file or creates new one
def getBook(self):
try:
tree = ET.parse('ebook.xml')
book = tree.getroot()
except:
book = ET.Element('book')
tree = ET.ElementTree(book)
tree.write('ebook.xml')
tree = ET.parse('ebook.xml')
book = tree.getroot()
return book
class TextUI:
#provides functions for text based user interface
aTree = Tree()
#common Tree instance referred to by Contact and CommandExec classes
def __init__(self):
#intro printed only when program is first run
print("Welcome to your electronic contact book!")
print("Here is the list of commands for your ebook.")
print("Enter one of the following letters to proceed.")
def commandList(self):
#main directory, referred to after each command entry
print()
print("N - New: creates a contact")
print("D - Delete: removes a contact")
print("U - Update: changes a contact's information")
print("S - Search: looks for an existing contact")
print("A - All: displays all contacts")
print("Q - Quit: exits the application")
return self.commandEntry()
def commandEntry(self):
#based on input, directs to contact creation or executes a command on an existing contact
print()
c = input("Please enter a command: ").upper()
if c == 'N':
name, address, phone, email = self.getInputs()
aContact = Contact(name, address, phone, email)
return True
elif c == 'D':
comDel = CommandExec()
comDel.delContact()
return True
elif c == 'U':
comUpdate = CommandExec()
comUpdate.updateContact()
return True
elif c == 'S':
print()
name = input("Enter the name of the contact you would like to look up: ")
comSearch = CommandExec()
comSearch.searchContact(name)
return True
elif c == 'A':
comAll = CommandExec()
comAll.displayAll()
return True
elif c == 'Q':
return False
else:
print()
print("Invalid entry.")
return True
def getInputs(self):
#gets and then returns 4 pieces of info about a new contact from the user
print()
self.name = input("Enter name: ")
self.address = input("Enter address: ")
self.phone = input("Enter phone number: ")
self.email = input("Enter email: ")
return self.name, self.address, self.phone, self.email
class Contact:
#creates a contact with name, address, phone, email and writes to an xml file
def __init__(self, name, address, phone, email):
#sets all tags with the contact's name as an attribute
aTree = TextUI.aTree
book = aTree.getBook()
#creates instance of Tree and sets book as root
#appends contact tag to root, book
contact = ET.SubElement(book, 'contact', key = name)
#appends each piece of information to its contact tag
nameTag = ET.SubElement(contact, 'name', key = name)
nameTag.text = name
addressTag = ET.SubElement(contact, 'address', key = name)
addressTag.text = address
phoneTag = ET.SubElement(contact, 'phone', key = name)
phoneTag.text = phone
emailTag = ET.SubElement(contact, 'email', key = name)
emailTag.text = email
tree = ET.ElementTree(book)
tree.write('ebook.xml')
print()
print("The contact has been saved in your ebook as shown.")
class CommandExec:
#contains all functions for acting on a contact
#includes getBook within class for up to date contact info
def __init__(self):
#creates instance of Tree and sets book as root
aTree = TextUI.aTree
self.book = aTree.getBook()
def displayAll(self):
#displays all information for all contacts
for node in self.book.iter():
if (node.tag != 'book') and (node.tag != 'contact'):
print(node.text)
else:
print()
def searchContact(self, name):
#searches for a specific contact by name and displays all info
print()
i = 0
for node in self.book.iter():
if (node.get('key') == name) and (node.tag != 'contact'):
print(node.text)
i = i + 1
if i == 0:
print("There is no contact by that name.")
return False
else:
return True
def delContact(self):
#removes a contact from the book
print()
name = input("Enter the name of the contact you would like to delete: ")
#confirms decision and then loops thru and deletes each tag matching the name attribute
deleteProceed = self.searchContact(name)
print()
while deleteProceed == True:
decision = input("Are you sure you want to delete this contact? (Y/N) ").upper()
print()
if decision == 'Y':
for parentnode in self.book.iter():
for childnode in parentnode:
if childnode.get('key') == name:
parentnode.remove(childnode)
tree = ET.ElementTree(self.book)
tree.write('ebook.xml')
print(name, "has been deleted.")
return False
elif decision == 'N':
return False
else:
print("Please type either Y or N.")
print()
def updateContact(self):
#updates a contact's information, one piece at a time
print()
name = input("Enter the name of the contact you would like to update: ")
#waits on user input and then writes over the selected value with new info
updateProceed = self.searchContact(name)
print()
while updateProceed == True:
print("N - name")
print("A - address")
print("P - phone")
print("E - email")
print("C - cancel")
print()
infoType = input("Type one of the above letters to update a field, or C to cancel: ").upper()
print()
if infoType == 'N':
infoType = 'name'
newInfo = input("Enter the new name: ")
self.updateInfo(name, infoType, newInfo)
#resets all tag attributes to the new name
for node in self.book.iter():
if node.get('key') == name:
node.set('key', newInfo)
tree = ET.ElementTree(self.book)
tree.write('ebook.xml')
self.searchContact(newInfo)
return False
elif infoType == 'A':
infoType = 'address'
newInfo = input("Enter the new address information: ")
self.updateInfo(name, infoType, newInfo)
self.searchContact(name)
elif infoType == 'P':
infoType = 'phone'
newInfo = input("Enter the new phone number: ")
self.updateInfo(name, infoType, newInfo)
self.searchContact(name)
elif infoType == 'E':
infoType = 'email'
newInfo = input("Enter the new email: ")
self.updateInfo(name, infoType, newInfo)
self.searchContact(name)
elif infoType == 'C':
return False
else:
print("Please type one of the above letters to update, or C to cancel.")
print()
def updateInfo(self, name, infoType, newInfo):
#called by all update selections, loops thru and changes info based on selection and name attribute
for node in self.book.iter():
if (node.get('key') == name) and (node.tag == infoType):
node.text = newInfo
tree = ET.ElementTree(self.book)
tree.write('ebook.xml')
print()
print("Update made.")
def main():
#main loop, waits for user input and keeps redirecting to command list
stillRunning = True
starter = TextUI()
while stillRunning == True:
stillRunning = starter.commandList()
main()
|
import numpy as np
print("Hallo Welt")
'''
W = np.array([[1.,2,3], [3,4,5]])
print(W.shape)
print(W.shape[0])
print(W.shape[1])
print(W.T.shape)
'''
M=np.arange(12).reshape(3,4)
print("Basic Array")
print(M)
print("*"*40)
print(M[:1])
'''
print(M[1,:])
print(M[1])
print(M[:,1])
print(M[:,[1]])
print(M[:,[3,0,1,1]])
print("x")
print(M[:,2:4])
print(M[-2,:])
print(M[-2:,:])
# M[:,2]=2
# print(M)
#########
print("*"*20)
print(M)
print("-")
print(M.shape)
print(M.shape[0])
print(M.shape[1])
s=0
for i in range(M.shape[0]):
for j in range(M.shape[1]):
s+=M[i,j]
print(s, ',', sep='', end='')
print(s)
##########
print("*"*20)
def func(x):
print(x*x)
return x
func(3)
'''
|
import random
randNum = random.randint(1,50)
print("Welcome to Guess the number game !!")
print(randNum)
userNum = int(input("Enter your number"))
while True:
if (randNum == userNum):
print("Congratulation you won !!")
break
elif (randNum > userNum):
print("Opps ...Your number is less.. Please Guess again ")
userNum = int(input("Enter your number"))
elif (randNum < userNum):
print("Opps ...Your number is Grater.. Please Guess again ")
userNum = int(input("Enter your number")) |
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
sums = 0
self.dp = []
self.nums = nums
for index, num in enumerate(nums):
self.dp.insert(index, sums + num)
sums += num
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
return self.dp[j] - self.dp[i] + self.nums[i]
# Your NumArray object will be instantiated and called as such:
nums = [-2, 0, 3, -5, 2, -1]
obj = NumArray(nums)
i = 0
j = 2
param_1 = obj.sumRange(i, j)
print(param_1)
|
# Definition for a binary tree node.
from functools import reduce
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
def sub_sum(r, l, sub_count, in_s):
"""
:param in_s: List
:param sub_count: List
:param r: TreeNode
:param l: List
:return:
"""
if r:
if len(l) != 0:
l.append(l[-1] + r.val)
else:
l.append(r.val)
if len(l) != 0:
if l[-1] == in_s:
count.append(1)
sub_sum(r.left, l, sub_count, in_s)
sub_sum(r.right, l, sub_count, in_s)
l.pop()
def visit(out_root, out_count, out_s):
if out_root:
l = []
sub_sum(out_root, l, out_count, out_s)
visit(out_root.left, out_count, out_s)
visit(out_root.right, out_count, out_s)
count = []
visit(root, count, sum)
if len(count) != 0:
return len(count)
else:
return 0
solution = Solution()
s = TreeNode(10)
s.left = TreeNode(5)
s.left.left = TreeNode(3)
s.left.right = TreeNode(2)
s.left.right.right = TreeNode(1)
s.left.left.left = TreeNode(3)
s.left.left.right = TreeNode(-2)
s.right = TreeNode(-3)
s.right.right = TreeNode(11)
print(solution.pathSum(s, 8))
|
from CityInformation import CityInformation
from flask import Flask, request
app = Flask(__name__)
c = CityInformation()
@app.route('/')
def home_page():
return """
<form action="/closest-neighbors" method="post">
Use this form to search for closest neighbors to a certain geo_id: <br>
Enter the geo_id: <input type="number" name="geo_id"><br>
Enter the number of closest points: <input type="number" name="neighbors"><br>
<input type="submit" value="Submit">
</form> <br><br><br>
<form action="/search" method="post">
Use this form to seach our dataset for city information: <br>
Enter a single word to search: <input type="text" name="search"><br>
<input type="submit" value="Submit">
</form>
"""
@app.route('/closest-neighbors', methods=['POST'])
def closest_neighbors():
#front end enforces that these have to be numbers in the post request
if len(str(request.form['geo_id']).strip()) == 0 or len(str(request.form['neighbors']).strip()) == 0:
return "Please enter numbers into the fields"
return c.get_closest_points(int(request.form['geo_id'].strip()), int(request.form['neighbors'].strip()))
@app.route('/search', methods=['POST'])
def search():
if len(str(request.form['search']).strip()) == 0:
return "please enter a search query"
return c.search(request.form['search'].strip())
if __name__=='__main__':
app.run(debug=False) |
# Santiago Naranjo
# 10 de agosto de 2020 primer entrega
# 24 de agosto de 2020 segunda entrega
# Mejoradas funciones de suma,resta, multiplicacion y division, agragadas funciones con matrices
import math
#crea una lista de 4 elementos donde los primeros 2 son un numero complejo y los otros 2 otro
#recibe dos listas de 2 elementos y los suma segun las propiedades de los numeros complejos
def suma(a,b):
num = (a[0]+b[0], a[1]+b[1])
return num
#recibe dos lista de 2 elementos y los resta segun las propiedades de los numeros complejos
def resta(a,b):
num = (a[0] - b[0], a[1] - b[1])
return num
#recibe dos lista de 2 elementos y los multiplica segun las propiedades de los numeros complejos
def mult(a,b):
num = (a[0]*b[0] - a[1]*b[1], a[0]*b[1] + a[1]*b[0])
return num
#recibe dos lista de 2 elementos y los divide segun las propiedades de los numeros complejos
def divi(a,b):
den = (b[0] ** 2) + (b[1] ** 2)
num = (round((a[0]*b[0] + a[1]*b[1]) / den,2), round((a[0]*b[1] - a[1]*b[0]) / den,2))
return num
#recibe una lista de 2 elementos y encuenta su modulo o la raiz de la suma de sus cuadrados
def modu(lista):
a = lista[0]
b = lista[1]
mod = round(((a**2)+(b**2))**0.5,2)
return mod
#recibe una lista de 2 elemento e invierte el valor del elemento en la segunda posicion
def conj(lista):
res = (lista[0],-lista[1])
return res
#recibe una lista de 2 elementos y encuentra el angulo entre los numeros
def fase(lista):
a = lista[0]
b = lista[1]
theta = round(math.atan(b/a),2)
return theta
#recibe una lista con coordenadas polares y las cambia al sistema cartesiano
def pola(lista):
a = round(int(lista[0])*math.cos(float(lista[1])),2)
b = round(int(lista[0])*math.sin(float(lista[1])),2)
carte = [a,b]
return carte
#recibe una lista con coordenadas cartesianas y las cambia al sistema polar
def car_pol(lista):
a = modu(lista)
b = fase(lista)
coord = [a,b]
return coord
#recibe n vectores de n elementos y los suma
def sumaVec(a,b):
resul = []
for i in range(len(a)):
resul += [suma(a[i],b[i])]
return resul
#recibe un vector y encuentra su inverso aditivo
def inverso(a):
resul = []
for i in range(len(a)):
resul += [mult(a[i],(-1,0))]
return resul
#recibe un vector y un escalar y los multiplica
def EscxVect(a,b):
resul = []
for i in range(len(a)):
resul += [mult(a[i],b)]
return resul
#recibe dos matrices de tamaños iguales y las suma
def Sum_Ma(a,b):
n, m = len(a), len(a[0])
N, M = len(b), len(b[0])
if n == N and m == M:
c = [[0 for j in range(m)]for i in range(n)]
for i in range(n):
for j in range(m):
c[i][j] = suma(a[i][j],b[i][j])
return c
#recibe una matriz y encuentra su inversa aditiva
def Inver_Mat(a):
n, m = len(a), len(a[0])
c = [[0 for j in range(m)]for i in range(n)]
for i in range(n):
for j in range(m):
c[i][j] = mult(a[i][j],[-1,0])
return c
#recibe una matriz y un num escalar y multiplica cada elemento de la matriz por el num escalar
def MatxEsc(a,b):
n, m = len(a), len(a[0])
c = [[0 for j in range(m)]for i in range(n)]
for i in range(n):
for j in range(m):
c[i][j] = mult(a[i][j],b)
return c
#encuentra la transpuesta de una matriz
def Transp(a):
n, m = len(a), len(a[0])
c = [[0 for j in range(m)]for i in range(n)]
for i in range(n):
for j in range(m):
c[i][j] = a[j][i]
return c
#encuentra la conjugada de una matriz
def conj_ma(a):
n, m = len(a), len(a[0])
c = [[0 for j in range(m)]for i in range(n)]
for i in range(n):
for j in range(m):
c[i][j] = conj(a[i][j])
return c
#encuentra la adjunta de una matriz
def adjunta(a):
c = Transp(conj_ma(a))
return c
#recibe dos matrices de tamaños compatibles y las multiplica
def Mul_Ma(a,b):
n, m = len(a), len(a[0])
N, M = len(b), len(b[0])
c = [[(0,0) for j in range(m)] for i in range(n)]
if m == N:
for i in range(n):
for j in range(M):
for k in range(N):
p = mult(a[i][k],b[k][j])
q = c[i][j]
c[i][j] = suma(p,q)
return c
#calcula la accion de una matriz sobre un vector
def Accion(a,b):
n, m = len(a), len(a[0])
B = len(b)
c = []
if B == m:
ceros = [0,0]
for i in range (n):
for j in range(m):
p = mult(a[i][j],b[j])
ceros = suma(ceros,p)
c += [ceros]
ceros = [0,0]
return c
#calcula el producto interno de dos vectores
def interno(a,b):
c = (0,0)
for i in range(len(a)):
aconj = conj(a[i])
n = mult(aconj, b[i])
c = suma(c, n)
return c
#calcula la norma de un vector
def norma(a):
e = interno(a,a)
r = e[0]**0.5
r = round(r,2)
return r
#calcula la distancia entre dos vectores
def distancia(a,b):
f = inverso(b)
d = sumaVec(a,f)
c = interno(d,d)
res = c[0]**0.5
res = round(res,2)
return res
#crea una matriz identidad de n*m
def identidad(m,n):
c = [[[0,0] for j in range(m)] for i in range(n)]
for i in range(n):
for j in range(m):
if i == j:
c[i][j] = ((2/2),0)
return c
#verifica si una matriz es unitaria
def unitaria(a):
mat = Mul_Ma(adjunta(a),a)
iden = identidad(len(a),len(a[0]))
if mat == iden:
return True
else:
return False
#verifica si una matriz es hermitiana
def hermitiana(a):
c = adjunta(a)
if a == c:
return True
else:
return False
#encuentra el producto tensor/cruz de dos matrices/vectores
def tensor(a,b):
res = []
m, n = 0, 0
while (m<((len(a)-1)**2)):
r1 = a[m]
r2 = b[n]
aux = []
for i in r1:
for j in r2:
aux += [mult(i,j)]
m += 1
r2 = b[n]
res += [aux]
aux = []
for i in r1:
for j in r2:
aux += [mult(i,j)]
m += 1
n -= 1
res += [aux]
return res
|
"""
validator.py
Steve Ashman
Basic validation library for console apps
"""
def get_valid_selection(valid_options, display_options):
"""
Gets a valid selection from stdin matching one of the provided options
:param valid_options: list of valid options for selection
:param display_options: function for displaying options to the user
:return: valid selection from the provided list
"""
valid = False
while not valid:
display_options()
in_value = input()
try:
in_value = int(in_value)
except ValueError:
pass
if in_value in valid_options:
valid = True
else:
print("Invalid input")
return in_value
def write_invalid_input():
"""
Prints "Invalid input"
:return: No return value
"""
print("Invalid input")
def get_selected_action(in_value, switcher):
"""
Gets the action for a selected menu item
:param in_value: validated input value
:param switcher: dictionary of actions to get value from
:return: selected action from switcher
"""
try:
return switcher.get(in_value, write_invalid_input)
except ValueError:
return None
|
for i in range(1, 100):
if i % 2 == 0 and i >= 20:
print("Not Weird", i, "this is from first condition")
elif i % 2 == 0 and 6 <= i <= 20:
print("Weird", i, "this is from second condition")
elif i % 2 == 0 and 2 <= i < 5:
print("Not Weird", i, "this is from last condition")
else:
print(i, "is a odd number")
|
#TODO Class Variables
"""
Reference: Class Objects
The way these objects work are whenever the instance variables are initialized
if the instance variables themselves don't have an attribute they go looking for
that variable in the class to which they belong and inherit the value from there
this will print the values that exist within the variable itself any value
that doesn't get listed out here but still returns a valid response will get
inherited from the class to which the object belongs
"""
class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
return int(self.pay * self.raise_amount)
emp_1 = Employee('Corey', 'Schaefer', 50000)
emp_2 = Employee('Test', 'User', 60000)
# TODO print out the value of class variable
print(Employee.raise_amount)
# TODO print out content of class object
print(emp_1.__dict__)
# TODO print out raise amount for employee 2
print(emp_2.raise_amount)
# TODO return amount after raise is applied for both employees
print(Employee.apply_raise(emp_1))
print(Employee.apply_raise(emp_2))
print(emp_1.apply_raise())
print(emp_2.apply_raise())
# TODO print out total number of employees
print(Employee.num_of_emps)
|
def median(size, values):
if size % 2 == 0:
median = (values[int(size / 2) - 1] + values[int(size / 2)]) / 2
else:
median = values[int(size / 2)]
return int(median)
size = int(input())
numbers = sorted(list(map(int, input().split())))
if size % 2 == 0:
data_low = numbers[0:int(size / 2)]
data_high = numbers[int(size / 2):size]
else:
data_low = numbers[0:int(size / 2)]
data_high = numbers[int(size / 2) + 1:size]
print(median(len(data_low), data_low))
print(median(size, numbers))
print(median(len(data_high), data_high))
|
# Hordó bor, befér nem fér
# Van egy henger alakú hordónk,
# melybe nem tudjuk, hogy belefér-e a rendelkezésre álló bor.
# Kérd be a bor mennyiségét literben, majd a hordó
# összes szükséges adatát cmben. Adj tájékoztatást,
# hogy hány literes a hordó, és hogy belefér-e a hordóba a bor!
# Ha belefér, akkor add meg, hogy mennyi férne még bele!
# Írd ki százalékosan is a telítettséget! Az adatokat egészre kerekítve írd ki!
pi = 3.14
borL = float(input("Add meg a bor mennyiségét (literben)!"))
d = float(input("Add meg a hordó átmérőjét (centiméterben)!"))
r = float(d/2)
m = float(input("Add meg a hordó magasságát (centiméterben)!"))
hordoV = float(pi*(r**2)*m)
hordoL = float(hordoV*0.001)
telitettsegSzamol = float((hordoL/borL)*float(100))
print(telitettsegSzamol)
if(borL != hordoL):
if(borL > hordoL):
print("A hordó kapacitása:",float(hordoL),"(liter) Ezért nem fér bele a hordóba a bor!")
print("A hordóba a bor",float(telitettsegSzamol),"százaléka fér bele!")
else:
print("A hordó kapacitása:", float(hordoL), "(liter) Ezért fér bele a hordóba a bor!")
print("A hordóba még", float(hordoL-borL), "(liter) bor fér bele",
"A hordó ",round(float(telitettsegSzamol)/float(100),3),"%-a telt meg!")
else:
print("A hordó kapacitása:", round(hordoL), "(liter) Ez megegyezol a bor mennyiségével!")
print("A hordóba pontosan", round(hordoL), "(liter) bor fér bele",
"A hordóba egy cseppel több bor sem fér! 100 százaléka tele van!")
|
class attendanceshortageexception(Exception):
def __init__(self, arg):
self.msg=arg
class incomeexception(Exception):
def __init__(self, arg):
self.msg=arg
class gpaexception(Exception):
def __init__(self, arg):
self.msg=arg
gpa = int(input("Enter cgpa:"))
if gpa<7:
raise gpaexception("your cgpa is less than 7")
attendance = int(input("enter your attendance:"))
if attendance<75:
raise attendanceshortageexception("your attendence is below 75")
income = int(input("enter your income:"))
if income>500000:
raise attendanceshortageexception("your parents income is higher than 500000")
else:
print( "CGPA:", gpa, "Attendance:", attendance, "Parents Income:", income) |
i=0
m=0
dict={12345:"Siddhant",
12346:"Samer",
12347:"Suyog",
12348:"Saurabh",
"Statement":[]}
while(i==m):
Ac_number=int(input("Enter your Account Number"))
x=dict.get(Ac_number)
if Ac_number in dict :
print("Your Name is",x)
Amount=int(input("Please enter opening balance"))
print("1.View Bal\n2.Deposite\n3.Withdrawl\n4.Transfer\n5.Statement")
c=int(input())
if c==1:
print("Your account balance is=",Amount)
print("Enter 5 to know statement or Press any key to move further")
c=int(input())
if c==5:
dict["Statement"].append("One View")
b=dict.get("Statement")
print(b)
elif c==2:
Deposite=int(input("Enter amount to be deposite"))
Now=Deposite+Amount
print("Your Account is credited for Rs=",Deposite,"Now your Balance is Rs=",Now)
print("Enter 5 to know statement or Press any key to move further")
c=int(input())
if c==5:
dict["Statement"].append("One Deposite")
b=dict.get("Statement")
print(b)
elif c==3:
Withdrawl=int(input("Enter a Amount to be withdrawl"))
if Withdrawl<=Amount:
Amount=Amount-Withdrawl
print("You have withdrawl Rs=",Withdrawl,"Now your balance is=",Amount)
print("Enter 5 to know statement or Press any key to move further")
c=int(input())
if c==5:
dict["Statement"].append("One Withdrawl")
b=dict.get("Statement")
print(b)
else:
print("Insufficiant Balance")
elif c==4:
print("Name is account holder is",x)
Ac_number=int(input("Enter benificery Account Number"))
x=dict.get(Ac_number)
if Ac_number in dict :
print("Name of benificery is",x)
Tra=int(input("Amount to be tranfer"))
if Tra<=Amount:
Tra=Amount-Tra
print("Money transfer successful")
print("Available balance is",Tra)
elif Tra>Amount:
print("Insufficent balance to transfer")
print("Enter 5 to know statement or Press any key to move further")
c=int(input())
if c==5:
dict["Statement"].append("One Transfer")
b=dict.get("Statement")
print(b)
else:
print("Wrong Account Number")
print("Do you want to continue? press 1 for yes or 2 for no")
d=int(input())
if d==1:
m=m+1
elif d==2:
m=1
print("exit")
elif c==5:
print("0 transaction ")
print("Do you want to continue? press 1 for yes or 2 for no")
d=int(input())
if d==1:
m=m+1
i=m
elif d==2:
m=1
print("exit")
else:
print("Wrong Account Number")
print("Do you want to continue? press 1 for yes or 2 for no")
d=int(input())
if d==1:
m=m+1
elif d==2:
m=1
print("exit")
|
"""A module for sets of tiles that make up a component of a map, such as a room or corridor"""
import random
import mapfeatures
class MapComponent():
def __init__(self, world_coordinates, width, height):
self.w_x, self.w_y = world_coordinates
self.width = width
self.height = height
self.mapfeatures = [[None for x in range(self.width)] for y in range(self.height)]
self.entities = []
def do_tiles_overlap(self, other):
"""Return true if any tiles in other occupy the same world space as the tiles
in this room.
"""
if not self.do_bounds_overlap(other):
return False
#Iterate over the bounding box intersection of both rooms and
#return True as soon as both contain a tile that is not None
self_left = max(self.x, other.x) - self.x
other_left = max(self.x, other.x) - other.x
self_top = max(self.y, other.y) - self.y
other_top = max(self.y, other.y) - other.y
intersect_width = min(self.x+self.width, other.x+other.width) - \
max(self.x, other.x)
intersect_height = min(self.y+self.height, other.y+other.height) - \
max(self.y, other.y)
for y in range(intersect_height):
for x in range(intersect_width):
if self.mapfeatures[y+self_top][x+self_left] is not None and \
other.mapfeatures[y+other_top][x+other_left] is not None:
return True
return False
def do_bounds_overlap(self, other):
"""Return True if the bounding box of other overlaps with the bounding
box of this room in world space. (The tiles may or may not overlap.
"""
#v_overlap is true if you can draw a vertical line that passes through
# both bounding boxes.
v_overlap = not (self.x >= (other.x + other.width) or (self.x + self.width) <= other.x)
#h_overlap, ditto but horizontally.
h_overlap = not (self.y >= (other.y + other.height) or (self.y + self.height) <= other.y)
return v_overlap and h_overlap
def append(self, other, x_offset, y_offset):
"""Return a room containing the tiles in self with the tiles in other mapped onto
them. Tiles from other overwrite tiles in self when they overlap.
x_offset: The number of tiles to the right that the tiles from other should start
y_offset: The number of tiles down that the tiles from other should start
"""
#First, get the new width, height, w_x, and w_y
new_width = max((self.x+self.width), (other.x+other.width)) - min(self.x, other.x)
new_height = max((self.y+self.height), (other.y+other.height)) - min(self.y, other.y)
new_x = min(self.x, other.x)
new_y = min(self.y, other.y)
new_component = MapComponent((new_x, new_y), new_width, new_height)
#Set the new mapfeatures to the union of both rooms' mapfeatures
new_component.mapfeatures = union_mapfeatures(self.mapfeatures, other.mapfeatures, x_offset, y_offset)
#Set the new entities to the union of both rooms' entities lists, and change the location
#of the entities in other to match the offset
new_entities = other.entities
for e in new_entities:
e.x += x_offset
e.y += y_offset
new_entities.extend(self.entities)
return new_component
class Room(MapComponent):
"""A randomly-sized box of floor tiles surrounded with wall tiles.
world_coordinates - a tuple containing the x,y coordintates of the room's upperleft-most tile
in world-space.
width_range - a tuple containing the min and max+1 possible width values
height_range - a tuple containing the min and max+1 possible height values
"""
def __init__(self, world_coordinates, width_range, height_range, *args, **kwargs):
self.width = random.randrange(*width_range)
self.height = random.randrange(*height_range)
super(Room, self).__init__(world_coordinates, self.width, self.height, *args, **kwargs)
self.mapfeatures = self.generate_room_mapfeatures()
self.entities = self.generate_room_entities()
def generate_room_mapfeatures(self):
wall_row = [mapfeatures.Wall() for x in range(self.width)]
floor_row = [mapfeatures.Wall()]
floor_row += [mapfeatures.Floor() for x in range(self.width-2)]
floor_row += [mapfeatures.Wall()]
roomfeatures = []
roomfeatures.append(wall_row.copy())
for y in range(self.height-1):
roomfeatures.append(floor_row.copy())
roomfeatures.append(wall_row.copy())
return roomfeatures
def generate_room_entities(self):
return []
class Corridor(MapComponent):
"""A hallway of floor tiles.
start_coords - a tuple of x,y coordinates denoting one end of the corridor
end_coords - a tuple of x,y coordinates denoting the other end of the corridor
start_vertical - If True, the corridor will try to move upward or downward before
it bends. If False, it will try to move left or right first. If None, it will start
in whichever direction is farther between the two points.
If start_coords and end_coords are not colinear, the corridor will bend in a Z or N shape
at a random point along its length.
"""
def __init__(self, start_coords, end_coords, start_vertical=None):
width = abs(start_coords[0] - end_coords[0])
height = abs(start_coords[1] - end_coords[1])
world_coords = (min(start_coords[0], end_coords[0]), min(start_coords[1], end_coords[1]))
super(Corridor, self).__init__(world_coords, width, height)
self.start_coords = start_coords
self.end_coords = end_coords
self.mapfeatures = self.generate_corridor_mapfeatures(start_vertical)
self.entities = self.generate_corridor_entities()
def generate_corridor_mapfeatures(self, start_vertical):
#Handle cases where endpoints are colinear
if self.start_coords[0] == self.end_coords[0]:
return [[mapfeatures.Floor() for tile in range(width)]]
if self.start_coords[1] == self.end_coords[1]:
return [[mapfeatures.Floor()] for row in range(height)]
#Otherwise, figure out where to bend
if start_vertical is None:
start_vertical = self.height > self.width
mapfeatures = [[None for tile in self.width] for row in range(self.height)]
if start_vertical:
bend_point = random.randrange(1, self.height-1)
else:
bend_point = random.randrange(1, self.width-1)
left_point, right_point = (self.start_point, self.end_point) if self.start_point[0] < self.end_point[0] \
else (self.end_point, self.start_point)
top_point, bottom_point = (self.start_point, self.end_point) if self.start_point[1] < self.end_point[1] \
else (self.end_point, self.start_point)
for y, row in enumerate(self.height):
for x, tile in enumerate(self.width):
if start_vertical and \
(x == self.top_point[0] and y < bend_point or \
x == self.bottom_point[0] and y > bend_point or \
y == bend_point) \
or not start_vertical and \
(y == self.left_point[1] and x < bend_point or \
y == self.right_point[1] and x > bend_point or \
x == bend_point):
mapfeatures[y][x] = mapfeatures.Floor()
return mapfeatures
def generate_corridor_entities(self):
return []
|
class union_find:
# Getters
def get_num_components(self):
return self.num_components
def print_parents(self):
for i in range(self.n):
print("%d -> %d\n" % (i, self.parent[i]))
# Constructor
def __init__(self, n):
# initialize your arrays here
# And maybe helpful to make them of size "n + 1"...one larger than n
self.parent = [0]*(n) # parent[i] = parent of i
self.rank = [0]*(n) # rank[i] = rank of subtree rooted at i
self.num_components = n # number of components
self.n = n
for i in range(len(self.parent)):
self.parent[i] = i
# This method should return the value of the "root" of the
# tree that "number" is found inside.
def find(self, calculated_idx):
if calculated_idx != self.parent[calculated_idx]:
self.parent[calculated_idx] = self.find(self.parent[calculated_idx])
return self.parent[calculated_idx]
# This method should union the two components that "a" and "b" belong to.
def union(self, from_vertex, to_vertex):
A = self.find(from_vertex)
B = self.find(to_vertex)
if (self.rank[A] == self.rank[B]):
self.parent[B] = A
self.rank[A]+=1
elif (self.rank[A] < self.rank[B]):
# stay rank of B
self.parent[A] = B
else:
# stay rank of A
self.parent[B] = A
self.num_components -= 1
# boolean areInSameComponent(a, b)::
# This method should return "true" if values "a" and "b" belong
# to the same component. Otherwise, "false" should be returned.
def are_in_same_component(self, a, b):
return self.find(a) == self.find(b)
|
def fizz_buzz(i):
if i%15 == 0: #Test for FizzBuzz
return("FizzBuzz")
elif i%3 == 0: #Test for Fizz
return("Fizz")
elif i%5 == 0: #Test for Buzz
return("Buzz")
else: #Condition if not Fizz,Buzz or FizzBuzz
return (i) |
def Main():
print("LEARNING PYTHON - ITERATION (looping words)")
words = ['cat','bat','hat','rat','sat']
for word in words:
print(word)
if __name__ == "__main__":
Main() |
firstName="Mohammad"
midName="Febri"
lastName="Ramadlan"
fullname=firstName+" "+midName+" "+lastName
print(fullname)
print(firstName)
print(fullname[3])
print(fullname[0:10])
print(fullname[3:]) |
import random
from copy import deepcopy
class Matrix:
def __init__(self, nrows, ncols):
self.nrows=nrows
self.ncols=ncols
self.matrix=[]
for i in range(self.nrows):
row=[]
for j in range(self.ncols):
row.append(random.randint(0,9))
self.matrix.append(row)
def add(self, m):
if self.nrows!=m.nrows or self.ncols!=m.ncols:
print("Matrixs's size should be in the same size")
return Matrix(0,0)
else:
matrixA=self.matrix
matrixB=m.matrix
new=Matrix(self.nrows,self.ncols)
for i in range(self.nrows):
for j in range(self.ncols):
new.matrix[i][j]=matrixA[i][j]+matrixB[i][j]
return new
def sub(self, m):
if self.nrows!=m.nrows or self.ncols!=m.ncols:
print("Matrixs's size should be in the same size")
return Matrix(0,0)
else:
matrixA=self.matrix
matrixB=m.matrix
new=Matrix(self.nrows,self.ncols)
for i in range(self.nrows):
for j in range(self.ncols):
new.matrix[i][j]=matrixA[i][j]-matrixB[i][j]
return new
def mul(self, m):
if self.nrows!=m.ncols :
print("I doesn't fit the martix multiplication rule")
return Matrix(0,0)
else:
matrixA=self.matrix
matrixB=m.matrix
new=Matrix(self.nrows,m.ncols)
new.nrows=self.nrows
new.ncols=m.ncols
for i in range(self.nrows):
for j in range(m.ncols):
total=0
for k in range(m.nrows):
newsum=0
newsum=matrixA[i][k]*matrixB[k][j]
total=total+newsum
new.matrix[i][j]=total
return new
def transpose(self):
matrixA=self.matrix
new=Matrix(self.ncols,self.nrows)
for i in range(self.nrows):
for j in range(self.ncols):
new.matrix[j][i]=matrixA[i][j]
return new
def display(self):
for i in range(self.nrows):
for j in range(self.ncols):
print(self.matrix[i][j],end=' ')
print(end='\n')
print(end='\n')
Ar=int(input('輸入A矩陣行數:'))
Ac=int(input('輸入A矩陣行數:'))
print('MatrixA(',Ar,Ac,')')
A=Matrix(Ar,Ac)
A.display()
Br=int(input('輸入B矩陣行數:'))
Bc=int(input('輸入B矩陣行數:'))
print('MatrixA(',Br,Bc,')')
B=Matrix(Br,Bc)
B.display()
print('='*10,'A+B','='*10)
C=A.add(B)
C.display()
print('='*10,'A-B','='*10)
D=A.sub(B)
D.display()
print('='*10,'A*B','='*10)
E=A.mul(B)
E.display()
print('='*5,'The transpose of A+B','='*5)
F=E.transpose()
F.display()
|
print "enter the limit"
n=int(raw_input())
i=1
s=0
while i<=n:
s=s+i
i=i+1
print "sum is",s
|
"""@Author: Maria DaRocha
Date: 23-8-2020
Title: Python Tutoring Session One
@Topics: Python 3 Basics
Arithmatic Operators
Boolean Operators
Importing
Lists
Print
Strings
Type Checking
@Source: https://www.learnpython.org
"""
#Demo a simple function
def run_basic_tasks():
#Strings
my_name = "Maria"
print("Hello and welcome " + my_name + "!")
#Variables
x = 1
if x == 1:
# indented four spaces
print("x is 1.")
#Float assignment
myfloat = 7.0
print(myfloat)
myfloat = float(7)
print(myfloat)
#String assignment
mystring = 'hello'
print(mystring)
mystring = "hello"
print(mystring)
# Demo some numeric operators
def operator_fun():
# a = 1
# b = 2
a, b = 1, 2
# Addition
c = a + b
print(str(a) + " + " + str(b) + " = " + str(c))
# Subtraction
c = a - b
print(str(a) + " - " + str(b) + " = " + str(c))
# Multiplication
c = a * b
print(str(a) + " * " + str(b) + " = " + str(c))
# Division
c = a / b
print(str(a) + " / " + str(b) + " = " + str(c))
# Modulo (Remainder)
c = a % b
print(str(a) + " % " + str(b) + " = " + str(c))
# Concatinate strings
hello = "hello"
world = "world"
helloworld = hello + " " + world
print(helloworld)
# Square a number
square = 7 ** 2
print("Seven to the power of two = %d" % square)
# Cube a number
cube = 7 ** 3
print("Seven to the power of three = %d" % cube)
# Demo type-checking
def type_checking():
mystring = 'hello'
myfloat = float(10)
myint = 20
# testing code
if mystring == "hello":
print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
print("Float: %f" % myfloat)
if isinstance(myint, int) and myint == 20:
print("Integer: %d" % myint)
# Demo print function syntax
def print_fun():
# This prints out whatever values a and b are with a '+' in between
a, b = 11, 234
print("%d + %d" % (a,b))
# This prints out "John is 23 years old."
name = "John"
age = 23
print("%s is %d years old." % (name, age))
# This prints out: A list: [1, 2, 3]
mylist = [1,2,3]
print("A list: %s" % mylist)
# Get the length of a string
astring = "hello"
print("hello is %d letters long" % len(astring))
# printing strings astring[start:stop:step]
astring = "Hello world!"
print(astring[3:7])
print(astring[3:7:1])
#String manipulation
# prints "!dlrow olleH"
print(astring[::-1])
# Uppercase
print(astring.upper())
# Lowercase
print(astring.lower())
# Startswith and Endswith
print(astring.startswith("Hello")) # TRUE
print(astring.endswith("asdfasdfasdf")) # FALSE
# Split string by a character (becomes a list)
two_words = astring.split(" ")
print("Two words: %s" % two_words)
# Demo lists
def list_fun():
mylist = []
mylist.append(4)
mylist.append("Aaron")
mylist.append(17)
#print(mylist[0]) # prints first number appended
#print(mylist[1]) # prints second number appended
#print(mylist[2]) # etc
# prints out values of list on separate lines
for x in mylist:
if isinstance(x, int):
print(x)
# prints out My List: [x, y, z, etc..]
print("My list: %s" % mylist)
# Demo boolean operators
def boolean_fun():
x = 2
# Equal to
print(x == 2) # prints out True
print(x == 3) # prints out False
# Less than
print(x < 3) # prints out True
# Greater than
print(x > 3) # prints out False
# NOT equal to
print(x != 3) # prints out True
# And operator
if x == 2 and x < 3: # True
print(x == 2 and x > 3) # False
# In operator
name = "John"
if name in ["John", "Rick"]:
print("Your name is either John or Rick.")
# Is operator
x = [1,2,3]
y = [1,2,3]
print(x == y) # Prints out True
print(x is y) # Prints out False
# Not operator
isthislit = (x is y) # False -> This is not lit
print(not isthislit) # Prints out True -> Now it's lit again
print((not True) == (False)) # Prints out True -> Not true is false
# IN THE NEXT SECTION...
# Loops
# Demo save function
# Demo load function |
name = input ("What is your name? ")
age = input ("How old are you? ")
numberofyearsto100 = 100 -int(age)
yearof100age = 2018 + numberofyearsto100
print("Your name is " + name " and will be 100s old in" + str(yearOf100Age))
|
#!/usr/bin/python
"""
email_terminal.py is a script written by Tina Quach (quachtina96@gmail.com). It
is meant to be game that reflects the email experiences of the typical MIT
undergraduate living in East Campus. Given that the script prompts for your email
information, and pulls real emails out of your inbox for the purpose of the game
interaction, it is ideal if you are an undergraduate MIT student living in East
Campus. No guarantees if you aren't.
At the same time, you should feel free to download a local version of the code
and tinker with it!
"""
import email, getpass, imaplib, os
from cmd import Cmd
import random
from collections import defaultdict
import time
type_to_filter_dict = {'EC': '(TO "ec-discuss@mit.edu")',
'Piazza': '(FROM "no-reply@piazza.com>")',
"Jobs": '(TO "eecs-jobs-announce@csail.mit.edu")'}
class Email():
def __init__(self, header, content, email_type):
self.sender = header[header.find('['): header.find(']')+1]
self.subject = header[header.find(':')+1 :]
self.header = header
self.content = content
self.type = email_type
class EmailClient():
def __init__(self, opt_email_list=None):
# self.map maps email type to a list of
if opt_email_list:
self.map = self.generate_map_from_email_list(opt_email_list)
else:
self.map = defaultdict(list)
self.user = None
def generate_map_from_email_list(self, email_list):
email_map = defaultdict(list)
for email in email_list:
email_map[email.email_type].append(email)
return email_map
def add_to_map(self, email_list):
for email in email_list:
self.map[email.type].append(email)
return self.map
def get_emails(self, opt_count=None, opt_email_type=None):
if opt_email_type:
result = self.map[opt_email_type]
else:
result = []
for values in self.map.values():
result += [value for value in values]
if opt_count:
return result[:min(len(result), opt_count)]
else:
return result
def get_random_email(self, opt_email_type=None):
if opt_email_type:
rand_email = random.choice(self.get_emails(email_type))
else:
rand_email = random.choice(self.get_emails())
return rand_email
def populate_basic_map(self, num_emails):
if not test:
self.user = raw_input("your email (without the @gmail.com): ")
#pwd = raw_input("password: ")
pwd=getpass.getpass()
else:
self.user = ''
pwd = ''
print('Loading...')
# of emails to fetch per category.
fetch = num_emails
# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(self.user+str("@gmail.com"),pwd)
m.select("INBOX") # here you a can choose a mail box like INBOX instead
# use m.list() to get all the mailboxes
email_list = []
date = (datetime.date.today() - datetime.timedelta(3)).strftime("%d-%b-%Y")
result, data = m.uid('search', None, '(SENTSINCE {date})'.format(date=date))
items = data[0].split()
if (int(fetch)>0):
sublist=items[-1*(min(int(fetch), len(items))):]
else:
sublist=items
for emailid in sublist:
resp, data = m.uid('fetch', emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
email_body = data[0][1] # getting the mail content
mail = email.message_from_string(email_body) # parsing the mail content to get a mail object
header = "["+mail["From"]+"] : Re:" + mail["Subject"]
# we use walk to create a generator so we can iterate on the parts and forget about the recursive headache
content = []
for part in mail.walk():
if part.get_content_type() == 'text/plain':
body = part.get_payload(decode=True)
content.append(body)
else:
continue
email_obj = Email(header, '\n'.join(content), 'any')
email_list.append(email_obj)
self.add_to_map(email_list)
def populate_map(self, type_to_filter_dict, num_emails_per_filter):
self.user = raw_input("your email (without the @gmail.com): ")
#pwd = raw_input("password: ")
pwd=getpass.getpass()
filename = 'emails'
print('Loading...')
# of emails to fetch per category.
fetch = num_emails_per_filter
# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(self.user+str("@gmail.com"),pwd)
m.select("INBOX") # here you a can choose a mail box like INBOX instead
# use m.list() to get all the mailboxes
for email_type, email_filter in type_to_filter_dict.items():
print email_type
try:
email_list = []
resp, items = m.search(None, email_filter) # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
items = items[0].split() # getting the mails id
f=open(filename,'w')
if (int(fetch)>0):
sublist=items[-1*(min(int(fetch), len(items))):]
else:
sublist=items
for emailid in sublist:
resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
email_body = data[0][1] # getting the mail content
mail = email.message_from_string(email_body) # parsing the mail content to get a mail object
header = "["+mail["From"]+"] : Re:" + mail["Subject"]
# we use walk to create a generator so we can iterate on the parts and forget about the recursive headache
content = []
for part in mail.walk():
if part.get_content_type() == 'text/plain':
body = part.get_payload(decode=True)
content.append(body)
else:
continue
email_obj = Email(header.decode('utf-8').strip(), '\n'.join(content).decode('utf-8').strip(), email_type)
email_list.append(email_obj)
self.add_to_map(email_list)
except:
print('FAILED')
def preview_email(self, email):
OKBLUE = '\033[94m'
ENDC = '\033[0m'
print OKBLUE + email.header + ENDC
def read_email(self, email):
OKBLUE = '\033[94m'
ENDC = '\033[0m'
print OKBLUE + email.content + ENDC
def get_email_address(self):
return self.user + '@gmail.com'
class JayGame(Cmd):
def __init__(self, email_client, jay):
Cmd.__init__(self)
self.email_client = email_client
self.jay = jay
self.current_email = self.email_client.get_random_email()
self.inbox = [self.current_email]
self.outbox = []
self.inbox_zero = False
def send_emails(self, opt_email_type_count_dict=None, opt_count=None):
emails_to_send = []
if opt_email_type_count_dict:
for email_type, count in opt_email_type_count_dict.items():
emails_to_send += self.email_client.get_emails(count, email_type)
elif opt_count:
# Send only the number of emails specified
emails_to_send = self.email_client.get_emails(opt_count)
else:
emails_to_send = self.email_client.get_emails()
random.shuffle(emails_to_send)
self.inbox = emails_to_send + self.inbox
self.jay.speak('You got mail!')
def do_read(self, args):
"""Given an email number, displays the contents of the email."""
try:
current_email = self.inbox[int(args)]
self.email_client.read_email(current_email)
except:
self.jay.speak('You need to tell me the number of the email you want to read!')
def do_check(self, args):
if len(self.inbox) == 0:
self.inbox_zero = True
self.jay.speak("CONGRATULATIONS! You've reached inbox zero!")
self.send_emails({"EC": 15, "Jobs": 10, "Piazza": 5})
"""Given an email, displays the contents of the email."""
for i, email in enumerate(self.inbox):
if email != None:
print i, self.email_client.preview_email(email)
def do_reply(self, args):
"""Given an email number, replies to that email. Removes the email from
your inbox. """
try:
arg_list = args.split(' ')
email_index = arg_list[0]
reply = ' '.join(arg_list[1:])
current_email = self.inbox[int(email_index)]
except:
self.jay.speak('You need to tell me the number of the email you want to reply to and then follow with the message you want to send!')
return
header = "["+self.email_client.get_email_address()+"] :" + current_email.header
content = reply
email_type = "Response"
reply = Email(header, content, email_type)
self.email_client.preview_email(reply)
self.email_client.read_email(reply)
self.jay.speak('Response sent!')
# Rules for response
if current_email.type == "EC":
self.send_emails({"EC": 10})
else:
self.send_emails(opt_count=3)
def do_delete(self, args):
# Remove email(s) from your inbox.
if args == "":
self.jay.speak('You need to tell me the number of the email(s) you want to delete or tell me if you want to delete all of them.')
elif args.find('all') != -1:
self.inbox = []
self.do_check('')
else:
try:
to_delete = args.split(' ')
for ind in to_delete:
current_email = self.inbox[int(ind)]
if current_email.type == "Jobs":
if random.random() > .7:
self.send_emails({"Jobs": 7})
self.inbox[int(ind)] = None
new_inbox = [email for email in self.inbox if email != None]
self.inbox = new_inbox
self.do_check('')
except:
self.jay.speak("Sorry, I don't understand")
self.jay.speak("You need to tell me the number of the email(s) you want to delete or tell me if you want to delete all of them.")
def do_quit(self, args):
"""Quits the program."""
self.jay.speak("Closing your email.")
self.jay.speak("Bye!")
raise SystemExit
class Jay():
def speak(self, words):
OKYELLOW = '\033[93m'
ENDC = '\033[0m'
print OKYELLOW + words + ENDC
time.sleep(2)
def intro(jay):
jay.speak("Hi, I'm Jay!")
jay.speak("I help MIT students like you manage your email!")
name = raw_input("What's your name?\n> ")
while name == "":
time.sleep(1)
name = raw_input("Please, what's your name?\n")
time.sleep(1)
jay.speak("Great to meet you, " + name)
jay.speak(name + ", I'm going to help you by turning email into a game where you want to keep your inbox as small as possible!")
jay.speak("Hint: be careful about the emails you delete and reply to!")
time.sleep(2)
if __name__ == '__main__':
jay = Jay()
intro(jay)
ec = EmailClient()
num_emails_per_filter = 5
ec.populate_map(type_to_filter_dict, num_emails_per_filter)
jay.speak("Oh!")
jay.speak("You got mail!")
prompt = JayGame(ec, jay)
prompt.prompt = '> '
prompt.cmdloop('')
|
numV = 4
a = [[True,True,False,False],[False,False,False,True],[True,False,True,False],[False,True,False,True]]
def Warshall(A,numV,W):
for i in range(numV):
for j in range(numV):
W[i][j] = A[i][j]
i=0
j=0
for k in range(numV):
for i in range(numV):
for j in range(numV):
W[i][j] = W[i][j] or (W[i][k] and W[k][j])
def Alcanca(A,numV, v1, v2):
W = [[0 for x in range(numV)]for y in range(numV)]
Warshall(A,numV,W)
print('Matriz Warshall: ' )
print(W )
print('\n')
if W[v1][v2]:
return True
return False
vIni = ''
vFim = ''
while vIni not in [0, 1, 2, 3]:
vIni = int(input("Fale qual o vertice inicial: [0,1,2,3] \n"))
while vFim not in [0, 1, 2, 3]:
vFim = int(input("Digite o vertice final: [0,1,2,3] \n"))
print('\n')
if Alcanca(a,numV,vIni,vFim):
print("Eh possivel ir do vertice "+ str(vIni)+ " para o " + str(vFim) + '!')
else:
print("Nao ha conexao entre o vertice "+ str(vIni) + " e o vertice "+str(vFim)+'!')
|
# Write your solution for 1.2 here!
x=0
for i in range(101):
if i% 2==1:
x+=i
print(x) |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
"""
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
length1 = len(num1)
length2 = len(num2)
num1 = num1[::-1]
num2 = num2[::-1]
nums = [0 for _ in range(length1+length2)]
for i in range(length1):
for j in range(length2):
nums[i+j] += (int(num1[i]) * int(num2[j]))
carry = 0
digits = []
for d in nums:
s = carry + d
carry = s // 10
digits.append(str(s % 10))
result = digits[::-1]
sub_index = 0
for x in range(length1+length2-1):
if result[x] == '0':
sub_index += 1
else:
break
return ''.join(result[sub_index:])
if __name__ == '__main__':
num1 = '123'
num2 = '234'
print Solution().multiply(num1, num2)
print Solution().multiply('9915', '9912')
print Solution().multiply('9', '8') |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Given a m x n grid filled with non-negative numbers,
find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
"""
class Solution(object):
def minPathSumRecur(self, m, n, table, grid, row, col):
if table[m][n] == -1:
table[m][n] = grid[row - m - 1][col - n - 1] + min(self.minPathSumRecur(m - 1, n, table, grid, row, col),
self.minPathSumRecur(m, n - 1, table, grid, row, col))
return table[m][n]
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
row = len(grid)
col = len(grid[0])
table = [[-1 for _ in range(col)] for _ in range(row)]
table[0][0] = grid[row - 1][col - 1]
for i in range(1, col):
table[0][i] = table[0][i - 1] + grid[row-1][col - i - 1]
for i in range(1, row):
table[i][0] = table[i - 1][0] + grid[row - i - 1][col-1]
return self.minPathSumRecur(row - 1, col - 1, table, grid, row, col)
if __name__ == '__main__':
print Solution().minPathSum([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
"""
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
numset, max_len = set(nums), 0
for n in set(nums):
temp = n+1
set_len = 1
while temp in numset:
set_len += 1
numset.discard(temp)
temp += 1
temp = n - 1
while temp in numset:
set_len += 1
numset.discard(temp)
temp -= 1
max_len = max(set_len, max_len)
return max_len
if __name__ == '__main__':
assert Solution().longestConsecutive([100, 4, 200, 1, 3, 2]) == 4 |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Given a 2D binary matrix filled with 0's and 1's,
find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
"""
class Solution(object):
def maximalRectangle(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if len(matrix) == 0 or len(matrix[0]) == 0:
return 0
n = len(matrix[0])
result = 0
heights = [0 for _ in range(n)]
for row in matrix:
for i in range(n):
heights[i] = heights[i] + 1 if row[i] == '1' else 0
heights.append(0)
stack = [-1]
for i in range(n+1):
while heights[i] < heights[stack[-1]]:
h = heights[stack.pop()]
w = i - stack[-1] - 1
result = max(result, h*w)
stack.append(i)
heights.pop()
return result
if __name__ == '__main__':
print Solution().maximalRectangle([['1', '1', '0', '1', '0', '1'],
['0', '1', '0', '0', '1', '1'],
['1', '1', '1', '1', '0', '1'],
['1', '1', '1', '1', '0', '1']])
print Solution().maximalRectangle(["10100","10111","11111","10010"]) |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1).
You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
"""
class Solution(object):
def __init__(self):
self.result = set()
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
if len(gas) == 0 or len(gas) != len(cost) or sum(gas) < sum(cost):
return -1
start = 0
total_gas = 0
for i in range(len(gas)):
if total_gas < 0:
total_gas = gas[i] - cost[i]
start = i
else:
total_gas += (gas[i] - cost[i])
return start
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
N = len(cost)
for i in range(N):
#self._can_complete_circuit_recur(i, i, 0, gas, cost, N, 'L')
self._can_complete_circuit_recur(i, i, 0, gas, cost, N, 'R')
if len(self.result) > 0:
return list(self.result)[-1]
else:
return -1
def _can_complete_circuit_recur(self, begin, pos, total_gas, gas, cost, N, direction):
if begin == (N + pos-1) % N and total_gas + gas[pos] >= cost[(N + pos-1) % N] and direction == 'L':
self.result.add(begin)
elif begin == (N + pos + 1) % N and total_gas + gas[pos] >= cost[pos] and direction == 'R':
self.result.add(begin)
else:
if total_gas + gas[pos] > cost[pos] and direction == 'R':
total_gas += (gas[pos] - cost[pos])
self._can_complete_circuit_recur(begin, (N + pos + 1) % N, total_gas, gas, cost, N, direction)
# if total_gas + gas[pos] > cost[(N + pos-1) % N] and direction == 'L':
# total_gas += (gas[pos] - cost[(N + pos-1) % N])
# self._can_complete_circuit_recur(begin, (N + pos - 1) % N, total_gas, gas, cost, N, direction)
if __name__ == '__main__':
print Solution().canCompleteCircuit([5], [4])
print Solution().canCompleteCircuit([5, 1, 2, 3, 4], [4, 4, 1, 5, 1])
print Solution().canCompleteCircuit([1, 2], [2, 1])
print Solution().canCompleteCircuit([1,2,3,4,5],[3,4,5,1,2]) |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 27 16:45:19 2014
@author: john
"""
#Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
#Convert Sorted Array to Binary Search Tree
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sortedArrayToBSTRecur(self,num,low,high):
if low == high:
return TreeNode(num[low])
elif low > high:
return None
middle=(low+high)/2
root=TreeNode(num[middle])
root.right=self.sortedArrayToBSTRecur(num,middle+1,high)
root.left = self.sortedArrayToBSTRecur(num,low,middle-1)
return root
# @param num, a list of integers
# @return a tree node
def sortedArrayToBST(self, num):
high=len(num)-1
low=0
return self.sortedArrayToBSTRecur(num,low,high)
def printTree(self,root):
if root==None:
return
self.printTree(root.left)
print root.val
self.printTree(root.right)
if __name__=="__main__":
solution=Solution()
solution.printTree(solution.sortedArrayToBST([1,2,3,4,5,6,7,8]))
|
class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
words = s.split(None,-1)
print len(words)
print words
result=""
wordsLen = len(words)
if wordsLen < 2:
return ""
for i in range(wordsLen-1,-1,-1):
result +=words[i]
result +=" "
return result
if __name__ == "__main__":
solution = Solution()
print solution.reverseWords("")
print solution.reverseWords(" ")
print solution.reverseWords("hello world adsd")
|
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Try to solve it in linear time/space.
Return 0 if the array contains less than 2 elements.
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.
"""
class Solution(object):
def maximumGap(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n < 2:
return 0
if __name__ == '__main__':
Solution() |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Given a binary tree, return the zigzag level order traversal of its nodes' values.
(ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
"""
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
stack = [[root]]
level_stack = [[root]]
while stack:
parents = stack.pop()
temp = []
for parent in parents:
if parent.left:
temp.append(parent.left)
if parent.right:
temp.append(parent.right)
if len(temp) > 0:
level_stack.append(temp)
stack.append(temp)
result = []
for i, level in enumerate(level_stack):
temp = []
for node in level:
temp.append(node.val)
if i % 2 == 1:
result.append(temp[::-1])
else:
result.append(temp)
return result
if __name__ == '__main__':
root = TreeNode(3)
node9 = TreeNode(9)
node20 = TreeNode(20)
node15 = TreeNode(15)
node7 = TreeNode(7)
root.left = node9
root.right = node20
node20.left = node15
node20.right = node7
print Solution().zigzagLevelOrder(root) |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 01 14:15:57 2014
@author: john
"""
#Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSameTree(self,p, q):
if p==None and q==None:
return True
elif p==None or q==None:
return False
if p.val==q.val:
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
else:
return False
def mirror(self,root):
if root:
tmpNode = root.right
root.right = root.left
root.left = tmpNode
self.mirror(root.left)
self.mirror(root.right)
# @param root, a tree node
# @return a boolean
def isSymmetric(self, root):
if root==None:
return True
self.mirror(root.left)
return self.isSameTree(root.left,root.right) |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Given an unsorted array of integers, find the length of longest continuous increasing subsequence.
Example 1:
Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.
Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4.
Example 2:
Input: [2,2,2,2,2]
Output: 1
Explanation: The longest continuous increasing subsequence is [2], its length is 1.
"""
class Solution(object):
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n == 0:
return 0
lcis = 0
counter = 1
for i in range(1, n):
if nums[i] > nums[i-1]:
counter += 1
else:
lcis = max(counter, lcis)
counter = 1
lcis = max(counter, lcis)
return lcis
if __name__ == '__main__':
assert Solution().findLengthOfLCIS([1, 3,5,4,7]) == 3
assert Solution().findLengthOfLCIS([2,2,2,2,2,2]) == 1
assert Solution().findLengthOfLCIS([1,3,5,7]) == 4
assert Solution().findLengthOfLCIS([1,3,5,4,2,3,4,5]) == 4 |
import itertools
class Solution(object):
def triangleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
iters = itertools.combinations(nums, 3)
result = 0
for it in iters:
if self.isValidTriangle(it):
result += 1
return result
def isValidTriangle(self, t):
t = sorted(t)
if t[0]+t[1] > t[2]:
return True
return False
if __name__ == '__main__':
s = Solution()
print s.triangleNumber([1,2,3,4,5,6])
print s.triangleNumber([2,2,3,4])
print s.triangleNumber([82,15,23,82,67,0,3,92,11]) |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 01 14:34:54 2014
@author: john
"""
class Solution:
# @param A a list of integers
# @return nothing, sort in place
def swap(self,A,a,b):
tmp=A[a]
A[a]=A[b]
A[b]=tmp
def sortColors(self, A):
if A==None:
return
red=0
length=len(A)
for i in range(0,length):
if A[i]==0:
self.swap(A,red,i)
red=red+1
white=red
for i in range(red,length):
if A[i]==1:
self.swap(A,white,i)
white=white+1
#get it wrong,colors in same color...
#I should be more careful next time!!!
#I misunderstood the problem...!
def sortColorsFails1(self,A):
length=len(A)
if length<2:
return
reds=0
whites=0
blues=0
for i in range(0,length):
if A[i]==0:
reds=reds+1
elif A[i]==1:
whites=whites+1
else:
blues=blues+1
i=0
while i<length:
if reds:
A[i]=0
i=i+1
reds=reds-1
if whites and i<length:
A[i]=1
i=i+1
whites=whites-1
if blues and i<length:
A[i]=2
i=i+1
blues=blues-1
if __name__=="__main__":
solution=Solution()
A=[1,2,1]
solution.sortColorsFails1(A)
print A |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Write an efficient algorithm that searches for a value in an m x n matrix.
This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
"""
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
if m == 0:
return False
n = len(matrix[0])
if n == 0:
return False
l, h = 0, m * n - 1
while l <= h:
mid = (l + h) // 2
if matrix[mid // n][mid % n] == target:
return True
elif matrix[mid // n][mid %n] < target:
l = mid + 1
else:
h = mid -1
return False
if __name__ == '__main__':
assert Solution().searchMatrix([
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
], 3) == True
assert Solution().searchMatrix([[1],[3],[5]], 0) == False
assert Solution().searchMatrix([], 0) == False
assert Solution().searchMatrix([[1],[3]], 3) == True
assert Solution().searchMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,50]], 30) == True |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
X=pd.read_csv('./Linear_X_Train.csv')
Y=pd.read_csv('./Linear_Y_Train.csv')
#convert pandas into numpy
X=X.values
Y=Y.values
#Normalization
u=X.mean()
std=X.std()
X=(X-u)/std
#visualize
plt.style.use('seaborn')
plt.scatter(X,Y,alpha=0.5)
plt.show()
# In[3]:
## Linear Regression
def hypothesis(x,theta):
y_=theta[0]+theta[1]*x
return y_
# In[4]:
def gradient(X,Y,theta):
m=X.shape[0]
grad=np.zeros((2,))
for i in range(m):
y_=hypothesis(X[i],theta)
grad[0]+=(y_-Y[i])
grad[1]+=(y_-Y[i])*X[i]
return grad/m
# In[5]:
def error(X,Y,theta):
total_error=0.0
m=X.shape[0]
for i in range(m):
y_=hypothesis(X[i],theta)
total_error+=(y_-Y[i])**2
return total_error/m
# In[6]:
def gradientDescent(X,Y,lr=0.1):
theta=np.zeros((2,))
max_steps=100
error_list=[]
for i in range(max_steps):
grad=gradient(X,Y,theta)
e=error(X,Y,theta)
error_list.append(e)
theta[0]=theta[0]-lr*grad[0]
theta[1]=theta[1]-lr*grad[1]
return theta,error_list
# In[ ]:
# In[7]:
theta,error_list=gradientDescent(X,Y)
# In[8]:
theta
# In[9]:
print(error)
# In[10]:
error_list
# In[11]:
#Predictions and BestLine
y_=hypothesis(X,theta)
# In[12]:
#Training + Prediction
plt.scatter(X,Y)
plt.style.use('seaborn')
plt.plot(X,y_,color='orange')
# In[21]:
X_test=pd.read_csv('Linear_X_Test_sub.csv').values
y_test=hypothesis(X_test,theta)
df=pd.DataFrame(data=y_test,columns=["y"])
df.to_csv('Y_prediction.csv',index=False)
# In[22]:
def r2score(Y,Y_):
num=np.sum((Y-Y_)**2)
den=np.sum((Y-Y_.mean())**2)
score=1-(num/den)
return score*100
# In[15]:
print(r2score(Y,y_))
# In[ ]:
|
class DNode:
def __init__(self, item=None):
self.item = item
self.right = None
self.left = None
class DoubleLinkedList():
def __init__(self):
self.root = None
def append(self, item):
NewNode = DNode(item)
CurNode = self.root
if self.root == None:
self.root = NewNode
else:
while CurNode.right != None:
CurNode = CurNode.right
CurNode.right = NewNode
NewNode.left = CurNode
def listSize(self):
CurNode = self.root
if self.root != None:
size = 1
while CurNode.right != None:
CurNode = CurNode.right
size += 1
else:
size = 0
return(size)
def insert(self, item, idx):
NewNode = DNode(item)
CurNode = self.root
if idx < 0 or idx > self.listSize():
print('index가 리스트 사이즈 범위에서 벗어났습니다.')
return(-1)
elif idx == 0:
_tmp1 = self.root
self.root = NewNode
NewNode.right = _tmp1
CurNode.left = NewNode
else:
cur_idx = 0
while cur_idx != idx-1:
CurNode = CurNode.right
cur_idx += 1
NextNode = CurNode.right
_tmp = CurNode.right
CurNode.right = NewNode
NewNode.left = CurNode
NewNode.right = _tmp
NextNode.left = NewNode
def delete(self, item):
CurNode = self.root
if self.root == None:
print('삭제할 item이 없습니다.')
else:
while CurNode.right != None:
CurNode = CurNode.right
if CurNode.item == item:
if CurNode.right == None:
CurNode.left.right = None
else:
CurNode.left.right = CurNode.right
CurNode.right.left = CurNode.left
def print(self):
CurNode = self.root
if self.root == None:
print("None")
else:
while CurNode.right != None:
print(CurNode.item, end=', ')
CurNode = CurNode.right
print(CurNode.item)
sports = DoubleLinkedList()
sports.append('축구')
sports.append('야구')
sports.insert('농구', 1)
sports.insert('배드민턴', 1)
sports.print()
sports.delete('농구')
sports.print()
sports.delete('야구')
sports.print()
|
tar, s1, s2 = input().split()
s1s = set(input().split())
s2s = set(input().split())
if tar in s1s and tar in s2s:
print("MrMaxValu")
elif tar in s1s:
print("MrMax")
elif tar in s2s:
print("MaxValu")
else:
print(-1)
|
# age = input("How old are you?\n") #blocked 1-5, Ctrl/
# if int(age) >= 21:
# print("You are old enough.")
# else:
# print("you are not old enough.")
age = int(input("How old are you?\n"))
if age == 21:
print("You are a great age to party.")
elif age > 37:
print("Your getting up there in age!")
elif age >= 21:
print("You are old enough.")
else:
print("You are not old enough.")
|
name = input("What is your name?")
num = len(name)
## You can have multiple conditions here
if num > 3 and num < 15: # Both statements must be truthy
if num == 4:
print('Perfect length!')
else:
print("It's an okay length.")
print(f"Welcome {name}.")
else:
print('%s is not a good number of characters' % len(name))
if num > 3 or num < 15: # either statement must be truthy
print("This is valid") # If input 2 because less than 15; 26 is greater than 3
#if num < 3 or num > 15:
print("Your number is not between 3 and 15")
#else:
print('Normal lengthed name.')
name = input("Give me your name.")
if not name:
print("You must give a name.")
else:
print(name)
|
#nesting putting one thing inside another
name = input("What is your name?")
if len(name) > 3: #counting the length of the value
print("Your name is long enough.")
if len(name) > 15:
print("That is way too long.")
else:
print(f"Welcome {name}")
name = input("What is your name?")
if len(name) > 3:
if len(name) < 10:
if len(name) == 4:
print('Perfect length!')
else:
print("it's an okay length.")
print(f"Welcome {name}")
else:
print("That's way to long partner!")
else:
print('%s is too few characters.' % length)
#print(f' {length} is too few characters.') #or alt pattern
|
# Nesting Code Block
## Objective
- Put code blocks inside of code blocks
- Use multiple condition
- Exercise
## Terms
- *Nesting* - `In programming nesting describes putting code blocks or other syntaxtual items inside of another item`
## Put code blocks inside code blocks
- ```python
name = input("what is your name?")
# wrapping a string / varaible in len() outputs how many characters the string is.
if len(name) > 3:
print('Your name is long enough')
if len(name) > 15:
#new block level
print("That's way to long partner")
else:
print(f"Welcome {name}")
#back out to the main block level
else:
print('%s is too few characters' % len(name))
- ```python
name = input("What is your name")
if len(name) > 3:
if len(name) < 10:
if len(name) = 4:
if len(name) == 4:
# Even one block lower
print('Perfect Length!')
else:
print("It's an ok length")
print(f"Welcme {name}")
else:
print("That's way to long partner")
else:
print('%s is too few characters' % len(name))
## Using multiple conditions
- ```python
name = input("what is your name?")
num = len(name)
## You can have multiple conditions here
if num > 3 and num < 15:
if num = 4:
print('Perfect Length!')
else:
print("It's an ok length")
print(f"Welcme {name}")
else:
print('%s is not a good number of characters' % len(name))
## Exercises
1. Create a program that will accept in input that is assigned to the variable pet_name.
- If pet_name length is less than 3 characters give a message that the name length is too short.
- If pet_name lenght is more than 3 characters output "AWWW sweet [pet_name]"
- If pet_name is "Shadow" output ONLY "El Gato Diablo!"
- If the input is equal to "Daisy" output ONLY "Good Dog!" |
# 201016 Class Reading "Sequences: Lists, Strings, and Tuples"
# Small Exercises
# 1. Sum the Numbers
# Create a list of numbers, print their sum.
##declare list
nums = [1, 2, 3, 4]
##print sum
print(sum(nums)) |
# Lists
## Objectives
- What are the parts of a list?
- Creating lists
- Accessing items from a list
- Exercises
## Terms
- *lists* - `Lists are a data type of ordered gropuing of values. They are called arrays in most other languages.`
- *index* - `In a list or an array, it is the number representation of the position of an item in the list or array`
## What are the parts of a list?
- ```python
[1,2,3] #List of intergers
["hi", "my", "name", "is", "Clint"] #List of strings
[1,"stringy", False] # List of mixed types
> List start with an opening square bracket '[' have coma seperated values and then end with the closing sqaure bracket ']'.
## Creating lists
- ```python
# creating a list and assigning it to a variable
some_numbers = [1,2,3]
my_children = ["Olivia", "Alle", "Mark"]
name = "Clint"
age = 38
married = True
my_info = [name, age, married]
#Putting the variables in the array
## Accessing items from a list
- ```python
my_children = ["Olivia", "Alle", "Mark"]
print(my_children[0]) #Olivia
print(my_children[2]) #Mark
print(my_children[1]) #Alle
>Lists are ordered so the order will remain the same.
>The list starts with 0, so the first item is always 0 and counts up in order.
> [Additional Information](https://learn.digitalcrafts.com/immersive/lessons/solving-problems-using-code/sequences/#how-do-i-access-items-in-a-sequence)
- ```python
my_children = ["Olivia", "Alle", "Mark"]
#Assigning the results to a variable
only_son = my_children[2]
print(only_son) #Mark
## Exercises
1. Create a program that has a list of at least 3 of your favorited foods in order and assign that list to a variable named "favorite_foods".
- print out the value of your favorite food by accessing by it's index.
- print out the last item on the list as well.
2. Create a program that contains a list of 4 different "things" around you.
- Print out the each item on a new line with the number of it's index in front of the item.
```python
0. Coffee Cup
1. Speaker
2. Monitor
3. Keyboard
```
3. Using the code from exercise 2, prompt the user for which item the user thinks is the most interesting. Tell the user to use numbers to pick. (IE 0-3).
- When the user has entered the value print out the selection that the user chose with some sort of pithy message associated with the choice.
```python
"You chose Coffee Cup, You must like coffee!" |
# 1. import GUI library
from tkinter import *
# 2. create an object of type tkinter
window = Tk()
# 3. set: title, size(geometry), background-color
window.title('Graphical User Interface')
window.geometry('450x350')
window.configure(background='pink')
# 4. create label & entry
lbl1 = Label(window, text="Username",
font=('Times New Roman', 10))
lbl1.place(x=30, y=40)
e1 = Entry(window,
font=('Times New Roman', 10))
e1.place(x=100, y=40)
lbl2 = Label(window, text="Password",
font=('Times New Roman', 10))
lbl2.place(x=30, y=80)
e2 = Entry(window, show='*',
font=('Times New Roman', 10))
e2.place(x=100, y=80)
# 5. create buttons
btn1 = Button(window, text='Submit',
font=('Times New Roman', 10),
# width = '10',
bg='green',
fg='pink')
btn2 = Button(window, text='Cancel',
font=('Times New Roman', 10),
# width = '10',
bg='red',
fg='pink')
btn1.place(x=30, y=120)
btn2.place(x=100, y=120)
window = mainloop()
|
##获取日期
# import datetime
# nowday=datetime.date.today()
# nday=(datetime.date.today() + datetime.timedelta(days = -3)).strftime("%Y-%m-%d")
# print("今天日期:",nowday)
# print("n天前日期:",nday)
#pandas读取csv文件
import pandas as pd
df = pd.read_csv("D:\\2021-12-31demo_assignDayData.csv")
print(df.to_string()) |
#output row of Pascal's triangle given row number, starting at 1
#use a list of lists to represent the triangle
#get n
rownum = int(input("Enter row number of Pascal's triangle: "))
if rownum <= 0:
print("Must have positive nonzero input. Start again")
else:
#put first two rows into triangle
triangle = [[1],[1,1]]
n=2
#populate triangle row
while n < rownum:
#populate triangle row as appropriate sized list
y=n+1
row=[None]*(y)
#populate first and last items in row
row[0]=1
row[n]=1
#populate middle elements of row (sums)
x = 1
while x < n:
row[x] = triangle[n-1][x-1]+triangle[n-1][x]
x +=1
triangle.append(row)
n+=1
print(*triangle[rownum-1], sep=' ')
|
# #Get number of Prime Factors for a number input by user
import math
def is_prime(n):
#to determine if a number is prime or not
if(n==1):
return False
elif(n==2):
return True
else:
for x in range (2,n):
if(n % x == 0):
return False
return True
#Number of prime factors:
big = 1234567890 # Number to find factors for.
def primes_up_to(n):
"""Generates all primes less than n. Sieve of Erastothenes; courtesy
David Eppstein, UC Irvine, 28 Feb 2002, faster code by Mike Dell'Amico
"""
if n <= 2: return
yield 2
F = [True] * n
seq1 = range(3, int(math.sqrt(n)) + 1, 2)
seq2 = range(seq1[-1] + 2, n, 2)
for p in filter(F.__getitem__, seq1):
yield p
for q in range(p * p, n, 2 * p):
F[q] = False
for p in filter(F.__getitem__, seq2):
yield p
def numfact(big):
#Now check big to see if those primes are Factors
count = 0
uniquefact = []
for n in range(2, big):
if big % n == 0:
if is_prime(n):
count +=1
uniquefact.append(n)
while big % n == 0:
big = big/n
if int(big) == 1:
break #stop when the divisor is 1
return (count, uniquefact)
# Check if number itself is prime:
if is_prime(big):
print ("Number is prime, so has only 1 unique prime factor, itself")
else:
unique_factors = numfact(big)
print ("%s has %s unique prime factors" %(big,unique_factors[0]))
print("Those are: ", unique_factors[1])
|
# Linear regression
# packagaes
import numpy as np
import pandas as pd
# y_i = beta0 + beta1 x1_i + beta2 x2_i + epsilon
# data generating proces - inserted from exam description
def DGP(N):
# a. independent variables
x1 = np.random.normal(0,1,size=N)
x2 = np.random.normal(0,1,size=N)
# b. errors
eps = np.random.normal(0,1,size=N)
extreme = np.random.uniform(0,1,size=N)
eps[extreme < 0.05] += np.random.normal(-5,1,size=N)[extreme < 0.05]
eps[extreme > 0.95] += np.random.normal(5,1,size=N)[extreme > 0.95]
# c. dependent variable
y = 0.1 + 0.3*x1 + 0.5*x2 + eps
return x1, x2, y
# accessable data - inserted from exam description
np.random.seed(2020)
x1,x2,y = DGP(10000)
#######################################################################################
# To define X, x1 and x2 must be included in the same dataframe. Also a column of one's
# for Beta_0.
x0 = 1
X = pd.DataFrame({'x0':x0,'x1':x1,'x2':x2})
X
# Question 1
# Now X can be transposed etc by numpy formulas.
X_trans = X.T
X_trans
X_trans_X = X_trans.dot(X)
X_trans_X
#
Inv_X_X_trans = np.linalg.inv(X_trans_X)
Inv_X_X_trans
X_trans_y = X_trans.dot(y)
X_trans_y
beta_hat = Inv_X_X_trans.dot(X_trans_y)
beta_hat
betas = pd.DataFrame({'Beta 0':beta_hat,'Beta 1':beta_hat,'Beta 2':beta_hat})
betas
#######################################################################################
# Question 2
# Lav stor fed 3D plot med beta vægte ganget på mulige forekomster af x1 og x2.
# Plane ind som Surface
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
y_hat = np.dot(X,beta_hat)
y_hat
df_y_hat = pd.DataFrame({'x1':x1,'x2':x2,'y_hat':y_hat})
df_y_hat.head()
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.scatter(df_y_hat['x1'],df_y_hat['x2'],df_y_hat['y_hat'], c='pink',marker='o',alpha=1)
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_zlabel('y3')
plt.show
#######################################################################################
## Question 3
# præsenter i data frame
from scipy.optimize import minimize
b0 = np.empty(1)
b1 = np.empty(1)
b2 = np.empty(1)
def function(x, b0, b1, b2):
b0 = x[0]
b1 = x[1]
b2 = x[2]
return np.sum((y - (b0 + b1*x1 + b2*x2))**2)
#initial guess
b = np.array([0.2, 1.5, 9.5])
estimate = minimize(function, b, args=(b0,b1,b2), method='SLSQP')
b0 = estimate.x[0]
b1 = estimate.x[1]
b2 = estimate.x[2]
print(estimate.message)
print(b0,b1,b2)
#######################################################################################
# Question 4
# præsenter i data frame
beta_hat[0]
from scipy.optimize import minimize
b0 = np.empty(1)
b1 = np.empty(1)
b2 = np.empty(1)
def function(x, b0, b1, b2):
b0 = x[0]
b1 = x[1]
b2 = x[2]
return np.sum(np.absolute(y - (b0 + b1*x1 + b2*x2)))
#initial guess
h = np.array([0.4, 1.2, 10.5])
estimate = minimize(function, h, args=(b0,b1,b2), method='SLSQP')
b0 = estimate.x[0]
b1 = estimate.x[1]
b2 = estimate.x[2]
print(estimate.message)
print(b0,b1,b2)
#######################################################################################
# Question 5
# OLS
b0_OLS = np.empty(5000)
b1_OLS = np.empty(5000)
b2_OLS = np.empty(5000)
for k in range(5000):
new_x1, new_x2, new_y = DGP(50)
def new_function(x, b0_OLS, b1_OLS, b2_OLS):
b0_OLS = x[0]
b1_OLS = x[1]
b2_OLS = x[2]
return np.sum((new_y- (b0_OLS + b1_OLS*new_x1 + b2_OLS*new_x2))**2)
new_est = minimize(new_function, b, args=(b0_OLS,b1_OLS,b2_OLS),method = 'SLSQP')
b0_OLS[k-1]=new_est.x[0]
b1_OLS[k-1]=new_est.x[1]
b2_OLS[k-1]=new_est.x[2]
# LAD
b0_LAD = np.empty(5000)
b1_LAD = np.empty(5000)
b2_LAD = np.empty(5000)
for k in range(5000):
new_x1, new_x2, new_y = DGP(50)
def new_function(x, b0_LAD, b1_LAD, b2_LAD):
b0_LAD = x[0]
b1_LAD = x[1]
b2_LAD = x[2]
return np.sum(np.absolute(new_y - (b0_LAD + b1_LAD*new_x1 + b2_LAD*new_x2)))
new_est = minimize(new_function, b, args=(b0_LAD,b1_LAD,b2_LAD),method = 'SLSQP')
b0_LAD[k-1]=new_est.x[0]
b1_LAD[k-1]=new_est.x[1]
b2_LAD[k-1]=new_est.x[2]
# OLS & LAD beta_0 print hist
OLS_b0_hist = plt.hist(b0_OLS,bins=50)
LAD_b0_hist = plt.hist(b0_LAD,bins=50)
plt.show(OLS_b0_hist,LAD_b0_hist)
OLS_b1_hist = plt.hist(b1_OLS,bins=50)
LAD_b1_hist = plt.hist(b1_LAD,bins=50)
plt.show(OLS_b1_hist,LAD_b1_hist)
OLS_b2_hist = plt.hist(b2_OLS,bins=50)
LAD_b2_hist = plt.hist(b2_LAD,bins=50)
plt.show(OLS_b2_hist,LAD_b2_hist)
|
from lib import *
import time
def is_divisible(num):
return all((num[i + 1] * 100 + num[i + 2] * 10 + num[i + 3]) % p == 0 for (i, p) in enumerate([2, 3, 5, 7, 11, 13, 17]))
def run():
return sum(int(''.join(map(str, num))) for num in permutations(list(range(10))) if is_divisible(num))
clear()
print('Challenge #43: Sub-String Divisibility')
print('======================================\n')
input('Press ENTER to run challenge . . . ')
print('')
timeElapsed = time.time()
ans = run()
report(ans)
timeElapsed = time.time() - timeElapsed
print(format_time(timeElapsed))
|
from time import time
# Здесь необходимо реализовать
# контекстный менеджер timer
# Он не принимает аргументов, после выполнения блока он должен вывести время выполнения в секундах
# Пример использования
# with timer():
# sleep(5.5)
#
# После завершения блока должно вывестись в консоль примерно 5.5
class timer:
def __init__(self):
pass
def __enter__(self):
self.time = time()
def __exit__(self, type, value, traceback):
print(time() - self.time)
|
import os.path
PATH = os.path.dirname(os.path.abspath(__file__))
def solve(problem_set: set):
for number in problem_set:
diff = 2020 - number
for num in problem_set:
second_diff = diff - num
if second_diff in problem_set:
return (number * num * second_diff)
return 'NO SOLUTION'
def main():
# This solution assumes there are no repeating values
with open(os.path.join(PATH, 'testcase.txt'), 'r') as r:
problem_set = {int(num) for num in r}
print(solve(problem_set))
main()
|
import re
# Input string
value = "Tiny programs that process text."
match = re.search("(process.*)", value)
if match:
print("Search result:", match.group(1))
match = re.match("(pr.*)", value)
if match:
print("match:", match.group(1))
|
# Zaimplementuj funkcję, która na podstawie podanej listy stworzy nową listę zawierającą tylko elementy
# oryginalnej kolekcji z podanego zakresu.
# Funkcja powinna przyjmować trzy parametry:
# listę
# początek zakresu
# koniec zakresu
# Przykład użycia:
# >>> filtruj([-2, 10, 0, 5, 1, 16, 9], 5, 15)
# [10, 5, 9]
def filtruj(lista, poczatek, koniec):
kolekcja = []
zbior = set(lista)
for i in zbior:
if i >= poczatek and i <= koniec:
kolekcja.append(i)
print(kolekcja)
filtruj([-1, -1, 0, 0, 10, 100], -1, 10)
filtruj([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 11, 14, 18, 0], 0, 10)
def test_filtruj1():
assert filtruj([1, 2, 3, 4, 5, 5, 5, 6, 7, 7, 7, 7, 8], 1, 2) == [1, 2]
def test_filtruj2():
assert filtruj([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 11, 14, 18, 0], 0, 10) == [0, 1, 2, 3, 4, 5]
|
# -*- coding: utf-8 -*-
"""
Investment Growth Graph
@author: MadMerlyn
"""
num_years = 30
from invest import Invest
import matplotlib.pyplot as plt
#Build data-table
_data = Invest(1000, 400, 0.08, years=num_years)
annual = range(12,(12*num_years)+1,12)
#Generate lists from data-table
plot_data = [item for item in _data if item['period'] in annual]
total = [item['total'] for item in plot_data]
invested = [item['invested'] for item in plot_data]
interest = [item['interest'] for item in plot_data]
time = [item/12 for item in annual]
labels = ['invested', 'interest', 'total']
colors = ['blue', 'red', 'green']
plt.plot(time, invested, 'r-', time, interest, 'b-', time, total, 'g-')
plt.xlabel('Years')
plt.ylabel('USD')
plt.show()
|
def divide(a,b):
try:
print (a/b)
except ZeroDivisionError :
print (a/1)
except TypeError as err:
print(err)
print("pass only numbers")
except :
print("Error ")
divide(10,0)
#ZeroDivisionError:
#TypeError: |
class Student:
sId = input("sid : ")
sName = input("sName :")
sAddr = input("sAddr :")
sPhone = input("phone no. :")
def get_student_details(self):
print(" Student data")
print("==============")
print("Student ID :" , self.sId)
print("Student Name :" , self.sName)
print("Student address :" , self.sAddr)
print("Student Phone no. :" , self.sPhone)
std=Student()
|
# a=float(input("enter value: "))
# b=float(input("enter value: "))
# c=float(input("enter value: "))
# if a>b :
# if a>c :
# print("%d is biggest no."%a)
# else:
# print("%d is biggest no."%c)
# elif b>c:
# if b>a :
# print("%d is biggest no."%b)
# else :
# print("%d is bigggest no."%a)
# elif c>a :
# if c>b :
# print("%s is biggest no."%c)
# else :
# print("%d is biggest no."%b)
# else :
# print("all nos. are equal")
# print(type(a),"a")
# print(type(b),"b")
# print(type(c),"c")
# v1=float(input("enter valus:"))
# v2=float(input("enter valus: "))
# if v1>v2 :
# print("%i is big no."%v1)
# elif v2>v1 :
# print("%i is big no."%v2)
# else :
# print("two equal nos.")
# day=int(input("week no.: "))
# if day==1 :
# print('today sunday')
# elif day==2 :
# print('today monday')
# elif day==3 :
# print('today tuesday')
# elif day==4 :
# print('tody wednesday')
# elif day==5 :
# print('today thursday')
# elif day==6 :
# print("today friday")
# elif day==7:
# print('today saturday')
# else:
# print("put only 1-7 no.")
# name =input("name: ")
# if name=="ram" :
# print("you successfully accessed")
# else:
# print("your name is not ram ,your name is %s"%name)
# no = int(input("Enter a Number : "))
# if no % 2 == 0 :
# print("%d is Even Number"%no)
# else:
# print("%d is Odd NUmber"%no)
# n1=int(input("enter value :"))
# n2=int(input("enter value :"))
# n3=int(input("enter value :"))
# if n1>=n2 and n1>n3 :
# print(n1 , "is big no.")
# elif n2>=n1 and n2>n3 :
# print(n2 , "is bi no.")
# elif n3>=n1 and n3>n2 :
# print(n3 ,"is big no.")
# else :
# print("all 3nos. equal")
# Rstar=input() # input() function o/p str datatype
# print(Rstar)
# print(type(Rstar))
# i/p = 5
# o/p = 5
# <class 'str'>
# Problem Statement #1
# In this challenge, you must discount a price according to its value.
# If the price is 300 or above, there will be a 30% discount.
# If the price is between 200 and 300 (200 inclusive), there will be a 20% discount.
# If the price is between 100 and 200 (100 inclusive), there will be a 10% discount.
# If the price is less than 100, there will be a 5% discount.
# If the price is negative, there will be no discount.
#ans:
price=int(input("value :"))
if price>=300 :
price*=0.7
elif price>=200 :
price*=0.8
elif price>=100 :
price*=0.9
elif price<100 :
price*=0.95
else:
price=price
print(price)
|
# str = "Durga Software Solutions"
# a = 0
# while a < len(str):
# print(str[a])
# a = a+ 1
# a=int(input("enter value :"))
# if a>1 :
# for x in range(2,a) :
# if a % x ==0 :
# print(a ,"not prime no")
# break
# else :
# print(a ,"is a prime no")
# fibonacci serise number print
# n=int(input("range value :"))
# fpoint=0
# spoint=1
# fibopoint=fpoint+spoint
# print(fpoint)
# print(spoint)
# while fibopoint <= n :
# print(fibopoint)
# fpoint=spoint
# spoint=fibopoint
# fibopoint=fpoint+spoint
#with for loop
# n=int(input("range value :"))
# fpoint=0
# spoint=1
# for i in range (n) :
# print(fpoint)
# new=fpoint
# fpoint=spoint
# spoint=new+spoint
|
import os
# file = open("c:/classss/ABC/hello.txt" , "w")
# print("File mode :" , file.mode)
# print("File Name :" , os.path.basename(file.name))
# print("File Directory :",os.path.dirname(file.name)) ## Get Parent location :
# print("Absolute Path :",file.name)
# print("Absolute Path :",os.path.abspath(file.name))
# print("Is Readable :",file.readable())
# print("Is Writable :",file.writable())
### dynamically read file
# fileName = input("Enter File Name : ")
# file = open(fileName,'r')
# data = file.read()
# print(data) #### i/p ===> file path
########################################
##### -Q)Write a python program to take file name as dynamic input and to display no of lines, no of words
# and no of characters of the respective file?
# filePut = input("enter file path : ")
# File = open(filePut,"r")
# data = (File.read())
# print(data)
# len(data)
# lines = 0
# words = 0
# chars = 0
# File.seek(0)
# # lines = data.count("\n")
# # print(lines)
# # words = len(data.split())
# # print(words)
# # chars = len(data)
# # print(chars)
# for li in File :
# lines = lines+1
# words = words+len(li.split())
# for wo in li.split() :
# chars = chars + len(wo)
# print()
# print(lines)
# print(words)
# print(chars)
###############################################
# f = open("c:/classss/ABC/2end.txt","r+")
# data = f.readlines()
# print(data)
# for s in data :
# print(s)
a = "44646"
b = "53466331313"
print(a,"\n",b) |
# convert Python dictionary object (sort by key) to JSON data. Print the object members with indent level 4
import json
python_dict = {'English': 78, 'Maths': 88, 'Computers': 100}
print(json.dumps(python_dict, sort_keys = True, indent = 4)) |
import turtle as t
import random as r
def tree(direction,level):
temp=0
t.pensize(10-level)
if(level<=5):
t.pencolor((100+level*30,0,0))
temp=r.random()*10
elif(level<=9 and level>5):
t.pencolor((0,100+(level-6)*30,0))
if(direction==1):
t.left(20)
elif(direction==2):
t.right(20)
t.pendown()
t.forward(60-(level-1)*4)
if(level<9):
if(temp>6):
t.pensize(2)
t.pencolor((100,100,100))
t.left(50)
t.forward(20)
t.left(180)
t.forward(20)
t.left(180)
t.right(100)
t.forward(20)
t.left(180)
t.forward(20)
t.left(180)
t.pensize(10-level)
t.left(50)
if(level<=5):
t.pencolor((100+level*30,0,0))
elif(level<=9 and level>5):
t.pencolor((0,100+(level-6)*30,0))
tree(1,level+1)
t.penup()
t.left(180)
t.forward(60-level*4)
t.left(180)
t.right(20)
tree(2,level+1)
t.left(180)
t.penup()
t.forward(60-level*4)
t.left(180)
t.left(20)
t.colormode(255)
t.pencolor((0,0,0))
t.pensize(9)
t.penup()
t.goto(0,-100)
t.left(90)
t.pendown()
t.forward(60)
tree(1,1)
t.penup()
t.left(180)
t.forward(60)
t.left(180)
t.right(20)
tree(2,1)
t.penup()
t.left(180)
t.forward(60)
t.left(180)
|
# -*- coding: utf-8 -*-
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words): #manglet ‘:’
"""Prints the first word after popping it off."""
word = words.pop(0) #tatt bort en 'o'
print word
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1) #manglet ‘)’
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
where there is none.
""" # fjernet 2x \t på siste linje
print "--------------"
print poem
print "--------------"
five = 10 - 3 + 3 - 5
print "This should be five: %s" % five
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000 #endret ‘\’ til ‘/’
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point)
print "With a starting point of: %d" % start_point
print "We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates)
start_point = start_point / 10
print "We can also do that this way:"
print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point) #manglet en ‘)’, satte inn _ istedenfor - og korrigerte variabelnavnet
sentence = "All good things come to those who weight."
words = break_words(sentence) #tatt bort ex25. da funksjonen ligger i dette dokumentet
sorted_words = sort_words(words) #tatt bort ex25. da funksjonen ligger i dette dokumentet
print_first_word(words)
print_last_word(words)
print_first_word(sorted_words) #fjernet ‘.’
print_last_word(sorted_words)
sorted_words = sort_sentence(sentence) #tatt bort ex25
print sorted_words #manglet ‘t’
print_first_and_last(sentence) #manglet en ‘f’ i funksjonsnavnet
print_first_and_last_sorted(sentence) #korrigerte variabel-navn, tok bort mellomrommene før funskjonsnavnet, korrigerte '_a_' til '_and_'
|
import unittest
import datetime
class TestCase (unittest.TestCase):
def test_date(self):
Date = "1992-04-08"
Today = str(datetime.datetime.now())
result = Today > Date
self.assertTrue(True,result)
self.assertFalse(Today < Date,result)
if __name__ == '__main__':
unittest.main() |
#!/usr/bin/env python3
#converts binary to hexadecimal
#maybelittleendianstyle
import sys
#print("Binary", list(binary))
class InvalidBinary(Exception):
pass
class BinaryToHex:
def binary_to_hex(self, binary):
#system check for binary digits only
for digit in list(binary):
if digit != "0" and digit != "1":
raise InvalidBinary(binary)
#print(list(binary))
x = 0
nybbles = []
first = 0
result = 0
for digit in (list(binary)):
x += 1
if x % 4 == 0:
if x != 1:
nybbles.append(binary[first:x])
first = x
#print(nybbles)
#division into nybbles
if x <= len(binary):
t = binary[first:]
r = len(binary) % 4
if r > 0:
for i in range(4-r):
t += "0"
nybbles.append(t)
#print(nybbles)
hexnum = ""
for nybble in nybbles:
if nybble == "0000":
hexnum += "0"
elif nybble == "0001":
hexnum += "8"
elif nybble == "0010":
hexnum += "4"
elif nybble == "0011":
hexnum += "c"
elif nybble == "0100":
hexnum += "2"
elif nybble == "0101":
hexnum += "a"
elif nybble == "0110":
hexnum += "6"
elif nybble == "0111":
hexnum += "e"
elif nybble == "1000":
hexnum += "1"
elif nybble == "1001":
hexnum += "9"
elif nybble == "1010":
hexnum += "5"
elif nybble == "1011":
hexnum += "d"
elif nybble == "1100":
hexnum += "3"
elif nybble == "1101":
hexnum += "b"
elif nybble == "1110":
hexnum += "7"
elif nybble == "1111":
hexnum += "f"
return hexnum
def main():
#print ("Number of arguments:", len(sys.argv), "arguments.")
#print ("Argument List:", str(sys.argv))
if len(sys.argv) != 2:
print("Incorrect Number of Arguments")
sys.exit(1)
binary = sys.argv[1]
bintohex = BinaryToHex()
try:
result = bintohex.binary_to_hex(binary)
print(result)
except InvalidBinary as e:
print("Invalid binary number " + str(e))
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""
Simple study related to threads performance
"""
import time
import random
import threading
parallel = random.choice(['True', 'False'])
counter = 0
max_for = 100000000
lock = threading.Lock()
def add_numbers():
global counter
for _ in range(0, max_for):
lock.acquire()
counter += 1
lock.release()
if __name__ == '__main__':
start_time = time.time()
if parallel is True:
t1 = threading.Thread(target=add_numbers)
t2 = threading.Thread(target=add_numbers)
t1.start()
t2.start()
t1.join()
t2.join()
else:
add_numbers()
add_numbers()
end_time = time.time() - start_time
print(end_time, parallel)
print(counter)
# assert max_for == max_for*2 |
# -*- coding: utf-8 -*-
"""
Simple study related to Multiprocessing
"""
import os
from multiprocessing import Process
#function 1
def calculate_square(n):
print('calculated square:', n*n)
proc = os.getpid()
print('{0} process id:'.format(proc))
#function 2
def calculate_cube(n):
print('calculated cube:', n*n*n)
proc = os.getpid()
print('{0} process id'.format(proc))
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
procs = []
for index, n in enumerate(numbers):
p = Process(target=calculate_square, args=(n,))
procs.append(p)
p.start()
#
# for proc in procs:
# proc.join()
|
import unittest
from hashing import *
class test_Hashtable(unittest.TestCase):
def test_Get_GeneralCase(self):
# Check the case where the element is present in the table; returns value
H = HashTable()
H[54]="Data Structures"
self.assertEqual(H.get(54), 'Data Structures')
def test_Get_InvalidCase(self):
# Check the case where the element is not present in the table; returns None
H = HashTable()
H[10]="CPS305"
self.assertEqual(H.get(100), None)
def test_put_GenralCase(self):
# Check if the item is added in the table
H=HashTable()
H[54]="1"
H[26]="2"
self.assertEqual(H.get(54), '1')
def test_table_Resize(self):
# Check the re-size of the table; returns new table size
H=HashTable()
H[54]="1"
H[26]="2"
H[93]="3"
H[17]="4"
H[77]="5"
H[31]="6"
H[44]="7"
H[55]="8"
H[20]="9"
# Putting an extra element would resize the table and the size would be 13(next prime number after default size 11)
H[95]="10"
H[96]="11"
self.assertEqual(H.size, 13)
def test_oldValue_after_Resize(self):
# After the re-size of the table; you can still get the old values with the same keys
H=HashTable()
H[54]="1"
H[26]="2"
H[93]="3"
H[17]="4"
H[77]="5"
H[31]="6"
H[44]="7"
H[55]="8"
H[20]="9"
# Resizes Table here from size of 11 to 13
H[95]="10"
H[96]="11"
self.assertEqual(H.get(54), '1')
if (__name__ == "__main__"):
unittest.main(argv=['first-arg-is-ignored'],exit=False)
|
"""
..module: Assistant - help to guess the riddled number by suggesting the list of the optimal requests
..author: Sergey Sumburov <sumburovsn@gmail.com>
"""
import random
# game_log dictionary keeps all the responses of the current session of the game
# in form "attempt: response"
game_log = {
'1234': 'B0 C2',
'8423': 'B0 C3',
'3947': 'B1 C0',
'0842': 'B2 C1',
# '4876': 'B2 C1',
# '7654': 'B1 C1'
}
class Attempt:
"""
class Attempt for easy sorting the optimal request based on the amount of possible numbers
to store them in list instead of dictionary
"""
def __init__(self, numeric, amount):
"""
function to make an instance of Attempt
"""
self.numeric = numeric
self.amount = amount
def __lt__(self, other):
"""
function for sorting based on amount
"""
return self.amount < other.amount
def compare(riddle, attempt):
"""
compare function gets answer for "Bulls&Cows" game
by comparison riddle to attempt
:param riddle: the string consisted of 4 different numeric symbols to be recognised
:param attempt: the string consisted of 4 different numeric symbols as an attempt to recognize the riddle
:return result: the string of template 'B1 C2' ('B0 C0', 'B2 C2', etc.)
"""
bulls = 0
cows = 0
# check every 4 symbols of the attempt against the riddle
for i in range(4):
if attempt[i] == riddle[i]:
# if symbol is in the same position it contributes to bulls
bulls += 1
else:
if attempt[i] in riddle:
# if symbol is in the different position it contributes to cows
cows += 1
# the response of template 'B1 C2' ('B0 C0', 'B2 C2', etc.)
return 'B' + str(bulls) + ' C' + str(cows)
def generate():
"""
generate function returns the list of all possible numeric which correspond to the trialLog dictionary
:return result: the list of all possible string of 4 numeric symbols
"""
result = []
numeric0 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
for number0 in numeric0:
numeric1 = numeric0.copy()
numeric1.remove(number0)
for number1 in numeric1:
numeric2 = numeric1.copy()
numeric2.remove(number1)
for number2 in numeric2:
numeric3 = numeric2.copy()
numeric3.remove(number2)
for number3 in numeric3:
number = number0 + number1 + number2 + number3
is_correspond = True
for key in game_log.keys():
if compare(key, number) != game_log[key]:
is_correspond = False
break
if is_correspond:
result.append(number)
return result
def generate_all():
"""
generate function returns the list of all possible arrangements of 4 from 10 numeric symbols
:return result: list of all possible arrangements of 4 from 10 numeric symbols
"""
result = []
numeric0 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
for number0 in numeric0:
numeric1 = numeric0.copy()
numeric1.remove(number0)
for number1 in numeric1:
numeric2 = numeric1.copy()
numeric2.remove(number1)
for number2 in numeric2:
numeric3 = numeric2.copy()
numeric3.remove(number2)
for number3 in numeric3:
result.append(number0 + number1 + number2 + number3)
return result
# def analyze(numeric):
# """
# analyze function returns the dictionary of the form, e.g.:
# {'1234': {'B0 C1': 14,
# 'B1 C1': 3}
# '5678': {'B1 C2': 1,
# 'B2 C0': 30}
# ...
# }
# for each numeric it contains the dictionary of the possible responses and corresponding them amounts of possible
# numeric
# :param numeric: the list of all possible string of 4 numeric symbols from the generate (or generate_all) function
# :return analysis: the dictionary of all possible answers and amounts of possible numeric for every entry
# """
#
# analysis = {}
#
# for head in numeric:
# matrix = {}
# analysis[head] = matrix
# for current in numeric:
# result = compare(head, current)
# if result not in matrix:
# matrix[result] = 1
# else:
# matrix[result] += 1
# return analysis
def analyze(whole, numeric):
"""
analyze function returns the dictionary of the form, e.g.:
{'1234': {'B0 C1': 14,
'B1 C1': 3}
'5678': {'B1 C2': 1,
'B2 C0': 30}
...
}
for each numeric it contains the dictionary of the possible responses and corresponding them amounts of possible
numeric
:param whole: the list of all possible arrangements of 4 from 10 numeric symbols
:param numeric: the list of all possible string of 4 numeric symbols from the generate function
:return analysis: the dictionary of all possible answers and amounts of possible numeric for every entry
"""
analysis = {}
i = 0
for head in whole:
i += 1
print("\r in progress... {:.0%}".format(i/5040), end='')
matrix = {}
analysis[head] = matrix
for current in numeric:
result = compare(head, current)
if result not in matrix:
matrix[result] = 1
else:
matrix[result] += 1
print("Ready.")
return analysis
def min_max(matrix):
"""
min_max function forms the optimal request based on the minimum of all maximums values of Attempt class instances
:param matrix: the dictionary from the analyze function
:return result: the list of all possible string of 4 numeric symbols with minimum of all maximum
"""
list_max = []
result = []
for key in matrix.keys():
current = Attempt(key, 0)
for value in matrix[key].values():
if value > current.amount:
current.amount = value
list_max.append(current)
list_max.sort()
minimum = list_max[0].amount
for attempt in list_max:
if attempt.amount <= minimum:
result.append(attempt)
return result
output = generate()
print(len(output))
# print(10*9*8*7)
if len(output) == 1:
print("The riddle is {}".format(output[0]))
else:
results_matrix = analyze(generate_all(), output)
list_optimal = min_max(results_matrix)
priority = []
for response in list_optimal:
if response.numeric in output:
priority.append(response)
if priority:
print("Priority length = {}".format(len(priority)))
list_optimal = priority
index = int(random.random() * len(list_optimal))
request = list_optimal[index]
print("Suggest {}".format(request.numeric))
# if input("Print the possible numbers ?(y/n)") == 'y':
# for element in output:
# print(element)
#
# if input("Analyze against the whole set of arrangements?(y/n)") == 'y':
# results_matrix = analyze_all(generate_all(), output)
# list_optimal = min_max(results_matrix)
# priority = []
# for response in list_optimal:
# if response.numeric in output:
# priority.append(response)
#
# if priority:
# print("Priority length = {}".format(len(priority)))
# list_optimal = priority
# if input("Print the all optimal requests list ?(y/n)") == 'y':
# for response in list_optimal:
# print(response.numeric, response.amount)
# if input("Choose the random optimal request?(y/n)") == 'y':
# index = int(random.random() * len(list_optimal))
# request = list_optimal[index]
# print("Suggest {}".format(request.numeric))
|
# OPTION 1
# def fib(n, output=None):
# if n < 2:
# return 0
# if output is None:
# a = 0
# b = 1
# output = [a, b]
# if len(output) <= n:
# c = output[-1] + output[-2]
# output.append(c)
# fib(n, output)
# return output
# OPTION 2 : running iteratively in loop
# def fib(n):
# a, b = 0, 1
# for i in range(n):
# a, b = b, a + b
# return a
# OPTION 3 : using recursion
# def fib(n):
# if n == 0 or n == 1:
# return n
# else:
# return fib(n-1) + fib(n-2)
# print(fib(10))
# OPTION 4: using memoization and recursion
n = 10
cache = [None] * (n+1)
def fib_memo_rec(n):
# Base Case
if n == 0 or n == 1:
return n
# Check Cache
if cache[n] is not None:
return cache[n]
# Keep setting cache
cache[n] = fib_memo_rec(n-1) + fib_memo_rec(n-2)
return cache[n]
print(fib_memo_rec(10))
# fib(7) = [0,1,1,2,3,5,8]
# fib(8) = [0,1,1,2,3,5,8,13, 21, 34, 55, 89]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.