text
stringlengths
37
1.41M
num1=int(input("value")) num2=int(input("value")) num3=int(input("value")) if ((num1>num2)&(num1>num3)): if(num2>num3): print(num1,",",num2,",",num3) else: print(num1, ",", num3, ",", num2) elif((num2>num1)&(num2>num3)): if(num1>num3): print(num2, ",", num1, ",", num3) else: print(num1, ",", num2, ",", num3) elif((num3>num1)&(num3>num2)): if(num1>num2): print(num3, ",", num1, ",", num2) else: print(num3, ",", num2, ",", num1)
#identifiers? #for comments #simply a name is called identifiers #variable name , function name , class name #variables are used fo representing a memory location #num1=2 #variable is num1 #1num=10 # not valid reason is variable name always start with alphabet #nummmmmmmm=12 #thre is no length limit foe variable name #name= "luminar" #print("company name=",name) name=input("enter value age") print("name=",name) #ptint() is used for displying messages in console #nput() is used for reading value through console
employees=[ [1001,"ajay","qa",1981,2003], [1002,"vijay","developer",1992,2008], [1003,"arun","ba",1989,2010], [1004,"amal","developer",2009,2014], [1005,"vimal","developer",1987,1989] ] #print all employee desigination for emp in employees: print(emp[2]) print() #print all employees whose desi=developer for emp in employees: if emp[2]=="developer": print(emp) print() #print all employees those who are working in 1980's for emp in employees: if ((emp[3] in range(1980,1990)) & (emp[4] in range(1980,1990))): print(emp) print() #print all employees details whose experience >9 yrs for emp in employees: if (emp[4]-emp[3])>9 : print(emp)
#to perform a specific task #input() #print() #def mul(num1,num2): #res=num1*num2 #print (res) #def div(num1,num2): #res=num1/num2 #print(res) #mul(10,20) #div(20,10) #function wit arguments and return value: #def add(num1,num2): #res=num1+num2 #return res #data=add(10,20) #print(data) def add(num1,num2): res=num1+num2 return res def evencheck(num1): if(num1%2==0): return "even" else: return "odd" data=add(10,20) print(evencheck(data))
lst=[-2,-1,0,2,3,4]#find least +ve missing integer #print(1 in lst) #check for 1 in lst or not cnt=1 for i in range(0,len(lst)): if cnt in lst: cnt+=1 else: print(cnt,"is missing least +ve integer") break
num=input("enter the value") i=1 sum=0 while(i<=int(num)): data=num*i sum=sum+int(data) i=i+1 print(sum)
limit=int(input("enter value")) sum=0 i=1 while(i<=limit): sum=sum+i i=i+1 print("sum is ", sum)
# -*- coding: utf-8 -*- # 'author':'zlw' """ 队列是一种操作被约束的线性表,队列可以使用数组或者链表实现。 队列的约束操作是: 在队列的一端追加元素,而在另一端弹出元素,满足FIFO的顺序特性。 """ # 定义链表元素 class Element(object): def __init__(self, value): self.value = value self.next_element = None # 基本的队列实现 class BasicQueue(object): element_class = Element # 实例对象初始化函数 def __init__(self, max_size=None): # 提供队列最大值的设定 self.max_size = max_size self.cur_size = 0 # 头结点用于表示队列第一个元素,不被计算,当head和tail都指向头结点说明队列空 self.first_element = self.element_class(None) self.head = self.first_element self.tail = self.first_element # 遍历队列生成器 def _each(self): yield 'ok' cur = self.head.next_element while cur: yield cur cur = cur.next_element # 遍历队列公开api def traverse_each(self): if self.is_empty: return [] else: each = self._each() next(each) # 激活生成器 return each # 清空队列 def clear(self): self.head = self.tail = self.first_element self.cur_size = 0 # 判定队列是否为满 @property def is_full(self): if not self.max_size: return False else: return self.cur_size >= self.max_size # 判定队列是否为空 @property def is_empty(self): return self.head is self.tail is self.first_element # 获取队列当前长度 @property def length(self): return self.cur_size @property def values(self): # 获取队列的所有元素的值列表 v_list = [] for element in self.traverse_each(): v_list.append(element.value) return v_list # 入队接口 def put(self, value): """队列的入队接口函数 该函数会将用户给定的值传入队列元素类并创建元素对象,然后尝试加入队列。 """ # 判断当前队列是否已经满了 if self.is_full: # 如果满了则抛出异常 raise RuntimeError(f'队列{self}已满,无法入队') else: # 如果没满,则实例化元素对象 element = self.element_class(value) # 将实例化对象加入队列中,更新尾指针,更新队列长度 self.tail.next_element = element self.tail = element self.cur_size += 1 # 出队接口 def get(self): """队列的出队接口函数 在队列不为空的情况下,该函数将会弹出最新入队的元素 """ # 判断队列是否为空 if self.is_empty: # 如果为空,则抛出异常 raise RuntimeError(f'队列{self}已空,无法出队') else: # 否则,获得队头的元素,更新头指针,更新队列长度 element = self.head.next_element self.head.next_element = element.next_element self.cur_size -= 1 # 判断删除的元素是否是最后一个元素,如果是,则需要更新尾指针 if element is self.tail: self.tail = self.head # 返回弹出的元素值 element.next_element = None return element.value
# !/usr/bin/env python # -*- coding: utf-8 -*- # 'author':'zlw' """策略模块 此模块定义了各种策略类。 """ class BasePolicy(object): pass # 价格策略基类 class BasePricePolicy(BasePolicy): pass # 普通价格策略类 class CommonPricePolicy(BasePricePolicy): name = 'common' # 正常收银 def calculate(self, price): print('检测价格,返回原始价格') return price class DiscountPricePolicy(BasePricePolicy): name = 'discount' # 打折优惠 def __init__(self, discount): self.discount = discount def calculate(self, price): print('检测价格,返回打折价格') return self.discount * price class ReductionPricePolicy(BasePricePolicy): name = 'reduction' # 满减优惠 def __init__(self, full, reduction): self.full = full self.reduction = reduction def calculate(self, price): if price >= self.full: print('检测价格,返回满减价格') return price - self.reduction print('检测价格,未达满减要求') return price
# !/usr/bin/env python # -*- coding: utf-8 -*- # 'author':'zlw' """工厂模块 为每一个业务类编写一个工厂类以提供:实例化控制、封装。 工厂类与业务类为一对一映射关系。 """ from abc import ABCMeta, abstractmethod from src.operators import ( Add, Sub, Multi, Division, ) class AbstractFactory(object, metaclass=ABCMeta): """抽象工厂类""" @abstractmethod def create_operator(self, x, y): """每一个工厂类均提供此方法""" pass class AddFactory(AbstractFactory): def create_operator(self, x, y): return Add(x, y) class SubFactory(AbstractFactory): def create_operator(self, x, y): return Sub(x, y) class MultiFactory(AbstractFactory): def create_operator(self, x, y): return Multi(x, y) class DivisionFactory(AbstractFactory): def create_operator(self, x, y): # 可以做逻辑控制 if y == 0: raise ZeroDivisionError return Division(x, y)
""" A simple selenium test example written by python """ import unittest import sys from selenium import webdriver from selenium.common.exceptions import NoSuchElementException class TestTemplate(unittest.TestCase): """Include test cases on a given url""" def setUp(self): """Start web driver""" chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') self.driver = webdriver.Chrome(options=chrome_options) self.driver.implicitly_wait(10) def tearDown(self): """Stop web driver""" self.driver.quit() def test_case_1(self): print("TESTCASE 1 : TEST IF 'about' ELEMENT EXISTS") try: about=[] self.driver.get(url) elem_about = self.driver.find_elements_by_css_selector('h1') for heading in elem_about: about.append(heading.text.lower()) if "about" not in about: self.fail("No heading found with 'about' text") except NoSuchElementException as ex: self.fail(ex.msg) def test_case_2(self): print("TESTCASE 2 : TEST IF 'img' ELEMENT EXISTS") try: self.driver.get(url) elem_img = self.driver.find_element_by_tag_name('img') except NoSuchElementException as ex: self.fail(ex.msg) def test_case_3(self): print ("TESTCASE 3 : FIND IF MULTIPLE PARAGRAPHS EXISTS WITH 100 CHARACTERS AT LEAST") try: self.driver.get(url) elem_paras = self.driver.find_elements_by_css_selector('p') word_count = 0 para_list = [] for paragraph in elem_paras: para_list = para_list+list(paragraph.text) Letter_count = len(para_list) assert(Letter_count >= 100) except NoSuchElementException as ex: self.fail(ex.msg) def test_case_4(self): print ("TESTCASE 4: FIND 2 LINKS TO 2 BLOG POSTS") try: self.driver.get(url) elems = self.driver.find_elements_by_css_selector('a') #for elem in elems: # elem.click() #current_url = self.driver.current_url links = [elem.get_attribute('href') for elem in elems] if len(links) < 2: self.fail("Two blog links are not present.") except NoSuchElementException as ex: self.fail(ex.msg) def test_case_5(self): print("TESTCASE 5: BLOG ONE HEADING SHOULD CONTAIN 'this course xxx'") try: self.driver.get(url) elems = self.driver.find_elements_by_css_selector('a') links = [elem.get_attribute('href') for elem in elems] self.driver.get(links[0]) hdrs=[] header = self.driver.find_elements_by_css_selector('h1') for heading in header: hdrs.append(heading.text.lower()) if "".join(s for s in hdrs if "this course" in s.lower()) == "": self.fail("No header element has 'this course' text") except NoSuchElementException as ex: self.fail(ex.msg) def test_case_6(self): print("TESTCASE 6: BLOG ONE CONTAINS PARAGRAPHS OR UNORDERED LIST , WORD LIMIT : 250-500") try: self.driver.get(url) elems = self.driver.find_elements_by_css_selector('a') links = [elem.get_attribute('href') for elem in elems] self.driver.get(links[0]) elem_paras = self.driver.find_elements_by_css_selector('p') para_list=[] for paragraph in elem_paras: para_list = para_list + list(paragraph.text) Letter_count = len(para_list) elem_list= self.driver.find_elements_by_tag_name("li") unordered_list=[] for li in elem_list: unordered_list = unordered_list + list(li.text) Letter_count_list = len(unordered_list) assert((Letter_count >= 250 and Letter_count <= 500) or (Letter_count_list >= 250 and Letter_count_list <= 500)) except NoSuchElementException as ex: self.fail(ex.msg) def test_case_7(self): print("TESTCASE 7: BLOG TWO HEADING SHOULD CONTAIN 'learned xxx'") try: self.driver.get(url) elems = self.driver.find_elements_by_css_selector('a') links = [elem.get_attribute('href') for elem in elems] self.driver.get(links[1]) hdrs=[] header = self.driver.find_elements_by_css_selector('h1') for heading in header: hdrs.append(heading.text.lower()) if "".join(s for s in hdrs if "learned" in s.lower()) == "": self.fail("No header element has 'learned' text") except NoSuchElementException as ex: self.fail(ex.msg) def test_case_8(self): print("TESTCASE 8: BLOG TWO CONTAINS PARAGRAPHS OR UNORDERED LIST , WORD LIMIT : 250-500") try: self.driver.get(url) elems = self.driver.find_elements_by_css_selector('a') links = [elem.get_attribute('href') for elem in elems] self.driver.get(links[1]) elem_paras = self.driver.find_elements_by_css_selector('p') para_list=[] for paragraph in elem_paras: para_list = para_list + (list(paragraph.text)) Letter_count = len(para_list) elem_list= self.driver.find_elements_by_tag_name("li") unordered_list=[] for li in elem_list: unordered_list = unordered_list + list(li.text) Letter_count_list = len(unordered_list) assert((Letter_count >= 250 and Letter_count <= 500) or (Letter_count_list >= 250 and Letter_count_list <= 500)) except NoSuchElementException as ex: self.fail(ex.msg) #URL should be VM's IP:PORT combination where the project is hosted #rl="https://cs-ej4104-fall-2020.github.io/asawari44-devopsproject/" org=str(sys.argv[0]) repo=str(sys.argv[1]) url="https://"+org+".github.io/"+repo print(url) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestTemplate) unittest.TextTestRunner(verbosity=2).run(suite)
class Node: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def getNextNode(self, node: Node) -> int: if node == None or node.next == None: return None return node.next def getNodeVal(self, node: Node) -> int: if node == None or node.val == None: return 0 return node.val def addTwoNumbers(self, l1: Node, l2: Node) -> Node: lStart = None lEnd = None one = l1 two = l2 addition = 0 while one != None or two != None or addition != 0: sum = self.getNodeVal(one) + self.getNodeVal(two) + addition addition = 0 if sum > 9: sum = sum % 10 addition = 1 if lStart == None: lStart = Node(sum) lEnd = lStart else: lEnd.next = Node(sum) lEnd = lEnd.next one, two = self.getNextNode(one), self.getNextNode(two) return lStart my = Solution() l1 = Node(2, Node(4, Node(3))) l2 = Node(5, Node(6, Node(4))) # l1 = Node() # l2 = Node() lAns = my.addTwoNumbers(l1, l2) while lAns != None: print(lAns.val) lAns = lAns.next print('end') # + # 2 4 3 # 5 6 4 # 1 # 7 0 8 # + # 1 # 9 9 9 # 1 1 1 # 0 0 0 1 # Results: # Runtime: 68 ms, faster than 92.49% of Python3 online submissions for Add Two Numbers. # Memory Usage: 13.8 MB, less than 79.88% of Python3 online submissions for Add Two Numbers.
import math import numpy as np import matplotlib.pyplot as plt #fun1 is y = 9.81 -0.0025*x**2 #fun2 is y = -x def rungeKuttaMethod(dim1,dim2,step,fun1,fun2): time = [0] dim1List = [dim1] dim2List = [dim2] dim2_current = dim2 i = 0 while dim2_current > 0: #F1 vF1 = fun1(dim1List[i]) pF1 = fun2(dim1List[i]) #F2 vF2 = fun1(dim1List[i]+(1/2)*step * vF1) pF2 = fun2(dim1List[i]+(1/2)*step * vF1) #F3 vF3 = fun1(dim1List[i]+(1/2)*step * vF2) pF3 = fun2(dim1List[i]+(1/2)*step * vF2) #F4 vF4 = fun1(dim1List[i]+step * vF3) pF4 = fun2(dim1List[i]+step * vF3) dim1List.append( dim1List[i] + (vF1+2*(vF2+vF3)+vF4)*step/6) dim2List.append( dim2List[i] + ( pF1+2*(pF2+pF3)+pF4)*step/6) dim2_current = dim2List[i+1] time.append(i*step) i += 1 print("Final dim1List: ",dim1List[-1]) print("Runge Kutta Method: the object reaches Position: ",dim2List[-2],"m at the time: ",time[-2],"s") plt.plot(time,dim2List,color='green', label="dim2List") plt.ylabel("Dimension 2",color='green') # plt.legend() plt.xlabel("Time (s)") plt.twinx() plt.plot(time,dim1List,color='red', label="dim1List") plt.ylabel("Dimension 1 ",color ="red") plt.title("Position and Velocity Vs Time \"Runge Kutta Method\"") # plt.legend() plt.show() return def eulerMethod (dim1,dim2,step,fun1,fun2): time = [0] dim1List = [dim1] dim2List = [dim2] dim2_current = dim2 i = 0 while dim2_current > 0: dim1List.append( dim1List[i] + fun1(dim1List[i])*step) dim2List.append( dim2List[i] +fun2(dim1List[i])*step) dim2_current = dim2List[i+1] time.append(i*step) i += 1 print("Final dim1List: ",dim1List[-1]) print("Euler Method: the object reaches Position: ",dim2List[-2],"m at the time: ",time[-2],"s") plt.plot(time,dim2List,color='green', label="dim2List") plt.ylabel("Dimension 2",color='green') # plt.legend() plt.xlabel("Time (s)") plt.twinx() plt.plot(time,dim1List,color='red', label="dim1List") plt.ylabel("Dimension 1 ",color ="red") plt.title("Position and Velocity Vs Time \"Runge Kutta Method\"") # plt.legend() plt.show() return
import numpy as np ''' 1. Linear algebraic equations can arise in the solution of differential equations. For example, the following heat equation describes the equilibrium temperature T = T(x)(oC) at a point x (in meters m) along a long thin rod, d2T/dx2 = h′(T − Ta), (1) where Ta = 10oC denotes the temperature of the surrounding air, and h′ = 0.03 (m−2) is a heat transfer coefficient. Assume that the rod is 10 meters long (i.e. 0 ≤ x ≤ 10) and has boundary conditions imposed at its ends given by T(0) = 20oC and T(10) = 100oC. ''' ''' a) Using standard ODE methods, which you do not need to repeat here, the general form of an analytic solution to (1) can be derived as T(x)=A+Beλx +Ce−λx, (2) where A, B, C, and λ are constants. Plug the solution of type (2) into both sides of equation (1). This should give you an equation that must be satisfied for all values of x, for 0 ≤ x ≤ 10, for some fixed constants A, B, C, and λ. Analyze this conclusion to determine what the values of A and λ must be. ''' ''' (b) Next, impose the boundary conditions T (0) = 20 oC and T (10) = 100 oC to derive a system of 2 linear algebraic equations for B and C. Provide the system of two equations you have derived. ''' ''' (c) Use one of the numerical algorithms you developed for homework 3 (Gauss elimination or LU decomposition) to solve the algebraic system you de- rived in question 2(b) above, and obtain an analytic solution to (1) of the form (2). By analytic solution we mean an explicit solution to equation (1) which is valid for each x in the interval [0, 10]. ''' ''' (d) Next we will discuss how to obtain a numerical solution to (1). That is, we will seek to obtain an approximate solution to (1) which describes the value of T at 9 intermediate points inside the interval [0,10]. More precisely, the equation (1) can be transformed into a linear algebraic system for the temperature at 9 interior points T1 = T(1), T2 = T(2), T3 = T(3), T4 =T(4), T5 =T(5), T6 =T(6), T7 =T(7), T8 =T(8), T9 =T(9), by using the following finite difference approximation for the second derivative at the ith interior point, d2Ti = Ti+1 −2Ti +Ti−1, (3) dx2 (∆x)2 where 1≤i≤9, T0 =T(0)=20oC, T10=T(10)=100oC, and ∆x is the equal spacing between consecutive interior points (i.e. with 9 equally spaced interior points inside [0,10] it holds that ∆x = 1). Use (3) to rewrite (1) as a system of 9 linear algebraic equations for the unknowns T1, T2, T3, T4, T5, T6, T7, T8, and T9. Provide the system of 9 equations you have derived. ''' bigArray =[ [ 1. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 20. ], [ 1. , -2.3, 1. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , -3. ], [ 0. , 1. , -2.3, 1. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , -3. ], [ 0. , 0. , 1. , -2.3, 1. , 0. , 0. , 0. , 0. , 0. , 0. , -3. ], [ 0. , 0. , 0. , 1. , -2.3, 1. , 0. , 0. , 0. , 0. , 0. , -3. ], [ 0. , 0. , 0. , 0. , 1. , -2.3, 1. , 0. , 0. , 0. , 0. , -3. ], [ 0. , 0. , 0. , 0. , 0. , 1. , -2.3, 1. , 0. , 0. , 0. , -3. ], [ 0. , 0. , 0. , 0. , 0. , 0. , 1. , -2.3, 1. , 0. , 0. , -3. ], [ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 1. , -2.3, 1. , 0. , -3. ], [ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 1. , -2.3, 1. , -3. ], [ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 1. , 100. ]] print( np.matrix(bigArray)) ''' (e) Use one of the numerical algorithms you developed for homework 3 (Gauss elimination or LU decomposition) to solve the system derived in question 1(d) above. Validate your numerical solution by comparison to the analytic solution that you obtained in 1(c) through depicting the two solutions on plots over the interval 0 ≤ x ≤ 10. ''' import NM_HW3 as hw consts =[20,-3,-3,-3,-3,-3,-3,-3,-3,-3,100] print( np.matrix(consts)) solutions = hw.guss2(bigArray,consts) import math def Temp(x): A=10 B=4.467121520 C=5.532878481 λ=math.sqrt(0.3) return A+B*math.exp(λ*x) +C*math.exp(-λ*x) solutions2 = [None]*11 for i in range(0,11): solutions2[i] = Temp(i) import matplotlib.pyplot as plt import matplotlib.patches as mpatches # xVals = range(0,11) # print('Solution1.D:',solutions) # print('Solution1.C:',solutions2) # orange_patch = mpatches.Patch(color='orange', label='The 1.C Data') # blue_patch = mpatches.Patch(color='blue', label='The 1.D Data') # plt.legend(handles=[orange_patch,blue_patch]) # plt.plot(solutions) # plt.plot(solutions2) # plt.ylabel('Temp') # plt.xlabel('Distance') # # plt.show() ''' (f) Write a function that takes as input the number of interior nodes n desired for your numerical solution (i.e. n = 9 in 1(d) above), and outputs the numerical solution to (1) in the form of the interior node values T1 = T(∆x), T2 = T(2∆x),..., Tn = T(n∆x). ''' def n_TempSolution(n,lengthOfRod): # deltaX = lengthOfRod/(n+1) # m= n+2 # solutionMat = [ [[0] * m for i in range(n+2)]] deltaX = lengthOfRod/(n+1) m= n+2 solutionMat = [[0] * m for i in range(n+2)] consts = [None]*(n+2) # Rows for i in range(1,n+1): # Colloms for j in range(0,m): if i==j: solutionMat[i][j]= (-2/(deltaX**2) -.3) elif i+1 == j or i-1==j: solutionMat[i][j]=1/(deltaX**2) else: solutionMat[i][j]= 0 solutionMat[i][m-1] = (-3) consts[i] = (-3) solutionMat[0][0] = 1 solutionMat[0][m-1] = 20 consts[0] = 20 solutionMat[n+1][m-2] =1 solutionMat[n+1][m-1] = 100 consts[n+1] = 100 print( np.matrix(solutionMat)) print( np.matrix(consts)) solutions = hw.guss2(bigArray,consts) return solutions lengthOfRod = 10 val = 1 solutions2 = [None]*(val+2) for i in range(0,val+2): solutions2[i] = Temp(i) solutionG_1=n_TempSolution(1,lengthOfRod) plt.plot(solutionG_1,) plt.plot(solutions2) plt.ylabel('Temp') plt.xlabel('Distance') plt.show() val = 4 solutions2 = [None]*(val+2) for i in range(0,val+2): solutions2[i] = Temp(i) solutionG_4=n_TempSolution(4,lengthOfRod) plt.plot(solutionG_4,) plt.plot(solutions2) plt.ylabel('Temp') plt.xlabel('Distance') plt.show() val = 9 solutions2 = [None]*(val+2) for i in range(0,val+2): solutions2[i] = Temp(i) solutionG_9=n_TempSolution(9,lengthOfRod) plt.plot(solutionG_9,) plt.plot(solutions2) plt.ylabel('Temp') plt.xlabel('Distance') plt.show() val = 19 solutions2 = [None]*(val+2) for i in range(0,val+2): solutions2[i] = Temp(i) solutionG_19=n_TempSolution(19,lengthOfRod) plt.plot(solutionG_19,) plt.plot(solutions2) plt.ylabel('Temp') plt.xlabel('Distance') plt.show() exit(0) ''' (g) Produce and submit 4 plots that compare your analytic solution to (1) derived in question 2(b) to the numerical solution generated in question 2(f) for n = 1, n = 4, n = 9, and n = 19, respectively. ''' ''' 2. Develop an algorithm that uses the golden section search to locate the minimum of a given function. Rather than using the iterative stopping criteria we have previously implemented, design the algorithm to begin by determining the number of iterations n required to achieve a desired absolute error |Ea| (not a percentage), where the value for |Ea| is input by the user. You may gain insight by comparing this approach to a discussion regarding the bisection method on page 132 of the textbook. Test your algorithm by applying it to find the minimum of f(x) = 2x+ (6/x) with initial guesses xl = 1 and xu = 5 and desired absolute error |Ea| = 0.00001. ''' import goldenSearch as gs def function1(x): return 2*x +(6/x) xl = 1 xu =5 tol = 0.00001 gs.goldenSearch(function1,xl,xu,tol) ''' 3. Given f(x,y)=2xy+2y−1.5x2−2y2, (a) Start with an initial guess of (x0,y0) = (1,1) and determine (by hand is fine) two iterations of the steepest ascent method to maximize f(x,y). (b) What point is the steepest ascent method converging towards? Justify your answer without computing any more iterations. '''
def Secant(function,xLower, xUpper, es, imax): # Secant method to finds a root of a funtion. # xLower: lower bound guess. # xUpper: upper bound guess. # es: error threshold. # imax: max iterations threshold. iter =0 xr = xLower ea = es xr_old = xr while (ea >= es) and (iter < imax): xr = xUpper - (function(xUpper)/ (function(xUpper)-function(xLower))) * (xUpper - xLower) xr_old = xr iter +=1 test = function(xLower) * function(xr) if test <0: # id the value is negative then the root is to the left xUpper = xr elif test >0: # the vale is positive and the root is to the right xLower = xr else: ea = 0 x = xr print("x: "+str(x)+ " is the root approx Bisection method") return x
import requests from bs4 import BeautifulSoup import pandas as pd """Gets page request and stores the content""" def getPageRequest(): newYork = "https://forecast.weather.gov/MapClick.php?lat=40.7146&lon=-74.0071" meadville = "https://forecast.weather.gov/MapClick.php?lat=41.63648000000006&lon=-80.15142999999995" city = input("Which city you which to know the weather for ? New York or Meadville : ").lower() if city == "new york": page = requests.get(newYork) soup = BeautifulSoup(page.content, 'html.parser') elif city == "meadville": page = requests.get(meadville) soup = BeautifulSoup(page.content, 'html.parser') else: return "please invalid city " return soup # page = requests.get("https://forecast.weather.gov/MapClick.php?lat=40.7146&lon=-74.0071") # soup = BeautifulSoup(page.content, 'html.parser') # return soup """Finds the weather table using id/class tags.""" def weeklyWeather(soup): seven_day = soup.find(id="seven-day-forecast") forecast_items = seven_day.find_all(class_="tombstone-container") tonight = forecast_items[0] return seven_day """Gets the day of the week""" def weekdays(seven_day): period_tags = seven_day.select(".tombstone-container .period-name") periods = [pt.get_text() for pt in period_tags] return periods """Stores short discriptions of each day's weather""" def getShortDescription(seven_day): short_descs = [sd.get_text() for sd in seven_day.select(".tombstone-container .short-desc")] return short_descs """Stores the weather""" def getTemp(seven_day): temps = [t.get_text() for t in seven_day.select(".tombstone-container .temp")] return temps """ Creates table""" def createTable(periods, short_descs, temps): weather = pd.DataFrame({ "Day": periods, "short description": short_descs, "temperature": temps # "full description":descs }) weather.to_csv('../build/weather.csv')
# for loop allows us to do something over # and over again # structure of for loop # for item in collection: # print(item) # print every letter in a word for char in "hello world": print(char) # range: used to generate a range # of numbers to help with looping # in for loops. range will start # its count at 0 if you only # provide one number. # range(end_number) # end_number -> the number to stop on # the range generated is up to but not # including the number passed # range(start, end, skip_count_by) # start -> starting number # end -> up to but not including # skip_count -> used to skip count # can count forward # or backward for num in range(10): print(num) nums = range(1, 10, 2) myList = list(nums) for num in myList: print(f"NUMBER IN LIST {num}")
def main(): # some simple data types that we have in Python # boolean: True or False isGameOver = False print("isGameOver is of type") print(type(isGameOver)) print() # integer: integers are whole numbers myAge = 23 print("myAge is of type") print(type(myAge)) print() # string: a stirng is a word / multipile characters in a row fName = "John" print("fName is of type") print(type(fName)) print() # list: list is a python array, it can hold any type of data # we can access and set data in a list using an index myList = ["John Doe", 23, False, {"name": "Billy"}] print("myList is of type") print(type(myList)) print() print("*** Here is what is in myList ***") print(myList[0]) print(myList[1]) print(myList[2]) print(myList[3]) print("Lets change False to True...") myList[2] = True print(myList[2]) print() # dictionary (dict): storing data with key / value pairs. This is # in a way storing a collection of different variables # just like in a list we can store ANY kind of data in here # we instead access its data via a key / name and in return # we get the value stored in that key / name myDict = {"name": "John Doe", "age": 22, "city": "Austin"} print("myDict is of type") print(type(myDict)) print("*** Here is what is in myDict") print(myDict["name"]) print(myDict["age"]) print(myDict["city"]) if __name__ == "__main__": main()
# some extra list methods # index: returns the index of the specified # item in the list # # you can also pass in a starting index # to start the search from # index(item, start_index) # # you can also pass in a ending index to # identify a stop point for the index search # index(item, start_index, end_index) numbers = [5, 6, 7, 8, 9, 10] print("The index of number 6 is: ", numbers.index(6)) print("The index of number 9 is: ", numbers.index(9)) # count: returns the number of times an item # appears in a list numbers = [1, 2, 3, 4, 3, 2, 1, 4, 10, 2] freqThree = numbers.count(3) print("The number 3 shows up " + str(freqThree) + " times") # reverse: will reverse the order of a list # this is an inplace operation, meaning that # it doesnt make a new copy or anything. It # updates the original copy names = ["Billy", "Joe", "Jane", "John", "Skylar"] print("Names before the reverse") print(names) names.reverse() print("Names after the reverse") print(names) # sort: sorts the list for you, another inplace # operation names.sort() print("Names sorted") print(names) # join: a string method, used to join / convert a list # to a string # # "string to join".join(list) # the string that calls on join will join # the list with every element joined with # the string provided phrase = "Coding is fun" # cretae an array from a string words = phrase.split(" ") print("Words is currently") print(words) print("*** Joining Words List ***") # join the words back into a string phrase = " ".join(words) print(phrase) name = ["Mr", "Blue"] print("Name before join") print(name) name = ". ".join(name) print("Name after join") print(name)
s=input("Enter String") if s>='a' and s<='z': print(s.upper())
''' Roy wanted to increase his typing speed for programming contests. His friend suggested that he type the sentence "The quick brown fox jumps over the lazy dog" repeatedly. This sentence is known as a pangram because it contains every letter of the alphabet. After typing the sentence several times, Roy became bored with it so he started to look for other pangrams. Given a sentence, determine whether it is a pangram. Ignore case. Function Description Complete the function pangrams in the editor below. It should return the string pangram if the input string is a pangram. Otherwise, it should return not pangram. pangrams has the following parameter(s): s: a string to test ''' #!/bin/python3 import math import os import random import re import sys # Complete the pangrams function below. def pangrams(s): alphabet = "abcdefghijklmnopqrstuvwxyz" letterDict = {} for x in alphabet: letterDict[x] = 0 for y in s: if y.lower() in alphabet: letterDict[y.lower()] += 1 for z in letterDict: if letterDict[z] == 0: return False return True print(pangrams("The quick brown fox jumps over the lazy dog")) print(pangrams("The fox jumps over the lazy dog")) # if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') # s = input() # result = pangrams(s) # fptr.write(result + '\n') # fptr.close()
# Sample code to read input and write output: ''' NAME = input() # Read input from STDIN print("Hello " + NAME) # Write output to STDOUT ''' # Warning: Printing unwanted or ill-formatted # data to output will cause the test cases to fail # Write your code here def problem3(): line = input() numCombos = [0] problem3Rec(line, numCombos) return numCombos[0] def problem3Rec(arr, numCombos): if len(arr) == 0: numCombos[0] += 1 elif len(arr) >= 2: if int(arr[0]) == 2 and int(arr[1]) <= 6: problem3Rec(arr[1:],numCombos) problem3Rec(arr[2:],numCombos) elif int(arr[0]) == 1: problem3Rec(arr[1:],numCombos) problem3Rec(arr[2:],numCombos) else: problem3Rec(arr[1:],numCombos) else: problem3Rec(arr[1:],numCombos) x = problem3() print(x)
''' Problem: Given the root node of a binary tree, return the length of the longest path in the tree (node to node) ex. 10 1 20 0 2 Ex. 10 / \ 4 11 / \ 3 5 / \ 2 9 / / 1 7 Longest path is (1-2-3-4-5-9-7) of length 7 ''' ''' base node if left and right are null, return 1 else return (look at left node), (look at right one) and add 1 return max () 10 returns 1 + strat: recursively somehow pass left branch greatest length --------- def rec(node,highest): if node.left and node.right are both null: highest = max(highest, 1) return 1 elif node.left == None and node.right != None: rightVal = rec(node.right, highest) highest = max(highest, rightVal+1) return rightVal+1 elif node.left != None and node.right == None: rightVal = rec(node.right, highest) highest = max(highest, rightVal+1) return rightVal+1 else: leftVal = rec(node.left, highest) rightVal = rec(node.right, highest) highest = max(highest, leftVal+rightVal+1) return max(leftVal+1, rightVal+1) def shellFunc(root): highest = 0 rec(root, highest) return highest ''' def longestPath(root): return
''' Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray. ''' ''' strat: -check all sub arrays of index 0:n -then check all sub arrays of index 1:n, etc if a product is larger than the current largest, then update it return the largest value ''' ''' class Solution { public int maxProduct(int[] nums) { int max = Integer.MIN_VALUE, imax = 1, imin = 1; for(int i=0; i<nums.length; i++){ if(nums[i] < 0){ int tmp = imax; imax = imin; imin = tmp;} imax = Math.max(imax*nums[i], nums[i]); imin = Math.min(imin*nums[i], nums[i]); max = Math.max(max, imax); } return max; } } ''' import math #O(n) def largestSubArray2(arr): maxNum = -500 imax = -500 imin = -500 #count for big O count = 0 #loops through array once for x in range(len(arr)): #increases count for big O count+=1 #if the number is negative if arr[x] < 0: #switch imax and imin numbers temp = imax imax = imin imin = temp #imax is the max of the current number, or the imax*current numbe #same with imin imax = max(imax*arr[x] , arr[x]) imin = min(imin*arr[x], arr[x]) #maxNumber is the max value of imax and maxNum maxNum = max(maxNum, imax) print("count: "+ str(count)) return maxNum #O(n^2) def largestSubArray(arr): count = 0 largest = 0 #double loop for the upper and lower bounds of the subArray for x in range(len(arr)): for y in range(1,len(arr[x:])+1): #used for big O calculation count+=1 #gets the product of the current crafted array within the bounds of [x:y] prodTemp = math.prod(arr[x:y]) #updates the largest product if the product is bigger if prodTemp > largest: largest = prodTemp print("count: "+ str(count)) return largest test4 = [-50, 1, 2 ,3] test1 = [item for item in range(-15,15)] test2 = [-2,0,-1] test3 = [2,3,-2,4] print(largestSubArray(test1)) # print(largestSubArray(test2)) print("--------") print(largestSubArray2(test1)) #print(largestSubArray2(test2))
''' Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character. Return the power of the string. Example 1: Input: s = "leetcode" Output: 2 Explanation: The substring "ee" is of length 2 with the character 'e' only. Example 2: Input: s = "abbcccddddeeeeedcba" Output: 5 Explanation: The substring "eeeee" is of length 5 with the character 'e' only. Example 3: Input: s = "triplepillooooow" Output: 5 Example 4: Input: s = "hooraaaaaaaaaaay" Output: 11 Example 5: Input: s = "tourist" Output: 1 ''' #O(n) time def consecChars(word): maxLen = 0 for x in range(len(word)-1): n = x+1 temp = 1 while(word[n]==word[x]): temp += 1 n+=1 if n+1 >= len(word): break x = n maxLen = max(maxLen,temp) return maxLen print(consecChars("leetcode")) #2 print(consecChars("abbcccddddeeeeedcba")) #5 print(consecChars("triplepillooooow")) #5 print(consecChars("hooraaaaaaaaaaay")) #11 print(consecChars("tourist")) #1
''' Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters. ''' '''' tree t:1 r:1 e:2 [] loop through dict. t [t] r [t,r] ''' def sortFreq(word): letDict = {} letArr = [] finalString = "" #maxFreq = 0 for x in word: if x in letDict: letDict[x] += 1 else: letDict[x] = 1 print(letDict) for y in letDict: if len(letArr) == 0: letArr.append(y) else: for z in range(len(letArr)): if letDict[y] <= letDict[letArr[z]]: letArr.insert(z,y) break else: letArr.insert(0,y) break print(letArr) for letter in letArr: for x in range(letDict[letter]): finalString+= letter return finalString test1 = "tree" test2 = "cccaaa" test3 = "Aabb" print(sortFreq(test3))
''' Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a time. Each transformed word must exist in the word list. Note: Return 0 if there is no such transformation sequence. All words have the same length. All words contain only lowercase alphabetic characters. You may assume no duplicates in the word list. You may assume beginWord and endWord are non-empty and are not the same. Example 1: Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: 5 Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", return its length 5. Example 2: Input: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log"] Output: 0 Explanation: The endWord "cog" is not in wordList, therefore no possible transformation. ''' ''' strat: recursive have a function where it detects if one letter is different- returns boolean loop through potential words and if they are one letter off, make that word the new word, and remove it from the wordList being passed in also have some sort of count passed down ''' def oneLetterOff(word1, word2): #assumes the words are of equal length numLettersOff = 0 for x in range(len(word1)): if not word1[x] == word2[x]: numLettersOff += 1 if numLettersOff <= 1: return True else: return False def wordLadder(begin, end, wordList): #supposed to be the system max, just picked a really high number ultMax = 5000 return wordLadderRec(begin, end, wordList, 0, ultMax, ultMax ) def wordLadderRec(begin, end, wordList, count, minVal, constMax): #print(wordList) #print(end in wordList) #if the begin word is equal to the end word, return the count +1 # +1 because the beginning word isnt counted if begin == end: #oneLetterOff(begin,end): #print("found!: " + str(count+1)) return count + 1 #if the end word isnt in the wordList, save the hassle and just return 0 #exception to this would be if begin and end are equal, in that case #it gets handled in the if statement above this one elif end not in wordList: return 0 else: #print("begin: " + begin) #for each word in the list, for x in range(len(wordList)): #it checks if its one letter off if oneLetterOff(begin,wordList[x]): #if it is, remove the word from the list that it is "transforming" #to, and then increase the count by 1 temp = wordLadderRec(wordList[x], end, wordList[:x]+wordList[x+1:], count+1, minVal, constMax) #if its greater than 0 (omits dead ends) if temp > 0: #the minimum value is the lesser of the current min value and #the number derived from that path minVal = min(minVal, temp) #if the minVal is equal to the constant max, it means it cycled #through the whole list and nothing was one letter off of begin #therefore we return 0 if minVal == constMax: return 0 #otherwise return the minimum Value else: return minVal test1 = ["hot","dot","dog","lot","log","cog"] test2 = ["hot","dot","dog","lot","log"] test3 = ["hot","dot","dog","lot","log","cog"] test4 = ["hot","dot","dog","lot","log","cog","dol"] test5 = test1 test6 = [] print(wordLadder("hit","cog",test1)) #5 print(wordLadder("hit","cog",test2)) #0 #pog - cog print(wordLadder("pog","cog",test3)) #2 #cot - dot - dol print(wordLadder("cot","dol",test4)) #3 #no correlation print(wordLadder("pis","cog",test5)) #0 #list is empty print(wordLadder("hit","cog",test6)) #0
''' We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. Example 1: Input: asteroids = [5, 10, -5] Output: [5, 10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. Example 2: Input: asteroids = [8, -8] Output: [] Explanation: The 8 and -8 collide exploding each other. Example 3: Input: asteroids = [10, 2, -5] Output: [10] Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. Example 4: Input: asteroids = [-2, -1, 1, 2] Output: [-2, -1, 1, 2] Explanation: The -2 and -1 are moving left, while the 1 and 2 are moving right. Asteroids moving the same direction never meet, so no asteroids will meet each other. ''' ''' [3,5,-8,9,-7] first compare 3 and 5. they are both positive, so nothing happens. then compare 5 and -8. they are different signs > -8 overpowers 5. so 5 gets deleted. now compare -8 to 3. > -8 overpowers 3, so 3 gets deleted. -8 is now the first element in the array. it rests there. Now compare -8 to 9. they are opposite signs but are going in diff directions. both are kept. now compare 9 to -7. > 9 overpowers -7. -7 gets deleted. theres nothing left, so we are done. strat: -have two running indecies which get updated. -have several if statements comparing the numbers - two positives - two negatives (two positives and two negatives can be done by multiplying and seeing if they result in a positive product) -if the product isnt negative, then compare the positions. ''' #O(n) solution def astroids(arr): x = 0 #this is the max x can go to by default, which is len(arr)-2 because #the comparison includes arr[x+1] arrLen = len(arr)-2 while(x<=arrLen): # print("x: "+ str(x)) # print("comparing: {0} and {1}".format(arr[x],arr[x+1])) #compare arr[x] with arr[x+1] #they are different signs if arr[x]*arr[x+1] < 0: #negative is on right; if negative on left, nothing happens if arr[x] >= 0: #positive is greater in value if abs(arr[x]) > abs(arr[x+1]): #delete it, and decrease the index by 2: #one to compensate the deletion #and one for the extra comparison to "percolate" the negative astroid back del arr[x+1] x -= 2 arrLen -= 1 #negative is greater in value elif abs(arr[x]) < abs(arr[x+1]): del arr[x] x -= 2 arrLen -= 1 #they are equal in value else: del arr[x-1] del arr[x] x -= 2 arrLen -= 2 x += 1 return arr # test1 = [3,5,-8,9,-7] # test2 = [-2,-1,1,2] # test3 = [1,2,3,4,5,6,7,-8] #test4 = [8,1,2,3,4,5,6,7,-8] # test5 = [8,1,-8] #print(astroids(test4))
#a child is running up a staircase with n steps and can hop either 1, 2 or 3 steps at a time. implement a method to count how many possible ways the child can run up the stairs ''' Example: 1 1 Ex: 2 1, 1 2 ex. 3 1, 1, 1 1, 2 2, 1 3 -- 1, 1, 1, 1, 1 1, 2, 1, 1 ''' #total = 0 def numPossibleWays(n): if (n<0): return 0 if (n==0): return 1 else: return numPossibleWays(n-1) + numPossibleWays(n-2) + numPossibleWays(n-3) print(numPossibleWays(3))
''' You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. Given n, find the total number of full staircase rows that can be formed. n is a non-negative integer and fits within the range of a 32-bit signed integer. Example 1: n = 5 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ Because the 3rd row is incomplete, we return 2. Example 2: n = 8 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ ¤ ¤ ¤ Because the 4th row is incomplete, we return 3. ''' def coinStairs(n): temp = n counter = 1 while(temp >= counter): # print("temp "+ str(temp)) # print("counter "+ str(counter)) temp -= counter counter += 1 return counter - 1 print(coinStairs(1)) #1 print(coinStairs(3)) #2 print(coinStairs(4)) #2 print(coinStairs(6)) #3 print(coinStairs(10)) #4
cost = 2 received = int(input("Insert money: ")) if received < cost: print("Insert more money") else: change = received - cost if change > 0: print(f"Change given {change}") else: print("No change needed")
import math import numpy as np def calculate_fuel(amount): return math.floor(amount / 3) -2 sum = 0 file = open("input.txt", "r") for line in file: fuel = calculate_fuel(int(line)) sum = sum + fuel print ("first answer ",sum) fuels = [] file = open("input.txt", "r") for line in file: fuel = calculate_fuel(int(line)) total_fuel = fuel while fuel > 0: fuel = calculate_fuel(fuel) if fuel > 0: total_fuel = total_fuel + fuel fuels.append(total_fuel) print(fuels) print("second answer ", np.sum(fuels))
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: qjk class Solution: def ReverseSentence(self, s): # write code here if s.strip() == "": return s result = s.split() str = '' for item in result[::-1]: str += " " + item return str.lstrip() if __name__ == '__main__': print(Solution().ReverseSentence(""))
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: qjk class Solution: def __init__(self): self.a = [] def Insert(self, num): # write code here self.a.append(num) def GetMedian(self): # write code here self.a.sort() if len(self.a)%2 == 1: return self.a[len(self.a)/2] else: return (self.a[len(self.a)/2-1] + self.a[len(self.a)/2])/2.0
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: qjk # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: def GetNext(self, pNode): # write code here if not pNode: return None if pNode.right: l = pNode.right while l.left: l = l.left return l while pNode.next: temp = pNode.next if temp.left == pNode: return temp pNode = temp
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: qjk # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def Convert(self, pRootOfTree): # write code here if not pRootOfTree: return None self.arr = [] self.midTravel(pRootOfTree) for i, v in enumerate(self.arr[:-1]): v.right = self.arr[i+1] self.arr[i+1].left = v return self.arr[0] def midTravel(self, root): if not root: return self.midTravel(root.left) self.arr.append(root) self.midTravel(root.right)
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: qjk class Solution: def VerifySquenceOfBST(self, sequence): # write code here if len(sequence) == 0: return False root = sequence[-1] # 寻找二叉树小于根节点的数 i = 0 for item in sequence[:-1]: if item > root: break i += 1 for item in sequence[i:-1]: if item < root: return False left = True if i > 1: left = self.VerifySquenceOfBST(sequence[:i]) right = True if i < len(sequence) - 2 and left: right = self.VerifySquenceOfBST(sequence[i:-1]) return left and right
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: qjk ''' 前提是一次只能跳1阶或者2阶的跳法 a.如果两种跳法,一阶或者两阶,那么假定第一次跳的是一阶,那么剩下的就是n-1阶,跳法是f(n-1) b.假定第一次跳的是2阶,那么剩下的是n-2阶,跳法是f(n-2) c.由a and b假设可以得出总跳法f(n)=f(n-1)+f(n-2) d f(1) = 1 f(2)=2 ''' class Solution: def jumpFloor(self, number): # write code here if number <= 0: return 0 f1, f2 = 1, 2 if number == 1: return f1 if number == 2: return f2 for i in range(3, number): f = f1+f2 f1 = f2 f2 = f return f1 + f2
totalSum = 0 f = open("day12input.txt", "r") textDump = f.readline() value = "" for i in range(len(textDump)): if(textDump[i].isdigit() or (textDump[i] == "-"and len(value)==0)): value += textDump[i] elif(len(value) != 0): totalSum += int(value) value = "" print(totalSum)
import re circuit = {} circuit['1'] = 1 circuit['b'] = 3176 operations = [] f = open('day7input.txt', 'r') def assignFunc (operand1, operand2, target): signal1 = circuit.get(operand1) signal2 = None if (signal1 == None): return False circuit[target] = signal1 return True def notFunc (operand1, operand2, target): signal1 = circuit.get(operand1) signal2 = None if (signal1 == None): return False circuit[target] = ~signal1 return True def andFunc (operand1, operand2, target): signal1 = circuit.get(operand1) signal2 = circuit.get(operand2) if (signal1 == None or signal2 == None): return False circuit[target] = signal1 & signal2 return True def orFunc (operand1, operand2, target): signal1 = circuit.get(operand1) signal2 = circuit.get(operand2) if (signal1 == None or signal2 == None): return False circuit[target] = signal1 | signal2 return True def lshiftFunc (operand1, operand2, target): signal1 = circuit.get(operand1) signal2 = int(operand2) if (signal1 == None): return False circuit[target] = signal1 << signal2 return True def rshiftFunc (operand1, operand2, target): signal1 = circuit.get(operand1) signal2 = int(operand2) if (signal1 == None): return False circuit[target] = signal1 >> signal2 return True for line in f: isNot = False isAssignment = False #Parsing parsed = re.match(R'^(\w+) -> (\w{1,2})', line) if (parsed != None): # If the operand consists of numbers, assign the circuit value if (re.match(R'^(\d+) -> (\w{1,2})', line) != None): if(parsed.group(2)!="b"): circuit[parsed.group(2)] = min(int(parsed.group(1)),65535) print("Value Set") continue #Otherwise, assign it later isAssignment = True elif ('NOT' in line): parsed = re.match(R'(NOT) (\w{1,2}) -> (\w{1,2})', line) isNot = True elif ('AND' in line): parsed = re.match(R'(\w{1,2}) (AND) (\w{1,2}) -> (\w{1,2})', line) elif ('OR' in line): parsed = re.match(R'(\w{1,2}) (OR) (\w{1,2}) -> (\w{1,2})', line) elif ('LSHIFT' in line): parsed = re.match(R'(\w{1,2}) (LSHIFT) (\w{1,2}) -> (\w{1,2})', line) elif ('RSHIFT' in line): parsed = re.match(R'(\w{1,2}) (RSHIFT) (\w{1,2}) -> (\w{1,2})', line) #Storage if(isAssignment): #(ASSIGN, Operand1, dud value, target) operations.append(("ASSIGN",parsed.group(1),None,parsed.group(2))) print("Command Added") elif(isNot): # (NOT, Operand1, dud value, target) operations.append((parsed.group(1),parsed.group(2),None,parsed.group(3))) print("Command Added") else: # (Operator, Operand1, Operand2, target) operations.append((parsed.group(2),parsed.group(1),parsed.group(3),parsed.group(4))) print("Command Added ") while(len(operations) > 0): #Iterate over all operations for operation in operations: #Check Operator type print (operation[0]) if (operation[0] == 'NOT'): operatorFunction = notFunc elif (operation[0] == 'ASSIGN'): operatorFunction = assignFunc elif (operation[0] == 'AND'): operatorFunction = andFunc elif (operation[0] == 'OR'): operatorFunction = orFunc elif (operation[0] == 'RSHIFT'): operatorFunction = rshiftFunc elif (operation[0] == 'LSHIFT'): operatorFunction = lshiftFunc else: print ("Something fell through") #Calculate Result/Check if operation can be performed successful = operatorFunction(operation[1],operation[2],operation[3]) print (successful) #Remove successful operation if(successful): operations.remove(operation) print (int(len(operations))) print ("The signal at a is " + str(circuit.get("a")))
#Given a range(l,r), print the maximum value of XOR obtained for a combination of 2 values that are present within the range import itertools import operator def maximizingXor(l, r): l1=[] for i in range(l,r+1): l1.append(i) l2=list(itertools.combinations(l1,2)) m=0 for i in range(len(l2)): if ((operator.xor(l2[i][0],l2[i][1])))>m: m=operator.xor(l2[i][0],l2[i][1]) print(m) maximizingXor(10,15)
def substractProductAndSum(n): n = str(n) length = len(n) product = 1 sumOfNumbers = 0 numberToConvert = "" for i in range (0, length): numberToConvert = n[i] numberToConvert = int(numberToConvert) product *= numberToConvert sumOfNumbers += numberToConvert print (product - sumOfNumbers) substractProductAndSum(234)
def threeSum(self, nums: List[int]) -> List[List[int]]: # returns empty array if not enough elements n = len(nums) if n < 3: return [] # sort the nums list nums.sort() # set of nums for faster lookup numSet = {integer: i for i, integer in enumerate(nums)} result = [] for i in range(n): for j in range(i+1,n): int1 = nums[i] int2 = nums[j] # look for 3sum0 and use index to reject duplicates int3 = -(int1 + int2) if int3 in numSet: index = numSet[int3] if i < index and j < index and [int1,int2,int3] not in result: result.append([int1, int2, int3]) return result
# temperature transfer Temp = input("¶ֵ(F/C):") # ϶ if Temp[-1] in ['C','c']: F = 1.8 * eval(Temp[0:-1]) + 32 print("{:.2f}".format(F)) # 뻪϶ elif Temp[-1] in ['F','f']: C = (eval(Temp[0:-1]) - 32) / 1.8 print("{:.2f}".format(C)) else: print("Error!!") # TemStr = input("input temp(F/C):") # if TemStr[-1] in ['F', 'f']: # C = (eval(TemStr[0:-1]) - 32)/1.8 # print("{:.2f}".format(C)) # elif TemStr[-1] in ['C', 'c']: # F = 1.8*eval(TemStr[0:-1]) + 32 # print("{:.2f}".format(F)) # else: # print("Error!")
# 倒背如流 st = input("请输入一段字符:") i = len(st) - 1 while i >= 0: print(st[i], end = "") i = i - 1
# body mass index v.01 height, weight = eval(input("请输入身高和体重[逗号分隔]:")) bmi = weight / pow(height, 2) print("bmi的值为:{:.2f}".format(bmi)) # 判断 18.5 25 30 who = "" if bmi < 18.5: who = "偏瘦" elif 18.5 <= bmi < 25: who = "标准" elif 25 <= bmi < 30: who = "偏胖" else: who = "肥胖" print("国际标准为:{}".format(who))
#!/usr/bin/python3 print('+---------------------+') print('| Best Friend Maker |') print('| By Ian Pierce |') print('+---------------------+') print('') name = input('What is your name? ') print('') num = 42 print("I'm thinking of a number between 0 and 100. Can you guess it?") guess = input("What is your guess? ") guess = float(guess) while guess != num: if guess < num: print("Sorry, too low. Guess again.") elif guess > num: print("Sorry, too high. Guess again.") guess = input("What is your guess? ") guess = float(guess) print(f"Congratulations {name}! You guessed the number!")
import re text = "Ten 10, Twenty 20, Thirty 30" result = re.split("\D+", text) for element in result: print(element)
import re def capital_words_spaces(str1): return re.sub(r"(\w)([A-Z])", r"\1 \2", str1) print(capital_words_spaces("Python")) print(capital_words_spaces("PythonExercises")) print(capital_words_spaces("PythonExercisesPracticeSolution"))
import re text1 = ' Python Exercises ' print("Original string:",text1) print("Without extra spaces:",re.sub(r'\s+', '',text1))
from card import Card class PyramidBoard(): """ Class for representing the pyramid structure. Class describes the structure of the pyramid and its functional: Create pyramid. Show pyramid. Checking the presence, obtaining, deleting cards. """ def __init__(self): """ Description of attributes deck. """ self.__pyramid = [] self.__size = 0 self.__skeleton = [] def create_pyramid(self, pyramid, size="small"): """ Create pyramid. :param pyramid: pyramid for copy. :param size: size pyramid: big = 9, small = 7 """ sizes = ['small', 'big'] assert size in sizes, 'wrong size' if size == "small": self.__size = 7 elif size == 'big': self.__size = 9 self.__pyramid = [[None] * (i + 1) for i in range(0, self.__size)] for i in range(self.__size): for j in range(i+1): self.__pyramid[i][j] = pyramid[i][j] def card_contains(self, i, j): """ Check the availability of a card. :param i: line in pyramid :param j: column in pyramid :return: 1 if the card is found, 0 if the map location is None, -1 if the coordinates are outside the pyramid """ if i > self.__size - 1 or i < 0 or j > i or j < 0: return -1 if type(self.__pyramid[i][j]) == Card: return 1 else: return 0 def get_card(self, i, j): """ Return card. :param i: line in pyramid :param j: column in pyramid :return: Card if card is found, -1 else """ if self.card_contains(i, j) == 1: return self.__pyramid[i][j] else: return -1 def usability_card(self, i , j): """ Check for openness of the card. :param i: line in pyramid :param j: column in pyramid :return: Card if card is usability, 0 else """ if self.card_contains(i, j) == 1 and ((i < self.__size - 1 and type(self.__pyramid[i + 1][j]) != Card and type(self.__pyramid[i + 1][j + 1]) != Card) or (i == self.__size - 1)): return 1 else: return 0 def delete_card(self, i, j): """ Delete card. :param i: line in pyramid :param j: column in pyramid :return: Card if can remove the card, None else """ if self.usability_card(i, j): card_ = self.__pyramid[i][j] self.__pyramid[i][j] = None return card_ return None def show(self): for i in range(self.__size): for j in range(i+1): if type(self.__pyramid[i][j]) == Card: print('[' + self.__pyramid[i][j].rank + ' ' + self.__pyramid[i][j].suit + ']', end=' ') else: print('[None]', end=' ') print()
T = int(input()) for t in range(1,T+1): word = input() new_word = '' for i in range(-1,-len(word)-1,-1): new_word += word[i] if word == new_word: print(f'#{t} 1') else : print(f'#{t} 0')
import sys sys.stdin = open('s_input.txt') # nC2를 통하여 부분집합을 구한다. # 곱한다 # 단조증가를 확인한다 def bubble_sort(number): for i in range(len(number)-1, 0, -1): for j in range(i): if number[j] > number[j+1]: number[j], number[j+1] = number[j+1], number[j] return number def plus_number(N, numbers): answer = -1 nC2_list = [] # nC2를 실행한다. for i in range(1 << N): check = [] for j in range(N): if i & (1 << j): check.append(numbers[j]) if len(check) == 2: nC2_list.append(check) # 만들어진 숫자 조합에서 단조 증가를 확인한다. for numb in nC2_list: a = numb[0] * numb[1] # 곱한 숫자를 정렬한 결과가 a와 일치하면 그대로 둔다. # string이 들어갔으므로 list를 다시 하나로 합쳐준다. new_a = int(''.join(bubble_sort(list(str(a))))) if a == new_a and new_a >= answer: answer = new_a return answer T = int(input()) for t in range(1, T+1): N = int(input()) numbers = list(map(int, input().split())) print('#{} {}'.format(t, plus_number(N, numbers)))
def check(times): if times[2] < times[0]: return times[0] - times[2] elif times[0] <= times[2] <= times[1]: return 0 else: return -1 T = int(input()) for t in range(1, T+1): times = list(map(int, input().split())) print('#{} {}'.format(t, check(times)))
import sys sys.stdin = open('sample_input.txt') def check(number, special): while number: if number % 10 == special: return True number = number // 10 return False def special_number(numb1, numb2, special): answer = 0 numbers = [] for number in range(numb1, numb2+1): if number == 2 or check(number, special) and number % 2: numbers.append(number) for number in numbers: flag = 1 for i in range(2, number): if number % i == 0: flag = 0 break if flag: answer += 1 print(answer) return answer T = int(input()) for t in range(1, T+1): special, numb1, numb2 = map(int, input().split()) print('#{} {}'.format(t, special_number(numb1, numb2, special)))
N = int(input()) for number in range(1, N+1): clap = 0 answer = str(number) for idx in ['3','6','9']: clap += answer.count(idx) if clap == 0 : answer = str(number) else : answer = '-' * clap print(answer, end = ' ')
import os import string def isValidDirectory(argument, path): '''Checks whether the inputted directory exists or not.''' if not os.path.isdir(path): raise ValueError(f'Folder path for {argument} does not exist.') def isIntOverZero(argument, someVariable): '''Checks if variable is of type int and is greater than zero.''' if not isinstance(someVariable, int) or someVariable < 0: raise ValueError(f"Argument {argument} must be an integer greater than zero.") def properStringSyntax(argument, inputtedString=""): '''This exists to verify various inputs are using allowed characters. One such character that isn't allowed is '\\', as that character is what the ASCII part of the stream header uses to divide attributes. ''' acceptableChars = string.ascii_letters + string.digits + string.punctuation.replace("\\", "") + " " if inputtedString: for letter in inputtedString: if letter not in acceptableChars: raise ValueError(f"Only ASCII characters excluding '\\' are allowed in {argument}.") def isBool(argument, variable): '''Will raise error if argument isn't type bool. Used in verifying arguments for read() and write()''' if not isinstance(variable, bool): raise ValueError(f'Argument {argument} must be type boolean.')
import random from art import logo from replit import clear print(logo) n=0 from game_data import data length= len(data) item2= random.randint(0, length-1) loop=True while loop: item1=item2 item2= random.randint(0, length-1) if item1==item2: continue first=data[item1] name= first["name"] profession= first["description"] country= first["country"] print(f"Compare A: {name}, a {profession}, from {country}.") from art import vs print(vs) second=data[item2] name= second["name"] profession= second["description"] country= second["country"] print(f"Against B: {name}, a {profession}, from {country}.") answer=input("Who has more followers? A or B? ").capitalize() if answer=="A": if first["follower_count"]> second["follower_count"]: n=n+1 clear() print(logo) print(f"You are right. Your current score is {n}.") else: loop=False if answer=="B": if first["follower_count"]< second["follower_count"]: n=n+1 clear() print(logo) print(f"You are right. Your current score is {n}.") else: loop=False clear() print(logo) print(f"Sorry that's wrong. Your total score is {n}.")
def fibonacci(n): result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a+b return result sequence = fibonacci(4000000) seq2 = [] for e in sequence: if e % 2 == 0: seq2.append(e) print sum(seq2) print sequence print seq2
from itertools import combinations from random import randint class Lotto: """ A Lotto class based on Steven Skiena's Algorithm Design Manual (Chapter 1) """ def __init__(self, n=15, k=6, j=4, l=3): self._n = n self._k = k # slots on ticket self._j = j # number of psychically-promised correct numbers in n self._l = l self._set = self._generate_numbers(); def numbers(self): return self._set def _generate_numbers(self): s = set() for i in range(1, self._n + 1): s.add(i) return s def possible_winning_number_combinations(self): s = set() # psychic promises at least j items are correct within n: # generate all possible winning combinations (n choose j). for combination in combinations(self._set, self._j): # use frozenset because it is hashable and can be placed in a set. # use set/frozenset because we care about set equality # not tuple equality. # also, we can use a frozenset as a dictionary key. s.add(frozenset(combination)) return s def possibilities_fully_covered(self, ticket_set): # after generating hashmap of all possible winning combinations (pwc), # set each possible winning combination as False # (False means this pwc is not 'covered' by any ticket) pwc_covered = {} for combination in self.possible_winning_number_combinations(): pwc_covered[combination] = False # for each ticket in set of tickets presented to us for ticket in ticket_set: # generate all pwcs covered by this ticket covered_pwcs = self._generate_covered_pwcs(ticket) # mark each covered possibility in hashmap as True for i in covered_pwcs: pwc_covered[i] = True # loop through to check if any of the pwcs is not covered for key,value in pwc_covered.items(): if (value == False): return False return True # assume l items within ticket's k slots is a winning combination def _generate_covered_pwcs(self, ticket): covered_pwcs = set() # each ticket has k slots, but only l are needed to 'win' # generate all winning combinations involving l items (k choose l) for l_combination in combinations(ticket, self._l): # within each l_combination, the remaining slots (k - l) can be filled # with any unused number and that is still a valid pwc pwc = frozenset(l_combination) # for set difference # remove pwc from n unused_numbers = self._set - pwc remaining_combinations = combinations(unused_numbers, self._k - self._l) # generate all winning pwc for this combination of l # by combining l combination with every remaining combinations for remaining_combination in remaining_combinations: s = set(l_combination).union(set(remaining_combination)) covered_pwcs.add(frozenset(s)) return covered_pwcs def generate_minimum_tickets_needed(self): # use a randomised algorithm (suggested by book) to generate tickets # until all possible winnning combinations are covered tickets = set() possibilities = list(combinations(self._set, self._k)) while not (self.possibilities_fully_covered(tickets)): random_possibility = frozenset(possibilities[randint(0, len(possibilities) - 1)]) tickets.add(random_possibility) return tickets
# Example of polynomial regression on synthetic dataset import numpy as np import pandas as pd import seaborn as sn import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.linear_model import Ridge from sklearn.preprocessing import MinMaxScaler from sklearn.linear_model import Lasso from sklearn.preprocessing import PolynomialFeatures # synthetic dataset for more complex regression from sklearn.datasets import make_friedman1 plt.figure() plt.title('Complex regression problem with one input variable') X_F1, y_F1 = make_friedman1(n_samples = 100, n_features = 7, random_state=0) plt.scatter(X_F1[:, 2], y_F1, marker= 'o', s=50) plt.show() # make train test split X_train, X_test, y_train, y_test = train_test_split(X_F1, y_F1, random_state = 0) # standard linear regression linreg = LinearRegression().fit(X_train, y_train) print('linear model coeff (w): {}'.format(linreg.coef_)) print('linear model intercept (b): {:.3f}'.format(linreg.intercept_)) print('R-squared score (training): {:.3f}'.format(linreg.score(X_train, y_train))) print('R-squared score (test): {:.3f}'.format(linreg.score(X_test, y_test))) # add polynomial features to dataset and do polynomial regression print('\nNow we transform the original input data to add\n\ polynomial features up to degree 2 (quadratic)\n') poly = PolynomialFeatures(degree=2) X_F1_poly = poly.fit_transform(X_F1) # do polynomial regression X_train, X_test, y_train, y_test = train_test_split(X_F1_poly, y_F1, random_state = 0) linreg = LinearRegression().fit(X_train, y_train) print('(poly deg 2) linear model coeff (w):\n{}'.format(linreg.coef_)) print('(poly deg 2) linear model intercept (b): {:.3f}'.format(linreg.intercept_)) print('(poly deg 2) R-squared score (training): {:.3f}'.format(linreg.score(X_train, y_train))) print('(poly deg 2) R-squared score (test): {:.3f}\n'.format(linreg.score(X_test, y_test))) # polynomial regression with ridge regularization print('\nAddition of many polynomial features often leads to\n\ overfitting, so we often use polynomial features in combination\n\ with regression that has a regularization penalty, like ridge\n\ regression.\n') X_train, X_test, y_train, y_test = train_test_split(X_F1_poly, y_F1, random_state = 0) linreg = Ridge().fit(X_train, y_train) print('(poly deg 2 + ridge) linear model coeff (w):\n{}'.format(linreg.coef_)) print('(poly deg 2 + ridge) linear model intercept (b): {:.3f}'.format(linreg.intercept_)) print('(poly deg 2 + ridge) R-squared score (training): {:.3f}'.format(linreg.score(X_train, y_train))) print('(poly deg 2 + ridge) R-squared score (test): {:.3f}'.format(linreg.score(X_test, y_test)))
# Binary logistic regression with fruits dataset (apple vs others) import numpy as np import pandas as pd import seaborn as sn import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression # prepare fruits dataset using only 2 features fruits = pd.read_table('readonly/fruit_data_with_colors.txt') feature_names_fruits = ['height', 'width', 'mass', 'color_score'] X_fruits = fruits[feature_names_fruits] y_fruits = fruits['fruit_label'] target_names_fruits = ['apple', 'mandarin', 'orange', 'lemon'] X_fruits_2d = fruits[['height', 'width']] y_fruits_2d = fruits['fruit_label'] fig, subaxes = plt.subplots(1, 1, figsize=(7, 5)) y_fruits_apple = y_fruits_2d == 1 # make into a binary problem: apples vs everything else X_train, X_test, y_train, y_test = (train_test_split(X_fruits_2d.as_matrix(), y_fruits_apple.as_matrix(), random_state = 0)) # logistic regression clf = LogisticRegression(C=100).fit(X_train, y_train) # use model to predict new samples h = 6 w = 8 print('A fruit with height {} and width {} is predicted to be: {}'.format(h,w, ['not an apple', 'an apple'][clf.predict([[h,w]])[0]])) h = 10 w = 7 print('A fruit with height {} and width {} is predicted to be: {}'.format(h,w, ['not an apple', 'an apple'][clf.predict([[h,w]])[0]])) subaxes.set_xlabel('height') subaxes.set_ylabel('width') # check accruracy of model on train and test sets print('Accuracy of Logistic regression classifier on training set: {:.2f}'.format(clf.score(X_train, y_train))) print('Accuracy of Logistic regression classifier on test set: {:.2f}'.format(clf.score(X_test, y_test))) # check influence of C parameter for this_C in [0.1, 1, 100]: clf = LogisticRegression(C=this_C).fit(X_train, y_train)
a= int(input()) b= int(input()) c= int(input()) if(a==1 and c==1): print 2+b elif(a==1): print (a+b)*c elif(b==1): print max((a+b)*c,a*(b+c)) elif(c==1): print a*(b+c) else: print a*b*c
# 1. Написати скрипт, який з двох введених чисел визначить, яке з них більше, # а яке менше. def int_is_bigg_or_small(a: int, b: int): return f'{a} is bigger than {b}' if a > b else f'{a} is smaller than {b}' if __name__ == '__main__': assert int_is_bigg_or_small(2, 4) == '2 is smaller than 4' assert int_is_bigg_or_small(12, 5) == '12 is bigger than 5' print('Tests is passed') # # # 2. Написати скрипт, який перевірить чи введене число парне чи непарне # # і вивести відповідне повідомлення. def pair_or_no(text): text = int(input('enter int: ')) return f'{text} is pair' if text % 2 == 0 else f'{text} is not pair' if __name__ == '__main__': assert pair_or_no(2) == '2 is pair' assert pair_or_no(3) == '3 is not pair' print('Tests is passed') # 3. Написати скрипт, який обчислить факторіал введеного числа. number = int(input('enter int:')) a = int(number) while a !=1: number *=a-1 a -=1 print(number) # 3.1 Написати скрипт, який обчислить факторіал введеного числа. chyslo = input('enter factorial :') t = 1 for i in range(1, int(chyslo)+1): t *= i print(t) # 1. Роздрукувати всі парні числа менші 100 використовуючи цикл while a = 1 while a < 100: if a % 2 == 0: print(a) a = a + 1 # 1.1 Роздрукувати всі парні числа менші 100 з використанням циклу for for i in range(0,101,2): print(i) # 2. Роздрукувати всі непарні числа менші 100. (написати два варіанти коду: # один використовуючи оператор continue, а інший без цього оператора). a = 0 while a < 100: a +=1 if a % 2 == 0: continue else: print(a) # 2.1 without continue for i in range(1,100,2): print(i) # 3. Перевірити чи список містить непарні числа. spusok = [12,3,12,3,4] only_odd =[num for num in spusok if num %2 == 0] print(only_odd) # list of numbers list1 = [10, 21, 4, 45, 66, 93] num = 0 while num < len(list1): if num % 2 != 0: print(list1[num], end = " ") num += 1 # 4. Створити список, який містить елементи цілочисельного типу, потім за # допомогою циклу перебору змінити тип даних елементів на числа з плаваючою # крапкою. (Підказка: використати вбудовану функцію float ()). list2 = list(range(0,20)) for x in list2: list2[x] = float(list2[x]) print(list2) # 5. Вивести числа Фібоначі включно до введеного числа n, використовуючи # цикли. (Послідовність чисел Фібоначі 0, 1, 1, 2, 3, 5, 8, 13 і т.д.) number = int(input("Enter the int for generated sequence of Fibonacci:")) fibo = [0, 1] for i in range(number-1): fibo[i+1] = fibo[i-1] + fibo[i] fibo.append(fibo[i+1]) fibo.remove(fibo[i+1]) print(fibo) # 6. Створити список, що складається з чотирьох елементів типу string. Потім, # за допомогою циклу for, вивести елементи по черзі на екран. spysok = ["Hello,", "World!", "Whats", "up?"] for i in spysok: print(i) # 7. Знайти прості числа від 10 до 30, а всі решта чисел представити у вигляді добутку чисел # (наприклад 10 equals 2 * 5 # 11 is a prime number # 12 equals 2 * 6 # 13 is a prime number # 14 equals 2 * 7 # ………………….) new_list = list(range(0, 50)) # for i in new_list: if 10 <= i <= 30: if i % 2 == 0: print(f'{i} equals 2 * {i // 2}') else: print(f'{i} is a prime number') else: print(f'{i} it number goes beyond') # 5. Перший випадок. # Написати програму, яка буде зчитувати числа поки не зустріне від’ємне число. # При появі від’ємного числа програма зупиняється (якщо зустрічається 0 програма теж зупиняється). create_list = [1,23,43,-2,22,2,-43] for i in create_list: if i <= 0: break else: print(i) # 4. Напишіть скрипт, який перевіряє логін, який вводить користувач. # Якщо логін вірний (First), то привітайте користувача. # Якщо ні, то виведіть повідомлення про помилку. # (використайте цикл while) login = input('Enter login:') while login != 'First': print('Login is failed') break else: print('Hello, user')
# try: # a = int(input('press int: ')) # if a % 2 == 0 : # print(f'{a} it int is odd') # elif a % 2 != 0: # print(f'{a} is not even') # except ValueError: # print('is type uncorrected, print pls integer') # 2. Напишіть програму, яка пропонує користувачу ввести свій вік, після чого виводить повідомлення про те чи вік є # парним чи непарним числом. Необхідно передбачити можливість введення від’ємного числа, в цьому випадку згенерувати # власну виняткову ситуацію. Головний код має викликати функцію, яка обробляє введену інформацію. # def enterage(age): # age = int(input('press age: ')) # if age % 2 < 0: # print(f'{age} this age is odd') # else: # print(f'{age} this age is even') # # # try: # age = int(input('Enter you age: ')) # enterage(age) # # except ValueError: # print('Print only positive integers') # except: # print('something is wrong') # 3. Напишіть програму для обчислення частки двох чисел, які вводяться користувачем послідовно через кому, # передбачити випадок ділення на нуль, випадки синтаксичних помилок та випадки інших виняткових ситуацій. # Використати блоки else та finaly. # try: # num1, num2 = eval(input("Enter two numbers, separated by a comma : ")) # result = num1 / num2 # print("Result is", result) # # except ZeroDivisionError: # print("Division by zero is error !!") # # except SyntaxError: # print("Comma is missing. Enter numbers separated by comma like this 1, 2") # # 65866hgjh75785 # except: # print("Wrong input") # # else: # print("No exceptions") # # finally: # print("This will execute no matter what") # 4. Написати програму, яка аналізує введене число та в залежності від числа видає день тижня, # який відповідає цьому числу (1 це Понеділок, 2 це Вівторок і т.д.) . # Врахувати випадки введення чисел від 8 і більше, а також випадки введення не числових даних. class OutOfDayIndex(Exception): def __init__(self, data): self.data = data def __str__(self): return self.data class NotNegativeDays(Exception): def __init__(self, data): self.data = data def __str__(self): return repr(self.data) try: n = int(input("Input an integer between 1 and 7: ")) days_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] if n in range(1, 8): print(f'Today is {days_of_week[n-1]}') if n > 7: raise OutOfDayIndex("There are only seven days!") if n < 1: raise NotNegativeDays("Day index cannot be negative or equal to zero!") except OutOfDayIndex as e: print(e.data) except NotNegativeDays as e: print(e.data) except ValueError: print("Value Error") finally: print("End of the program.")
# Consider an array of sheep where some sheep may be missing from their place. # We need a function that counts the number of sheep present in the array (true means present). array1 = [True, True, True, False, True, True, True, True, True, False, True, False, True, False, False, True, True, True, True, True, False, False, True, True] def count_sheeps(arrayOfSheeps): a = int(0) for x in (arrayOfSheeps): if x == 1: a += 1 return a if __name__ == '__main__': assert count_sheeps(array1) == 17 print("Well job!")
# We will here attempt to predict continuous values for an attribute using regression techniques such as ordinary least squares regression model from helper import * from sklearn.model_selection import train_test_split import sklearn.linear_model as lm import sklearn.neural_network as nn import numpy as np import matplotlib.pyplot as plt from sklearn import model_selection # Load marketing data to get attributes names, a pandas dataframe object and a numpy array attNames, marketingData_pd, marketingData_np = loadMarketingData() # Encode categorical attributes as integer for ordinal and 1-of-k for nominal ordinals = {"education": { "illiterate": 1, "basic.4y": 2, "basic.6y": 3, "basic.9y": 4, "high.school": 5, "professional.course": 6, "university.degree": 7, "unknown": "WeightedAverage" } } nominals = [ "job", "marital", "default", "housing", "loan", "contact", "month", "day_of_week", "poutcome", "y" ] attNamesEncoded, marketingDataEncoded_pd, marketingDataEncoded_np = encodeCategorical(marketingData_pd, ordinals=ordinals, nominals=nominals) # Select attribute to predict (y) attToPredictName = "education" attToPredictId = attNamesEncoded.index(attToPredictName) # Select attributes for the model (X) (all except y for now) attIdsForModel = list(range(len(attNamesEncoded))) attIdsForModel.remove(attToPredictId) # Standardize the data N, _ = marketingDataEncoded_np.shape means = marketingDataEncoded_np.mean(axis=0) # get mean of each column marketingDataEncoded_np_std = marketingDataEncoded_np - np.ones((N,1))*means # Get matrix X by substracting the mean from each value in the marketingdata marketingDataEncoded_np_std = marketingDataEncoded_np_std*(1/np.std(marketingDataEncoded_np_std,0)) #Deviding by standard deviation to normalize # Make X and y arrays X = marketingDataEncoded_np_std[:,attIdsForModel] y = marketingDataEncoded_np_std[:,attToPredictId] # Split dataset into training and test set #testSize = 0.1 # 10% of the dataset will be taken out at random for testing only X, _, y, _ = train_test_split(X, y, test_size=0.7, random_state=42) lamdas = np.logspace(-5, 3, num=20) # 2-level crossvalidation K = 5 CV_outer = model_selection.KFold(K, shuffle=True, random_state = 42) k=0 for train_index, test_index in CV_outer.split(X,y): print('\nCrossvalidation fold: {0}/{1}'.format(k + 1, K)) k += 1 # extract training and test set for current CV fold X_train = X[train_index] y_train = y[train_index] X_test = X[test_index] y_test = y[test_index] N_par, M_par = X_train.shape CV_inner = model_selection.KFold(K, shuffle=True, random_state = 42) j=0 for train_inner, test_inner in CV_inner.split(X_train, y_train): # extract training and test set for current CV fold print('\nInner Crossvalidation fold: {0}/{1}'.format(j + 1, K)) X_train_in = X_train[train_inner] y_train_in = y_train[train_inner] X_test_in = X_train[test_inner] y_test_in = y_train[test_inner] j += 1 # Train linear model train_errors = list() test_errors = list() for lamda in lamdas: #print(f"Fitting for lamda={lamda}") regmodel = lm.ElasticNet(alpha=lamda, max_iter=1000, l1_ratio=0.5) regmodel = regmodel.fit(X_train, y_train) train_errors.append(regmodel.score(X_train, y_train)) test_errors.append(regmodel.score(X_test, y_test)) i_alpha_optim = np.argmax(test_errors) alpha_optim = lamdas[i_alpha_optim] bestscore = test_errors[i_alpha_optim] print(f"Best lamda: {alpha_optim}") print(f"Best score: {bestscore}") # Train ANN model hs = [1, 2, 3, 4, 5] train_errors = list() test_errors = list() for h in hs: #print(f"Fitting for h={h}") annmodel = nn.MLPRegressor(hidden_layer_sizes=tuple([h])) annmodel = annmodel.fit(X_train, y_train) train_errors.append(annmodel.score(X_train, y_train)) test_errors.append(annmodel.score(X_test, y_test)) i_h_optim = np.argmax(test_errors) h_optim = hs[i_h_optim] bestscore = test_errors[i_h_optim] print(f"Best h: {h_optim}") print(f"Best score: {bestscore}")
# # Gradient descent with 1D data i.e. 2 features # import numpy as np import matplotlib.pyplot as plt # Load data file filenameIn = 'OneFeature.csv' data = np.loadtxt(filenameIn, delimiter=',') print('Shape of data matrix', data.shape) # Extract x and y vectors from data x = data[:,0] y = data[:,1] # Reshape to have them in column vector style x = x.reshape(-1,1) y = y.reshape(-1,1) print('Shape of target vector', y.shape) # Construct X matrix onesVect = np.ones((x.shape[0],1), dtype=int) X = np.concatenate((onesVect, x), axis=1) print('Shape of X matrix', X.shape) # Initialize theta vector theta = np.zeros((2,1)) print('Shape of theta vector', theta.shape) # define descent rate and number of iterations alpha = 0.01 nIter = 1500 m = y.size #Gradient descent loop jTheta = [] for i in range(1, nIter): t1 = X.dot(theta) t2 = np.subtract(t1, y) XT = np.transpose(X) t3 = XT.dot(t2) temp = theta - alpha / m * t3 theta = temp jThetaLoop = 0.5 / m * np.transpose(t2).dot(t2) jTheta.append(jThetaLoop[0,0]) print('theta_0 = ' + str(theta[0,0])) print('theta_1 = ' + str(theta[1,0])) plt.plot(jTheta, marker='.') plt.show()
''' Antonio Pelayo April 2, 2020 Problem: 189 Rotate Array Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2: Input: [-1,-100,3,99] and k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. Could you do it in-place with O(1) extra space? ''' def rotate(nums, k): # Array with same length as nums rotated = [0 for i in range(len(nums))] # Set numbers in rotated array for i in range(len(nums)): rotated[(i + k) % len(nums)] = nums[i] # Assign numbers back to nums array for i in range(len(nums)): nums[i] = rotated[i] return nums a = {'nums': [1, 2, 3, 4, 5, 6, 7], 'k': 3} b = {'nums': [-1, -100, 3, 99], 'k': 2} print(f"{a['nums']} rotated {a['k']} times is {rotate(a['nums'], a['k'])}") print(f"{b['nums']} rotated {b['k']} times is {rotate(b['nums'], b['k'])}")
''' Antonio Pelayo March 8, 2020 Problem 7. Reverse Integer Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. ''' def reverse(x): result = '' sign = 1 # -1 if negative # Check if negative if x < 0: sign = -1 result = str(x)[1:] # String of x without negative sign else: result = str(x) result = sign * int(result[::-1]) # Reverse and turn to int # Handle overflow case if result > (2 ** 31) or result < -(2 ** 31): return 0 return result a = 123 b = -123 c = 120 print(reverse(a)) print(reverse(b)) print(reverse(c)) print(reverse(1534236469))
''' Antonio Pelayo March 15, 2020 Problem: Contains Duplicate Difficulty: Easy Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. Example 1: Input: [1,2,3,1] Output: true Example 2: Input: [1,2,3,4] Output: false Example 3: Input: [1,1,1,3,3,4,3,2,4,2] Output: true ''' def containsDuplicate(nums): # Edge cases if len(nums) < 2: return False nums = sorted(nums) # Numbers will be next to eachother if duplicate for i in range(len(nums) - 1): if nums[i] == nums[i+1]: return True # No duplicates found return False a = [1, 2, 3, 1] b = [1, 2, 3, 4] c = [1, 1, 1, 3, 3, 5, 3, 2, 4, 2] print(containsDuplicate(a)) print(containsDuplicate(b)) print(containsDuplicate(c))
#!/usr/bin/python # -*- coding: utf-8 -*- import sys, os,re,time def countWords(texto): tiempo=time.time() palabras=0 for linea in texto.splitlines(): linea= re.sub(r'[-,;:?!.¿¡\'\(\)\[\]\"|*+-_<>#@&^%$]'," ",linea) for p in linea.split(): palabras+=1 print ("\nCountWords: Palabras obtenidas: "+str(palabras)+"\n\ttiempo: "+str(time.time()-tiempo)) def wordCount(texto): tiempo=time.time() palabras={} for linea in texto.splitlines(): linea= re.sub(r'[-,;:?!.¿¡\'\(\)\[\]\"|*+-_<>#@&^%$]'," ",linea) for p in linea.split(): p=p.lower() if p not in palabras: palabras[p]=1 else: palabras[p]=palabras[p]+1 print palabras print ("\nWordCount: Palabras obtenidas: "+str(palabras)+"\n\ttiempo: "+str(time.time()-tiempo)) if __name__ == "__main__": file=open(sys.argv[1],'r') texto=file.read() countWords(texto) wordCount(texto)
# %% # Question 1: # Traverse a nested list and print all elements. names = [ "Adam", [ "Bob", [ "Chet", "Cat", ], "Barb", "Bert", ], "Alex", ["Bea", "Bill"], "Ann", ] # %% # Question 2: # FInd the sum of all the elements of a nested list. numbers = [1, 2, [3, 4], [5, 6]]
# WAF to generate a random alphabetical string and alphabetical string of a # fixed length. import random import string LETTERS = string.ascii_letters + string.digits def password_generator(length): my_string = "" for _ in range(0, length): n = random.randrange(0, len(LETTERS)) nth_char = LETTERS[n] my_string += nth_char return my_string def test_function(): assert password_generator(4) != password_generator(4) assert len(password_generator(4)) == 4 assert password_generator(10) != password_generator(10) assert len(password_generator(10)) == 10
import random from colorama import Fore, init import utils init(autoreset=True) words = utils.data to_guess = utils.Word(random.choice(words)) spaces = utils.Guess(to_guess) number_of_guesses = 0 total_guesses = int(input('How many guesses would you like to make? ')) letters_guessed = set() while True: print(f"\n{spaces}") if spaces.completed(): print( f"{Fore.GREEN}Congratulations, you guessed the word correctly! " f"{Fore.GREEN}The word was {to_guess.data}." ) break elif total_guesses == number_of_guesses: print(f"{Fore.RED}You can guess {total_guesses} times. Game Over!") break print(f"{Fore.BLUE}Enter your guess: ", end='') char = input().lower() if len(char) != 1: print(f"{Fore.RED}You can guess only one letter at a time!") continue elif char not in letters_guessed: letters_guessed.add(char) else: print(f"{Fore.RED}You have already tried this letter!") continue number_of_guesses += 1 if not spaces.fill_guess(char): print(f"{Fore.RED}Your guess was incorrect!") print(f"{Fore.YELLOW}You have attempted {number_of_guesses} times")
# coding=utf-8 ''' Problem 25 - 1000-digit Fibonacci Number The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? ''' from functools import partial from lib.helpers.runtime import print_answer_and_elapsed_time def fibonacci_number_of_size(digits): f1 = 1 f2 = 1 index = 2 while len(str(f2)) < digits: f1, f2 = f2, f1 + f2 index += 1 return index answer = partial(fibonacci_number_of_size, digits=1000) if __name__ == '__main__': print_answer_and_elapsed_time(answer)
''' Problem 41 - Pandigital Prime We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. What is the largest n-digit pandigital prime that exists? ''' from lib.helpers.runtime import print_answer_and_elapsed_time from lib.helpers.numbers import sieve_of_eratosthenes def largest_pandigital_prime(): maximum = 7654321 # 8- and 9-digit pandigital primes are divisible by 3 primes = sieve_of_eratosthenes(maximum) for number in sorted(primes, reverse=True): number_string = ''.join(sorted(str(number))) number_length = len(number_string) if ''.join(sorted(str(number))) == '1234567'[:number_length]: return number answer = largest_pandigital_prime if __name__ == '__main__': print_answer_and_elapsed_time(answer)
# coding=utf-8 ''' Problem 46 - Goldbach's Other Conjecture It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×1**2 15 = 7 + 2×2**2 21 = 3 + 2×3**2 25 = 7 + 2×3**2 27 = 19 + 2×2**2 33 = 31 + 2×1**2 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? ''' from math import sqrt from lib.helpers.numbers import is_prime from lib.helpers.runtime import print_answer_and_elapsed_time def smallest_non_goldbach_number(): primes = [2] n = 1 while True: n += 2 if is_prime(n): primes.append(n) else: is_goldbach = False for p in primes: if sqrt((n - p) / 2).is_integer(): is_goldbach = True break if not is_goldbach: return n answer = smallest_non_goldbach_number if __name__ == '__main__': print_answer_and_elapsed_time(answer)
''' Problem 34 - Digit Factorials 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not included. ''' from math import factorial from lib.helpers.runtime import print_answer_and_elapsed_time def sum_digit_factorial(number): return sum([factorial(int(digit)) for digit in str(number)]) def digit_factorials(): # 10000000 is an analytical upper bound since 9999999 > 7 * 9! maximum = 50000 return [n for n in range(10, maximum) if sum_digit_factorial(n) == n] def answer(): return sum(digit_factorials()) if __name__ == '__main__': print_answer_and_elapsed_time(answer)
''' Problem 3 - Largest Prime Factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? ''' from functools import partial from lib.helpers.runtime import print_answer_and_elapsed_time from lib.helpers.numbers import prime_divisors def largest_prime_factor(number): return max(prime_divisors(number)) answer = partial(largest_prime_factor, number=600851475143) if __name__ == '__main__': print_answer_and_elapsed_time(answer)
''' Problem 44 - Pentagon Numbers Pentagonal numbers are generated by the formula, P_n=n(3n−1)/2. The first ten pentagonal numbers are: 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... It can be seen that P_4 + P_7 = 22 + 70 = 92 = P_8. However, their difference, 70 − 22 = 48, is not pentagonal. Find the pair of pentagonal numbers, P_j and P_k, for which their sum and difference are pentagonal and D = |P_k − P_j| is minimised; what is the value of D? ''' from math import sqrt from lib.helpers.numbers import is_pentagonal from lib.helpers.runtime import print_answer_and_elapsed_time def pentagonal_number_pair(): n = 0 pentagonal_numbers = [] while True: n += 1 current_number = int(n * (3 * n - 1) / 2) for number in pentagonal_numbers: total = number + current_number difference = current_number - number if is_pentagonal(total) and is_pentagonal(difference): return number, current_number pentagonal_numbers.append(current_number) def answer(): pair = pentagonal_number_pair() return abs(pair[0] - pair[1]) if __name__ == '__main__': print_answer_and_elapsed_time(answer)
''' Problem 54 - Poker Hands In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way: High Card: Highest value card. One Pair: Two cards of the same value. Two Pairs: Two different pairs. Three of a Kind: Three cards of the same value. Straight: All cards are consecutive values. Flush: All cards of the same suit. Full House: Three of a kind and a pair. Four of a Kind: Four cards of the same value. Straight Flush: All cards are consecutive values of same suit. Royal Flush: Ten, Jack, Queen, King, Ace, in same suit. The cards are valued in the order: 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace. If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives (see example 1 below). But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared (see example 4 below); if the highest cards tie then the next highest cards are compared, and so on. The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Player 2's cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player's hand is in no specific order, and in each hand there is a clear winner. How many hands does Player 1 win? ''' from enum import IntEnum from itertools import groupby from lib.config import assets_path from lib.helpers.runtime import print_answer_and_elapsed_time class Card: def __init__(self, card_string): self.value = card_string[0] self.suit = card_string[1] def __repr__(self): return 'Card(value=%r, suit=%r)' % (self.value, self.suit) def __sub__(self, other): return self.rank() - other.rank() def __lt__(self, other): return self.rank() < other.rank() def rank(self): try: return int(self.value) except: if self.value == 'T': return 10 if self.value == 'J': return 11 if self.value == 'Q': return 12 if self.value == 'K': return 13 if self.value == 'A': return 14 class Hands(IntEnum): HIGH_CARD = 0 ONE_PAIR = 1 TWO_PAIR = 2 THREE_OF_A_KIND = 3 STRAIGHT = 4 FLUSH = 5 FULL_HOUSE = 6 FOUR_OF_A_KIND = 7 STRAIGHT_FLUSH = 8 class Hand: def __init__(self, cards): self.cards = sorted( [Card(card) for card in cards][:5], key=lambda card: card.rank(), reverse=True, ) def __repr__(self): return 'Hand(cards=%r)' % (self.cards) def __lt__(self, other): self_hand = self.rank() other_hand = other.rank() if self_hand[0] < other_hand[0]: return True if other_hand[0] < self_hand[0]: return False for (self_card, other_card) in zip(self_hand[1], other_hand[1]): if self_card < other_card: return True if other_card < self_card: return False return False def is_wheel(self): return self.cards[0].value == 'A' \ and self.cards[1].value == '5' \ and self.cards[2].value == '4' \ and self.cards[3].value == '3' \ and self.cards[4].value == '2' def rank(self): sets = sorted( [(rank, len(list(grouper))) for (rank, grouper) in groupby(self.cards, key=lambda card: card.rank())], key=lambda set: (set[1], set[0]), reverse=True, ) tie_breakers = [value for (value, _) in sets] sets_length = len(sets) if sets_length == 4: return (Hands.ONE_PAIR, tie_breakers) if sets_length == 3: if sets[0][1] == 2: return (Hands.TWO_PAIR, tie_breakers) if sets[0][1] == 3: return (Hands.THREE_OF_A_KIND, tie_breakers) if sets_length == 2: if sets[0][1] == 3: return (Hands.FULL_HOUSE, tie_breakers) if sets[0][1] == 4: return (Hands.FOUR_OF_A_KIND, tie_breakers) straight = self.is_wheel() or \ all([i == 0 or self.cards[i - 1] - card == 1 for (i, card) in enumerate(self.cards)]) flush = len(list(groupby(self.cards, key=lambda card: card.suit))) == 1 if flush and straight: return (Hands.STRAIGHT_FLUSH, tie_breakers) if flush and not straight: return (Hands.FLUSH, tie_breakers) if straight: return (Hands.STRAIGHT, tie_breakers) return (Hands.HIGH_CARD, tie_breakers) def answer(): with open('%s/problem54/poker.txt' % assets_path) as file: def parse(line): cards = line.split(' ') return (Hand(cards[:5]), Hand(cards[5:])) return sum([1 for (hand1, hand2) in [parse(line) for line in file] if hand1 > hand2]) if __name__ == '__main__': print_answer_and_elapsed_time(answer)
def is_palindrome(string): if (len(string) < 2): return True if (not string.endswith(string[0])): return False return is_palindrome(string[1:-1])
# Exercise 6, Learn Python the Hard Way # define a variable types_of_people = 10 # define var x with a formatted string x = f"There are {types_of_people} types of people." # define variable binary = "binary" # define variable do_not = "don't" # define var y with formatted string y = f"Those who know {binary} and those who {do_not}." #print var x and y print(x) print(y) #use fstring to print x and y. Same as before, but string in string print(f"I said: {x}") print(f"I also said: '{y}'") #define variable hilarious = False # define variable with input joke_evaluation = "Isn't that joke so funny?! {}" #print using .format and variable print(joke_evaluation.format(hilarious)) #define variables w = "This is the left side of..." e = "a string with a right side." #concatenate strings print(w + e)
""" Class representing the pen """ from vectdraw.draw.colour import Colour class Pen(object): __kDefaultColour = Colour() # determines the position of pen. False is Up, True is Down __isDown = False # Current colour of the pen (red, green, blue, alpha) __colour = __kDefaultColour def ChangeColour(self, rgba): if isinstance(rgba, Colour): self.__colour = rgba else: raise TypeError( "Expected board.Colour instance" "Received {}".format(str(rgba))) def lift(self): """ sets the pen position to up """ self.__isDown = False def colour(self): return self.__colour def down(self): """ sets the pen position to down """ self.__isDown = True def reset(self): self.lift() self.ChangeColour(self.__kDefaultColour) def IsPenDown(self): return self.__isDown
""" Class for rgba colour representation """ class Colour(object): red = 0 green = 0 blue = 0 alpha = 255 def __init__(self, rgba=None): """ Returns a colour instance. If nothing is passsed, the default is 0,0, 0, 255 for red, green, blue and alpha respectively :param rgba: a tuple containing numbers between 0-255 for red, green, blue and alpha respectively """ if rgba: self.SetColour(rgba) def SetColour(self, rgba): if not isinstance(rgba, tuple) and len(rgba) != 4: raise TypeError( "Unexpected type given. Expected tuple of size 4 " "(int, int, int, int), received {}".format(type(rgba))) for c in rgba: if c > 255 or c < 0: raise ValueError( "Colour values are outside of the domain (0-255)") self.red, self.green, self.blue, self.alpha = rgba def __eq__(self, other): if isinstance(other, self.__class__): return (self.red == other.red and self.green == other.green and self.blue == other.blue and self.alpha == other.alpha) else: raise NotImplemented
# ================================= # Simple bank Account Class # ================================= # This is the Bank Account Class (template for bank account instances) class BankAccount: """ Creating simple bank account with balance """ def __init__(self, name, balance): self.name = name self.balance = balance print("Account balance created for " + self.name) def deposit(self, amount): # pass amount to deposit if amount > 0: self.balance += amount # if amount to deposit > 0, new balance = old balance + amount def withdraw(self, amount): # pass amount to withdraw if amount > 0: self.balance -= amount # if amount to withdraw > 0, new balance = old balance - amount def show_balance(self): # you don't pass anything here. We just use self print("Balance is {}".format(self.balance)) # Now we create bank account named DylanAccount if __name__ == "__main__": # Note. name is always __main__ if running code where it is written. not imported DylanAccount = BankAccount("DylanAccount_1", 0) # initialize it with name and balance. Balance is initially 0 DylanAccount.show_balance() # Show initial balance # Then we deposit $1000 to DylanAccount DylanAccount.deposit(1000) # Give it amount $1000 DylanAccount.show_balance() # Now we show balance after deposit. # Now we withdraw $500 from DylanAccount DylanAccount.withdraw(500) DylanAccount.show_balance() # Now we show balance after withdrawal print("="*30) # ============================================================================ # We can improve above code so that it prints balance automatically after every withdrawal or deposit # And then also make sure we don't withdraw more than is available in the balance. # We can see that the Class BankAccount encapsulates methods and variables and the "client" of the class # does not have to worry about the details. # NOTE: "client" is any code that uses a class class BankAccount: """ Creating simple bank account with balance """ def __init__(self, name, balance): self.name = name self.balance = balance print("Account balance created for " + self.name) def deposit(self, amount): # pass amount to deposit if amount > 0: self.balance += amount # if amount to deposit > 0, new balance = old balance + amount self.show_balance() # Shows balance here after we deposit by calling method show_balance def withdraw(self, amount): # pass amount to withdraw if 0 < amount <= self.balance: # if amount to withdraw is more than 0, and is less or equal to balance self.balance -= amount # if amount to withdraw > 0, new balance = old balance - amount else: print("The withdrawal amount must be > 0 and no more than your account balance") self.show_balance() # Then call show_balance method to show balance def show_balance(self): # you don't pass anything here. We just use self print("Balance is {}".format(self.balance)) # Now we create bank account named DylanAccount # DylanAccount is an instance of class BankAccount and is also a client of the Class # DylanAccount just calls the Class "BankAccount" and does not need to know the details of the Class # "Signature" is the definition of the name and parameters of a function or class # So as long as a "client" does not modify the signature of the "Class", it will still work. if __name__ == "__main__": # Note. name is always __main__ if running code where it is written. not imported DylanAccount = BankAccount("DylanAccount_2", 0) # initialize it with name and balance. Balance is initially 0 DylanAccount.show_balance() # Show initial balance # Then we deposit $1000 to DylanAccount DylanAccount.deposit(1000) # Give it amount $1000 # Now we withdraw $500 from DylanAccount DylanAccount.withdraw(250) print("="*30) # ============================================================================== # We will add a transaction log to keep the details of deposits and withdrawals # ============================================================================== # We will first write code to track deposits. # Then we will later add class method to use for both deposits and withdrawals # Transaction log of deposits will include date/time and amount deposited # So we will need to import "datetime" module # We will also import "pytz" module so we can log a location and UTC time # NOTE: pytz is not installed by default. We installed it in earlier code import datetime import pytz class BankAccount: """ Creating simple bank account with balance """ def __init__(self, name, balance): self.name = name self.balance = balance self.transaction_list = [] # we initialize transaction_list with an empty list print("Account balance created for " + self.name) def deposit(self, amount): # pass amount to deposit if amount > 0: self.balance += amount # if amount to deposit > 0, new balance = old balance + amount self.show_balance() # Shows balance here after we deposit by calling method show_balance # we will then append "UTC time" to deposit "amount" and add it to transaction_list self.transaction_list.append((pytz.utc.localize(datetime.datetime.utcnow()), amount)) def withdraw(self, amount): # pass amount to withdraw if 0 < amount <= self.balance: # if amount to withdraw is more than 0, and is less or equal to balance self.balance -= amount # if amount to withdraw > 0, new balance = old balance - amount else: print("The withdrawal amount must be > 0 and no more than your account balance") self.show_balance() # Then call show_balance method to show balance def show_balance(self): # you don't pass anything here. We just use self print("Balance is {}".format(self.balance)) # Now we create "show_transactions" method def show_transactions(self): for date, amount in self.transaction_list: # transaction list has date and amount, unpacked if amount > 0: # if amount in transaction_list is more than 0 trans_type = "deposited" # then transaction type is deposited else: trans_type = "withdrawn" # If amount is negative number, then transaction type is withdrawn amount *= -1 # we convert the new amount to positive by saying negative amount = amount x -1 print("{:6} {} on {} (Local time was {})".format(amount, trans_type, date, date.astimezone())) # Now we create bank account named DylanAccount if __name__ == "__main__": # Note. name is always __main__ if running code where it is written. not imported DylanAccount = BankAccount("DylanAccount_3", 0) # initialize it with name and balance. Balance is initially 0 DylanAccount.show_balance() # Show initial balance # Then we deposit $1000 to DylanAccount DylanAccount.deposit(1000) # Give it amount $1000 # Now we withdraw $500 from DylanAccount DylanAccount.withdraw(250) # Now we can call method "show_transactions" DylanAccount.show_transactions() print("="*30) # ============================================================================== # Static Methods # ============================================================================== # We can use "static method" here so we don't repeat code for transaction_list above # for both "withdrawal" and "deposit" import datetime import pytz class BankAccount: """ Creating simple bank account with balance """ # We add "static method" here. it starts with @staticmethod # if you CTRL + click staticmethod, you will see where it is defined # NOTE: definition of static method starts with _ e.g. _current_time. # This is convention to show it is not local to BankAccount Class @staticmethod def _current_time(): # NOTE we don't use (self) here because this is static method that does not include parameters in BankAccount utc_time = datetime.datetime.utcnow() # Assigns UTC time to variable utc_time return pytz.utc.localize(utc_time) # Returns localized UTC time def __init__(self, name, balance): self.name = name self.balance = balance self.transaction_list = [] # we initialize transaction_list with an empty list print("Account balance created for " + self.name) def deposit(self, amount): # pass amount to deposit if amount > 0: self.balance += amount # if amount to deposit > 0, new balance = old balance + amount self.show_balance() # Shows balance here after we deposit by calling method show_balance # We call BankAccount._current_time here to get UTC time. Also add amount to transaction_list self.transaction_list.append((BankAccount._current_time(), amount)) def withdraw(self, amount): # pass amount to withdraw if 0 < amount <= self.balance: # if amount to withdraw is more than 0, and is less or equal to balance self.balance -= amount # if amount to withdraw > 0, new balance = old balance - amount # We call BankAccount._current_time here to get UTC time. Also add amount to transaction_list # NOTE: you can use self._current_tume() but it is innefficient and its better to use class name # NOTE: we use -amount here so the test in "show_transactions" becomes negative for withdrawals hence types withdrawn self.transaction_list.append((BankAccount._current_time(), -amount)) else: print("The withdrawal amount must be > 0 and no more than your account balance") self.show_balance() # Then call show_balance method to show balance def show_balance(self): # you don't pass anything here. We just use self print("Balance is {}".format(self.balance)) # Now we create "show_transactions" method def show_transactions(self): for date, amount in self.transaction_list: # transaction list has date and amount, unpacked if amount > 0: # if amount in transaction_list is more than 0 trans_type = "deposited" # then transaction type is deposited else: trans_type = "withdrawn" # If amount is negative number, then transaction type is withdrawn amount *= -1 # we convert the new amount to positive by saying negative amount = amount x -1 print("{:6} {} on {} (Local time was {})".format(amount, trans_type, date, date.astimezone())) # Now we create bank account named DylanAccount if __name__ == "__main__": # Note. name is always __main__ if running code where it is written. not imported DylanAccount = BankAccount("DylanAccount_4", 0) # initialize it with name and balance. Balance is initially 0 DylanAccount.show_balance() # Show initial balance # Then we deposit $1000 to DylanAccount DylanAccount.deposit(1000) # Give it amount $1000 # Now we withdraw $500 from DylanAccount DylanAccount.withdraw(250) # Now we can call method "show_transactions" DylanAccount.show_transactions() # ============================================================== # Now we will make another account with initial balance of $800 # ============================================================== print("="*20) MarenAccount = BankAccount("MarenAccount_1", 800) MarenAccount.show_balance() MarenAccount.deposit(100) MarenAccount.withdraw(200) MarenAccount.show_transactions() print("="*30) # In results from MarenAccount above, although we see Balance changing from 800, to 900 to 700 # The transaction log only shows 100 deposited and 200 withdrawn. # It does not show initial balance of $800 as a deposit. # 100 deposited on 2018-04-08 22:10:36.416750+00:00 (Local time was 2018-04-08 17:10:36.416750-05:00) # 200 withdrawn on 2018-04-08 22:10:36.416750+00:00 (Local time was 2018-04-08 17:10:36.416750-05:00) # We can include initial balance of $800 as a deposit by changing initialization under __init__ # from empty list "self.transaction_list = []" to "self.transaction_list = [(BankAccount._current_time(), balance)]" # ============================================================================== # Initializing self.transaction_list = [] # ============================================================================== # We can include initial balance of $800 as a deposit by changing initialization under __init__ # from empty list "self.transaction_list = []" to "self.transaction_list = [(BankAccount._current_time(), balance)]" import datetime import pytz class BankAccount: """ Creating simple bank account with balance """ # We add "static method" here. it starts with @staticmethod # if you CTRL + click staticmethod, you will see where it is defined # NOTE: definition of static method starts with _ e.g. _current_time. # This is convention to show it is not local to BankAccount Class @staticmethod def _current_time(): # NOTE we don't use (self) here because this is static method that does not include parameters in BankAccount utc_time = datetime.datetime.utcnow() # Assigns UTC time to variable utc_time return pytz.utc.localize(utc_time) # Returns localized UTC time def __init__(self, name, balance): self.name = name self.balance = balance # we initialize transaction_list with current time and account balance. The result shows initial $800 as a deposit. self.transaction_list = [(BankAccount._current_time(), balance)] print("Account balance created for " + self.name) def deposit(self, amount): # pass amount to deposit if amount > 0: self.balance += amount # if amount to deposit > 0, new balance = old balance + amount self.show_balance() # Shows balance here after we deposit by calling method show_balance # We call BankAccount._current_time here to get UTC time. Also add amount to transaction_list self.transaction_list.append((BankAccount._current_time(), amount)) def withdraw(self, amount): # pass amount to withdraw if 0 < amount <= self.balance: # if amount to withdraw is more than 0, and is less or equal to balance self.balance -= amount # if amount to withdraw > 0, new balance = old balance - amount # We call BankAccount._current_time here to get UTC time. Also add amount to transaction_list # NOTE: you can use self._current_tume() but it is innefficient and its better to use class name # NOTE: we use -amount here so the test in "show_transactions" becomes negative for withdrawals hence types withdrawn self.transaction_list.append((BankAccount._current_time(), -amount)) else: print("The withdrawal amount must be more than Zero and less than your account balance") self.show_balance() # Then call show_balance method to show balance def show_balance(self): # you don't pass anything here. We just use self print("Balance is {}".format(self.balance)) # Now we create "show_transactions" method def show_transactions(self): for date, amount in self.transaction_list: # transaction list has date and amount, unpacked if amount > 0: # if amount in transaction_list is more than 0 trans_type = "deposited" # then transaction type is deposited else: trans_type = "withdrawn" # If amount is negative number, then transaction type is withdrawn amount *= -1 # we convert the new amount to positive by saying negative amount = amount x -1 print("{:6} {} on {} (Local time was {})".format(amount, trans_type, date, date.astimezone())) # Now we create bank account named DylanAccount if __name__ == "__main__": # Note. name is always __main__ if running code where it is written. not imported DylanAccount = BankAccount("DylanAccount_5", 0) # initialize it with name and balance. Balance is initially 0 DylanAccount.show_balance() # Show initial balance # Then we deposit $1000 to DylanAccount DylanAccount.deposit(1000) # Give it amount $1000 # Now we withdraw $500 from DylanAccount DylanAccount.withdraw(250) DylanAccount.withdraw(700) # Now we can call method "show_transactions" DylanAccount.show_transactions() # ============================================================== # Now we will make another account with initial balance of $800 # ============================================================== print("="*20) MarenAccount = BankAccount("MarenAccount_2", 800) MarenAccount.show_balance() MarenAccount.deposit(100) MarenAccount.withdraw(200) MarenAccount.show_transactions() print("="*30) # ============================================================================== # How to prevent class attributes from being modified # ============================================================================== # In this case, we will go to MarenAccount and modify the balance # We will see how to prevent client accessing BankAccount Class from directly modifying balance (or other) attribute # First we rename all BankAccount attributes in the __init__ method (name, balance, transaction_list ) # so they start with underscore (_name, _balance, _transaction_list) # We will change the names by refactoring them # NOTE that even with the new names with underscore, this change does not get error from intellij => "MarenAccount._balance = 200" # In modules, intellij would have shown error message, but with class, it is for use to remember this convention # ============================ # _name for internal use only # ============================ # The rule is: Attributes whose name start with a single underscore (_name), are for internal use only. # There is nothing to prevent you from messing with them, but things will break down the road if you do that. # ====================== # Non-Public vs Private # ====================== # Private - means that _name are enforced as being private # Non-Public - means _name are for private use but that is not enforced. # ==================================== # difference between _name and __name # ==================================== # if you rename the __init__ names to use one underscore, the attributes can still be changed by "MarenAccount._balance = 200" # but if you rename them using two underscores, the attributes are not changed by "MarenAccount.__balance = 200" # The reason for this is because python mangles the names of class attributes (both methods and variables) that # start with two underscores (__name). # We will see what is happening by printing __dict__ method. "print(MarenAccount.__dict__)" # This is the result from __dict__ # {'_name': 'MarenAccount', '_BankAccount__balance': 700, '_transaction_list': # [(datetime.datetime(2018, 4, 9, 17, 43, 19, 442427, tzinfo=<UTC>), 800), # (datetime.datetime(2018, 4, 9, 17, 43, 19, 442427, tzinfo=<UTC>), 100), # (datetime.datetime(2018, 4, 9, 17, 43, 19, 442427, tzinfo=<UTC>), -200)], '__balance': 200} # We can see that MarenAccount has an attribute called __balance with value of 200 # This data attribute was created when we assigned a value 200 to it using "MarenAccount.__balance = 200" # Python did not find a variable with that name in MarenAccount namespace, and also did not find it in the BankAccount Class # So it created a new data attribute called __balance # Second reason why python did not find the __balance attribute is there is a data attribute called _BankAccount__balance # that has the expected value of 700. # By adding two underscores to balance (__balance), we are asking python to perform name Mangling and it automatically # renames the attribute to start with an underscore and the name of the class. This is done behind the scenes and our source code is unchanged. # Whenever we refer to the attribute __balance within class BankAccount, python automatically mangles it for us # When we use the same name outside the class BankAccount, it does not mangle it (add it to class BankAccount) # So the attribute balance within class BankAccount is hidden so it is not accidentally changed when accessing it from outside the class # If we want to change the attribute, we can change the mangled attribute "MarenAccount._BankAccount__balance = 40". # When we print, we now see "Balance is 40" as is expected. # This mechanism is intended to prevent accidental shadowing of attributes when creating subclasses. # Although it can be used as private access to variables, this use (using __ to force private access) is discouraged # because you can use format "MarenAccount._BankAccount__balance = 40" to access the private variables # Remember, names are mangled if they start with double underscore and if they end with no more than a single underscore import datetime import pytz class BankAccount: """ Creating simple bank account with balance """ # We add "static method" here. it starts with @staticmethod # if you CTRL + click staticmethod, you will see where it is defined # NOTE: definition of static method starts with _ e.g. _current_time. # This is convention to show it is not local to BankAccount Class @staticmethod def _current_time(): # NOTE we don't use (self) here because this is static method that does not include parameters in BankAccount utc_time = datetime.datetime.utcnow() # Assigns UTC time to variable utc_time return pytz.utc.localize(utc_time) # Returns localized UTC time def __init__(self, name, balance): self._name = name self.__balance = balance # we initialize transaction_list with current time and account balance. The result shows initial $800 as a deposit. self._transaction_list = [(BankAccount._current_time(), balance)] print("Account balance created for " + self._name) def deposit(self, amount): # pass amount to deposit if amount > 0: self.__balance += amount # if amount to deposit > 0, new balance = old balance + amount self.show_balance() # Shows balance here after we deposit by calling method show_balance # We call BankAccount._current_time here to get UTC time. Also add amount to transaction_list self._transaction_list.append((BankAccount._current_time(), amount)) def withdraw(self, amount): # pass amount to withdraw if 0 < amount <= self.__balance: # if amount to withdraw is more than 0, and is less or equal to balance self.__balance -= amount # if amount to withdraw > 0, new balance = old balance - amount # We call BankAccount._current_time here to get UTC time. Also add amount to transaction_list # NOTE: you can use self._current_tume() but it is innefficient and its better to use class name # NOTE: we use -amount here so the test in "show_transactions" becomes negative for withdrawals hence types withdrawn self._transaction_list.append((BankAccount._current_time(), -amount)) else: print("The withdrawal amount must be more than Zero and less than your account balance") self.show_balance() # Then call show_balance method to show balance def show_balance(self): # you don't pass anything here. We just use self print("Balance is {}".format(self.__balance)) # Now we create "show_transactions" method def show_transactions(self): for date, amount in self._transaction_list: # transaction list has date and amount, unpacked if amount > 0: # if amount in transaction_list is more than 0 trans_type = "deposited" # then transaction type is deposited else: trans_type = "withdrawn" # If amount is negative number, then transaction type is withdrawn amount *= -1 # we convert the new amount to positive by saying negative amount = amount x -1 print("{:6} {} on {} (Local time was {})".format(amount, trans_type, date, date.astimezone())) # Now we create bank account named DylanAccount if __name__ == "__main__": # Note. name is always __main__ if running code where it is written. not imported DylanAccount = BankAccount("DylanAccount_6", 0) # initialize it with name and balance. Balance is initially 0 DylanAccount.show_balance() # Show initial balance # Then we deposit $1000 to DylanAccount DylanAccount.deposit(1000) # Give it amount $1000 # Now we withdraw $500 from DylanAccount DylanAccount.withdraw(250) DylanAccount.withdraw(700) # Now we can call method "show_transactions" DylanAccount.show_transactions() # ============================================================== # Now we will make another account with initial balance of $800 # ============================================================== # if we modify balance to $200, we see balances don't match transaction history print("="*20) MarenAccount = BankAccount("MarenAccount_3", 800) MarenAccount.show_balance() MarenAccount.__balance = 200 # We modify MarenAccount Balance to $200 here MarenAccount.show_balance() MarenAccount.deposit(100) MarenAccount.withdraw(200) # We see balance here is $100 due to the modification we made above. MarenAccount.show_transactions() print(MarenAccount.__dict__) MarenAccount._BankAccount__balance = 40 # change the balance MarenAccount.show_balance()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Example embedding look-up for explaining how torch.index_select and torch.view work Inspired by assignment 3 of Stanford's CS224n class on NLP, spring 2020 For explanations, see dstei.github.io/pytorch-index_select-example """ import torch torch.manual_seed(0) batch_size = 2 no_features = 3 embedding_size = 5 num_words = 100 words = torch.randint(100, (batch_size, no_features)) # Initialise w with random words words[:, 0] = torch.arange(batch_size) # This is to mark/recognise the head of each row of words print('words', '\n', words, '\n') embeddings = torch.rand(num_words, embedding_size) # Initialise embeddings with random word vectors embeddings[:, 0] = torch.arange(num_words) # This is to mark/recognise the head of each row of embeddings print('embeddings[:10]', '\n', embeddings[:10], '\n') words_reshaped = words.view(batch_size*no_features) print('words_reshaped', '\n', words_reshaped, '\n') selected_embeddings = torch.index_select(embeddings, 0, words_reshaped) print('selected_embeddings', '\n', selected_embeddings, '\n') embedded_words = selected_embeddings.view(batch_size, no_features*embedding_size) print('selected_embeddings reshaped', '\n', embedded_words, '\n') embedded_words = torch.index_select(embeddings, 0, words.view(-1)).view(-1, no_features*embedding_size) #fully vectorised, i.e. fast to compute print('one-liner', '\n', embedded_words, '\n')
""" Домашнее задание №1 Исключения: KeyboardInterrupt * Перепишите функцию ask_user() из задания while2, чтобы она перехватывала KeyboardInterrupt, писала пользователю "Пока!" и завершала работу при помощи оператора break """ def ask_user(): """ Замените pass на ваш код """ q_and_a = {'How are you?': 'Just fine!', 'What are you doing?': 'Working', 'How old are you?': '100500', 'Where do you come from?': 'Neverland', 'Where are you going?': 'Nowhere'} while True: try: q = input('Your question: ') a = q_and_a.get(q, 0) if not a == 0: print(a) else: print('I don\'t know the answer') except KeyboardInterrupt: print('Bye-Bye') break if __name__ == "__main__": ask_user()
# Homework #2 # https://github.com/SunJieMing/python-minicamp-homework-2 # Special thanks to @Taic who help me to understand the last part of the extra credit. # ------------------------------------- # from flask import Flask from flask import Flask, render_template, jsonify app = Flask(__name__) # ------------------------------------- # 01-Setup your initial route at / to return 'Hello World'. # Example: A GET request to localhost:5000/ would return 'Hello World'. @app.route("/") # Now we write a function that tells the Route what to do def index(): return "Hello Edxael" # ------------------------------------- # Build a route called /birthday that returns your birthday as a string in this format: 'October 30 1911'. # Example: A GET request to localhost:5000/birthday returns 'October 30 1911' (Use your birthday instead) @app.route("/birthday") def birthday(): return "July 01 1992" # ------------------------------------- # Build a route called /greeting that accepts a parameter called name. The route should return a string that says 'Hello <name>' where <name> is the name that you passed to the route. # Example: A GET request to localhost:5000/greeting/ben would return 'Hello ben!' @app.route("/greeting/<name>") def greeting(name): return "Hello {}".format(name) # ------------------------------------- # Modify your home route (/) to return the html template provided below. # . # -Create a folder called templates in the root of your project's directory. # -Create a file called home.html in the templates directory. # -Paste the HTML shown below into home.html and save. # -In your main server file modify the flask import line to say: from flask import Flask, render_template # -In your home (/) route return render_template('home.html'). # -Navigate to localhost:5000/ and you should see the rendered HTML. @app.route("/template1") def template1(): return app.send_static_file("home.html") # ------------------------------------- # Extra Credit # . # Create a route called /sum that adds two parameteres together and returns them. # . # -localhost:5000/sum/5/10 would return '15' # -You will need to convert the parameters to integers using int() # -Example: fiveAsInt = int('5') => fiveAsInt == 5 # -You then have to convert the int back into a string using str() # -Example: fiveAsString = str(5) => fiveAsString == '5' # -You can also prefix the parameter with the keyword int => <int:param>. Make sure you turn it back into a string @app.route("/sum/<int:num1>/<int:num2>") def sum(num1, num2): total = num1 + num2 return "The SUM of: " + str(num1) + " and " + str(num2) + " is: " + str(total) # ------------------------------------- # Create a route called /multiply and a route called /subtract # . # -localhost:5000/multiply/6/5 would return '30' # -localhost:5000/subtract/25/5 would return '20' # -Make sure you are converting the parameters to ints and returning a string @app.route("/multiply/<int:num1>/<int:num2>") def multiply(num1, num2): total = num1 * num2 return "The MULTIPLICATION of: " + str(num1) + " and " + str(num2) + " is: " + str(total) # ----------- @app.route("/subtract/<int:num1>/<int:num2>") def subtract(num1, num2): total = num1 - num2 return "The SUBSTRACTION of: " + str(num1) + " minus " + str(num2) + " is: " + str(total) # ------------------------------------- # Create a route called /favoritefoods that returns a list of your favorite foods # . # -A list is a collection of different values. => ['football', 'basketball', 'rugby'] # -The server must return a string so we need to convert our list into a string. # -One common string format for sending complex data is JSON. # -Change the top line of your server file to from flask import Flask, render_template, jsonify # -Pass your list to jsonify() when returning it. return jsonify(myList) @app.route("/favfood") def favfood(): listx= ["Pizza", "Hamburger", "HotDog"] return jsonify(listx)
# Find possible ways in a Dice Game # using efficient approach instead of Decision Tree import sys def find_possible_ways_dice_game(faces, distance): pre_values = [0 for x in range(faces)] cur_values = [0 for x in range(faces)] for i in range(1, distance+1): if i <= faces: if i == 1: cur_values[0] = 1 elif i > 1: cur_values[0] = pre_values[0]*2 else: cur_values[0] = sum(pre_values) for j in range(1, faces): cur_values[j] = pre_values[j-1] for k in range(faces): pre_values[k] = cur_values[k] return cur_values[0] if __name__=="__main__": if len(sys.argv) >= 3: try: faces = int(sys.argv[1].strip()) distance = int(sys.argv[2].strip()) possible_moves = find_possible_ways_dice_game(faces, distance) print 'Possible moves for Distance',distance,'with',faces,'faces dice: ', possible_moves except: print 'Kindly provide integer values as arguments' else: print 'Kindly provide integer values as arguments for faces of dice and total distance.'
adj = [ [4, 2, 1], # 0 [0, 2], # 1 [0, 1, 3], # 2 [2], # 3 [0], # 4 [], # 5 ] def dfs(node, end, visited): if node == end: return True for neigh in adj[node]: if not visited[neigh]: visited[neigh] = True if dfs(neigh, end, visited): return True return False start, end = input().split() start, end = int(start), int(end) visited = [False for i in range(6)] visited[start] = True if dfs(start, end, visited): # depth first search print('Encontrei') else: print('Não Encontrei')
# coding: utf-8 linhas = ['ana', 'beatriz', 'clara'] linhas # lista de strings >>> string ' '.join(linhas) '--'.join(linhas) s = ''.join(linhas) s s = ' '.join(linhas) # string >>> lista de strings s.split() s = '--'.join(linhas) s s.split() s.split('--') s = '1 2 3 4' l = s.split() l [1, 2, 3, 4] nums = [] l for num in l: print( int(num) ) for num in l: print( int(num) + 1 ) l for num in l: print( num + 1 ) nums = [] for num in l: n = int(num) nums.append(n) nums nums = [int(num) for num in l] s list(s) s = 'cão' list(s) l = list(s) l l[2] = 'a' l ''.join(l) l = [1, 2, 2] l.remove(2) l l.remove(2) l l.remove(2) s = 'ola' for c in s: # c = 'a' print(c) l = [1,2, 3, ] l l.index(3) d = {} # dict() d d['a'] = 1 d d['b'] = 1 d d['a'] d['b'] {} # dict get_ipython().magic('save comandos.py ~0/')
import random array = input().split() array = [int(num) for num in array] def selection_sort(array): N = len(array) start = 0 while start < N: index = start min_index = start while index < N: # [start, ..., N-1] if array[index] < array[min_index]: min_index = index index += 1 # swap elementos array[start], array[min_index] = array[min_index], array[start] start += 1 # retorna array ordenado return array def array_is_sorted(array): N = len(array) for i in range(N-1): if array[i] > array[i+1]: return False return True def brute_force_sort(array): while not array_is_sorted(array): random.shuffle(array) return array print (brute_force_sort(array))
import time from collections import deque N = int(input()) lista = [0] * N # 10k queue = deque(lista) start = time.time() while len(queue) > 0: # while lista: queue.pop() end = time.time() print('Tempo Necessário tirando do final: ', end-start) lista = [0] * N # 10k queue = deque(lista) start = time.time() while len(queue) > 0: # while lista: queue.popleft() end = time.time() print('Tempo Necessário tirando do início: ', end-start)
# dictionary to store data nick_names ={ "jason" : "jay", "kenneth" : "ken", "Jacob" : "Coby", "William" : "Bill", "Alexander": "Alex", } print(nick_names.get("Alexander", "key not found")) #the key with get function
import numpy as np from random import shuffle def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X: A numpy array of shape (N, D) containing a minibatch of data. - y: A numpy array of shape (N,) containing training labels; y[i] = c means that X[i] has label c, where 0 <= c < C. - reg: (float) regularization strength Returns a tuple of: - loss as single float - gradient with respect to weights W; an array of same shape as W """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) ############################################################################# # TODO: Compute the softmax loss and its gradient using explicit loops. # # Store the loss in loss and the gradient in dW. If you are not careful # # here, it is easy to run into numeric instability. Don't forget the # # regularization! # ############################################################################# num_train = X.shape[0] num_classes = W.shape[1] for i in range(num_train): scores = X[i].dot(W) scores -= np.max(scores) exp_scores = np.exp(scores) softmax_dominator = np.sum(exp_scores) softmax_scores = exp_scores / softmax_dominator loss += -np.log(softmax_scores[y[i]]) for j in range(num_classes): dW[:, j] += (softmax_scores[j] - (j == y[i])) * X[i] ''' A mistake implementation, as I got incorrectly understanding on softmax derivative!!! Check http://neuralnetworksanddeeplearning.com/chap3.html to find answer eq59 ~ eq61''' # loss_derivative = softmax_scores[i, y[i]] # softmax_scores_derivative = softmax_scores[i, y[i]] * (1 - softmax_scores[i, y[i]]) # d_w = loss_derivative * softmax_scores_derivative * X[i] # # print loss_derivative * softmax_scores_derivative, d_w.shape, X[i].shape # dW[ :, y[i]] += d_w # for k in range(num_classes): loss /= num_train loss += 0.5 * reg * np.sum(W*W) dW /= num_train dW += reg * W ############################################################################# # END OF YOUR CODE # ###################################exp########################################## return loss, dW def softmax_loss_vectorized(W, X, y, reg): """ Softmax loss function, vectorized version. Inputs and outputs are the same as softmax_loss_naive. """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) ############################################################################# # TODO: Compute the softmax loss and its gradient using no explicit loops. # # Store the loss in loss and the gradient in dW. If you are not careful # # here, it is easy to run into numeric instability. Don't forget the # # regularization! # ############################################################################# num_train = X.shape[0] num_classes = W.shape[1] scores = np.dot(X, W) scores -= scores.max(axis=1)[:, np.newaxis] exp_scores = np.exp(scores) softmax_dominators = np.sum(exp_scores, axis=1)[:, np.newaxis] softmax_scores = exp_scores / softmax_dominators correct_class_scores = softmax_scores[np.arange(num_train), y] loss += np.sum(-np.log(correct_class_scores)) / num_train loss += 0.5 * reg * np.sum(W*W) mask = np.zeros_like(softmax_scores) mask[np.arange(num_train), y] = 1 dW = np.dot(X.T, (softmax_scores - mask)) dW /= num_train dW += reg * W ############################################################################# # END OF YOUR CODE # ############################################################################# return loss, dW
from tkinter import* import tkinter.messagebox import stdDatabase class Student: def __init__(self,root): self.root = root self.root.title("Students Database Management System") self.root.geometry("1350x750+0+0") self.root.config(bg="dark orange") StdID = StringVar() Firstname = StringVar() Lastname = StringVar() DOB = StringVar() Age = StringVar() Gender = StringVar() Branch = StringVar() Mobileno = StringVar() #function def iExit(): iExit=tkinter.messagebox.askyesno("Students Database Management System","Confirm if you want to Exit") if iExit > 0: root.destroy() return def clearData(): self.txtStdID.delete(0,END) self.txtfna.delete(0, END) self.txtSna.delete(0, END) self.txtDOB.delete(0, END) self.txtAge.delete(0, END) self.txtGender.delete(0, END) self.txtBranch.delete(0, END) self.txtMobile.delete(0, END) def addData(): if(len(StdID.get())!=0): stdDatabase.addStdRec(StdID.get(), Firstname.get(), Lastname.get(),DOB.get(), Age.get(), Gender.get() ,Branch.get() ,Mobileno.get()) studentlist.delete(0,END) studentlist.insert(END,(StdID.get(), Firstname.get(), Lastname.get(),DOB.get(), Age.get(), Gender.get() ,Branch.get() ,Mobileno.get())) def displayData(): studentlist.delete(0, END) for row in stdDatabase.viewData(): studentlist.insert(END,row,str("")) def StudentRec(event): global sd searchStd=studentlist.curselection()[0] sd=studentlist.get(searchStd) self.txtStdID.delete(0, END) self.txtStdID.insert(END,sd[1]) self.txtfna.delete(0, END) self.txtfna.insert(END, sd[2]) self.txtSna.delete(0, END) self.txtSna.insert(END, sd[3]) self.txtDOB.delete(0, END) self.txtDOB.insert(END, sd[4]) self.txtAge.delete(0, END) self.txtAge.insert(END, sd[5]) self.txtGender.delete(0, END) self.txtGender.insert(END, sd[6]) self.txtBranch.delete(0, END) self.txtBranch.insert(END, sd[7]) self.txtMobile.delete(0, END) self.txtMobile.insert(END, sd[8]) def DeleteData(): if (len(StdID.get()) != 0): stdDatabase.deleteRec(sd[0]) clearData() displayData() def searchDatabase(): studentlist.delete(0, END) for row in stdDatabase.searchData(StdID.get(), Firstname.get(), Lastname.get(),DOB.get(), Age.get(), Gender.get() ,Branch.get() ,Mobileno.get()): studentlist.insert(END, row, str("")) def update(): if (len(StdID.get()) != 0): stdDatabase.deleteRec(sd[0]) if (len(StdID.get()) != 0): stdDatabase.addStdRec(StdID.get(), Firstname.get(), Lastname.get(), DOB.get(), Age.get(), Gender.get(), Branch.get(), Mobileno.get()) studentlist.delete(0, END) studentlist.insert(END, (StdID.get(), Firstname.get(), Lastname.get(), DOB.get(), Age.get(), Gender.get(), Branch.get(),Mobileno.get())) #frames MainFrame = Frame(self.root, bg="dark orange") MainFrame.grid() TitFrame = Frame(MainFrame, bd=2 , padx=54 , pady=8 , bg="dark salmon" , relief =RIDGE) TitFrame.pack(side=TOP) self.lblTit = Label(TitFrame , font=('arial',47 ,'bold'), text= "Student Database Management Systems", bg="Ghost White") self.lblTit.grid() ButtonFrame = Frame(MainFrame, bd=2 , width=1350 , height=70, padx=18, pady=10, bg="Ghost White", relief=RIDGE) ButtonFrame.pack(side=BOTTOM) DataFrame = Frame(MainFrame, bd=1, width=1300 , height=400, padx=20, pady=20, bg="Ghost White", relief=RIDGE) DataFrame.pack(side=BOTTOM) DataFrameLEFT = LabelFrame(DataFrame, bd=1, width=1000 , height=600, padx=20, bg="Ghost White", relief=RIDGE ,font=('arial',20 ,'bold') ,text="Student Info\n") DataFrameLEFT.pack(side=LEFT) DataFrameRIGHT = LabelFrame(DataFrame, bd=1, width=450, height=300, padx=31, pady=3, bg="Ghost White", relief=RIDGE ,font=('arial',20 ,'bold') ,text="Student Details\n") DataFrameRIGHT.pack(side=RIGHT) #labels self.lblStdID = Label(DataFrameLEFT,font=('arial', 20, 'bold'), text="Student ID:", padx=2, pady= 2,bg="Ghost White") self.lblStdID.grid(row=0,column=0,sticky=W) self.txtStdID = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=StdID,width=39) self.txtStdID.grid(row=0, column=1) self.lblfna = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text="First Name:", padx=2, pady= 2,bg="Ghost White") self.lblfna.grid(row=1, column=0, sticky=W) self.txtfna = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=Firstname, width=39) self.txtfna.grid(row=1, column=1) self.lblSna = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text="Last Name:", padx=2, pady=2, bg="Ghost White") self.lblSna.grid(row=2, column=0, sticky=W) self.txtSna = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=Lastname, width=39) self.txtSna.grid(row=2, column=1) self.lblDOB = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text="Date of Birth:", padx=2, pady=2, bg="Ghost White") self.lblDOB.grid(row=3, column=0, sticky=W) self.txtDOB = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=DOB, width=39) self.txtDOB.grid(row=3, column=1) self.lblAge = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text="Age:", padx=2, pady=2, bg="Ghost White") self.lblAge.grid(row=4, column=0, sticky=W) self.txtAge = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=Age, width=39) self.txtAge.grid(row=4, column=1) self.lblGender = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text="Gender:", padx=2, pady=2, bg="Ghost White") self.lblGender.grid(row=5, column=0, sticky=W) self.txtGender = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=Gender, width=39) self.txtGender.grid(row=5, column=1) self.lblBranch = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text="Branch:", padx=2, pady=2, bg="Ghost White") self.lblBranch.grid(row=6, column=0, sticky=W) self.txtBranch = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=Branch, width=39) self.txtBranch.grid(row=6, column=1) self.lblMobile = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text="Mobile:", padx=2, pady=2, bg="Ghost White") self.lblMobile.grid(row=7, column=0, sticky=W) self.txtMobile = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=Mobileno, width=39) self.txtMobile.grid(row=7, column=1) #listbox and scrollbar scrollbar= Scrollbar(DataFrameRIGHT) scrollbar.grid(row=0, column=1,sticky='ns') studentlist= Listbox(DataFrameRIGHT, width=41, height=16, font=('arial', 12, 'bold'), yscrollcommand=scrollbar.set ) studentlist.bind('<<ListboxSelect>>',StudentRec) studentlist.grid(row=0, column=0,sticky='ns') scrollbar.config(command = studentlist.yview) #button widget self.btnAddData= Button(ButtonFrame, text='Add New',font=('arial',20, 'bold'), height=1, width=10, bd=4, command=addData) self.btnAddData.grid(row=0,column=0) self.btnDisplayData = Button(ButtonFrame, text='Display', font=('arial', 20, 'bold'), height=1, width=10, bd=4 ,command=displayData) self.btnDisplayData.grid(row=0, column=1) self.btnClearData = Button(ButtonFrame, text='Clear', font=('arial', 20, 'bold'), height=1, width=10, bd=4 ,command=clearData) self.btnClearData.grid(row=0, column=2) self.btnDeleteData = Button(ButtonFrame, text='Delete', font=('arial', 20, 'bold'), height=1, width=10, bd=4,command=DeleteData) self.btnDeleteData.grid(row=0, column=3) self.btnSearchData = Button(ButtonFrame, text='Search', font=('arial', 20, 'bold'), height=1, width=10, bd=4,command=searchDatabase) self.btnSearchData.grid(row=0, column=4) self.btnUpdateData = Button(ButtonFrame, text='Update', font=('arial', 20, 'bold'), height=1, width=10, bd=4,command=update) self.btnUpdateData.grid(row=0, column=5) self.btnExit = Button(ButtonFrame, text='Exit', font=('arial', 20, 'bold'), height=1, width=10, bd=4 ,command=iExit) self.btnExit.grid(row=0, column=6) if __name__=='__main__': root=Tk() application= Student(root) root.mainloop()
my_pets = ['lily', 'moss', 'tabbie'] print('Enter a pet name:') name = input() if name not in my_pets: print('I do not have a pet named ' + name) else: print(name + ' is my pet.')
def spam(): eggs = "spam local" print(eggs) #prints spam local def bacon(): eggs = "bacon local" print(eggs) #prints bacon local spam() print(eggs) #prints bacon local eggs = "global" bacon() #overwrites with parameters within the called function print(eggs) #prints "global" #set to global #overwrites with bacon local, prints bacon local #overwrites with spam local, prints spam local #returns to bacon local, prints bacon local #returns to global, prints global