text
stringlengths
37
1.41M
n = int(input("Enter Number : ")) counter = 0 for i in range(1,(n+1)) : if (i % 7 == 0) : counter = counter + 1 print(counter)
Solution = '42' guess = input ('Enter Your Guess: ') guess = int(guess) print(guess) if guess == Solution: print('You are a winer!') print ('Here is another statement') else: print('You are a non-winner') print('so sorry') print('The game is over')
# coding: utf-8 # In[ ]: import numpy as np def total_profit(input_price,beg ,stock_data,quarterly_price_data,stocks): """ finds the total profit and number of quarters and returns a list Parameters ---------- input_price : amount to buy the stocks beg : variable to loop through stock_data : Quarterly price data quarterly_price_data :quarterly price data """ # obtaining the TICKER symbols of the stocks stock = stocks # obtaining Quarterly returns of stock data stock_data = stock_data # finding the number of stocks no_of_stocks = len(stock) # calculating each stock price each_stock_price = int(input_price)/no_of_stocks # list to store all return values all_profits = [] # for each TICKER symbol in stock for abbv in stock: # obtaining quarterly price data stock_data[abbv] = quarterly_price_data[abbv] # converting to numpy array for calculation data = np.array(stock_data[abbv]) # calculating number of stocks can be buyied number_of_stocks = each_stock_price/int(data[beg]) # obtainig price data quart_ret = stock_data[abbv] # filtering to obtain quarterly price data quart_ret = quart_ret.resample('Q', how='last') # finding the profit or loss quart_ret = quart_ret.diff() # converting into numpy array data = np.array(quart_ret) #creating a list to convert numpy into a list of float of values val = [] for i in data: if np.isnan(i): i = float(0) val.append(i) else: i = float(i) val.append(i) # slicing to remove the first data from list ,ie:0 quart_ret = val[1:] # taking the beg position value rets = quart_ret[beg] # find the total profit of stock tot_ret = number_of_stocks*rets # add all the profits to the all returns list all_profits.append(tot_ret) # create a list to store the profit and number of quarters portfolio_ret = [] # sum all the profits of all stocks col_sum = sum(all_profits) # append all profit to portfolio_ret[] list portfolio_ret.append(col_sum) # append number of quarters to portfolio_ret[] list portfolio_ret.append(len(quart_ret)) return portfolio_ret
#! /usr/bin/python # -*- coding: utf8 -*- a= input ("Digite un entero ") b=0 while a> (b+1): b=b+1 print b
#! /usr/bin/python # -*- coding: utf8 -*- def factorial(x): a=1 b=2 while a<=x: a=a*b b=b+1 return a print factorial(5)
import turtle as t import random as r color=[] def LerpColor(c1,c2,t): return (int(c1[0]+(c2[0]-c1[0])*t),int(c1[1]+(c2[1]-c1[1])*t),int(c1[2]+(c2[2]-c1[2])*t)) #color generator입니다. def genTree(length,level): if level != 0: t.pensize(level) #level 값에 따라 Pensize가 바뀝니다. t.pencolor(color[level]) t.forward(length) curPosition = t.position() # 현재 turtle의 위치를 저장 curHead=t.heading() # 현재 turtle의 head 방향을 저장 degree=r.randint(90,180)%90 t.left(degree/2) # 왼쪽으로 가지치는 recursion """ 여기서 degree값을 상위 레벨 함수에서 받아오지 않고 degree=randint(90, n )%90으로 생성하면 됩니다. %90을 하는 이유는 90도를 넘어가게 되면 가지가 너무 꺾여 보기 안좋습니다. """ genTree(length * (r.randint(60,90)/100),level-1) """ 여기서 length * 0.7를 하지 않고 length * (randint(60,90)/100)을 해주면 적당한 범위 내에서 길이를 알아서 줄여줍니다. """ t.penup() # turtle의 위치를 원래대로 t.setposition(curPosition) t.setheading(curHead) t.pendown() degree=r.randint(100,180)%90 t.right(degree/2) # 오른쪽으로 가지치는 recursion """ 여기서도 degree값을 상위 레벨 함수에서 받아오지 않고 degree=randint(90, n )%90으로 생성하면 됩니다. """ genTree(length * (r.randint(60,90)/100),level-1) """ 여기서도 length * 0.7를 하지 않고 length * (randint(60,90)/100)을 해주면 적당한 범위 내에서 길이를 알아서 줄여줍니다. """ t.penup() # turtle의 위치를 원래대로 t.setposition(curPosition) t.setheading(curHead) t.pendown() def main(): t.hideturtle() t.setup(width=.75,height=1.0,startx=0,starty=0) t.title("Tree Generator using Fractal Copyright 2016. TGISaturday All rights reserved.") t.penup() t.left(90) t.backward(int(t.window_height()/2)) # tree가 시작되는 위치를 설정할 수 있다. t.pendown() t.clear() t.tracer(0.0) #update가 나오기 전까진 tree를 그리지 않는다. flag=int(input("Option: 1.Generate random Tree 2.Customize Your Tree:")) if flag==1: length=r.randint(120,500) else: length=int(input("Enter the starting length of the branch:")) level=int(input("Enter the level of branch:")) maxlen=(0.2*t.window_height())/(1-0.8**(level-1)) if length > maxlen: length=maxlen t.screensize(int(20*length*(1-0.9**level)),int(length*(1-0.8**(level)))) list_of_colors=[] if flag==1: for i in range(3): list_of_colors.append((r.randint(0,255),r.randint(0,255),r.randint(0,255)))#randint를 활용하여 색의 RGB 값을 자동으로 생성한다. else: list_of_colors.append(tuple(map(int,input("Enter the RGB value of color 1:").split(',')))) list_of_colors.append(tuple(map(int,input("Enter the RGB value of color 2:").split(',')))) list_of_colors.append(tuple(map(int,input("Enter the RGB value of Background color:").split(',')))) no_steps = level for i in range(2): for j in range(no_steps): color.append(LerpColor(list_of_colors[i],list_of_colors[i+1],j/no_steps)) t.colormode(255) t.bgcolor(list_of_colors[2]) genTree(length,level) t.update() #tracer와 update를 지우면 tree가 그려지는 과정을 볼 수 있다. t.done() main()
# Filter Function is one of the functional programing primitives in python programs. # Lets use the scientists dataset and let's play with filtering! """ filter() is one of the functional programming primitives (or building blocks) available in Python and that it’s useful in a number of contexts. filter() takes another function object, and you can define a function object inline with lambda expressions. """ import collections from pprint import pprint Scientists = collections.namedtuple('Scientists', [ 'name', 'age', 'comp' ]) scientists2 = (Scientists(name='kaushik', age=20, comp='Microsoft'), Scientists(name='chow', age=20, comp='Adobe'), Scientists(name='Tk rahul', age=19, comp='Google'), Scientists(name='Rohith', age=20, comp='Oracle')) # print(scientists2) #m = scientists2(lambda x: x.age == 20) # print(m) """ Traceback (most recent call last): File "section2.py", line 16, in <module> m = scientists2(lambda x: x.age == 20) TypeError: 'tuple' object is not callable """ fs = filter(lambda x: x.comp == 'Microsoft', scientists2) # print(fs) # <filter object at 0x10ed51940> # So it is returning a iterator object where you have to unpack it by using next keyword # print(next(fs)) # print(next(fs)) """ Scientists(name='kaushik', age=21, comp='Microsoft') Scientists(name='kau', age=20, comp='Microsoft') """ # print(next(fs)) If we do this we get: """ Traceback (most recent call last): File "section2.py", line 30, in <module> print(next(fs)) StopIteration BCZ WE HAVE NO MORE TO UNPACK FROM THE FILTER FUNCTION """ # With the results that we got we can convert this into some immutable data structure! fs = tuple(filter(lambda x: x.comp == 'Microsoft', scientists2)) pprint(fs) fs1 = tuple(filter(lambda x: x.comp == 'Google' or x.age == 20, scientists2)) pprint(fs1) """ (Scientists(name='kaushik', age=20, comp='Microsoft'), Scientists(name='chow', age=20, comp='Adobe'), Scientists(name='Tk rahul', age=19, comp='Google'), Scientists(name='Rohith', age=20, comp='Oracle')) """ # Instead of lambda function we can also create a function like: def age_filter_comp(x): return x.comp == 'Google' and x.age == 20 fs1 = tuple(filter(age_filter_comp, scientists2)) pprint(fs1) # The above step also works exactly the same as the lambda functions. # But why should we write code like this and not a for loop: # Bcz we can apply the transformations in a simplified way and # a cleaner way where its flexible enough to change the properties but # I dont mean that this way of writing code is good but this relies on application # or evaluating functions rather than writing stuff and also this can make things a lot # easier if we deal with parallel programming. # Python also has a wonderful thing called as list comprehensions(can be a replacement to filter): pprint([x for x in scientists2 if (x.age == 20 or x.comp == 'Google')]) """ [Scientists(name='kaushik', age=20, comp='Microsoft'), Scientists(name='chow', age=20, comp='Adobe'), Scientists(name='Tk rahul', age=19, comp='Google'), Scientists(name='Rohith', age=20, comp='Oracle')] """ # And also tuple(list()) is a tuple ex: tuple([1,2,3]) is (1,2,3)
# coding: utf-8 # In[ ]: import random def game(): sjb = ['shitou','jiandao','bu'] count_equal = 0 count_computer = 0 count_human = 0 def ask_input(message): while True: value= input(message) try: value = str(value) if value in sjb: break else: print("Your input is not valid,please input 'shitou', 'jiandao','bu', Thank you") except ValueError as e: print("Your input is not valid, please input 'shitou', 'jiandao','bu', Thank you", e) return value for i in range(3): human = ask_input("Your choice is ") computer = random.choice(sjb) if human == computer: count_equal =count_equal +1 print("Computer's choice is", computer, "Tie") elif human == 'shitou' and computer == 'jiandao': count_human= count_human+1 print("Computer's choice is", computer,"human win") elif human == 'jiandao' and computer == 'bu': count_human = count_human +1 print("Computer's choice is", computer,"human win") elif human == 'bu' and computer == 'shitou': count_human = count_human +1 print("Computer's choice is", computer,"human win") else: count_computer = count_computer +1 print("Computer's choice is", computer,'computer win') if count_computer > 2: break return print("Computer won", count_computer, "rounds","Human won", count_human, "rounds","Tie", count_equal, "rounds") game()
def dirname(my_path, full_path=False): """Return the name of the last directory in the path: /x/y/ ==> y ; /x/y ==> x \\ if full_path: /x/y/z ==> /x/y/ ; /x/y/ ==> /x/y/""" list_dir = [] directory = "" for character in my_path: if character == "/": list_dir.append(directory) directory = "" else: directory += character if full_path: full_path = "" for directory in list_dir: full_path += directory + "/" return full_path else: return list_dir[-1] if __name__ == "__main__": a = dirname("/home/francois/fichier") print(a)
# A majority of this code is taken from example code posted by Dr. Omari # The test code was created by Carter Burzlaff # The timing and list generation was added by Carter Burzlaff import time import random class Heap: def __init__(self): self._heap = [] def _swap(self, i, j): self._heap[i], self._heap[j] = self._heap[j], self._heap[i] def _last_idx(self): return len(self._heap) - 1 def _left(self, i): return i * 2 + 1 def _right(self, i): return i * 2 + 2 def _parent(self, i): return (i - 1) // 2 def _has_left(self, i): return self._left(i) < len(self._heap) def _has_right(self, i): return self._right(i) < len(self._heap) def empty(self): return len(self._heap) == 0 def add(self, key): self._heap.append(key) j = self._last_idx() while j > 0 and self._heap[j] < self._heap[self._parent(j)]: self._swap(j, self._parent(j)) j = self._parent(j) def remove_min(self): if self.empty(): raise Exception() self._swap(0, self._last_idx()) result = self._heap[-1] self._heap.pop() # push new element down the heap j = 0 while True: min = j if self._has_left(j) and self._heap[self._left(j)] < self._heap[min]: min = self._left(j) if self._has_right(j) and self._heap[self._right(j)] < self._heap[min]: min = self._right(j) if min == j: #found right location for min, break break self._swap(j, min) j = min return result def heap_sort(list): heap = Heap() for e in list: heap.add(e) sorted_list = [] while not heap.empty(): sorted_list.append(heap.remove_min()) return sorted_list # Basic insertion sort method def insertion_sort(list): sorted_list = list for i in range(1, len(sorted_list)): e = sorted_list[i] j = i-1 while j >= 0 and e < sorted_list[j]: sorted_list[j+1] = sorted_list[j] j -= 1 sorted_list[j+1] = e return sorted_list list = [] for i in range(0, 50): # filling the list with these numbers repeated 20 times list.append(random.randint(0, 100)) # test heap sorting start = time.time() print("\nHeap sorted list:\n", heap_sort(list)) heapTimeTaken = time.time() - start print("Heap sort elapsed time: ", round(heapTimeTaken, 9), "s\n") # test insertion sorting start = time.time() print("Insertion sorted list:\n", insertion_sort(list)) insertionTimeTaken = time.time() - start print("Insertion sort elapsed time: ", round(insertionTimeTaken, 9), "s") # print results print("\nInsertion sort was faster by: ", round(insertionTimeTaken / heapTimeTaken, 7), "%")
def findMinimum(array): if len(array) == 0: return None if len(array) == 1: return array[0] return min(array[0], findMinimum(array[1:])) def findMaximum(array): if len(array) == 0: return None if len(array) == 1: return array[0] return max(array[0], findMaximum(array[1:])) testArray = [20, 6, 15, 35, 4] print(findMinimum(testArray)) print(findMaximum(testArray))
def isEqual(num1,num2): if num1<num2: print '%d is too small!' %num1 return False; elif num1>num2: print '%d is too large!' %num1 return False; elif num1==num2: print '%d is the correct answer!' %num1 return True; from random import randint num = randint(1,100) print 'Guess the number I thought,it\'s a integer' bingo = False while bingo == False: answer = input() bingo = isEqual(answer,num)
sum =0 i=1 while(i<=100): sum+=i i=i+1 print '1+2+3+...+100=' print sum
str1 = 'boring' str2 = 'day' num = 18 #print 'My age is'+num ֱֲַ+ print 'My age is '+str(18) #str()תΪַ print 'My age is '+str(num) print 'My age is %d' %num #%תַ print 'Price is %f' %4.99 #%dֻС%f print 'Prince is %.2f' %4.99 #λС day = 'Today' print '%s is a boring day.' %day #%sһַ print '%s is a boring day.' %'Saturday'
def sort_words(y): x=y.lower() word_list=x.split("-") word_list.sort() str="" for i in range(len(word_list)): if i==0: str += word_list[i] else: str+=("-"+word_list[i]) return str txt=input("Please enter the text with hypent(-):\n") print(sort_words(txt))
# you can write to stdout for debugging purposes, e.g. # print "this is a debug message" def solution(N): """ lessons test by codility https://codility.com/programmers/lessons/1-iterations/binary_gap/ :param N:integer :return: binary gap """ # change integer to string bin_str = bin(N).replace('0b', '') # find all 1 postions one_pos = [] for idx,v in enumerate(bin_str): if v == '1': one_pos.append(idx) # calculate max binary gap binary_gap = 0 for i in range(len(one_pos) - 1 ): gap = one_pos[i+1] - one_pos[i] - 1 if gap > binary_gap: binary_gap = gap return binary_gap def solution2(N): 'https://codesays.com/2014/solution-to-binary-gap-by-codility/' max_gap = 0 current_gap = 0 # Skip the tailing zero(s) while N > 0 and N%2 == 0: N //= 2 while N > 0: remainder = N%2 if remainder == 0: # Inside a gap current_gap += 1 else: # Gap ends if current_gap != 0: max_gap = max(current_gap, max_gap) current_gap = 0 N //= 2 return max_gap if __name__ == '__main__': A = 529 print solution(A)
def solution(K, A): """ https://codility.com/programmers/lessons/16-greedy_algorithms/tie_ropes """ n = len(A) sum_ropes = 0 max_num = 0 for i in xrange(n): sum_ropes += A[i] if sum_ropes >= K: max_num += 1 sum_ropes = 0 return max_num if __name__ == '__main__': A = [1, 2, 3, 4, 1, 1, 3] K = 4 print solution(K, A)
#coding=utf-8 ##下面这种是新式类 class Man(object): def __init__(self): self.legs = 25 def get_legs(self): return self.legs class Yinshuai(Man): def __init__(self): super(Yinshuai,self).__init__() self.eyes = 2 def get_eyes(self): return self.eyes print Yinshuai().get_eyes() print Yinshuai().get_legs() print '--------new start --------' def checkIndex(key): """ is the key can be receviced ?? in order to recevice the key,the key must be a nonegative interger,if the key is not interger, it will raise TypeError if the key is a negative interger, it will raise IndexError,for that the length of the sequence if unlimit """ if not isinstance(key,(int,long)):raise TypeError if key < 0: raise IndexError ####看下如何创建一个无穷序列 class ArithmeticSequence(object): def __init__(self,start=0,step=1): """ init ArithmeticSequence start first value in sequence step 两个相邻值之间的差别 changed 用户修改的值的字典 """ self.start = start self.step = step self.changed = {} def __getitem__(self,key): """ Get an item from arithmetic sequence """ checkIndex(key) try: return self.changed[key] #if has been modified ?? except KeyError: # or return self.start + key*self.step ##calc the value def __setitem__(self,key,value): """ modify an item in arithmetic sequence """ checkIndex(key) self.changed[key] = value #save the value been modified seq = ArithmeticSequence(1,2) print seq[4] ###直接在对象中进行索引 """ 9 """ try: index = input('Enter your index number ') print seq[index] ##直接在对象中进行索引而且是直接取值,会调用到对象中的__getitem__魔术方法,其中的index作为参数传入 except IndexError: print 'wrong index' except TypeError: print 'wrong type ' """ 1 3 -77 wrong index 'tt' wront type """ seq[4] = 6666 ##通过索引进行值的设置 传入index 和 value参数 print seq[4] ##6666 print seq.changed#{4: 6666} ### ########about property class Rectangle(object): def __init__(self): self.width = 100 self.height = 0 def setSize(self,size): self.width,self.height = size def getSize(self): return self.width,self.height size = property(getSize,setSize) @property def getWidth(self): return self.width r = Rectangle() r.width = 300 r.height = 600 print r.size print r.getWidth """ (300,600) 300 """ ####### 生成器 def flatten(nested): for sublist in nested: for element in sublist: yield element #任何包含yield语句的函数称为迭代器 nested = [[1,2,3],[4,5,6],[7,8,9]] flat = flatten(nested) print flat ##<generator object flatten at 0x7f768a97a0f0> for num in flat: print num ##通过在生成器上迭代来使用所有的值 #######递归生成器 def flattenR(nested): try: for sublist in nested: for element in flatten(sublist): yield element except TypeError: yield nested #########stop at page 155
#coding=utf-8 import operator new_list = sorted([5,2,3,1,4]) print new_list #[1, 2, 3, 4, 5] 当然也可以使用list.sort() 但是会改变原始list ## user_info = [{'username':'yinshuai','age':25,'sex':'man'},{'username':'yinkai','age':18,'sex':'man'},{'username':'yinna','age':19,'sex':'woman'}] ##key参数的值为一个函数,此函数只有一个参数且返回一个值用来进行比较。这个技术是快速的因为key指定的函数将准确地对每个元素调用。 ##这里的user是自动被迭代出来的list中的元素 当然list当中也可以是tuple print sorted(user_info,key=lambda user: user['age'])# sort by age """ [{'username': 'yinkai', 'age': 18, 'sex': 'man'}, {'username': 'yinna', 'age': 19, 'sex': 'woman'}, {'username': 'yinshuai', 'age': 25, 'sex': 'man'}] """ print sorted(user_info,key=lambda user: user['sex'])#sort by sex """ [{'username': 'yinshuai', 'age': 25, 'sex': 'man'}, {'username': 'yinkai', 'age': 18, 'sex': 'man'}, {'username': 'yinna', 'age': 19, 'sex': 'woman'}] """ print '------------' ##上面这种使用key的方式很常用,于是python提供了更加方便的函数 user_info = [{'username':'yinshuai','age':25,'sex':'man'},{'username':'yinkai','age':18,'sex':'man'},{'username':'yinna','age':19,'sex':'woman'}] print sorted(user_info,key=operator.itemgetter('age')) print sorted(user_info,key=operator.itemgetter('age'),reverse=True) """ [{'username': 'yinkai', 'age': 18, 'sex': 'man'}, {'username': 'yinna', 'age': 19, 'sex': 'woman'}, {'username': 'yinshuai', 'age': 25, 'sex': 'man'}] #default asc [{'username': 'yinshuai', 'age': 25, 'sex': 'man'}, {'username': 'yinna', 'age': 19, 'sex': 'woman'}, {'username': 'yinkai', 'age': 18, 'sex': 'man'}]# desc """ print '------------------' #当然这同样适用于元组构成的list etc score_info = [('yinshuai','B',52),('yinna','A',100),('yinkai','C',44)] print sorted(score_info,key=operator.itemgetter(2),reverse=True) #[('yinna', 'A', 100), ('yinshuai', 'B', 52), ('yinkai', 'C', 44)] print '--------------' # python 字典排序 my_dict = {'a':3,'b':1,'c':2} print my_dict.iteritems()#以迭代器对象返回字典键值对 print sorted(my_dict.iteritems(),key=lambda asd : asd[0],reverse=True) #[('c', 2), ('b', 1), ('a', 3)] print sorted(my_dict.iteritems(),key=lambda asd : asd[1],reverse=True) #[('a', 3), ('c', 2), ('b', 1)] #: 在函数sorted(dic.iteritems(), key = lambda asd:asd[1])中,第一个参数传给第二个参数“键-键值”,第二个参数取出其中的键([0])或键值(1]) #当然还可以使用更加便捷的方法 print sorted(my_dict.iteritems(),key=operator.itemgetter(0),reverse=True) ##[('c', 2), ('b', 1), ('a', 3)]
from tkinter import* # configuracion ventana principal ventana = Tk() ventana.geometry("240x240") ventana.title("CALCULADORA") ventana.configure(bg="light blue") #widget de entrada de datos y salida numero_a = IntVar() numero_1 = Entry(ventana, textvariable = numero_a,width=18) numero_b = IntVar() numero_2 = Entry(ventana, textvariable = numero_b,width=18) resultado = StringVar() # definicion funciones botones def suma(): x= float(numero_a.get()) y= float(numero_b.get()) suma = x + y resultado.set(suma) def resta(): x= float(numero_a.get()) y= float(numero_b.get()) resta = x - y resultado.set(resta) def multiplicacion(): x= float(numero_a.get()) y= float(numero_b.get()) multiplicacion = x * y resultado.set(multiplicacion) def division(): x= float(numero_a.get()) y= float(numero_b.get()) if y != 0: division = x / y else: division = "ERROR!!!" resultado.set(division) def reset(): numero_a.set(0) numero_b.set(0) resultado.set(0) #botones de comandos boton_suma = Button(ventana,text="SUMA",command=suma ,width=15) boton_resta = Button(ventana,text="RESTA",command=resta,width=15) boton_multiplicacion = Button(ventana,text="MULTIPLICACION",command=multiplicacion,width=15) boton_division = Button(ventana,text="DIVISION",command=division,width=15) boton_reset = Button(ventana,text="RESET",command=reset, width=15) boton_salir = Button(ventana, text="SALIR",command=ventana.quit,width=15) #salida de datos res = Label(ventana,textvariable=resultado,bg="yellow",width=15,relief = SUNKEN) #posicionamiento widgets Label(ventana,text="",bg="light blue").grid(row=0) Label(ventana,text="Ingrese primer Valor",bg="light blue").grid(row=1) numero_1.grid(row = 1,column=1) Label(ventana,text="Ingrese segundo Valor",bg="light blue").grid(row=2) numero_2.grid(row = 2,column=1) Label(ventana,text="",bg="light blue").grid(row=3) boton_suma.grid(row = 4,column=0)
def letters_range(start, end, step=1): letrange = list() for one in range(ord(start), ord(end), step): letrange.append(chr(one)) return letrange
def MultipleSummer(maxVal): retSum = 0 i = 1 while i < maxVal: if i % 5 == 0: retSum += i elif i % 3 == 0: retSum += i i += 1 return retSum
# x = [1, 2, 3] # def test(some_list): # some_list.append(100) # test(x) # print(x) # def test(some_list): # some_list = [3] # return some_list # a = test(x) # print(a) # x = [1, 2, 3, 4] # # for number in x.copy(): # print(number) # x.remove(number) # print(x) # a = [1, 2, 3, 4] # b = a.copy() # b.append(100) # print(a) # import copy # a = [1, 2, 3, [100]] # b = copy.deepcopy(a) # b[3].append(200) # print(a) # qwe = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # for line in qwe: # for number in line: # print(number) # print(qwe[1][2]) # name = input('Name') # print(name or 'Гость') # age = input('Age') # print('Welcome' if int(age) >= 18 else 'No Access') # def admin(): # print('I am admin') # login = input('login ') # admin() if login == 'admin' else print('Hello user') # от -5 до 256 # a = 257 # b = 257 # print(id(a), id(b), a is b) # result = [] # for i in range(10): # result.append(i) # print(result) # result1 = [i for i in range(-10, 10) if i % 2 == 0] # print(result1) # keys = 'qwerty' # values = (1,2,3,4,5,6) # my_dict = {key: value*2 for key, value in zip(keys, values)} # print(my_dict) # a = [1, 2] # try: # a[5] # except IndexError: # print('проверь индекс') # print(1) # try: # age = int(input('Age: ')) # except ValueError: # print('Вы должны ввести цифры') # def get_user_data(): # try: # age = int(input('Age: ')) # except ValueError: # print('деление на ноль!') # # get_user_data() # print(1) import re text = 'dfs df sdf alex@mail.comhgfjfg kjhkljh alex@mail.com ;lk ;lk alex@mail.com' pattern = '([a-zA-Z_0-9]+@[a-z]+\.[a-z]{2,3})' # print(re.match(pattern, text)) print(re.findall(pattern, text))
from Tkinter import * def getValue(): num1 = int(e1.get()) num2 = int(e2.get()) print num1 + num2 root = Tk() v1 = StringVar() v2 = StringVar() e1 = Entry(root, textvariable = v1) e2 = Entry(root, textvariable = v2) b = Button(root, command = getValue, text="Test") e1.pack() e2.pack() b.pack() v1.set("Tal 1") v2.set("Tal 2") root.mainloop()
nome = str(input('Qual o nome do(a) funcionário(a)? ')) si = float(input('Qual o salário inicial do(a) funcionário(a) {}? R$'.format(nome))) p = si + (si * 15 / 100) print('O salário inicial do(a) funcionario(a) {} era de {:.2f} e com o aumento de 15% foi para R${:.2f}!'.format(nome, si, p))
l = float(input('Qual a largura total da parede a ser pintada? :')) h = float(input('Qual a altura total da parede a ser pintada? :')) area = l * h tinta = area/2 print('A área total do cômodo é de {:.2f}m² e será necessário {:.1f} litros de tinta para pintar tudo!!!'.format(area, tinta))
""" author: fangren """ class WordDictionary(object): def __init__(self): """ Initialize your data structure here. """ self.dict = [] def addWord(self, word): """ Adds a word into the data structure. :type word: str :rtype: void """ if word not in self.dict: self.dict.append(word) def search(self, word): """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. :type word: str :rtype: bool """ for existing_word in self.dict: if len(existing_word) != len(word): continue matching = True for i in range(len(word)): if word[i] == '.': continue if word[i] != existing_word[i]: matching = False break if matching == True: return True return False dictionary = WordDictionary() a = dictionary.dict dictionary.addWord("bad") dictionary.addWord("dad") dictionary.addWord("mad") print dictionary.dict print dictionary.search('mat')
""" author: fangren """ class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): left = nums[:i] right = nums[i+1:] #print nums[i], rest if (target-nums[i]) in left: return [i, left.index(target-nums[i])] elif (target-nums[i]) in right: return [i, right.index(target-nums[i])+i+1] return None solution = Solution() nums = [3,3] target = 6 print solution.twoSum(nums, target)
""" author: fangren """ from collections import defaultdict class Solution(object): def repaceWord(self, dict, word): found = False i = 1 while not found and i <= len(word): short_word = word[:i] if short_word in dict[i]: found = True break else: i += 1 if found: return short_word else: return word def replaceWords(self, dict, sentence): """ :type dict: List[str] :type sentence: str :rtype: str """ if not sentence: return '' root_dict = defaultdict(list) for root in dict: root_dict[len(root)].append(root) sentence_list = sentence.split(' ') for i, word in enumerate(sentence_list): word = self.repaceWord(root_dict, word) sentence_list[i] = word return ' '.join(sentence_list) solution = Solution() dict = ["cat", "bat", "rat"] sentence = "the cattle was rattled by the battery" print solution.replaceWords(dict, sentence)
""" author: Fang Ren (SSRL) 9/5/2017 """ """ WAP to modify the array such that arr[I] = arr[arr[I]]. Do this in place i.e. without using additional memory. example : if a = {2,3,1,0} o/p = a = {1,0,3,2} Note : The array contains 0 to n-1 integers. """ import numpy as np a = np.array([2,3,1,0]) #print a[a] print [a[i] for i in a]
""" author: fangren """ class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ zero_count = 0 for num in nums: if num == 0: zero_count += 1 if zero_count > 1: return [0] * len(nums) output = [0] * len(nums) if zero_count == 1: index_zero = nums.index(0) product = 1 for i in nums: if i != 0: product *= i output[index_zero] = product else: first_product = 1 for i in nums[1:]: first_product *= i output[0] = first_product current_product = first_product for i in range(1, len(nums)): current_product = current_product/nums[i]*nums[i-1] output[i] = current_product return output solution = Solution() nums = [1,2,3,4] print solution.productExceptSelf(nums)
from math import sqrt from time import sleep from random import uniform import pygame CAPTION = "~~~" SCREEN_W = 800 SCREEN_H = 600 ACCURACY = 5 MIN_SPEED = 1 MAX_SPEED = 2 class Point: def __init__(self, x, y): self.x = x self.y = y self.dx = uniform(MIN_SPEED, MAX_SPEED) self.dy = uniform(MIN_SPEED, MAX_SPEED) def __eq__(self, other): near_x = abs(self.x - other.x) < ACCURACY near_y = abs(self.y - other.y) < ACCURACY return near_x and near_y def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y) def __mul__(self, number): x = self.x * number y = self.y * number return Point(x, y) def __len__(self): return int(sqrt(self.x**2 + self.y**2)) def pair(self): return int(self.x), int(self.y) class Polyline: def __init__(self): self.points = [] def toggle_point(self, x, y): point = Point(x, y) if point in self.points: self.points.remove(point) else: self.points.append(point) def del_last_point(self): if len(self.points): del self.points[-1] def set_points(self): for i in range(len(self.points)): self.points[i].x += self.points[i].dx self.points[i].y += self.points[i].dy if self.points[i].x > SCREEN_W: self.points[i].dx *= -1 if self.points[i].y > SCREEN_H: self.points[i].dy *= -1 if self.points[i].x < 0: self.points[i].dx *= -1 if self.points[i].y < 0: self.points[i].dy *= -1 def get_avg_dx(self): a = [abs(point.dx) for point in self.points] return sum(a) / len(a) if len(a) else 0 def get_avg_dy(self): a = [abs(point.dy) for point in self.points] return sum(a) / len(a) if len(a) else 0 def change_speed(self, percent): for i in range(len(self.points)): coeff = (100 + percent) / 100 self.points[i].dx *= coeff self.points[i].dy *= coeff @staticmethod def draw_line(gamedisplay, points, color): for i in range(-1, len(points) - 1): curr_p = points[i].pair() next_p = points[i+1].pair() pygame.draw.line(gamedisplay, color, curr_p, next_p, 3) @staticmethod def draw_points(gamedisplay, points, color): for p in points: pygame.draw.circle(gamedisplay, color, p.pair(), 3) class Knot(Polyline): def get_point(self, points, alpha, deg=None): if deg == 0: return points[0] if deg is None: deg = len(points) - 1 return points[deg] * alpha + self.get_point(points, alpha, deg-1) * (1 - alpha) def get_points(self, base_points, count): points = [] alpha = 1 / count for i in range(count): points.append(self.get_point(base_points, i * alpha)) return points def get_knot(self, count): knot = [] if len(self.points) < 3: return knot for i in range(-2, len(self.points) - 2): base_points = [ (self.points[i] + self.points[i+1]) * 0.5, self.points[i+1], (self.points[i+1] + self.points[i+2]) * 0.5 ] knot.extend(self.get_points(base_points, count)) return knot class MyScreenSaver: def __init__(self): self.steps = 35 self.show_help = True self.show_info = True self.working = True self.pause = True self.hue = 0 self.knot = Knot() pygame.init() pygame.display.set_caption(CAPTION) self.color = pygame.Color(0) self.gameDisplay = pygame.display.set_mode((SCREEN_W, SCREEN_H)) def handle_keydown(self, event): if event.key == pygame.K_h: self.show_help = not self.show_help if event.key == pygame.K_i: self.show_info = not self.show_info if event.key == pygame.K_r: self.pause = True self.knot = Knot() if event.key == pygame.K_p: self.pause = not self.pause if event.key == pygame.K_w: self.steps += 1 if event.key == pygame.K_s: self.steps -= 1 if self.steps > 1 else 0 if event.key == pygame.K_q: self.knot.change_speed(5) if event.key == pygame.K_a: self.knot.change_speed(-5) if event.key == pygame.K_ESCAPE: self.working = False def handle_mousebuttondown(self, event): if event.button == 1: x, y = event.pos self.knot.toggle_point(x, y) if event.button == 3: self.knot.del_last_point() def handle_event(self, event): if event.type == pygame.QUIT: self.working = False if event.type == pygame.KEYDOWN: self.handle_keydown(event) if event.type == pygame.MOUSEBUTTONDOWN: self.handle_mousebuttondown(event) def draw_frame(self): self.gameDisplay.fill((0, 0, 0)) self.hue = (self.hue + 1) % 360 self.color.hsla = (self.hue, 100, 50, 100) self.knot.draw_points(self.gameDisplay, self.knot.points, (255, 255, 255)) self.knot.draw_line(self.gameDisplay, self.knot.get_knot(self.steps), self.color) def draw_text(self, x, y, text): color = (255, 255, 255) font = pygame.font.SysFont("serif", 14) self.gameDisplay.blit(font.render(text, True, color), (x, y)) def draw_info(self): lines = [ f'[dx] {self.knot.get_avg_dx():.2f}', f'[dy] {self.knot.get_avg_dy():.2f}', f'[hue] {self.hue}', f'[steps] {self.steps}', f'[points] {len(self.knot.points)}', '[pause]' if self.pause else '' ] for i in range(len(lines)): self.draw_text(10, 10 + 30 * i, lines[i]) def draw_help(self): lines = [ '[esc] exit', '[h] show help', '[i] show info', '[p] pause', '[r] restart', '[q] speed up', '[a] slow down', '[w] more steps', '[s] less steps', '[left click] add / delete point', '[right click] delete last point' ] for i in range(len(lines)): self.draw_text(10, 220 + 30 * i, lines[i]) def run(self): while self.working: for event in pygame.event.get(): self.handle_event(event) if not self.pause: self.knot.set_points() self.draw_frame() if self.show_info: self.draw_info() if self.show_help: self.draw_help() pygame.display.flip() sleep(0.01) pygame.display.quit() pygame.quit() exit(0) if __name__ == "__main__": screen_saver = MyScreenSaver() screen_saver.run()
from sys import argv script, input_file = argv def print_all(f): print(f.read()) def rewind(f): f.seek(0) def print_a_line(line_count, f): print(line_count, f.readline(), end='') # Open the variable file and assign it to a variable current_file = open(input_file) print("First let's print the whole file:\n") # Call the function print_all(current_file) print("Now let's rewind, kind of like a tape.") # Call the function rewind(current_file) print("Let's print three lines:") # Assign value 1 to the variable current_line current_line = 1 # current_line = 1 # Call the function print_a_line(current_line, current_file) # Add the variable current_line by 1 and assign it to variable current_line current_line = current_line + 1 # current_line = 2 # Call the function print_a_line(current_line, current_file) # Add the variable current_line by 1 and assign it to variable current_line current_line = current_line + 1 # current_line = 3 # Call the function print_a_line(current_line, current_file)
# Assign value to the variable with data type integer cars = 100 # Assign value to the variable with data type float space_in_a_car = 4.0 # This makes the number a float type. Not necessary # Assign value to the variable with data type integer drivers = 30 # Assign value to the variable with data type integer passengers = 90 # Assign value to the variable after doing arithmetic operations between variables cars_not_driven = cars - drivers # Assign value to the variable after doing arithmetic operations between variables cars_driven = drivers # Assign value to the variable after doing arithmetic operations between variables carpool_capacity = cars_driven * space_in_a_car # Assign value to the variable after doing arithmetic operations between variables average_passengers_per_car = passengers / cars_driven # Line 10 will produce an error because there is no variable # car_pool_capacity # average_passengers_per_car = car_pool_capacity / passenger print("There are", cars, "cars available.") print("There are only", drivers, "drivers available.") print("There will be", cars_not_driven, "empty cars today.") print("We can transport", carpool_capacity, "people today.") print("We have", passengers, "to carpool today.") print("We need to put about", average_passengers_per_car, "in each car.")
# valores de triangulo maiores que zero # comprimento de um lado tem que ser menor que a soma dos dois lados base = float(input(f'Digite o valor da base: ')) if base <= 0: print(f'valor de {base} inválido! digite novamente ') base = float(input(f'Digite o valor da base: ')) hipotenusa = float(input(f'Digite o valor da hipotenusa: ')) if hipotenusa <= 0: print(f'valor de {hipotenusa} inválido! digite novamente ') hipotenusa = float(input(f'Digite o valor da hipotenusa: ')) altura = float(input(f'Digite o valor da altura: ')) if altura <= 0: print(f'valor de {altura} inválido! digite novamente ') altura = float(input(f'Digite o valor da altura: ')) def triangulo(base, hipotenusa, altura): if base+hipotenusa > altura or base+altura > hipotenusa or hipotenusa+altura > base: if base==hipotenusa and base==altura: print(f'triangulo é equilátero') elif base==hipotenusa or base==altura or altura==hipotenusa: print('Triangulo isoceles ') else: print("triangulo escaleno") triangulo(base, hipotenusa, altura)
class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums[0:] = sorted( nums[0:], reverse = False) global Result Result = [] self.copyResult(nums) while self.nextPermutation(nums)==True: self.copyResult(nums) return Result def copyResult(self, nums): result_combination = [] for i in range(nums.__len__()): result_combination.append(nums[i]) global Result Result.append(result_combination) return 0 def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ for i in range(1,nums.__len__())[::-1]: if nums[i] > nums[i-1]: minindex = i for j in range(i,nums.__len__()): if nums[i-1] < nums[j] and nums[j] < nums[minindex]: minindex = j tmp = nums[minindex] nums[minindex] = nums[i-1] nums[i-1] = tmp nums[i:] = sorted(nums[i:], reverse=False) return True return False
class Solution(object): def reverseString(self, s): stringLength = s.__len__() stringList = list(s) for charIndex in range(stringLength/2): tmp = stringList[charIndex] stringList[charIndex] = stringList[stringLength - charIndex - 1] stringList[stringLength - charIndex - 1] = tmp return ''.join(stringList)
# Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None CurrentDepth = 0 NodeDepth = -1 Node = None class Solution: # @param root, a tree link node # @return nothing def connect(self, root): global CurrentDepth, Node, NodeDepth if (root is None or (root.left is None and root.right is None)): return
class Solution(object): def isPowerOfFour(self, num): """ :type num: int :rtype: bool """ if (num<0): return False oddBit = False bitCount = 0 while (num!=0): print num," ", num&1 if oddBit: oddBit = False else: oddBit = True if (oddBit and num & 1 == 1): print "bit Count + 1" bitCount += 1 if (oddBit == False and num & 1 == 1): return False num = num >> 1 if (bitCount == 1): return True return False print Solution().isPowerOfFour(16) print Solution().isPowerOfFour(234) print Solution().isPowerOfFour(256)
class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ candidates = sorted(candidates) Stack = [] global Result_Combination Result_Combination = [] for i in range(target / candidates[0] + 1): Stack.append(-1) self.DFS(0, 0, Stack, candidates, target) return Result_Combination def DFS(self, item, last_value, Stack, candidates, target): #print "item = ",item, " target = ", target if target < 0: return 0 if target == 0: #find a combinationSum # print "Find Combination..." Result = [] for i in range(item): Result.append(Stack[i]) Result_Combination.append(Result) return 0 for i in range(last_value, len(candidates)): Stack[item] = candidates[i] self.DFS(item+1, i, Stack, candidates, target - candidates[i]) Stack[item] = -1 return 0
import os import math def PushHashTable(x): global HashTable HashTable[ord(x)] = 1 return 0 def PopHashTable(x): global HashTable HashTable[ord(x)] = 0 return 0 def CheckHashTable(x): # if exists, return True # if not exists, return False global HashTable if HashTable[ord(x)] == 1: return True else: return False def max(a,b): if a>b: return a else: return b def LongestSubstring(s): if len(s)>=1: maxLength = 1 else: maxLength = 0 return maxLength global HashTable HashTable = [] for i in range(300): HashTable.append(0) flag_start = 0 flag_ending = 0 StringLength = len(s) PushHashTable(s[flag_start]) while (flag_start < StringLength) and (flag_ending < StringLength): flag_ending += 1 if flag_ending >= StringLength: break if CheckHashTable(s[flag_ending]) == False: PushHashTable(s[flag_ending]) maxLength = max(maxLength, flag_ending - flag_start + 1) continue else: while (flag_start < StringLength) and (flag_ending < StringLength): PopHashTable(s[flag_start]) flag_start += 1 if CheckHashTable(s[flag_ending]) == False: PushHashTable(s[flag_ending]) maxLength = max(maxLength, flag_ending - flag_start + 1) break return maxLength class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ return LongestSubstring(s)
# -*- coding:utf-8 -*- # 计算回测指标 重写 用已经计算好的年化收益率来计算 import pandas as pd import numpy as np from scipy import stats class GetIndex(object): # data: 策略每天的年化收益率 # 有两列数据, # 一列为市场,市场的基准收益, # 一列为策略,为我们的策略收益 def __init__(self, data): self.data = data #每天的年化收益率 self.MD = 0.0 #最大回撤 self.AB = 0.0 #αβ值 self.SHR = 0.0 #夏普比例 self.INR = 0.0 #信息比例 self.indicators = 0.0 #合并的回测结果 # 最大回撤 def max_drawdown(self): #md=((self.data.cummax()-self.data)/self.data.cummax()).max() md = (self.data.cummax()-self.data).max() self.MD = pd.DataFrame(md.values, columns=["最大回撤"], index = md.index) return self.MD # αβ值 def alpha_beta(self): x = self.data["市场"].values y = self.data["策略"].values b,a,r_value,p_value,std_err=stats.linregress(x, y) self.AB = pd.DataFrame([a], columns = ["alpha"], index = ["策略"]) self.AB["beta"] = [b] # print(self.AB) return self.AB # 夏普比例 def sharp(self): # 无风险年化收益率3% exReturn = self.data - 0.03 sharperatio=np.sqrt(len(exReturn))*exReturn.mean()/exReturn.std() self.SHR=pd.DataFrame(sharperatio, columns=["夏普比例"]) return self.SHR # 信息比例 def information(self): ex_return = pd.DataFrame() ex_return = self.data.iloc[:,1] - self.data.iloc[:,0] information=np.sqrt(len(ex_return))*ex_return.mean()/ex_return.std() self.INR=pd.DataFrame([information],columns=['信息比率'], index = ["策略"]) return self.INR # 合并回测策略 def combine(self): self.indicators=pd.concat([self.MD, self.AB, self.SHR, self.INR], axis=1, join='outer') return self.indicators # 计算回测策略 def run(self): self.max_drawdown() self.alpha_beta() self.sharp() self.information() self.combine() # print(self.MD) # print(self.AB) # print(self.SHR) # print(self.INR) return self.indicators if __name__ == "__main__": data1 = [1, -3, -5, 3, -8, 6, 5] data2 = [2,-100, 3, 7, -5, -7, 9] d = {"市场":data1, "策略":data2} data = pd.DataFrame(d) print(data) print(data.cummax()) index = GetIndex(data) md = index.max_drawdown() print(md) print(data["市场"].values, data["策略"].values) a= np.var(data["市场"].values) b=np.cov(data["策略"].values, data["市场"].values) beta = b[0][1]/a print(beta) B,A,r_value,p_value,std_err=stats.linregress(data["市场"].values, data["策略"].values) print(B) ab = index.alpha_beta() print(ab) shr = index.sharp() print(shr) print(data) print(data.iloc[:,0]) print(data.iloc[:,1]) inf = index.information() print(inf) indicators = index.run() print(indicators)
#! python3 # itemRotator.py - Rotates items into and out of a temporary holding queue following a specified amount of time required in the queue # # Usage: Run program twice per day to determine what items can be removed from the waiting queue and what should be added. # The user must enter the itemIDs of those they wish to add to the queue. # # Items in the item shelf are formatted as below: # itemShelf = {'itemID': [TIME_ADDED_TO_SHELF, CURRENT_USAGE_STATUS]} # CURRENT_USAGE_STATUS Possibilities: [TESTING, WAITING, READY] # # @author - Will Parker import shelve, time, sys from pathlib import Path import pyinputplus as pyip from datetime import datetime #----------------------------------------------------- Definitions -----------------------------------------------------# #Prints a divider line to improve readability def dividerLine(): print('\n--------------------------------------------------------------------------------\n') #The possibilities for CURRENT_USAGE_STATUS CURRENT_USAGE_STATUS = ['TESTING', 'WAITING', 'READY'] #For testing purposes the time required to stay in the queue will only be 10 seconds numSecondsInQueue = 10 numMinutesInQueue = 0 numHoursInQueue = 0 numDaysInQueue = 0 #timeInQueue will be the number of seconds the item stays in the queue. Adjust the timeInQueue with the above parameters timeInQueue = numSecondsInQueue + (60 * numMinutesInQueue) + (3600 * numHoursInQueue) + (216000 * numDaysInQueue) #-------------------------------------------------------- What is Waiting? What can be removed? --------------------------------------------------------# #Get the state of the items from the shelf file itemShelf = shelve.open('itemData') #Record the current time so as to determine which items are ready to get dequeued now = time.time() #Get the list of items that are still waiting itemsToWait = {} #Get the list of items in the waiting queue that still have time to go before they can get removed for keys, values in (list(itemShelf.items())): if (values[1] == CURRENT_USAGE_STATUS[1]) and ((now - values[0]) < timeInQueue): #itemsToWait.append(keys) itemsToWait.setdefault(keys, (timeInQueue - (now - values[0]))) queueCounter = 1 if len(itemsToWait) > 0: print('The following items still have time to wait before they can be removed from the waiting queue:\n') for keys, values in itemsToWait.items(): print(str(queueCounter) + ': ', end='') seconds = values formattedSeconds = "{:.0f}".format(values) print(keys + ' - ' + formattedSeconds + ' seconds left in the waiting queue.') queueCounter += 1 dividerLine() #Set up the list that will become the items to dequeue and put back into use itemsToDequeue = [] #Loop through the items in the shelf file. If they are ready to be dequeued, add them to the list and do so for keys, values in (list(itemShelf.items())): if (values[1] == CURRENT_USAGE_STATUS[1]) and ((now - values[0]) >= timeInQueue): itemsToDequeue.append(keys) #Prompt the user to remove items from the waiting queue as needed if len(itemsToDequeue) > 0: print('Please remove the following items from the waiting queue for further use: ') print() removeCounter = 1 for i in range(len(itemsToDequeue)): print(str(removeCounter) + ': ', end='') print(itemsToDequeue[i]) #Set the item's status in the shelf to 'QUALIFIED' and assign a timestamp for removal itemShelf[itemsToDequeue[i]] = [now, CURRENT_USAGE_STATUS[2]] removeCounter += 1 dividerLine() if len(itemsToWait) == 0 and len(itemsToDequeue) == 0: print('There are no items in the waiting queue') dividerLine() #Close the shelf file itemShelf.close() #-------------------------------------------------------- Begin populating log file. --------------------------------------------------------# #Generate log files to maintain record timeStamp = datetime.now() timeStamp = datetime.now() timeStamp = str(timeStamp) timeStamp = timeStamp[0:13] + '_' + timeStamp[14:16] + '_' + timeStamp[17:19] baseFile = str('log_' + timeStamp) logFilePath = Path.cwd() / 'logs' / baseFile logFile = open(logFilePath, 'w') logFile.write('Items still in waiting queue:\n') if len(itemsToWait) == 0: logFile.write('None\n') elif len(itemsToWait) > 0: for keys, values in itemsToWait.items(): formattedSeconds = "{:.0f}".format(values) logFile.write(keys + ' - ' + formattedSeconds + ' seconds left in the waiting queue.\n') logFile.write('\nItems removed from waiting queue:\n') if len(itemsToDequeue) == 0: logFile.write('None\n') elif len(itemsToDequeue) > 0: for i in range(len(itemsToDequeue)): logFile.write(str(i + 1) + ': ' + itemsToDequeue[i] + '\n') logFile.close() #-------------------------------------------------------- What to add to Waiting Queue? --------------------------------------------------------# #Ask the user if any items need to be added to the waiting queue print('Do any items need to be added to the waiting queue?') #Get the user's answer (Yes or No) print() answer = pyip.inputYesNo("Type 'Yes' or 'No' and press Enter: ") print() #The list of items to add to the queue itemsToAdd = [] #True if list of items to add is confirmed. False otherwise. itemsToAddConfirmed = False #If there are items to add to the queue, do so if answer == 'yes': #Open the shelf for manipulation itemShelf = shelve.open('itemData') while itemsToAddConfirmed == False: #Used to number the items in the list itemCounter = 1 print('Enter the itemIDs to add to the waiting queue. Press Enter after each item entry. When done press Enter with no text entered.\n') print(str(itemCounter) + ': ', end='') itemToAdd = input() itemCounter += 1 #Get items until the user is done while (itemToAdd != ''): print(str(itemCounter) + ': ', end='') itemsToAdd.append(itemToAdd) itemToAdd = input() itemCounter += 1 print() #Let the user verify that what they have entered is correct print('You have entered the below items to add to the waiting queue. Is this correct?\n') addCounter = 1 for i in range(len(itemsToAdd)): print(str(addCounter) + ': ', end='') print(itemsToAdd[i]) addCounter += 1 print() response = pyip.inputYesNo("Type 'Yes' or 'No' and press Enter: ") #If the list is correct exit the while loop and add the items to the queue print() if response == 'yes': print('Items have been added to the waiting queue.') dividerLine() itemsToAddConfirmed = True #If the list is incorrect start over (can improve later to edit the items that need to be modified) elif response == 'no': itemsToAdd.clear() dividerLine() elif answer == 'no': dividerLine() #Update the 'now' variable to account for time spent typing, double-checking, etc. now = time.time() #Add the items to the shelf once the list is confirmed for i in range(len(itemsToAdd)): itemShelf[itemsToAdd[i]] = [now, CURRENT_USAGE_STATUS[1]] #Close the shelf file itemShelf.close() #-------------------------------------------------------- Finish the log file. --------------------------------------------------------# logFile = open(logFilePath, 'a') logFile.write('\nItems added to waiting queue:\n') if len(itemsToAdd) == 0: logFile.write('None\n') elif len(itemsToAdd) > 0: for i in range(len(itemsToAdd)): logFile.write(str(i + 1) + ': ' + itemsToAdd[i] + '\n') logFile.close() #-------------------------------------------------------- Exit program. --------------------------------------------------------# print('Please exit the program.') dividerLine() #Close the program sys.exit()
import pygame from node import Node from node_type import NodeType from constants import NODE_SIZE, BORDER, PADDING HORIZONTAL = 0 VERTICAL = 1 class Graph: """Represents a Graph as a grid (2d list).""" def __init__(self, rows, collumns, start=(0, 0), end=None): """Construct a new Graph.""" if end is None: self.end = (rows - 1, collumns - 1) else: self.end = end self.start = start self._grid = [] self.rows = rows self.collumns = collumns for row in range(rows): self._grid.append([]) for col in range(collumns): if (row, col) == self.start: node_type = NodeType.START elif (row, col) == self.end: node_type = NodeType.END else: node_type = NodeType.EMPTY self._grid[row].append(Node(row, col, node_type)) def get_neighbors(self, node: Node): """Returns the neighbors of the specified Node.""" neighbors = [] row, col = node.row, node.col # top if self.__in_grid((row - 1, col)): neighbors.append(self._grid[row - 1][col]) # left if self.__in_grid((row, col - 1)): neighbors.append(self._grid[row][col - 1]) # right if self.__in_grid((row, col + 1)): neighbors.append(self._grid[row][col + 1]) # bottom if self.__in_grid((row + 1, col)): neighbors.append(self._grid[row + 1][col]) return neighbors def __in_grid(self, coordinate): """ Returns if the specified coordinate (row, col) is in this graph's boundary. """ row, col = coordinate return 0 <= row < self.rows and 0 <= col < self.collumns def update_start(self, new_start): """Makes the Node at the specified (row, col) as the start Node.""" if not self.__in_grid(new_start): return old_row, old_col = self.start row, col = new_start self.start = new_start self._grid[old_row][old_col].update_type(NodeType.EMPTY) self._grid[row][col].update_type(NodeType.START) def update_end(self, new_end): """Makes the Node at the specified (row, col) as the end Node.""" if not self.__in_grid(new_end): return old_row, old_col = self.end row, col = new_end self.end = new_end self._grid[old_row][old_col].update_type(NodeType.EMPTY) self._grid[row][col].update_type(NodeType.END) def make_wall(self, coordinate): """Makes the Node at the specified (row, col) as a wall Node.""" if not self.__in_grid(coordinate): return node = self.get(coordinate) if node.is_start() or node.is_end(): return node.update_type(NodeType.WALL) def make_empty(self, coordinate): """Makes the Node at the specified (row, col) as an empty Node.""" if not self.__in_grid(coordinate): return node = self.get(coordinate) if node.is_start() or node.is_end(): return node.update_type(NodeType.EMPTY) def is_wall(self, coordinate): """Returns if the Node at the specified (row, col) is a wall.""" if not self.__in_grid(coordinate): return False node = self.get(coordinate) return node.is_wall() def is_empty(self, coordinate): """Returns if the Node at the specified (row, col) is empty.""" if not self.__in_grid(coordinate): return False node = self.get(coordinate) return node.is_empty() def is_start(self, coordinate): """Returns if the Node at the specified (row, col) is a start Node.""" return coordinate == self.start def is_end(self, coordinate): """Returns if the Node at the specified (row, col) is an end Node.""" return coordinate == self.end def toggle_wall(self, coordinate): """ Makes the Node at the specified (row, col) empty if it's a wall; otherwise a wall. """ if not self.__in_grid(coordinate): return node = self.get(coordinate) if node.is_empty() or node.is_path() or node.is_visited(): self.make_wall(coordinate) elif self.is_wall(coordinate): self.make_empty(coordinate) def get_start_node(self): """Gets the start Node of this Graph.""" return self.get(self.start) def get_end_node(self): """Gets the end Node of this Graph.""" return self.get(self.end) def get(self, coordinate): """Gets the Node at the specified (row, col).""" if not self.__in_grid(coordinate): return row, col = coordinate return self._grid[row][col] def get_grid(self): """Returns the grid of this graph.""" return self._grid def clear_path(self): """ Resets the boards by making all visited Node and path Node into empty node. """ for row in self._grid: for node in row: if node.is_path() or node.is_visited(): node.update_type(NodeType.EMPTY) def clear(self): """ Resets the boards by making all nodes empty and set the start Node at top left corner and end Node at bottom right corner. """ self.start = (0, 0) self.end = (self.rows - 1, self.collumns - 1) for row in self._grid: for node in row: node.update_type(NodeType.EMPTY) self._grid[0][0].update_type(NodeType.START) self._grid[self.end[0]][self.end[1]].update_type(NodeType.END) def draw(self, window): """Draws this Graph on the specified window.""" self.__draw_nodes(window) self.__draw_line(window) pygame.display.update() def __draw_line(self, window): """Draws the border between each node on the specified window.""" # top of the Graph top = PADDING # bottom of the Graph bottom = NODE_SIZE * self.rows + PADDING # left side of the Graph left = PADDING # right side of the Graph right = NODE_SIZE * self.collumns + PADDING for i in range(self.rows + 1): y = i * NODE_SIZE + PADDING pygame.draw.line(window, BORDER, (left, y), (right, y)) for j in range(self.collumns + 1): x = j * NODE_SIZE + PADDING pygame.draw.line(window, BORDER, (x, top), (x, bottom)) def __draw_nodes(self, window): """Draws the nodes of this graph on the specified window.""" for row in self._grid: for node in row: node.draw(window)
import random a = [1,3,5,6,8,9] for i in range(10): chose1 = random.choice(a) print(chose1)
import math class Vector(): def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): x = self.x + other.x y = self.y + other.y return Vector(x, y) def __float__(self): return math.hypot(self.x, self.y) # 平方根函数 def __mul__(self, beishu): x = self.x * beishu y = self.y * beishu return Vector(x, y) def __str__(self): return 'Vector(%s,%s)' % (self.x, self.y) mo = __float__ # 因为hypot返回的是float型,所有必须是特殊方法__float__或者__abs__(目前我已知的),但是这样就不直观,所以有这句话 v1 = Vector(2, 3) v2 = Vector(4, 4) v3 = v1.__add__(v2) v4 = v1 + v2 print(v3, v4) print(v3.mo(), v3.__float__(), float(v3))
print(list(range(10))) print([x*x for x in range(1,11)]) print([m+n for m in 'ABC' for n in 'XYZ']) for m in 'abc': for j in 'def': for k in 'hij': print(m+j+k) print([x * x for x in range(1, 11) if x % 2 == 0]) print([x * x for x in range(1, 11)[1::2]]) import os print([d for d in os.listdir('.')]) L1 = ['Hello', 'World', 18, 'Apple', None] L2 = [s.lower() for s in L1 if isinstance(s, str)] print(L2) g=(x*x for x in range(10)) # print(g.next()) # print(g.next()) # print(g.next()) # print(g.next()) # print(g.next()) # print(g.next()) # print(next(g))
print(dict(a='ad',b=2)) print(dict([('1',2),('a',3)])) print(dict(zip(['a','b'],[1,2]))) print(["data{}".format(i) for i in range(100) if i % 2 == 0]) print([f"data{i}" for i in range(100) if i % 2 == 0]) print([f"data{i}" if i % 2 == 0 else f"lemon{i}" for i in range(100)]) a = ([f"data{i}" if i % 2 == 0 else f"lemon{i}" for i in range(100)]) li = ['gao', 'ao', 'lei'] print({k: v for k, v in enumerate(li)}) print({i[0]: i[1] for i in enumerate(li)}) print({k: v for k, v in enumerate(li) if k > 0}) # print({k: v.upper() if v.startswith('a') else k: v for k, v in enumerate(li)}) 不支持三目? # 列表推导式 dic = {'a': 1, 'b': 2, 'c': 3} res = [(k, v) for k, v in dic.items()] print(res) # [('a',1),('b',2),('c',3)] res = ((k, v) for k, v in dic.items()) print(list(res)) print(tuple(res)) # 结果为空,因为上一条已经将值取走了 ''' Iterable() 可迭代对象 Iterator() 迭代器,继承自Iterable Generator() 生成器,继承自Iterator ''' from collections.abc import Iterable,Iterator,Generator a,b = {1,2} print(a,b) name = "Fred" print(f"He said his name is {repr(name)}")
# _*_coding:utf-8_*_ choose = input('输入s或者p:') if choose == 's': class Student(object): # 将方法变成属性 @property def score(self): return self._score @score.setter def score(self,value): if (not isinstance(value,int)) or value<0 or value>100: raise ValueError('成绩必须为0-100间整数') self._score=value s=Student() s.score=99 print(s.score) else: class People(object): @property def birth(self): return self._birth @birth.setter def birth(self, value): self._birth = value @property def age(self): return 2017 - self._birth p=People() p.birth=2011 print(p.birth) print(p.age) p.ti=100 print(p.ti)
import tkinter as tk window = tk.Tk() window.title("my win") window.geometry('400x400') l = tk.Label(window, bg='yellow', width=20, text=None) l.pack() var1 = tk.StringVar() def print_selection(e): l.config(text='you have selected ' + var1.get()) # HORIZONTAL 横向,tickinterval 标签单位长度 resolution 保留两位小数 s = tk.Scale(window, label='try me', from_=2, to=20, orient=tk.HORIZONTAL, length=200, showvalue=0, tickinterval=3, resolution=0.01, variable=var1, command=print_selection) s.pack() window.mainloop()
# Linear Regression with Gradient Descent # Import packages import numpy as np import pandas as pd import matplotlib.pyplot as plt # Set parameters for figure plt.rcParams['figure.figsize'] = (12.0, 9.0) # Preprocessing input data # Read the file with pandas data = pd.read_csv('linear_regression_data.csv', header=None) # Define variables from columns in the dataset. iloc integer based position. x = data.iloc[:,0] # 0 column is x y = data.iloc[:,1] # 1 column is y # Plot the dataset with matplotlib plt.scatter(x,y) plt.show() # Now lets build the model theta0 = theta1 = 0 # define linear equation parameters, set to zero alpha = 0.0002 # learning rate num = 100000 # number of iterations to perform gradient descent n = float(len(x)) # number of elements in x # Perform gradient descent for i in range(num): htheta = theta0 + theta1*x # hypothesis function d0 = 1/n*(sum(htheta-y)) # derivative with respect to j=0 d1 = 1/n*(sum(x*(htheta-y))) # derivative with respect to j=1 theta0 = theta0 - alpha*d0 theta1 = theta1 - alpha*d1 print(theta0, theta1) plt.scatter(x,y) plt.plot([min(x), max(x)], [min(htheta), max(htheta)], color='red') # regression line plt.show()
print("1. Arithmetic") print("2. Comparision") c=int(input("Enter your choice (1,2 or 3) ")) if(c==1): print("1. Addition") print("2. Subtraction") print("3. Multiplication") print("4. Division") o=int(input("Enter the operation(1,2,3 or 4) ")) a=int(input("Enter first number")) b=int(input("Enter second number")) if(o==1): res=a+b print("Addition of the number: ",res) elif(o==2): res=a-b print("Subtraction of the number: ",res) elif(o==3): res=a*b print("Multiplication of the number: ",res) else: res=a//b print("Division of the number: ",res) elif(c==2): a=int(input("Enter first number")) b=int(input("Enter second number")) if(a>b): print(a," is greater than ",b) elif(a<b): print(a," is less than ",b) elif(a==b): print(a," is equal to ",b) else: print("Invalid input")
''' Find longest palindromic substring Manacher's Algorithm ''' def longest_palondromic_substring(s): mid = len(s) // 2 # initialize s[i][i] = False T = [[False for i in range(0, len(s))] for i in range(0, len(s))] for i in range(0, len(T)): T[i][i] = False mx = 1 for l in range(2, len(s) + 1): length = 0 for i in range(0, len(s) - l + 1): j = i + l - 1 print(s[i], s[j]) length = 0 if l == 2: if s[i] == s[j]: T[i][j] = True length = 2 else: if s[i] == s[j] and T[i + 1][j - 1] == True: T[i][j] = True print(T) length = j - i + 1 if length > mx: mx = length return mx def longestPalindrome(s): res = "" for i in range(len(s)): # odd case, like "aba" tmp = helper(s, i, i) if len(tmp) > len(res): res = tmp # even case, like "abba" tmp = helper(s, i, i + 1) if len(tmp) > len(res): res = tmp return res # get the longest palindrome, l, r are the middle indexes # from inner to outer def helper(s, l, r): while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1 r += 1 return s[l + 1:r] def n_squared(s): if s is None or len(s) < 1: return "" start = 0 end = 0 for i in range(0, len(s)): # odd case len1 = expand(s, i, i) # even case len2 = expand(s, i, i + 1) ll = max(len1, len2) print("i", i) print("end", end, "start", start) if ll > end - start: start = i - end - start // 2 end = (i + ll) // 2 return s[start:end + 1] def expand(s, left, right): l = left r = right while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1 r += 1 return r - l - 1 t1 = "babad" # r = longest_palondromic_substring(t1) # print(r) r = n_squared(t1) print(r)
''' Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5. O(n) solution exits with O(1) space. ''' # S = lst[i] + lst[j], such that j != i + 1 and j != i - 1 ''' 0: [2, 5] 1: [2, 6, 5] 2: [4, 2] 3: [4, 5] ''' def largest_adj_sum(lst): incl = 0 excl = 0 new_excl = 0 i = 0 while i < len(lst): new_excl = excl if excl > incl else incl incl = excl + lst[i] excl = new_excl i += 1 return max(incl, excl) # return 13 t1 = [2, 4, 6, 2, 5] t2 = [5, 1, 1, 5] res = largest_adj_sum(t2) print(res)
#!/usr/bin/env python # coding: utf-8 # In[ ]: class Solution(object): def merge(self, intervals): """ :type intervals: List[List[int]] :rtype: List[List[int]] """ intervals.sort(key= lambda x:x[0]) merged=[] for interval in intervals: if not merged or interval[0]>merged[-1][1]: merged.append(interval) else: merged[-1][1]=max(merged[-1][1],interval[1]) return merged
#!/usr/bin/env python # coding: utf-8 # In[ ]: class Solution(object): def validPalindrome(self, s): """ :type s: str :rtype: bool """ isPalindrome = lambda x: x == x[::-1] left, right = 0, len(s) -1 while left <= right: if s[left] == s[right]: left += 1 right -= 1 else: #print(left+1,right+1,s[left+1:right+1]) #print(left,right,s[left:right]) return isPalindrome(s[left+1:right+1]) or isPalindrome(s[left:right]) return True
#!/usr/bin/env python # coding: utf-8 # In[ ]: class Solution(object): def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: None Do not return anything, modify board in-place instead. """ row = [set(range(1,10)) for _ in range(9)] col = [set(range(1,10)) for _ in range(9)] box = [set(range(1,10)) for _ in range(9)] empty = [] for i in range(9): for j in range(9): if board[i][j] !=".": val = int(board[i][j]) row[i].remove(val) col[j].remove(val) box[(i//3)*3+j//3].remove(val) else: empty.append((i,j)) def backtrack(iter = 0): if iter == len(empty): return True i,j = empty[iter] b = (i//3) * 3 + j//3 for val in row[i] & col[j] & box[b]: row[i].remove(val) col[j].remove(val) box[b].remove(val) board[i][j] = str(val) if backtrack(iter+1): return True row[i].add(val) col[j].add(val) box[b].add(val) return False backtrack()
#!/usr/bin/env python # coding: utf-8 # In[ ]: class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if len(nums) == 0: return -1 left,right = 0, len(nums)-1 while left < right: mid = (right-left)// 2 +left if nums[mid] == target: return mid if nums[mid] > nums[left]: if nums[left] <= target <= nums[mid]: right = mid else: left = mid+1 else: if nums[mid+1] <= target <= nums[right]: left = mid +1 else: right = mid if nums[left] == target: return left else: return -1
class LinkedList: def __init__(self, head): node = Node(head, None) self.head = node self.tail = None self.length = 1 def insert_at_beginning(self, value): node = Node(value, self.head) self.head = node self.tail = node self.length += 1 def insert_after_value(self, data_after, data_to_insert): ptr = self.head while ptr.value != data_after: ptr = ptr.next node = Node(data_to_insert, ptr.next) ptr.next = node self.length+=1 def insert_at(self, value, index): if index == self.length: self.insert_at_end(value) self.length += 1 if index == 0: self.insert_at_beginning(value) self.length += 1 return ptr = self.head count = 0 while ptr: if count == index - 1: node = Node(value, ptr.next) ptr.next = node self.length+=1 break ptr = ptr.next count += 1 def remove_by_value(self, value): ptr = self.head count = 0 while ptr.value != value: count += 1 ptr = ptr.next self.remove_at(count) def pop(self): ptr = self.head while ptr.next is not None: prev = ptr ptr = ptr.next prev.next = None self.tail = prev self.length -= 1 def remove_at(self, index): if index == 0: self.head = self.head.next self.length -= 1 return if index == self.length: self.pop() ptr = self.head count = 0 while ptr: if count == index - 1: ptr.next = ptr.next.next self.length -= 1 break ptr = ptr.next count += 1 def insert_at_end(self, value): if self.length == 0: self.insert_at_beginning(value) return ptr = self.head while ptr.next: ptr = ptr.next ptr.next = Node(value, None) self.tail = ptr.next self.length += 1 def print_list(self): if self.head is None: print("List is empty") return ptr = self.head output = "" while ptr: output += str(ptr.value) + " --> " ptr = ptr.next print(output) def reverse_list(self): next = None prev = None node = self.head self.head = self.tail self.tail = node for i in range(0,self.length): next = node.next node.next = prev prev = node node = next class Node: def __init__(self, value, next): self.value = value self.next = next if __name__ == '__main__': myLinkedList = LinkedList(10) myLinkedList.insert_at_beginning(9) myLinkedList.insert_at_beginning(7) myLinkedList.insert_at_end(8) myLinkedList.remove_at(1) myLinkedList.insert_at(5, 2) myLinkedList.insert_after_value(10, 51) myLinkedList.remove_by_value(51) myLinkedList.insert_at_end(10) myLinkedList.pop() myLinkedList.pop() myLinkedList.insert_at_end(15) myLinkedList.print_list() print(myLinkedList.head.value) print(myLinkedList.tail.value) myLinkedList.reverse_list() myLinkedList.print_list()
import numpy as np import random from scipy import linalg as la import pdb def random_chain(n): """Create and return a transition matrix for a random Markov chain with 'n' states. This should be stored as an nxn NumPy array. plan: create a random matrix, use scipy to normalize the columns, then return it """ #create a random matrix A = np.random.random((n,n)) #construct it so the columns add up to one B = np.sum(A,axis = 0) # the difficulty is getting it to broadcast appropriately # website of reference - only minorly helpful - https://stackoverflow.com/questions/19602187/numpy-divide-each-row-by-a-vector-element return A / B def forecast(n): """Forecast n next days of weather given that today is hot.""" transition = np.array([[0.7, 0.6], [0.3, 0.4]]) weather = [] previous_conditions = 0 # Sample from a binomial distribution to choose a new state. #change the weather based upon previous day's conditions for _ in range(n): #if previous day was warm if previous_conditions == 0: weather.append(np.random.binomial(1, transition[1, 0])) #if the previous day was cold else: weather.append(np.random.binomial(1, transition[1, 1])) previous_conditions = weather[-1] return weather def four_state_forecast(days): """Run a simulation for the weather over the specified number of days, with mild as the starting state, using the four-state Markov chain. Return a list containing the day-by-day results, not including the starting day. Examples: >>> four_state_forecast(3) [0, 1, 3] >>> four_state_forecast(5) [2, 1, 2, 1, 1] """ four_state = np.array( [ [0.5, 0.3, 0.1, 0 ], [0.3, 0.3, 0.3, 0.3], [0.2, 0.3, 0.4, 0.5], [0, 0.1, 0.2, 0.2] ]) weather = [] previous_conditions = 1 for _ in range(days): if previous_conditions == 0: weather.append(np.argmax(np.random.multinomial(1, four_state[:,0]))) elif previous_conditions == 1: weather.append(np.argmax(np.random.multinomial(1, four_state[:,1]))) elif previous_conditions == 2: weather.append(np.argmax(np.random.multinomial(1, four_state[:,2]))) else: weather.append(np.argmax(np.random.multinomial(1, four_state[:,3]))) previous_conditions = weather[-1] return weather def steady_state(A, tol=1e-12, N=400): """Compute the steady state of the transition matrix A. Inputs: A ((n,n) ndarray): A column-stochastic transition matrix. tol (float): The convergence tolerance. N (int): The maximum number of iterations to compute. Raises: ValueError: if the iteration does not converge within N steps. Returns: x ((n,) ndarray): The steady state distribution vector of A. """ m,n = np.shape(A) #generate random state distribution vector xNaught = np.random.random(n) #the random vector elements must sum to one temp = np.sum(xNaught,axis = 0) x = xNaught / temp k = 0 #calculate limit of x as k approaches N while True: xPlus = A @ x #if the vector is less than the tolerance then return it if la.norm(xPlus - x) < tol: break else: x = xPlus if k >= N: raise ValueError("transition matrix does not converge") else: k+= 1 return x def steady_state_test(): """ test the steady state function""" transition = np.array([[0.7, 0.6], [0.3, 0.4]]) two_by_two_vector_limit = np.array([2/3,1/3]) print(steady_state(transition),two_by_two_vector_limit, sep='\n') four_state = np.array( [ [0.5, 0.3, 0.1, 0 ], [0.3, 0.3, 0.3, 0.3], [0.2, 0.3, 0.4, 0.5], [0, 0.1, 0.2, 0.2] ]) # four_state_vector_limit = np.array([]) class SentenceGenerator(object): """Markov chain creator for simulating bad English. Attributes: (what attributes do you need to keep track of?) Example: >>> yoda = SentenceGenerator("Yoda.txt") >>> print(yoda.babble()) The dark side of loss is a path as one with you. """ def __init__(self, filename): """Read the specified file and build a transition matrix from its contents. You may assume that the file has one complete sentence written on each line. """ library = set() #read in the content with open(filename, 'r') as myfile: contents = myfile.readlines() #segment each line into sublists for i in range(len(contents)): contents[i] = contents[i].strip().split(' ') # contents[i] = contents[i].split(' ') #for each sublist, add each entry to the library set for j in range(len(contents)): # for j in range(3): #to see a small subset of the file l = len(contents[j]) for k in range(l): library.add(contents[j][k]) count = len(library) #initialize as a data member for use in the babble method self.count = count #the matrix maps the column word to the next word in the sentence to the row corresponding to the next word #the domain is the columns, mapping to the rows matrix = np.zeros((count+2,count+2)) indices = {"$tart":0,"$top":count+1} #j represents the index j = 1 #iterate through the set adding it to the dictionary with a index for i in library: indices.update({i:j}) j += 1 if j >= count + 2: raise ValueError("error with index") #intialize for use in the babble method self.indices = indices #for each sentence for sentence in contents: #connect $start with first word which has index 0 NOT ONE!!!!!!! matrix[indices.get(sentence[0])][0] += 1 #for each word in the sentence map it to the next word and it's column increasing count by 1 l = len(sentence) for k in range(l): # pdb.set_trace() #if it's the last word in the sentence it needs to map to stop if k == l-1: matrix[-1][indices.get(sentence[k])] += 1 else: matrix[indices.get(sentence[k+1])][indices.get(sentence[k])] += 1 #map stp to stop matrix[-1][-1] += 1 #adjust each column so the sum is one temp = np.sum(matrix,axis = 0) matrix = matrix / temp #initialize for use in the babble self.matrix = matrix def babble(self): """Begin at the start sate and use the strategy from four_state_forecast() to transition through the Markov chain. Keep track of the path through the chain and the corresponding words. When the stop state is reached, stop transitioning and terminate the sentence. Return the resulting sentence as a single string. """ #string to be printed declaration = "" previous_conditions = 0 #add a word until the final word is $top while previous_conditions < (self.count + 1): #the index of the random multinomial sample word_index = np.argmax(np.random.multinomial(1, self.matrix[:,previous_conditions])) #find the word for the given index word = list(self.indices.keys())[list(self.indices.values()).index(word_index)] if word != "$top": declaration += word + " " #set the previous condition with the probabilities for the next sample previous_conditions = word_index return declaration if __name__ == "__main__": pass """ favorites babbles: yoda mourn them do not, miss them do not trump: We don't want the country that's happened. Hey, I'm with our values? for more text processing - see this website https://www.gutenberg.org/ """ # print(random_chain(2)) # print(forecast(3)) # print(four_state_forecast(3)) # steady_state_test() # file = SentenceGenerator("trump.txt") # file = SentenceGenerator("yoda.txt") #count is 687 unique words # file = SentenceGenerator("tswift1989.txt") # file = SentenceGenerator("sample.txt") # print(file.babble()) #for trump the count is 11802 unique words, so thats a big matrix
import numpy as np a = input("Enter string : ") nth = int(input("Enter nth: ")) if len(a)<nth: print("Not Possible") else: f=np.array([a[:nth]]) l=np.array([a[nth+1:]]) print(np.concatenate((f,l),axis=0))
# Day05 # The first line contains an integer, N (the size of our array).\ # The second line contains N space-separated integers that describe array A's elements # Print the elements of array A in reverse order as a single line of space-separated numbers # The code starts here: N = int(input()) A = list(map(int,input().rstrip().split())) [:N] # For loop for reverese order array element for i in range(N-1, -1, -1): print(A [i], end = " ")
answer = 'yes' print "guess a number between 1 and 1000" while answer == 'yes': numoftry = 10 numtoguess = 500 limitlow = 1 limithigh = 1000 while numoftry != 0: try: print numtoguess print "type 1 if guess is too high" print "type 2 if guess is too low" print "type 3 if guess is right" humananswer = int(input() if 1 < humananswer > 3: print "enter valid answer" numoftry = numoftry + 1 if humananswer == 1 limithigh = numtoguess
#High low guessing game. def show_instructions(): print '''pick a number between 1 and 1000 and I will try to guess it. I can do this in no more then 10 guesses. After each guess, enter: 0 - if I got it right -1 - if I guessed too high 1 - if I guessed too low.''' def take_guess(): low = 1 high = 1000
# Given two sorted list. We need to merge these two list such that the initial numbers (after complete sorting) # are in the first list and the remaining numbers are in the second list. Extra space allowed in O(1). # # Example: # # Input: ar1 = [10] # ar2 = [2, 3] # Output: ar1 = [2] # ar2 = [3, 10] # # Input: ar1 = [1, 5, 9, 10, 15, 20] # ar2 = [2, 3, 8, 13] # Output: ar1 = [1, 2, 3, 5, 8, 9] # ar2 = [10, 13, 15, 20]
import random as rn def noReplacementSimulation(numTrials): ''' Runs numTrials trials of a Monte Carlo simulation of drawing 3 balls out of a bucket containing 3 red and 3 green balls. Balls are not replaced once drawn. Returns the a decimal - the fraction of times 3 balls of the same color were drawn. ''' reds = [1, 2, 3] greens = [4, 5, 6] allballs = reds + greens balls = 0 for i in range(numTrials): if rn.choice(allballs) in reds: balls += 1 return balls print noReplacementSimulation(3)
# -*- coding: utf-8 -*- """ Created on Tue Sep 11 00:46:34 2018 @author: Shilpi """ N = int(input()) myList = [] for i in range(0,N): i = input() myList.append(i) for j in myList: j_eve = "" j_odd = "" for k in range(0, len(j)): if k%2 == 0: j_eve+=j[k] else: j_odd+=j[k] print(j_eve + " "+ j_odd)
def findBestShift(wordList, text): """ Finds a shift key that can decrypt the encoded text. text: string returns: 0 <= int < 26 """ ### TODO noWords=0 bestShift=0 Shift=0 while Shift<26: decodedMessage = applyShift(text,Shift) words = decodedMessage.split(" ") counter = 0 for w in words: if isWord(wordList,w)==True: counter +=1 if counter > noWords: noWords = counter bestShift = Shift Shift += 1 return bestShift """ >>> s = applyShift('Hello, world!', 8) >>> s 'Pmttw, ewztl!' >>> findBestShift(wordList, s) 18 >>> applyShift(s, 18) 'Hello, world!'""" def decryptStory(): """ Using the methods you created in this problem set, decrypt the story given by the function getStoryString(). Once you decrypt the message, be sure to include as a comment your decryption of the story. returns: string - story in plain text """ ### TODO story = getStoryString() wordList = loadWords() return applyShift(story,findBestShift(wordList,story)) if __name__ == '__main__': decryptStory()
class BankAccount: all_accounts = [] def __init__(self, int_rate, balance = 0): self.int_rate = int_rate self.balance = balance def make_deposit(self, amount): self.balance += amount return self def make_withdrawal(self, amount): if self.balance < 0: print('insufficient funds: Charging a $5 fee') self.balance -= 5 else: self.balance -= amount return self def display_account_info(self): print('Balance:', self.balance) return self def yeild_interest(self): if self.balance>0: self.int_rate = 0.01 self.balance = self.balance * (1+self.int_rate) return self Batou = BankAccount(0.5, 0) Major = BankAccount(0.5, 0) Batou.make_deposit(100).make_deposit(200).make_deposit(300).make_withdrawal(50).yeild_interest().display_account_info() Major.make_deposit(1000).make_deposit(2000).make_withdrawal(100).make_withdrawal(100).make_withdrawal(200).make_withdrawal(200).yeild_interest().display_account_info()
a=1 for i in range(0, 5): a=1 for j in range(0,i+1): print(a, end = ' ') a = a + 1 print('\r')
# Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused. # You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid. # Example 1: # Input: "19:34" # Output: "19:39" # Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours and 59 minutes later. # Example 2: # Input: "23:59" # Output: "22:22" # Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22. It may be assumed that the returned time is next day's time since it is smaller # Simulate the clock. def NextClosetTime2(time): cur = 60 * int(time[:2]) + int(time[3:]) print("cur=", cur) allowed = {int(x) for x in time if x != ':'} while True: cur = (cur + 1) % (24 * 60) print("cur=(cur + 1) % (24 * 60)",cur) if all(digit in allowed for block in divmod(cur, 60) for digit in divmod(block, 10)):# divmod(a,b)=(a//b,a%b) return "{:02d}:{:02d}".format(*divmod(cur, 60)) # Ta sử dụng % để xử lý khi một số nào đó vượt quá một ngưỡng mà quay lại số ban đầu. VD. 1%12 = 13%12 =1. # Lợi dụng điều này, ta sẽ đặt 12 là ngưỡng. Một variable tăng dần, nếu >12 thì coi như quay lại là 1. #print(NextClosetTime2("19:34")) print(NextClosetTime2("13:59"))
# Given a binary array, find the maximum number of consecutive 1s in this array. # # Example 1: # Input: [1,1,0,1,1,1] # Output: 3 # Explanation: The first two digits or the last three digits are consecutive 1s. # The maximum number of consecutive 1s is 3. ######################################################################################################################## def MaxConsecutiveOnes(s): i, maxlength = 0, 0 while (i < len(s)): count = 0 # to count number of ones while i < len(s) and s[i] == 1: # để tránh out of range of s count += 1 i = i + 1 maxlength = max(maxlength, count) i=i+1 print(maxlength) return maxlength # print(MaxConsecutiveOnes([1, 1, 0, 1, 1, 1])) # print(MaxConsecutiveOnes([1,1,1,1,0,0,0,0,1,1])) # điểm đặc biệt là: # * Chỉ sử dụng i cho cả while vòng trong và vòng ngoài # * Check điều kiện i < len(s) ở cả 2 vòng while # Phương pháp này chỉ là O(n) bởi tuy là 2 vòng while lồng nhau nhưng thực chất với mỗi phần tử, ta chỉ duyệt qua một lần ######################################################################################################################## # 2. Ta duyệt toàn bộ list, cứ gặp 0 thì ta reset count. Còn cứ gặp 1 thì count tăng 1 def MaxConsecutiveOnes2(s): count, maxlength=0,0 for i in s: if i==1: count+=1 maxlength=max(maxlength,count) else: count=0 return maxlength print(MaxConsecutiveOnes2([1, 1, 0, 1, 1, 1])) print(MaxConsecutiveOnes2([1,1,1,1,0,0,0,0,1,1]))
# You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. # Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase. # Given a non-empty string S and a number K, format the string according to the rules described above. # Example 1: # Input: S = "5F3Z-2e-9-w", K = 4 # Output: "5F3Z-2E9W" # Explanation: The string S has been split into two parts, each part has 4 characters. # Note that the two extra dashes are not needed and can be removed. # Example 2: # Input: S = "2-5g-3-J", K = 2 # Output: "2-5G-3J" # Explanation: The string S has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above. ############################################################################################################################ def LisenseKeyFormat(s, K): s = str.upper(s).replace("-", "") print(s) remainder = len(s) % K s1 = "" if remainder != 0: s1 = s[:remainder] s1 = s1 + "-" i = remainder while (i + K <= len(s)): s1 = s1 + s[i:i + K] + "-" i = i + K print(s1) s1 = s1[:-1] print(s1) return s1 ############################################################################################################################ # improve def LisenseKeyFormat2(S, K): S = str.upper(S).replace("-", "") remainder = len(S) % K s1 = S[:remainder]+"-" if remainder != 0 else "" i = remainder while (i < len(S)): s1 = s1 + S[i:i + K] + "-" # i+ K has no problem of over index i = i + K print(s1) s1 = s1[:-1] print(s1) return s1 LisenseKeyFormat2("5F3Z-2e-9-w", 4) LisenseKeyFormat2("2-5g-3-j", 2)
from numpy import diff def pairedMovement(a, b): """If both klines go up, go up.""" output = [1] for i in range(0, len(a)): if i == 0: continue elif a[i - 1] < a[i] and b[i - 1] < b[i]: # Go up output.append(output[i - 1] + 1) elif a[i - 1] > a[i] and b[i - 1] > b[i]: output.append(output[i - 1] - 1) else: output.append(output[i - 1]) return output def pairedWave(a, b): """If both klines go up, give one.""" output = [] for i in range(0, len(a)): if i == 0: continue diffA = a[i] - a[i - 1] diffB = b[i] - b[i - 1] output.append((diffA + diffB) / 2) output.append(output[0]) return output
nome=input('Qual é o seu nome?') idade=input('Qual é a sua idade?') hobbie=input('Qual é o seu Hobbie?') print('Meu nome é: ' + nome,'e minha idade é: ' + idade,'e gosto de: ' + hobbie)
import re patterns = ['term1', 'term2'] text = 'This is a string with term1, but it does not have the other term.' for pattern in patterns: print('Searching for "%s" in: \n"%s"'%(pattern,text)) if re.search(pattern, text): print('\n') print('Match was found. \n') else: print('\n') print('No Match was found.\n') pattern = 'term1' text = 'This is a string with term1, but it does not have the other term.' match = re.search(pattern,text) type(match) print(match.start()) print(match.end()) split_term = '@' phrase = 'What is the domain name of someone with the email:hello@email.com' print(re.split(split_term,phrase)) print(re.findall('match', 'test phrase match is in middle')) def multi_re_find(patterns,phrase): for pattern in patterns: print('Searching the phrase using the re check: %r'%pattern) print(re.findall(pattern, phrase)) print('\n') test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dssss...sdddd' test_patterns = ['sd*','sd+','sd?','sd{3}','sd{2,3}',] print(multi_re_find(test_patterns,test_phrase)) test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dssss...sdddd' test_patterns = ['[sd]', 's[sd]+'] print(multi_re_find(test_patterns,test_phrase)) test_phrase = 'This is a string! But it has punctuation. How can we remove it?' print(re.findall('[^abcdefgh]+', test_phrase)) test_phrase = 'This is an example sentence. Lets see if we can find some letters.' test_patterns=[ '[a-z]+', '[A-Z]+', '[a-zA-Z]+', '[A-Z][a-z]+'] print(multi_re_find(test_patterns,test_phrase))
#Tuplas t = (1,2,3) print(len(t)) #Variação tipos de dados t = ('one', 2) print(t) #indexação print(t[0]) #corte de dados print(t[-1]) #Métodos basicos da Tupla #use .index() com o valor de parâmetro para retornar o indice do mesmo print(t.index('one')) #use .count() com o valor de parâmetro para retornar o indice do mesmo print(t.count('one')) #imutabilidade #t[0] = 'change' #t.append('nope') #As tuplas não podem crescer, as tuplas são imutáveis.Esses dois comandos se #executados irá acarretar em erro.
a = [8, 1, 2, 3, 0, 0, 0, 0] for i in range(7, 0): print(a[i]) print(range(0,7)) print(range(7, -1, -1))
dia = input('Dia?') mês = input('Mês?') ano = input('Ano?') print('Você nasceu no dia',dia,'de',mês,'de',ano,',Correto?')
from syntax import * import sys def main(): if len(sys.argv) < 2: print("Too few arguments in function main. A Starlet script should be passed as an argument.") exit(0) elif len(sys.argv) > 2: print("Too many arguments in function main. A Starlet script should be passed as an argument.") exit(0) try: file = open(sys.argv[1], "r") except (FileNotFoundError, IOError): sys.exit("Error opening file " + sys.argv[1] + ". Please, check input file and try again.") exit(0) syntax() main()
# -*- coding: utf-8 -*- """ Created on Thu Nov 22 21:27:09 2018 @author: V510 """ import numpy as np import tensorflow as tf import random as rn import os os.environ['PYTHONHASHSEED'] = '0' np.random.seed(36) rn.seed(777) tf.set_random_seed(89) from keras import backend as K sess = tf.Session(graph = tf.get_default_graph()) K.set_session(sess) from keras.models import Sequential from keras.layers import Convolution2D # 2D is for images unlike videos that are 3D from keras.layers import MaxPool2D from keras.layers import Flatten from keras.layers import Dense classifier = Sequential() # Step one convolution classifier.add(Convolution2D(32, (3, 3), input_shape = (64, 64, 1), activation = 'relu')) # Step two the pooling step classifier.add(MaxPool2D(pool_size = (2, 2))) # Adding more convolutional layer because I want to increase the accuracy classifier.add(Convolution2D(32, (3, 3), activation = 'relu')) #Add second max pooling classifier.add(MaxPool2D(pool_size = (2, 2))) # Step three Flattening classifier.add(Flatten()) # dense connecting layers classifier.add(Dense(128, activation = 'relu')) classifier.add(Dense(1, activation = 'sigmoid')) # Compile the CNN classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) #Image augmentation -- used typically when we have low amount of images extracted from the image generator function from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator( rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator(rescale = 1./255) training_set = train_datagen.flow_from_directory('dataset/training_set', color_mode = 'grayscale', target_size = (64, 64), batch_size = 8, class_mode = 'binary') test_set = test_datagen.flow_from_directory('dataset/test_set', color_mode = 'grayscale', target_size = (64, 64), batch_size = 8, class_mode = 'binary') classifier.fit_generator(training_set, samples_per_epoch = 5216, nb_epoch = 50, validation_data = test_set, nb_val_samples = 624) # save the model from keras.models import load_model classifier.save('xray_prediction.h5') # check the labeling of the test set test_set.class_indices
# -*- coding: utf-8 -*- ponoviVajo = 'da' print "Pozdravljeni. Sem pretvornik enot, kilometrov v milje. " \ "\nVpiši željene kilometre in pretvoril jih bom v kilometre." while ponoviVajo == "da": try: kilometri = float(raw_input("\nVpiši kilometre: ")) milje = round(kilometri * 0.621371192, 1) print "Vpisal si" ,kilometri, " kilometrov, kar je približno ", milje," milj" except ValueError: print "Napačen vnos! Poskusi ponovno, tokrat s številko..." ponoviVajo = str(raw_input("Ali želiš še kaj pretvoriti? (da/ne)"))
#Q.1- Write a Python program to read n lines of a file from itertools import islice n = int(input("Enter how much lines of file you want to read? ")) try: f = open('Ques1.txt','r') lines = f.readlines(n) for i in islice(f,n): print(i) f.close() except FileNotFoundError: print("File not found") #Q.2- Write a Python program to count the frequency of words in a file. try: from collections import Counter f = open('Ques2.txt','r') data = f.read() dit = Counter(data.split()) print(dit) f.close() except FileNotFoundError: print('file not found') #Q.3- Write a Python program to copy the contents of a file to another file. try: f1 = open('Ques2.txt') f2 = open('Ques3.txt','w') data = f1.read() f2.write(data) f1.close() f2.close() except FileNotFoundError: print('File not found') #Q.4- Write a Python program to combine each line from first file with the corresponding line in second file. try: print('hi') with open('Ques2.txt') as ff1, open('Ques4.txt') as ff2: items = zip(ff1,ff2) for li1,li2 in items: print(li1+li2) except FileNotFoundError: print('File not found') #Q.5- Write a Python program to write 10 random numbers into a file. Read the file and then sort the numbers and then store it to another file. import random with open("random1.txt","w+") as f: for i in range(10): f.write(str(random.randint(0,9))) f.write("\n") with open("random1.txt") as f1,open("random2.txt","w+") as f2: l = [] for line in f1: l.append(int(line.strip("\n"))) l = sorted(l) for i in l: f2.write(str(i)+"\n") with open("random2.txt") as f: for i in f: print(i.strip("\n"))
# coding=utf-8 # Py从小喜欢奇特的东西,而且天生对数字特别敏感,一次偶然的机会,他发现了一个有趣的四位数2992, # 这个数,它的十进制数表示,其四位数字之和为2+9+9+2=22,它的十六进制数BB0,其四位数字之和也为22, # 同时它的十二进制数表示1894,其四位数字之和也为22,啊哈,真是巧啊。 # Py非常喜欢这种四位数,由于他的发现,所以这里我们命名其为Py数。 # 现在给你一个十进制4位数n,你来判断n是不是Py数,若是,则输出Yes,否则输出No。 # 如n=2992,则输出Yes; n = 9999,则输出No。 n = 2992 def SumBase(a,b): res = 0 while a: res += a%b a //=b return res if SumBase(n,10) == SumBase(n,12) and SumBase(n,10) == SumBase(n,16): print 'Yes' else: print 'No'
# coding=utf-8 # 给你一个整数a,数出a在二进制表示下1的个数,并输出。 a = 34 res = 0 while a: if a%2: res += 1 a //= 2 print res
''' The votes.csv consists of the data as is. votes for each law and each member. 7057 laws X 143 members. values represents: 1 - for the law, 2 - opposed to the law, 0 - didn't attend. Here, we would like to convert this data to an input for a cooperative game. That is, sets of players (members) and theirs values. 1. represent as sets: A group is all the members that voted the same. We extracted only groups members that voted 1 or 2 which is for or against the law and ignored the others. each group is represented by a binary vector. The output A is a matrix of all of these sets. 2. calculate the value of each set: We calculate the value of a set to be 1 if the set won (they were the majority) and 0 otherwise. The output b is a vector of the values for each set in A (same order as A) we multiply A and b by -1 to suited the input for the LP ''' import helper from collections import Counter LAW_PICKLE = 'law2vector.pickle' #LAW_PICKLE = 'law2vecA.pickle' A_PICKLE = 'A.pickle' B_PICKLE = 'b.pickle' def is_zeroes(x): new_x=[] new_x[:] = (value for value in x if value != 0) # trim the zeroes #print (new_x) if len(new_x)==0: return True return False # input: x - votes' list, output: int. return 1 if the majority voted 1 (for the law), else, return 2. def majority(x): new_x=[] new_x[:] = (value for value in x if value != 0) # trim the zeroes new_x[:] = (value for value in new_x if value != 3) new_x[:] = (value for value in new_x if value != 4) occrs = Counter(new_x).most_common(2) #print (occrs) #if len(occrs)==0: return 2 if len(occrs)==2 and occrs[0][1] == occrs[1][1]: #equal votes for and against return 2 # 2 - the law has not being approved else: return occrs[0][0] # x = [0,0,0] # print (majority(x)) def to_sets(items): set1 = [1 if x == 1 else 0 for x in items] set2 = [1 if x == 2 else 0 for x in items] return set1, set2 #x = [0,0,0] def to_set_and_value(A,b,x): m = majority(x) set1, set2 = to_sets(x) v1 = 1 if m == 1 else 0 b.append(v1) A.append(set1) b.append(1 - v1) A.append(set2) #print(A,b) return A, b def to_set_and_value_no_dup(A,b,x): m = majority(x) set0, set1, set2 = to_sets(x) if set0 not in A: A.append(set0) b.append(0) v1 = 1 if m == 1 else 0 if set1 not in A: b.append(v1) A.append(set1) if set2 not in A: b.append(1 - v1) A.append(set2) #print(A,b) return A, b def to_set_and_value_lst(A,b,x): m = majority(x) set0, set1, set2 = to_sets(x) if set0 not in A: A.append(set0) b.append([0]) else: inx = A.index(set0) b[inx].append(0) v1 = 1 if m == 1 else 0 if set1 not in A: b.append([v1]) A.append(set1) else: inx = A.index(set1) b[inx].append(v1) if set2 not in A: b.append([1 - v1]) A.append(set2) else: inx = A.index(set2) b[inx].append(1 - v1) #print(A,b) return A, b def to_avg_val(b): #calc the avg value newb = [] for l in b: avg = (l.count(1))/len(l) newb.append(avg) return newb #laws = {991:[1,1,0], 990:[1,1,0] ,992:[2,2,0] ,999:[0,0,0]} def iterate(laws): A=[] b=[] for vote_id, l in laws.items(): if is_zeroes(l): continue A, b = to_set_and_value(A,b,l) # use the other functions if there are duplicates in the data (right now, we don't have) #print("NOTE: calc the avg value.") #b = to_avg_val(b) #print(A,b) return A, b def minus(A,b): # multiply A and b by -1 newA=[] for a in A: new_a = [-1 if x == 1 else 0 for x in a] newA.append(new_a) b = [-1 if x == 1 else 0 for x in b] return newA, b # Includes additional constraint that sum-total of payoffs must EXCEED a certain amount # This should be DONE AFTER the A,b = minus(A,b) step def minpay(A,b,payout): dim = len(A[0]) A.append([-1] * dim) b.append(-1*payout) return A, b laws = helper.load_pickle(LAW_PICKLE) #'law2vector.pickle' is of the same sturcture as votes.csv. that is a vector of all the vote results for each law A,b = iterate(laws) A,b = minus(A,b) A,b = minpay(A,b,18.81) helper.init_pickle(A_PICKLE) helper.init_pickle(B_PICKLE) helper.dump_pickle(A_PICKLE, A) helper.dump_pickle(B_PICKLE, b)
nums = [] for a in range(2, 101): for b in range(2, 101): if a**b not in nums: nums.append(a**b) nums.sort() print(len(nums))
#Artificial Intelligence: A Modern Approach # Search AIMA #AIMA Python file: mdp.py """Markov Decision Processes (Chapter 17) First we define an MDP, and the special case of a GridMDP, in which states are laid out in a 2-dimensional grid. We also represent a policy as a dictionary of {state:action} pairs, and a Utility function as a dictionary of {state:number} pairs. We then define the value_iteration and policy_iteration algorithms.""" #Answers """ 1. What action is assigned in the terminal states? Action is assigned to None to prohibit further moving. 2. Where are the transition probabilities defined in the program, and what are those probabilities? The transition probabilities are defined in the T (transition model) function of the GridMDP class. The probabilities are an 80% chance to complete the intended action, a 10% chance to go right of the intended move, and another 10% chance to go left of the intented move. 3. What function needs to be called to run value iteration? You call the value_iteration function with two parameters; the MDP and an epsilon value. If you want to get a policy out of this, you can pass that result (the utility mapping) along with the MDP into the best_policy function. 4. When you run value_iteration on the MDP provided, the results are stored in a variable called myMDP. What is the utility of (0,1), (3, 1), and (2, 2)? (0,1): 0.398 (3,1): -1.0 (2,2): 0.795 5. How are actions represented, and what are the possible actions for each state in the program? Actions are represented by an (x, y) vector that describes the direction of the next move. The action (0,-1) translates to moving south (or down). Your actions are you can move a unit NSEW or stay put depending on current state and the surrounding environment. At a terminal state you wouldn't continue to move, and the borders restrict moving further in its respective direction. """ from utils import * orientations = [(1,0), (0, 1), (-1, 0), (0, -1), (2, 0), (0, 2), (-2, 0), (0, -2)] jumplist = [(2,0), (0, 2), (-2, 0), (0, -2)] class MDP: """A Markov Decision Process, defined by an initial state, transition model, and reward function. We also keep track of a gamma value, for use by algorithms. The transition model is represented somewhat differently from the text. Instead of T(s, a, s') being probability number for each state/action/state triplet, we instead have T(s, a) return a list of (p, s') pairs. We also keep track of the possible states, terminal states, and actions for each state. [page 615]""" def __init__(self, init, actlist, terminals, gamma=.9): update(self, init=init, actlist=actlist, terminals=terminals, gamma=gamma, states=set(), reward={}) def R(self, state): "Return a numeric reward for this state." return self.reward[state] def T(state, action): """Transition model. From a state and an action, return a list of (result-state, probability) pairs.""" abstract def actions(self, state): """Set of actions that can be performed in this state. By default, a fixed list of actions, except for terminal states. Override this method if you need to specialize by state.""" if state in self.terminals: return [None] else: return self.actlist class GridMDP(MDP): """A two-dimensional grid MDP, as in [Figure 17.1]. All you have to do is specify the grid as a list of lists of rewards; use None for an obstacle (unreachable state). Also, you should specify the terminal states. An action is an (x, y) unit vector; e.g. (1, 0) means move east.""" def __init__(self, grid, terminals, init=(0, 0), gamma=.9): grid.reverse() ## because we want row 0 on bottom, not on top MDP.__init__(self, init, actlist=orientations, terminals=terminals, gamma=gamma) update(self, grid=grid, rows=len(grid), cols=len(grid[0])) for x in range(self.cols): for y in range(self.rows): self.reward[x, y] = grid[y][x] if grid[y][x] is not None: self.states.add((x, y)) def T(self, state, action): if action == None: return [(0.0, state)] next_state = vector_add(state, action) if next_state not in self.states: return [(0.0, state)] if action in jumplist: return [(0.5, self.go(state, action)), (0.5, state)] else: return [(0.8, self.go(state, action)), (0.1, self.go(state, turn_right(action))), (0.1, self.go(state, turn_left(action)))] def go(self, state, direction): "Return the state that results from going in this direction." state1 = vector_add(state, direction) return if_(state1 in self.states, state1, state) def to_grid(self, mapping): """Convert a mapping from (x, y) to v into a [[..., v, ...]] grid.""" return list(reversed([[mapping.get((x,y), None) for x in range(self.cols)] for y in range(self.rows)])) def to_arrows(self, policy): chars = {(1, 0):'>', (0, 1):'^', (-1, 0):'<', (0, -1):'v', None: '.'} return self.to_grid(dict([(s, chars[a]) for (s, a) in policy.items()])) def value_iteration(mdp, epsilon=0.001): "Solving an MDP by value iteration. [Fig. 17.4]" U1 = dict([(s, 0) for s in mdp.states]) R, T, gamma = mdp.R, mdp.T, mdp.gamma while True: U = U1.copy() delta = 0 for s in mdp.states: U1[s] = R(s) + gamma * max([sum([p * U[s1] for (p, s1) in T(s, a)]) for a in mdp.actions(s)]) delta = max(delta, abs(U1[s] - U[s])) if delta < epsilon * (1 - gamma) / gamma: return U def best_policy(mdp, U): """Given an MDP and a utility function U, determine the best policy, as a mapping from state to action. (Equation 17.4)""" pi = {} for s in mdp.states: pi[s] = argmax(mdp.actions(s), lambda a:expected_utility(a, s, U, mdp)) return pi def expected_utility(a, s, U, mdp): "The expected utility of doing a in state s, according to the MDP and U." return sum([p * U[s1] for (p, s1) in mdp.T(s, a)]) def policy_iteration(mdp): "Solve an MDP by policy iteration [Fig. 17.7]" U = dict([(s, 0) for s in mdp.states]) pi = dict([(s, random.choice(mdp.actions(s))) for s in mdp.states]) while True: U = policy_evaluation(pi, U, mdp) unchanged = True for s in mdp.states: a = argmax(mdp.actions(s), lambda a: expected_utility(a,s,U,mdp)) if a != pi[s]: pi[s] = a unchanged = False if unchanged: return pi def policy_evaluation(pi, U, mdp, k=20): """Return an updated utility mapping U from each state in the MDP to its utility, using an approximation (modified policy iteration).""" R, T, gamma = mdp.R, mdp.T, mdp.gamma for i in range(k): for s in mdp.states: U[s] = R(s) + gamma * sum([p * U[s1] for (p, s1) in T(s, pi[s])]) return U myMDP = GridMDP([[0, 0, 0, 0, -1, 0, -1, -1, 0, 50], [None, None, -1, -1, 0, -.5, None, 0, None, 0], [0, 0, 0, 0, 0, -.5, None, 0, 0, 0], [None, 2, None, None, None, -.5, 0, 2, None, 0], [None, 0, 0, 0, 0, None, -1, -.5, -1, 0], [0, -.5, None, 0, 0, None, 0, 0, None, 0], [0, -.5, None, 0, -1, None, 0, -1, None, None], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], terminals=[(9,7)]) myMDP2 = GridMDP([[-.05, -.05, -.05, -.05, -1, -.05, -1, -1, -.05, 50], [None, None, -1, -1, -.05, -.5, None, -.05, None, -.05], [-.05, -.05, -.05, -.05, -.05, -.5, None, -.05, -.05, -.05], [None, 2, None, None, None, -.5, -.05, 2, None, -.05], [None, -.05, -.05, -.05, -.05, None, -1, -.5, -1, -.05], [-.05, -.5, None, -.05, -.05, None, -.05, -.05, None, -.05], [-.05, -.5, None, -.05, -1, None, -.05, -1, None, None], [-.05, -.05, -.05, -.05, -.05, -.05, -.05, -.05, -.05, -.05]], terminals=[(9,7)], gamma=.9) U = value_iteration(myMDP, .001) U2 = value_iteration(myMDP2, .001) P = policy_iteration(myMDP) P2 = policy_iteration(myMDP2) bestP = best_policy(myMDP, U) bestP2 = best_policy(myMDP2, U2) i = 0 j = 0 state = (i,j) terminal = (9,7) print "Policy for MDP2" #reformatting the print for easier comprehension for i in range (0,10): for j in range (0, 8): if (myMDP.R((i,j)) != None): print "State {0}: Action {1}".format((i,j), P2[(i,j)]) #print out the desired path of states i = 0 j = 0 state = (i,j) print "\nDesired path" while (state in myMDP.states and state != terminal): print "{0} -> ".format(state), action = P[state] if (action == (1,0)): i = i + 1 elif (action == (-1,0)): i = i - 1 elif (action == (0,1)): j = j + 1 elif (action == (0,-1)): j = j - 1 if (action == (2,0)): i = i + 2 elif (action == (-2,0)): i = i - 2 elif (action == (0,2)): j = j + 2 elif (action == (0,-2)): j = j - 2 next_state = (i,j) if (next_state not in myMDP.states): print "Hit wall: {0}".format(next_state) elif next_state == terminal: print "Terminal state: {0}".format(next_state) state = next_state i = 0 j = 0 state = (i,j) print "\nDesired path 2" while (state in myMDP.states and state != terminal): print "{0} -> ".format(state), action = P2[state] if (action == (1,0)): i = i + 1 elif (action == (-1,0)): i = i - 1 elif (action == (0,1)): j = j + 1 elif (action == (0,-1)): j = j - 1 if (action == (2,0)): i = i + 2 elif (action == (-2,0)): i = i - 2 elif (action == (0,2)): j = j + 2 elif (action == (0,-2)): j = j - 2 next_state = (i,j) if (next_state not in myMDP.states): print "Hit wall: {0}".format(next_state) elif next_state == terminal: print "Terminal state: {0}".format(next_state) state = next_state if P == P2: print "\nSame policy" else: print "\nDifferent policy" ''' myMDP = GridMDP([[-0.04, -0.04, -0.04, +1], [-0.04, None, -0.04, -1], [-0.04, -0.04, -0.04, -0.04]], terminals=[(3,1),(3,2)]) #AI: A Modern Approach by Stuart Russell and Peter Norvig Modified: Jul 18, 2005 '''
def suma(a,b): #archivo de FUNCIONES print ("la suma de ",a," y ",b," es-> ",a+b) def resta(a,b): print ("la resta de ",a," y ",b," es-> ",a-b) def multiplicacion(a,b): print ("la multiplicacion de ",a," y ",b," es-> ",a*b) def division(a,b): print ("la division de ",a," y ",b," es-> ",a/b) def mod(a,b): print ("la mod de ",a," y ",b," es-> ",a%b) def suma_varios(num): temp = 0 for i in range(len(num)): temp = temp + num[i]; return temp
def main(): #variables numero = 15 decimal = 12.56 caracter = 'a' cadenas = "hola mundo" booleano = True #entrada y salida de informacion print ("hola mundo", numero ,"-", decimal) dato = input() #como el cin print (dato) #operaciones basicas print ("introduce el valor de a: ") a = int(input()) #para introducir un valor entero print ("introduce el valor de b: ") b = int(input()) print("el resultado de a + b = ",a+b) print("el resultado de a - b = ",a-b) print("el resultado de a * b = ",a*b) print("el resultado de a / b = ",a/b) print("el resultado de a mod b = ",a%b) main()
import os import random import cherrypy import math import time # added """ This is a simple Battlesnake server written in Python. For instructions see https://github.com/BattlesnakeOfficial/starter-snake-python/README.md """ # Rules: 0=available space, 1=snake body, 2=Food, 3=head, 4= Bigger enemy's head # 5 = smaller head class Battlesnake(object): @cherrypy.expose def index(self): # If you open your snake URL in a browser you should see this message. return "Your Battlesnake is alive!" @cherrypy.expose def ping(self): # The Battlesnake engine calls this function to make sure your snake is working. return "pong" @cherrypy.expose @cherrypy.tools.json_in() @cherrypy.tools.json_out() def start(self): # This function is called everytime your snake is entered into a game. # cherrypy.request.json contains information about the game that's about to be played. # TODO: Use this function to decide how your snake is going to look on the board. data = cherrypy.request.json print("START") return {"color": "#736CCB", "headType": "silly", "tailType": "bolt"} # --------------------------------------------------------------------- # Function priority moves: Retruns priority movement # flag = 0 need prob. def priority(self, matrix, head, possible_moves, height, width, flag): priority_moves = ["up", "down", "left", "right"] # check if the distance between my head and enemy's head (=4) is =< 2 # enemy is at the right within range 2. head[0] is height, head[1] is width # head[1]+2 =>col +2 if head[1] + 2 <= width - 1 and matrix[head[0]][head[1] + 2] == 4: priority_moves.remove("right") if head[1] - 2 >= 0 and matrix[head[0]][head[1] - 2] == 4: priority_moves.remove("left") if head[0] + 2 <= height - 1 and matrix[head[0] + 2][head[1]] == 4: priority_moves.remove("down") if head[0] - 2 >= 0 and matrix[head[0] - 2][head[1]] == 4: priority_moves.remove("up") print("priority_moves=", priority_moves) # match possible moves and priority moves. # avoid nessy, blind spot avoid = [] if head[1] + 1 <= width - 1 and head[0] - 1 >= 0 and matrix[head[0] - 1][head[1] + 1] == 4: # row-1, col+1 # avoid.append("up") # avoid.append("right") avoid.append("left") avoid.append("down") if head[1] - 1 >= 0 and head[0] - 1 >= 0 and matrix[head[0] - 1][head[1] - 1] == 4: # avoid.append("top") # avoid.append("left") avoid.append("down") avoid.append("right") if head[1] - 1 >= 0 and head[0] + 1 <= height - 1 and matrix[head[0] + 1][head[1] - 1] == 4: # avoid.append("left") # avoid.append("down") avoid.append("right") avoid.append("up") if head[1] + 1 <= width - 1 and head[0] + 1 <= height - 1 and matrix[head[0] + 1][head[1] + 1] == 4: # avoid.append("right") # avoid.append("down") avoid.append("left") avoid.append("up") # debug print("Avoid: ", avoid) if( len(list(set(possible_moves) & set(priority_moves))) > 0 ):# then combined_move = list(set(possible_moves) & set(priority_moves)) if (len(list(set(combined_move) & set(avoid))) > 0): # then combined_move = list(set(combined_move) & set(avoid)) if flag == 1: # avoid eating food when health > 50 if len(combined_move) > 1: # at least we have two choice. print("combined move in avoid eating food: ", combined_move, "len: ", len(combined_move)) for i in range(len(combined_move)): if combined_move[i] == "up": if head[0] - 1 >= 0 and matrix[head[0] - 1][head[1]] == 2: combined_move.remove("up") print("call combined_move remove up") break elif combined_move[i] == "down": if head[0] + 1 <= height - 1 and matrix[head[0] + 1][head[1]] == 2: combined_move.remove("down") print("call combined_move remove down") break elif combined_move[i] == "right": if head[1] + 1 <= width - 1 and matrix[head[0]][head[1] + 1] == 2: combined_move.remove("right") print("call combined_move remove right") break elif combined_move[i] == "left": if head[1] - 1 >= 0 and matrix[head[0]][head[1] - 1] == 2: combined_move.remove("left") print("call combined_move remove left") break print("combined move in avoid eating food(after): ", combined_move) ####Prob start#### if flag == 0: # choose the best move from combined_move number_of_0 = 0 for row in range(height // 2): for col in range(width // 2): # Upper left if (matrix[row][col] not in [1, 4]): number_of_0 += 1 ratio1 = number_of_0 / ((height // 2) * (width // 2)) number_of_0 = 0 for row in range(height // 2): for col in range(width // 2, width): # Upper right if (matrix[row][col] not in [1, 4]): number_of_0 += 1 ratio2 = number_of_0 / ((height // 2) * (width - width // 2)) number_of_0 = 0 for row in range(height // 2, height): for col in range(width // 2): # Lower left if (matrix[row][col] not in [1, 4]): number_of_0 += 1 ratio3 = number_of_0 / ((height - height // 2) * (width // 2)) number_of_0 = 0 for row in range(height // 2, height): for col in range(width // 2, width): # Lower right if (matrix[row][col] not in [1, 4]): number_of_0 += 1 ratio4 = number_of_0 / ((height - height // 2) * (width - width // 2)) list_ratio = [ratio1, ratio2, ratio3, ratio4] list_ratio.sort() # debug best_cordinate = (0, 0) if (max(list_ratio) == ratio1): print("best ratio is:", "ratio1") best_cordinate = (0, 0) elif (max(list_ratio) == ratio2): print("best ratio is:", "ratio2") best_cordinate = (0, width - 1) elif (max(list_ratio) == ratio3): print("best ratio is:", "ratio3") best_cordinate = (height - 1, 0) else: print("best ratio is:", "ratio4") best_cordinate = (height - 1, width - 1) # compute distance of each possible moves? # From combined_move, We want corner_dist =[left:1000, right:1000] corner_dist = [100] * len(combined_move) # between each combined_move for i in range(len(combined_move)): if (combined_move[i] == "right"): # head[1] is width corner_dist[i] = abs(best_cordinate[1] - (head[1] + 1)) + abs(best_cordinate[0] - (head[0])) elif (combined_move[i] == "left"): # head[1] is width corner_dist[i] = abs(best_cordinate[1] - (head[1] - 1)) + abs(best_cordinate[0] - (head[0])) elif (combined_move[i] == "up"): # head[0] is height corner_dist[i] = abs(best_cordinate[1] - (head[1])) + abs(best_cordinate[0] - (head[0] - 1)) elif (combined_move[i] == "down"): # head[0] is height corner_dist[i] = abs(best_cordinate[1] - (head[1])) + abs(best_cordinate[0] - (head[0] + 1)) # find shortest min = 100 min_move = "" for i in range(len(combined_move)): if min > corner_dist[i]: # corner_dist and combined_move have same order min = corner_dist[i] min_move = combined_move[i] # debug print("combined_move=", combined_move) print("corner_dist=", corner_dist) move = min_move ################End of Prob######## else: move = combined_move return move # --------------------------------------------------------------------- @cherrypy.expose @cherrypy.tools.json_in() @cherrypy.tools.json_out() def move(self, possible_move=None): # This function is called on every turn of a game. It's how your snake decides where to move. # Valid moves are "up", "down", "left", or "right". # TODO: Use the information in cherrypy.request.json to decide your next move. data = cherrypy.request.json # Choose a random direction to move in # possible_moves = ["up", "down", "left", "right"] # move = random.choice(possible_moves) # add my code-------------------------------------------- # debug (delete later) print("turn: ", data["turn"]) start_time = time.time() # board info height = data["board"]["height"] width = data["board"]["width"] # Create Adjacency Matrix matrix = [0] * (width) for i in range(width): matrix[i] = [0] * (height) # Input my snake location into matrix for i in range(len(data["you"]["body"])): # body[i]=head, body, or tail... x = data["you"]["body"][i]["x"] y = data["you"]["body"][i]["y"] matrix[y][x] = 1 # get my_size my_size = len(data["you"]["body"]) # Input "other" snakes location into matrix for i in range(len(data["board"]["snakes"])): # body[i]=[x,y] # j is head, body, or tail...by index # get enemy's size size = len(data["board"]["snakes"][i]["body"]) for j in range(len(data["board"]["snakes"][i]["body"])): x = data["board"]["snakes"][i]["body"][j]["x"] y = data["board"]["snakes"][i]["body"][j]["y"] if j == 0 and my_size <= size: # j == 0 means head matrix[y][x] = 4 elif j == 0 and my_size > size: # j == 0 means head matrix[y][x] = 5 else: if data["turn"] > 0: matrix[y][x] = 1 # Input food location into matrix food = [] for i in range(len(data["board"]["food"])): # food[i]=[x,y] x = data["board"]["food"][i]["x"] y = data["board"]["food"][i]["y"] food.append([y, x]) matrix[y][x] = 2 # get head x = data["you"]["body"][0]["x"] y = data["you"]["body"][0]["y"] matrix[y][x] = 3 head = (y, x) # get health h = data["you"]["health"] load_factor = 0 # load factor = 0 when health > 50 if h < 100: load_factor = 1 # head.append(x) #now, head=[row, col] shortest = 100 s_food = None for item in food: # items are tuples path = abs(head[0] - item[0]) + abs(head[1] - item[1]) item.append(path) # if shortest > path: # shortest = path # s_food = item food.sort(key=lambda x: (x[2])) # sort the array using food[2](shortest path) # print("s_food =", s_food, "shortest path = ", shortest) print(food) print("health: ", h) # print health print("load factor: ", load_factor) # debug print("------matrix------") for line in matrix: print(line) if load_factor == 1: possible_moves = [] if head[0] - 1 >= 0 and matrix[head[0] - 1][head[1]] not in [1, 4]: possible_moves.append("up") if head[0] + 1 <= height - 1 and matrix[head[0] + 1][head[1]] not in [1, 4]: possible_moves.append("down") if head[1] - 1 >= 0 and matrix[head[0]][head[1] - 1] not in [1, 4]: possible_moves.append("left") if head[1] + 1 <= width - 1 and matrix[head[0]][head[1] + 1] not in [1, 4]: possible_moves.append("right") print("possible_moves=", possible_moves) if head[1] < food[0][1] and (matrix[head[0]][head[1] + 1] != 1): # that means head is left side of food. movement = "right" move = self.priority(matrix, head, possible_moves, height, width, load_factor) print("move: ", move) if movement in move: move = movement else: move = random.choice(move) print("final move: ", move) elif head[1] > food[0][1] and (matrix[head[0]][head[1] - 1] != 1): # that means head is left side of food. movement = "left" move = self.priority(matrix, head, possible_moves, height, width, load_factor) print("move: ", move) if movement in move: move = movement else: move = random.choice(move) print("final move: ", move) else: # that means head and food are in the same column! if head[0] < food[0][0] and (matrix[head[0] + 1][head[1]] != 1): # that means hard is above the food. movement = "down" move = self.priority(matrix, head, possible_moves, height, width, load_factor) print("move: ", move) if movement in move: move = movement else: move = random.choice(move) print("final move: ", move) elif head[0] > food[0][0] and (matrix[head[0] - 1][head[1]] != 1): # that means hard is below the food. movement = "up" move = self.priority(matrix, head, possible_moves, height, width, load_factor) print("move: ", move) if movement in move: move = movement else: move = random.choice(move) print("final move: ", move) else: possible_moves = [] if head[1] + 1 != width and matrix[head[0]][head[1] + 1] not in [1, 4]: possible_moves.append("right") if head[1] - 1 >= 0 and matrix[head[0]][head[1] - 1] not in [1, 4]: possible_moves.append("left") if head[0] + 1 != height and matrix[head[0] + 1][head[1]] not in [1, 4]: possible_moves.append("down") if head[0] - 1 >= 0 and matrix[head[0] - 1][head[1]] not in [1, 4]: possible_moves.append("up") if len(possible_moves) > 0: move = self.priority(matrix, head, possible_moves, height, width, load_factor) move = random.choice(move) print("final move: ", move) elif load_factor == 0: print("head[0]: ", head[0], "head[1]: ", head[1]) possible_moves = [] if head[0] - 1 >= 0 and matrix[head[0] - 1][head[1]] not in [1, 4]: possible_moves.append("up") if head[0] + 1 <= height - 1 and matrix[head[0] + 1][head[1]] not in [1, 4]: possible_moves.append("down") if head[1] - 1 >= 0 and matrix[head[0]][head[1] - 1] not in [1, 4]: possible_moves.append("left") if head[1] + 1 <= width - 1 and matrix[head[0]][head[1] + 1] not in [1, 4]: possible_moves.append("right") print("possible_moves=", possible_moves) move = self.priority(matrix, head, possible_moves, height, width, load_factor) print("--- %s seconds ---" % (time.time() - start_time)) # end of my code-------------------------------------------- print(f"MOVE: {move}") return {"move": move} @cherrypy.expose @cherrypy.tools.json_in() def end(self): # This function is called when a game your snake was in ends. # It's purely for informational purposes, you don't have to make any decisions here. data = cherrypy.request.json print("END") return "ok" if __name__ == "__main__": server = Battlesnake() cherrypy.config.update({"server.socket_host": "0.0.0.0"}) cherrypy.config.update( {"server.socket_port": int(os.environ.get("PORT", "8080")), } ) print("Starting Battlesnake Server...") cherrypy.quickstart(server)
usernameinput = input("username : ") passwordinput = input("password : ") if usernameinput == "admin" and passwordinput == "1234": item = "" print("------------MAX SHOP------------") print("-------เลือกรายการสินค้าที่ต้องการ------") print("1.น้ำดื่ม ขวดละ 10 บาท") print("2.แล็คตาซอย กล่องละ 15 บาท") print("3.MAMA ซองละ 10 บาท") print("4.เลย์มันฝรั่ง ห่อละ 35 บาท") print("5.ชาเขียว แก้วละ 25 บาท") print("6.ชาดำเย็น แก้วละ 15 บาท") print("7.ชามะนาว แก้วละ 20 บาท") print("8.ถั่วกรอบแก้ว ซองละ 10 บาท") print("9.น้ำลิ้นจี่ แก้วละ 10 บาท") print("10.น้ำลำไย แก้วละ 10 บาท") choice=int(input("Please Selected Choice =>")) if choice == 1: quan = int(input("ใส่จำนวนที่ต้องการ")) unitprice = 10 item = "น้ำดื่ม" elif choice == 2: quan = int(input("ใส่จำนวนที่ต้องการ")) unitprice = 15 item = "แล็คตาซอย" elif choice == 3: quan = int(input("ใส่จำนวนที่ต้องการ")) unitprice = 10 item = "MAMA" elif choice == 4: quan = int(input("ใส่จำนวนที่ต้องการ")) unitprice = 35 item = "เลย์มันฝรั่ง" elif choice == 5: quan = int(input("ใส่จำนวนที่ต้องการ")) unitprice = 25 item = "ชาเขียว" elif choice == 6: quan = int(input("ใส่จำนวนที่ต้องการ")) unitprice = 15 item = "ชาดำเย็น" elif choice == 7: quan = int(input("ใส่จำนวนที่ต้องการ")) unitprice = 20 item = "ชามะนาว" elif choice == 8: quan = int(input("ใส่จำนวนที่ต้องการ")) unitprice = 10 item = "ถั่วกรอบแก้ว" elif choice == 9: quan = int(input("ใส่จำนวนที่ต้องการ")) unitprice = 10 item = "น้ำลิ้นจี่" elif choice == 10: quan = int(input("ใส่จำนวนที่ต้องการ")) unitprice = 10 item = "น้ำลำไย" if item == "": print("ไม่มีรายการที่ต้องการ") else: total = unitprice * quan print("คุณได้ซื้อ",item,"จำนวน",quan,"หน่วยๆ ละ",unitprice,"บาท รวมเป็นเงิน",total,"บาท") else: print("Wrong Username or Password")
def vatcalculate(totalprice): result = totalprice + (totalprice * 0.07) return result print(vatcalculate(int(input("ใส่ราคาสินค้าที่ต้องการ : "))))
from typing import List from enum import Enum import operator class State(Enum): FLOOR = 1 EMPTY = 2 OCCUPIED = 3 def __repr__(self): if self.value == self.FLOOR.value: return '.' elif self.value == self.OCCUPIED.value: return '#' else: return 'L' class Direction(Enum): UP = (0, 1) DOWN = (0, -1) LEFT = (-1, 0) RIGHT = (1, 0) UP_LEFT = (-1, 1) UP_RIGHT = (1, 1) DOWN_LEFT = (-1, -1) DOWN_RIGHT = (1, -1) def from_char(char) -> State: mapping = { '.': State.FLOOR, 'L': State.EMPTY, '#': State.OCCUPIED } return mapping[char] def parse_input(filename: str) -> List[List[State]]: with open(filename, 'r') as f: lines = f.readlines() return_list = [] for row in lines: return_list.append([from_char(char) for char in row.rstrip('\n')]) return return_list def find_state(rows: List[List[State]], coord: (int, int), part2: bool) -> State: row, column = coord current_state = rows[coord[1]][coord[0]] def valid(i: int, j: int, row_length: int, col_length: int) -> bool: return not (i==row and j==column) and i >= 0 and j >= 0 and i < row_length and j < col_length def coord_generator(row: int, column: int, row_length: int, col_length: int): for i in range(row - 1, row + 2): for j in range(column - 1, column + 2): if valid(i, j, row_length, col_length): yield (i, j) def vector_coord_gen(row: int, column: int, row_length: int, col_length: int): for d in Direction: current_coord = (row, column) next_coord = tuple(map(operator.add, d.value, current_coord)) while valid(next_coord[0], next_coord[1], row_length, col_length): if(rows[next_coord[1]][next_coord[0]] != State.FLOOR): yield (next_coord[0], next_coord[1]) break current_coord = next_coord next_coord = tuple(map(operator.add, d.value, current_coord)) if current_state == State.FLOOR: return State.FLOOR else: gen = coord_generator(row, column, len(rows[0]), len(rows)) if not part2 else \ vector_coord_gen(row, column, len(rows[0]), len(rows)) occupies = 0 for x, y in gen: position = rows[y][x] if position == State.OCCUPIED: occupies += 1 if occupies == 0: return State.OCCUPIED elif not part2 and occupies >= 4: return State.EMPTY elif part2 and occupies >= 5: return State.EMPTY else: return current_state def run_rules(plane: List[List[State]], part2: bool) -> List[List[State]]: return [[find_state(plane, (x,y), part2) for x, _ in enumerate(row)] for y, row in enumerate(plane)] def get_occupied_seats(part2: bool) -> int: rows = parse_input('input.txt') changed = True sum_total = current_sum = 0 while changed: sum_total = current_sum rows = run_rules(rows, part2) current_sum = sum([1 if (item == State.OCCUPIED) else 0 for row in rows for item in row]) if(current_sum == sum_total): changed = False return current_sum print(f"Part 1: {get_occupied_seats(False)}") print(f"Part 2: {get_occupied_seats(True)}")
# -*- coding: utf-8 -*- class Calculator: def add(self, a, b): if (type(a)!= int and type(a)!=float) or (type(b) != int and type(b)!=float): return "请输入数字" return a + b def sub(self,a,b): if (type(a)!=int and type (a)!=float) or (type(b)!=int and type(b)!=float): return "请输入数字" return a-b def mul(self,a,b): if isinstance(a,(int,float)) and isinstance(a,(int,float)): return a*b else: return "请输入数字" def div(self, a, b): if (type(a)!= int and type(a)!=float) or (type(b)!= int and type(b)!=float): return "输入无效,请输入数字" elif b == 0: return 'ZeroDivisionError' else: return a / b a=Calculator() print(a.mul('2','\\n'))
# -*- coding: utf-8 -*- class person: name : str = None age : int = 0 gen : str = "男" __money : float = 20000 def __init__(self,name,age,gen,money): print('这是一个构造函数') self.name = name self.age = age self.gen=gen self.__money=money def get_money(self): return self.__money def eat (self): print(f"{self.name} is eating") return True def run(self): print('run') def jump(self): print(f"{self.name} is jumping") class funnyman(person): skill : str = '' def __init__(self,skill,name,age,gen,money): self.skill=skill super().__init__(name,age,gen,money) def fun(self): print(f'{self.name} is funny') def skill_skill(self): print(f"{self.name} is a actor,he`s age is {self.age},hes gender is {self.gen}") st = funnyman('haha','st',20,'男',2000) print(st.name) st.skill_skill() zl = funnyman('haha','zl',20,'男',2000) zl.skill_skill() # zs=person('张三',20,'男',2000) # print(zs.name) # print(zs.age) # print(zs.gen) # zs.eat() # print(zs.get_money()) # # print(dir(zs)) # zs.jump() # zs.name='王五' # person.name="default" # print(person.name) # print(zs.name)
''' Create the below pattern using nested for loop in Python. * * * * * * * * * * * * * * * * * * * * * * * * * ''' for i in range(1,6): for j in range(i): print("*",end=" ") print() for m in range(5,1,-1): for n in range(m-1,0,-1): print("*",end=" ") print()
#number guessing game from random import randrange def hidden_number(): random_generated_numer = randrange(1,1000) str_random_number = str(random_generated_numer) r_g_n_len = len(str_random_number) hint_count = 0 print("\nWELCOME TO NUMBR GUESSING GAME....\n") start_game = input("Wanna play ? (Y or N : ") print(f'HINT - 1 : ITS A NUMBER WITH {r_g_n_len} CHARACTERS') user_guess1 = int(input("\nGuess The Number : ")) while True: if user_guess1 == random_generated_numer: print("CONGRATULATIONS YOU WON !....") break else: if r_g_n_len == hint_count + 1: print(f'your loose Hidden number is {random_generated_numer}') break else: if hint_count == 0: print(f'WRONG : HINT - 2 : FIST NUMBER IS {str_random_number[0]}') elif hint_count == 1: print(f'WRONG : Hint - 3 FISRT 2 NUMBERS ARE {str_random_number[0:-1]}') elif hint_count == 2: print(f'WRONG : HINT - 4 : SECOND NUMBER IS {str_random_number[0:-1]}') user_guess2 = int(input("\nGuess The Number Again: ")) user_guess1 = user_guess2 hint_count += 1 game_end_question = input("\nWant To play again ? 'Y OR N' : ") if game_end_question == "Y": hidden_number() else: print("\nTHANK YOU HAVE A NICE DAY...") hidden_number()
def bubblesort(nlist): i=0 n=len(nlist) while i<n-1: j=0 sw=0 while j<n-i-1: if nlist[j]<nlist[j+1]: x=nlist[j] nlist[j]=nlist[j+1] nlist[j+1]=x sw=1 j=j+1 if sw==0: break i=i+1 nlist=[14,12,10,13,15] bubblesort(nlist) print(nlist)
a=int(input("Enter the value of a:")) b=int(input("Enter the value of b:")) c=int(input("Enter the value of c:")) i=b**2-(4*a*c) d=i**0.5 f1=(-b+d)/2*a f2=(-b-d)/2*a print("The value of x1=",f1) print("The value of x2=",f2)