text
stringlengths
37
1.41M
""" 类 与对象(实例) 类:模板定义属性和方法的封装 实例:具体的类对象 ,类的表现 1实例属性会根据实例不同而不同,类属性由类决定 2实例属性通常在构造赋值 3类属性(类变量)属于类 , 实例属性属于实例 实例确定,实例属性确定 实例可以调用类属性 ,类不可以调用实例属性 """ class Good(): name = 'tea' def __init__(self, _addr): self.addr = _addr g1 = Good("fujian") g2 = Good("guangdong") print(g1.addr,g2.addr,g1.name,g2.name) Good.name = 'coffee' print(Good.name, g1.name) # print(id(g1), id(g2)) # print(id(g1.name), id(g2.name), id(Good.name)) # 给g1对象添加name 属性 g1.name = 'cookle' print(id(g1.name), id(g2.name), id(Good.name)) """ 实例方法:需要第一个参数为self 类方法:需要第一个参数为cls,并且使用@classmethod声明 静态方法:需要使用@staticmethod声明 类可以调用,类方法, 静态方法 实例可以调用, 类方法,静态方法,实例方法 """ class Good(): """ 这是一个商品类 """ def __init__(self,_name): self.name = _name def getname(self): return self.name @classmethod def getinfo(cls): print(cls.__doc__) @staticmethod def pprint(): print("hellogood") g1 = Good("tea") print(g1.getname()) g1.getinfo() g1.pprint() # Good.getname() Good.getinfo() Good.pprint() """ 类属性类方法 类属性类方法 属于类 只占一份内存 实例方法,实例属性属于实例 每使用一个实例生成一个内存 声明实例属性,实例方法 浪费内存,适当的选择声明类属性和类方法节省内存 """ class Util(): @staticmethod def max(x,y): if x>y: return x else: return y """ 属性编写 """ class Good(): def __init__(self,_name): self.name = _name @property def gname(self): return self.name @gname.setter def gname(self,_name): self.name = _name g1 = Good("tea") print(g1.name) g1.gname = "coffee" print(g1.gname) "调用形式 没有赋值就是获取 赋值就是设置"
""" 引用计数 """ from sys import getrefcount list1 = [x for x in range(10)] list2 = [x for x in range(10, 20)] print(list1) print(list2) print("=========================================") print(getrefcount(list1)) print(getrefcount(list2)) print("=========================================") list1.append(list2) print(list1) print(getrefcount(list1)) print(getrefcount(list2)) print("=========================================") list2.append(list1) print(list2) print(getrefcount(list1)) print(getrefcount(list2)) print("=========================================") del list1 print(list2) print(getrefcount(list2)) print("=========================================")
# -*- coding: utf8 -*- ''' Программа принимает действительное положительное число x и целое отрицательное число y. Выполните возведение числа x в степень y. Задание реализуйте в виде функции my_func(x, y). При решении задания нужно обойтись без встроенной функции возведения числа в степень. Подсказка: попробуйте решить задачу двумя способами. Первый — возведение в степень с помощью оператора **. Второй — более сложная реализация без оператора **, предусматривающая использование цикла. ''' def my_func(a,b:int): if type(a) == float and b < 0: res = a**b return res else: print('Неправильно введено число!') print(my_func(2.0,-4)) #рекурсия - зло def exp_rec(b, n:int): if n == 0: return 1 return 1 / b * exp_rec(b, abs(n) - 1) print(exp_rec(2.0, -4)) #цикл for def exp_for(b, n): temp = 1 for i in range(0,abs(n)): temp *= b return 1/temp print(exp_for(2, -4)) #цикл While def exp_whi(b, n): err = 'Неправильно введено число!' clm = 'Основание введено неправильно - ' clm1 = 'Степень введена неправильно - ' temp = 1 if type(b) == float and n < 0: while n != 0: temp *= b n += 1 return 1/temp else: print(f'{err if type(b) != float or n >= 0 else ""}: {clm if type(b) != float else ""}{b if type(b) != float else ""},{clm1 if n >= 0 else ""}{n if n >= 0 else ""}') print(exp_whi(2, 4))
# -*- coding: utf8 -*- ''' Создать (программно) текстовый файл, записать в него программно набор чисел, разделённых пробелами. Программа должна подсчитывать сумму чисел в файле и выводить её на экран. ''' # with open('Digits_kit.txt', 'w+', encoding='utf-8') as dig_kit: # print(' '.join([str(i) for i in range(1,11)]), file=dig_kit) # # with open('Digits_kit.txt', 'r', encoding='utf-8') as dig_kit: # line = dig_kit.read() # print(line) # summary = sum([int(i) for i in line.split()]) # print(summary) with open('Digits_kit.txt', 'w+', encoding='utf-8') as dig_kit: print(' '.join([str(i) for i in range(1,11)]), file=dig_kit) dig_kit.seek(0) #как вот этой строчки избежать? что я не так делаю? line = dig_kit.read() print(sum([int(i) for i in line.split()]))
# -*- coding: utf-8 -*- """ Created on Tue Mar 12 15:28:02 2019 @author: Chengcheng Ding """ from tkinter import * from tkinter import messagebox from random import * class App(Frame): def __init__(self,master = None): Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): self.line1 = Label(self, text='在此输入最小值Put the minimum value here') self.line1.pack() self.minInput = Entry(self) self.minInput.pack() self.line2 = Label(self, text='在此输入最大值Put the maxmium value here') self.line2.pack() self.maxInput = Entry(self) self.maxInput.pack() self.generateButton = Button(self,text='Generate Random Number',command=self.generate) self.generateButton.pack() def generate(self): try: maxNum = int(self.maxInput.get()) or 100 minNum = int(self.minInput.get()) or 0 except ValueError: messagebox.showinfo("Message",'非法输入Illegal input!') result = randint(minNum,maxNum) messagebox.showinfo('Message','结果是the result is: \n %s' % str(result)) app = App() app.master.title('随机数生成器random number generator / by 丁成城Chengcheng Ding') app.mainloop()
# Python program to explain os.getenv() method # importing os module import os import sys key = 'HOME' value = os.getenv(key) print("Value of 'HOME' environment variable :", value) key = 'JAVA_HOME' value = os.getenv(key) print("Value of 'JAVA_HOME' environment variable :", value) key="IN_MPI" value = os.getenv(key, "value does not exist") print("Value of 'IN_MPI' environment variable :", value) os.environ.update( IN_MPI="1" ) print("Value of 'IN_MPI' environment variable :", os.getenv('IN_MPI')) # current python.exe path print('sys.excutable return current python.exe path: ', sys.executable) # current python lib path print('sys.prefix return current python lib path: ', sys.prefix) # return file name and args when calling using python # try run python os_env_example.py we are args print(sys.argv) # in macos seems no difference, which are all dicts # print(os.environ.keys()) print(os.environ)
a = 3 a = a + 7 print(a) a += 5 # a = a +5 print(a) a -=5 print(a) a *=2 print(a) a /=4 print(a) a %= 4 print(a) a += 1 print(a) a **=10 print(a)
a = {1, 2, 3} print(type(a)) b = set('angelo mutti') print(b) print('a' in b, 'sousa' not in b) # o que vale são os valores que compõem o conjunto, verdadeiro print({1, 2, 3} == {3, 2, 1, 3, 2}) c1 = {1, 2} c2 = {2, 3} print(c1.union(c2)) print(c1.intersection(c2)) c1.update(c2) print(c1) c3 = {1, 2, 3, 4, 5, 6} c4 = {7, 8, 9, 10, 11, 12} c3.update(c4) print(c3) print(c4) print(c2 <= c1) print(c1 - {2}) c1.union(c2) print(c1) # print(c1 -= {2}) rrr = set('1234567890') # rrr = set(1234567890) # não funciona! por que? print(rrr)
trabalho_terca = True trabalho_quinta = False ''' os 2 = tv de 50 apenas 1 = tv de 32 ''' tv_50 = trabalho_quinta and trabalho_terca sorvete = trabalho_terca or trabalho_quinta tv_32 = trabalho_terca != trabalho_quinta mais_saudavel = not sorvete print("tv50={} tv32={} sorvete={} mais_saudavel={}" .format( tv_50, tv_32, sorvete, mais_saudavel)) Sbc_available = True print("abcd={}, sbc {}".format(1234, Sbc_available)) print("{}".format("sbc já disponível")) print("{}".format("Conteúdo Indisponível para a sua região")) print(8 ** 8)
salario = 3450.45 despesas = 2456.2 print(despesas / salario * 100) #esta é porcentagem do salário que vai nas despesas #metodo do professor percentual_comprometido = despesas / salario * 100 print(percentual_comprometido)
# 표준 입력으로 삼각형의 높이가 입력됩니다. # 입력된 높이만큼 산 모양으로 별을 출력하는 프로그램을 만드세요. # (input에서 안내 문자열은 출력하지 않아야 합니다). # 이때 출력 결과는 예제와 정확히 일치해야 합니다. # 모양이 같더라도 공백이나 빈 줄이 더 들어가면 틀린 것으로 처리됩니다. n = int(input()) index = 1 for i in range(n): for j in range(n): if j > i: print(' ', end = '') if i > 0: index = index + 2 print('*' * index, end = '') print() else: print('*', end = '') print() # 정답 # n = int(input()) # for i in range(n): # for j in reversed(range(n)): # if j > i: # print(' ', end='') # else: # print('*', end='') # # for j in range(5): # if j < i: # print('*', end='') # # print()
# 회문 판별하기 # 회문은 순서를 거꾸로 읽어도 제대로 읽은 것과 같은 단어와 문장 word = input('단어를 입력하세요.') is_palindrome = True for i in range(len(word) // 2): if word[i] != word[-1 - i]: is_palindrome = False break print(is_palindrome)
if True: print('참') else: print('거짓') # True는 참 if False: print('참') else: print('거짓') # False는 거짓 if None: print('참') else: print('거짓') # None은 거짓 if 0: print('참') else: print('거짓') # 0은 거짓 if 1: print('참') else: print('거짓') # 1은 참 # 숫자는 정수, 실수 관계없이 0은 거짓이고 0이 아닌 수는 참이다. # 문자열은 비어있으면 거짓, 비어있지 않으면 참이다. if not 0: print('참') if not '': print('참') if not None: print('참') # 0, None, 빈 문자열을 뒤집으면 참이 되므로 if를 동작시킬 수 있다. # 비어 있는 문자열, 리스트, 튜플, 딕셔너리, 세트도 False로 간주 # '', "", [ ], (), { }, set() # 클래스 인스턴스의 __bool__(), __len__() 메서드가 0 또는 False를 반환할 때도 False로 간주
print(1, 2, 3) print(1, 2, 3, sep='\n') # print의 sep에 개행 문자(\n) 이라는 특별한 문자를 지정하면 값을 여러 줄로 출력할 수 있다. print('1\n2\n3') # 결과가 같음 # 제어 문자 # 제어 문자는 화면에 출력되지는 않지만 출력 결과를 제어한다고 해서 제어 문자라 부른다. # 또한, 제어 문자는 \ 로 시작하는 이스케이프 시퀀스이다. # \n : 다음 줄로 이동하며 개행이라고도 부른다. # \t : 탭 문자, 키보드의 Tab 키와 같으며 여러 칸을 띄운다. # \\ : \ 문자 자체를 출력할 때는 \ 를 두 번 써야한다. print(1, end='') print(2, end='') print(3) # 한 줄에 여러 개의 값을 출력할 때는 end에 빈 문자열 저장 # 원래는 기본적으로 print의 end에 \n 이 지정된 상태인데 빈 문자열을 지정하면 강제로 \n을 지워주기 때문
# while True: # print("참") list = [1, 2, 3, 4, 5] while 5 == 5: print("참") # 부울 타입 앞글자가 대문자 isData = False # True while isData: print("참")
count = int(input('반복할 횟수를 입력하세요: ')) i = 0 while i < count: print('Hello, world! %d' % i) i += 1 # %d : 문자열 포맷 코드 # 삽입할 숫자는 % 문자 다음에 써넣는다.
# 집합을 표현하는 세트(set)라는 자료형 제공 # 합집합, 교집합, 차집합 등의 연산이 가능 fruits = {'strawberry', 'grape', 'orange', 'pineapple', 'cherry'} print(fruits) # [ ] 로 특정 요소만 출력할 수 없음 a = set('apple') print(a) # 중복된 문자는 포함되지 않는다. b = set(range(5)) print(b) c = set() print(type(c)) # 빈 set 만들기 # 세트가 { } 를 사용한다고 해서 c = { }와 같이 만들면 # 빈 딕셔너리가 만들어지므로 주의! # 세트 안에서 세트 사용 불가능 a = frozenset(range(10)) print(a) # 내용을 변경할 수 없는 세트도 제공
# if, else에서 변수에 값을 할당할 때는 # 변수 = 값 if 조건문 else 값 형식으로 축약 가능 # 이런 문법을 조건부 표현식이라고 부른다. # 보통 람다 표현식에서 사용 x = 5 y = x if x == 10 else 0 print(y) x = 5 if x == 10: y = x else: y = 0 print(y) # 위 표현식과 아래 조건문은 같다.
print('=-' * 20) print(' ' * 10, 'LOJA BALBINO') print('=-' * 20) print() soma = contador = totmil = menorpreco = 0 nomemenorpreco = ' ' while True: nomeproduto = str(input('Informe o nome do produto: ')).strip().title() precoproduto = float(input('Informe o preço do produto: R$ ')) contador += 1 if precoproduto > 1000: totmil += 1 soma += precoproduto if contador == 1 or precoproduto < menorpreco: menorpreco = precoproduto nomemenorpreco = nomeproduto continuar = str(input('Quer continuar? [ S / N ]: ')).strip().upper() if continuar == 'N': break while continuar != 'S': continuar = str(input('Quer continuar? [ S / N ]: ')).strip().upper() print('=-' * 20) print() print('TOTAL DA COMPRA') print() print(f'O total gasto nessa compra foi de R${soma}') print(f'Você comprou {totmil} produtos que custam mais de R$1000.00') print(f'O produto mais barato que foi coprado foi {nomemenorpreco}, e custa R${menorpreco}')
soma = 0 cont = 0 for n in range(1, 501, 2): if n % 3 == 0: cont += 1 soma += n print('A soma de todos os %i valores solicitados é igual a: %i' % (cont, soma))
print('{:^40}'.format(' \033[1;4;35mLOJAS BALBINO\033[m ')) print() preco = float(input('Informe o preço do produto: R$')) print('''Qual será a condição de pagamento? [ 1 ] Dinheiro/cheque (\033[4;1mà vista\033[m) [ 2 ] Cartão (\033[4;1mà vista\033[m) [ 3 ] Até \033[4;1m2x no cartão\033[m [ 4 ] \033[4;1m3x ou mais\033[m no cartão''') print() escolha = int(input('Escolha: ')) if escolha == 1: pag = int(input('[ 1 ]Dinheiro ou [ 2 ]Cheque?: ')) if pag == 1: print('O valor de R$\033[1;4;32m{:.2f}\033[m com o pagamento '.format(preco,), end='') print(' a vista com \033[1;34mDINHEIRO\033[m,', end='') print(' se torna R$\033[1;4;32m{:.2f}\033[m com 10% de desconto'.format(preco - (preco * 10 / 100))) elif pag == 2: print('O valor de R$\033[1;4;32m{:.2f}\033[m com o pagamento '.format(preco,), end='') print(' a vista com \033[34;1mCHEQUE\033[m,', end='') print(' se torna R$\033[1;4;32m{:.2f}\033[m com 10% de desconto'.format(preco - (preco * 10 / 100))) else: print() print('\033[1;4;31mERRO, TENTE NOVAMENTE\033[m') elif escolha == 2: print('O valor de R$\033[1;4;32m{:.2f}\033[m,'.format(preco, ), end='') print(' com o pagamento em cartão, se torna R$\033[1;4;32m{:.2f}\033[m'.format(preco - (preco * 5 / 100))) elif escolha == 3: pag = int(input('Deseja pagar em 1 ou 2 vezes?: ')) if pag == 1: print('Valor à pagar: R$\033[1;4;32m{:.2f}\033[m'.format(preco)) elif pag == 2: print('Para quitar o valor de R$\033[1;4;32m{:.2f}\033[m em duas prestações,'.format(preco), end='') print(' você terá que pagar DUAS parcelas de R$\033[1;4;32m{:.2f}\033[m'.format(preco / 2)) else: print('\033[1;4;31mERRO, TENTE NOVAMENTE\033[m') elif escolha == 4: p20 = preco * 20 / 100 pag = int(input('Você deseja pagar o valor de R$\033[1;4;32m{:.2f}\033[m em quantas vezes?: '.format(preco + p20))) print('Para quitar o valor de R$\033[1;4;32m{:.2f}\033[m em {} prestações,'.format(preco + p20, pag), end='') print(' você terá que pagar {} parcelas de R$\033[1;4;32m{:.2f}\033[m COM JUROS'.format(pag, (preco + p20) / pag)) else: print('\033[1;4;31mERRO, TENTE NOVAMENTE')
import sys def allstrings(alphabet, length): """Find the list of all strings of 'alphabet' of length 'length'""" if length == 0: return [] c = [[a] for a in alphabet[:]] if length == 1: return c c = [[x,y] for x in alphabet for y in alphabet] if length == 2: return c for l in range(2, length): c = [[x]+y for x in alphabet for y in c] return c length = int(sys.argv[1]) alphabet = ['A', 'C', 'G', 'T'] outfile = sys.argv[2] my_strings = allstrings(alphabet, length) with open(outfile,'w') as barcodes: for s in my_strings: outstring = ''.join(s) print(outstring, file=barcodes)
def Chorus(count): for i in range(count): print("Old MacDonald had a farm, E-I-E-I-O") def Inner(Animal, Sound): print("And on his farm he had some", Animal, ", E-I-E-I-O") print("With a", Sound, Sound, "here, And a", Sound, Sound, " there") print("Here a ", Sound, ", there a", Sound, " , Everywhere a", Sound, Sound) print("Imported")
class Solution(object): def trapRainWater(self, heightMap): """ :type heightMap: List[List[int]] :rtype: int """ #Brickstacks=[[3,4,5,0],[5,2,3,0],[6,4,5,0]] #the formation of bricks Brickstacks = heightMap Layer_n=[[0]*len(Brickstacks[0])for _ in range(len(Brickstacks))]#creating a copy of brickstacks except everything is 0 highestnum=0#used in accounting which layer to start on watercollected=0# total water collected oneswitchedchecker=1# checks if water has been marked X #print(Brickstacks,"Brickstacks") for x in range(0,len(Layer_n)):#coordinate x in finding highest layer for y in range(0,len(Layer_n[0])):#coordinate y in finding highest layer if (highestnum<Brickstacks[x][y]):#testing if there is a lyaer higher than current highest layer highestnum=Brickstacks[x][y]#changing highest layer if needed for i in range(0,highestnum):#used in switching in between layers for x in range(0,len(Layer_n)):#coordinate x in updating 2d array with blocked tiles for y in range(0,len(Layer_n[0])):#coordinate y in updating 2d array with blocked tiles if(Brickstacks[x][y]==highestnum-i):#testing whether a current tile is blocked Layer_n[x][y]=2#blocking which ever tile is blocked #print(Layer_n,"Layer_n") #print(highestnum-i,"current layer") while(oneswitchedchecker==1):#keeps repeating unless no tile is switched to has no water aka 1 oneswitchedchecker=0#resets this variable for the next round of checking for x in range(0,len(Layer_n)):#coordinate x used in figureing out if a certain tile contains water for y in range(0,len(Layer_n[0])):#coordinate y used in figuring out if a certain tile contains water if(Layer_n[x][y]==0):#making sure we are only changing the correct ones and not all of them to 1 if (x == 0 or y == 0 or x == len(Layer_n)-1 or y == len(Layer_n[0])-1):#all possible edge tiles Layer_n[x][y]=1#switched to water flows out or 1 oneswitchedchecker=1#confirms atleast one water has been marked to flow out #print(oneswitchedchecker) #print(Layer_n) #print("a") elif(Layer_n[x+1][y]==1 or Layer_n[x-1][y]==1 or Layer_n[x][y+1]==1 or Layer_n[x][y-1]==1):#tests if atleast one orthoganally adjacent spot cannot contain water Layer_n[x][y]=1#switched to water flows out or 1 oneswitchedchecker=1#confirms atleast one water has been marked to flow out #print(oneswitchedchecker) #print(Layer_n) #print("b") #print(Layer_n[x+1][y]) #print(x,y) #print(Layer_n,"this is the result") for x in range(0,len(Layer_n)):#coordinate x for setting up the array for the next layer and counting all water collected this layer for y in range(0,len(Layer_n[0])):#coordinate y for setting up the array for the next layer and counting all water collected this layer if(Layer_n[x][y]==0):#testing if this water was marked stay Layer_n[x][y]=3#marking the water permanent stay if(Layer_n[x][y]==3):#checking for the permanent stays watercollected=watercollected+1#adding one water collected since this water can stay #print(Layer_n,"what it looks like when watercollected added a water") if(Layer_n[x][y]==1):#testing if this water in uncollectable to reset for next layer Layer_n[x][y]=0#reseting any water that was deemed uncollectable oneswitchedchecker=1#just reseting this variable for its next use #print(watercollected)#the final answer return watercollected x = Solution() print(x.trapRainWater([[3,4,5,0],[5,2,3,0],[6,4,5,0]])) print(x.trapRainWater([[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]))
ThisIsAList=list() print(ThisIsAList) x = 8 ThisIsAList.append(x) ThisIsAList.append(6) print(ThisIsAList) ThisIsAList[0] = 7 print(ThisIsAList) for i in range(0,len(ThisIsAList)): ThisIsAList[i]=ThisIsAList[i]*5 print(ThisIsAList)
# Even and Odd function def evenOdd( x ): if (x % 2 == 0): print("even") else: print("odd") evenOdd(2) evenOdd(3)
import re as regex pattern = "^966" test_string = "966598739980" result = regex.match(pattern,test_string) if result: print("Saudi number") else: print("Not Saudi number")
def evenOdd(x): if (x % 2 == 0): print("even") else: print("odd") evenOdd(2) evenOdd(3) evenOdd(122) #------------------------------------------------------ # String lab: name = "Abdullah Alsrhri" print(name[9:]) #-------------------------------------------------------- # Loop lab i = 1; print() while (i <= 19): print(19 , " x " , i , " = " , i*19) i+=1 #---------------------------------------------------------- # exception handling lab try: print(5/0) except ZeroDivisionError: print() print("Exception of type ZeroDivisionError occurred") finally: print("*** inside finally ***")
import re as regex pattern = '^(966)(5|05)[0-9]{8}' test_string = ( input ( "Enter a number: " ) ) result = regex.match(pattern, test_string) if result: print("Saudi Number.") else: print(" Not Saudi Number.")
class RingBuffer: def __init__(self, capacity): self.capacity = capacity self.storage = [] self.counter = 0 def append(self, item): # if storage is less than the max capacity of the buffer # append new item to the end of the buffer if len(self.storage) < self.capacity: self.storage.append(item) # if storage is at max capacity # check if counter represents a position in storage # if counter doesn't represent a position in storage reset counter to 0, counter now represents first position # if counter represents a position in storage # make the element at that position equal to the new item # increment counter by +1 to represent the next position which will now be the oldest element in storage elif len(self.storage) == self.capacity: # change to dynamic if self.counter == self.capacity: self.counter = 0 self.storage[self.counter] = item self.counter += 1 def get(self): return self.storage
# def my_math_func(x, f): # return f(x) # def x_cube(x): # return x ** 3 # my_lambda = lambda x: x ** 3 # print(my_math_func(5, lambda x: x ** 3)) # print(my_lambda(5)) # my_letters = ['a', 'b', 'c', 'd', 'e'] # print(list(map(str.capitalize, my_letters))) # print(list(map(lambda x:x+x.capitalize(), my_letters))) from random import randint my_ints = [randint(1, 1000) for num in range(100)] print(list(map(lambda x:x ** 3, my_ints)))
#import the os module and module for reading csv files import os import csv budget_data = os.path.join("Resources","budget_data.csv") #file where data is held #read through csv file with open(budget_data) as csvfile: csvreader=csv.reader(csvfile,delimiter=",") csv_header=next(csvfile) #skip header row #variables/lists months = [] Profit = [] revenue_change = [] for rows in csvreader:#read through cvs after header months.append(rows[0]) Profit.append(int(rows[1])) for x in range(1, len(Profit)):#look for revenue change revenue_change.append((int(Profit[x]) - int(Profit[x-1]))) revenue_average = sum(revenue_change) / len(revenue_change)#find average rev change total_months = len(months)#total # of months/length greatest_increase = max(revenue_change)#greatest incr in rev change greatest_decrease = min(revenue_change)#greatest decr in rev change #print the Results in gitbash/terminal print(" ") print("Financial Analysis") print(".........................................................") print("total months: " + str(total_months)) print("Total: " + "$" + str(sum(Profit))) print("Average change: " + "$" + str(revenue_average)) print("Greatest Increase in Profits: " + str(months[revenue_change.index(max(revenue_change))+1]) + " " + "$" + str(greatest_increase)) print("Greatest Decrease in Profits: " + str(months[revenue_change.index(min(revenue_change))+1]) + " " + "$" + str(greatest_decrease)) #create new txt file and print to it analysis_file = os.path.join("Analysis","analysis.txt",) with open(analysis_file, "w") as file: file.write("Election Results" + "\n") file.write("......................................................." + "\n") file.write("total months: " + str(total_months) + "\n") file.write("Total: " + "$" + str(sum(Profit)) + "\n") file.write("Average change: " + "$" + str(revenue_average) + "\n") file.write("Greatest Increase in Profits: " + str(months[revenue_change.index(max(revenue_change))+1]) + " " + "$" + str(greatest_increase) + "\n") file.write("Greatest Decrease in Profits: " + str(months[revenue_change.index(min(revenue_change))+1]) + " " + "$" + str(greatest_decrease) + "\n")
# def gcd(a, b): from math import gcd def sum_of_digits(m): s = 0 while m > 0: s += m % 10 m = m // 10 return s for n in range(1, 100000): a = 2009 * n + 2019 * 2014 b = 2014 * n g = gcd(a, b) a = a / g if a % 1004 == 0: print(sum_of_digits(n)) break
#Problem Set 1 #Part A portion_down_payment = 0.25 current_savings = 0 r = 0.04 #investments earn a return of 4% annual_salary = int(input("Enter your starting annual salary:")) #120000 portion_saved = float(input("Enter the percent of your salary to save in decimal:")) #0.10 total_cost = int(input("Enter cost of your dream home:"))#1000000 months = 0 n = 0 def house_hunting(): print(portion_saved) print(total_cost) print(annual_salary) down_payment = total_cost * 0.25 while current_savings <= down_payment: current_savings += (portion_saved*annual_salary/12) + ((current_savings * r/12)) months = months + 1 print("Number of months: " + str(months)) #invest = current_savings * r/12 """ Enter your annual salary: 120000 Enter the percent of your salary to save, as a decimal: .10 Enter the cost of your dream home: 1000000 Number of months: 183 """
import csv # csv2dict.py # # This script takes csv-type data files and converts them into a python dictionary with the "first" line of the csv-file read in as the "headers" and, accordingly, as the dictionary "keys." # Created 2012Mar12 by BChoi # Ex.: mydict = csv2dict('/Users/bchoi/Documents/Rearden_Related/Axciom_Related/acxiomSample2.csv'); # # INPUTS: # fname = location and filename of csvfile containing data # OUTPUTS: # mydict = outputted python dictionary containing "hashtable" of csv-data # ----------------------------- csv2dict.py ------------------------------- def csv2dict(fname): #fname = '/Users/bchoi/Documents/Rearden_Related/Axciom_Related/acxiomSample2.csv' data = csv.reader(open(fname,"rU")) datalist = [] # initialize list datalist.extend(data) # extend data (csvtype) to list type headers = datalist[0]; # read in first line of data as "headers" listlist = [[] for k in range(len(headers))]; # initialze list of lists to STORE data for col in range(len(headers)): # loop thru all headers (features) rownum = 0; for obs in datalist: # loop thru all "rows" of data if rownum == 0: # dont read in first line (headers) rownum=0; else: if len(obs) != len(headers): # fill in with blanks if data in row is insufficient for k in range(len(obs),len(headers)): obs.append(''); print "added blank for missing column at location " + str(k) listlist[col].append(obs[col]); # "append" all rows in data for col in listlist rownum+=1; # create a dictionary (hashmap) for easier callable data structure mydict = {}; mydict = dict(zip(headers,listlist)); return mydict; # ----------------------------- csv2str.py ------------------------------- # Reads a delimited file and converts it into an array of strings # Created 2012May07 by BChoi # # Ex.: a = csv2dict.csv2str("/Users/bchoi/Desktop/ex5Data/ex5Linx.dat"); def csv2str(fname): data = csv.reader(open(fname,"rU")) datalist = [] # initialize list datalist.extend(data) # extend data (csvtype) to list type dataArray = array(datalist).flatten() # flatten() method used like "squeeze" in MATLAB return dataArray # ----------------------------- csv2num.py ------------------------------- # Reads a delimited file and converts it into a numerical array # Created 2012May07 by BChoi # # Ex.: a = csv2dict.csv2num("/Users/bchoi/Desktop/ex5Data/ex5Linx.dat"); from numpy import array def csv2num(fname): data = csv.reader(open(fname,"rU")) datalist = [] # initialize list datalist.extend(data) # extend data (csvtype) to list type dataArray = array(datalist,float).flatten() # flatten() method used like "squeeze" in MATLAB return dataArray
# Abstract Class class Animal(): def __init__(self, name): self.name = name def speak(self): raise NotImplementedError("Subclass must implement this abstract method") class Dog(Animal): def speak(self): return self.name + " says woof" class Cat(Animal) def speak(self): return self.name + " says meow"
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) [Clang 6.0 (clang-600.0.57)] on darwin Type "copyright", "credits" or "license()" for more information. >>> """ Tsagan Garyaeva CS 100 2018F Section 01 HW 0, Sep 7, 2018 """ # Exercise 5b
 days_in_year = 356 age = 35 gramms_in_kg = 1000 # Exercise 5c
 cost_per_pound_apple = 2.88 my_weight = 122.99 dim_to_ceiling = 8.3 # Exercise 5d
 my_name = 'Tsagan' fav_color = 'black' home_town = 'Howell' # Exercise 5e >>> song1 = ['na'] *17 >>> song1 [16] = 'Batman!' >>> song1 # 6 """ Exercise 1.1 1. In a print statement, what happens if you leave out one of the parentheses, or both? a) When I did not put the parantheses it gave me : built-in function print> b) When I left just one paranthese it broght me to the nest line and expected my input. 2. If you are trying to print a string, what happens if you leave out one of the quotation marks, or both? a) print('tsagan) SyntaxError: EOL while scanning string literal b) print(tsagan) Traceback (most recent call last): File "<pyshell#44>", line 1, in <module> print(tsagan) NameError: name 'tsagan' is not defined 3. You can use a minus sign to make a negative number like -2. What happens if you put a plus sign before a number? What about 2++2? >>> 3++7 10 >>> 2++2 4 >>> 4. In math notation, leading zeros are ok, as in 02. What happens if you try this in Python? >>> 02+9 SyntaxError: invalid token >>> 09 SyntaxError: invalid token >>> x = 09 SyntaxError: invalid token >>> 5. What happens if you have two values with no operator between them? SyntaxError: invalid token >>> 55 55 >>> 55 55 >>> 8 8 >>> 9 9 SyntaxError: invalid syntax >>> 8 7 SyntaxError: invalid syntax >>> Exercise 1.2. Start the Python interpreter and use it as a calculator. 1. How many seconds are there in 42 minutes 42 seconds? >> 42*60 2520 >>> 2520+42 2562 >>> 2. How many miles are there in 10 kilometers? Hint: there are 1.61 kilometers in a mile. >>> 10* 0.621371 6.21371 3. If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace (time per mile in minutes and seconds)? What is your average speed in miles per hour? 10km = 6.21371miles 42mins42sec = 42.7 mins s = d/t s= 6.21371 / 42.7 = 0.14 miles per min >>> 6.2137/42.7 0.145519906323185 >>> t = 2562 sec = 42.7mins / 60 = 0.71 hour >>> 6.2137/0.71 8.75169014084507 mph Exercise 2.1. Repeating my advice from the previous chapter, whenever you learn a new feature, you should try it out in interactive mode and make errors on purpose to see what goes wrong. • We’ve seen that n = 42 is legal. What about 42 = n? • >>> 42=n SyntaxError: can't assign to literal How about x = y = 1? >>> x= y= 1 >>> x 1 >>> y 1 • In some languages every statement ends with a semi-colon, ;. What happens if you put a semi-colon at the end of a Python statement? >>> print("hello"); hello >>> 2+3; 5 • What if you put a period at the end of a statement? >>> 3+5. 8.0 >>> print('hello'). SyntaxError: invalid syntax >>> 7/7. 1.0 >>> • In math notation you can multiply x and y like this: xy. What happens if you try that in Python? >>> x=3 >>> y=3 >>> xy Traceback (most recent call last): File "<pyshell#118>", line 1, in <module> xy NameError: name 'xy' is not defined Exercise 2.2. Practice using the Python interpreter as a calculator: 1. The volume of a sphere with >>> print(4/3.0*math.pi*5**3) 523.598775598298886 2. Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies? >>> book_price = 24.94 >>> discount = 40 >>> discount = book_price *(40/100) >>> discount_price =book_price - discount >>> shipping = 3 + (0.75 * (60 - 1)) >>> whole_sale = discount_price *60 + shipping >>> whole_sale 945.09 >>> discount 9.976 >>> print(discount_price) 14.964 >>> shipping 47.25 >>> whole_sale 945.09 >>> 3. If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast? start_time_hr = 6 + 52 / 60.0 easy_pace_hr = (8 + 15 / 60.0 ) / 60.0 tempo_pace_hr = (7 + 12 / 60.0) / 60.0 running_time_hr = 2 * easy_pace_hr + 3 * tempo_pace_hr breakfast_hr = start_time_hr + running_time_hr breakfast_min = (breakfast_hr-int(breakfast_hr))*60 breakfast_sec= (breakfast_min-int(breakfast_min))*60 print ('breakfast_hr', int(breakfast_hr) ) print ('breakfast_min', int (breakfast_min) ) print ('breakfast_sec', int (breakfast_sec) )
# pattern1 from heapq import heappush from heapq import heappop def linked_heap_sort(nums: list) -> list: heap = [] while nums: heappush(heap, nums.pop()) while heap: nums.append(heappop(heap)) return nums # pattern2 def heap_sort(nums: list) -> list: heapify(nums) index = len(nums) - 1 while index: nums[0], nums[index] = nums[index], nums[0] _siftup(nums, 0, index) index = index - 1 nums.reverse() return nums def _siftdown(heap, startpos, pos): newitem = heap[pos] while pos > startpos: parentpos = (pos - 1) >> 1 parent = heap[parentpos] if newitem < parent: heap[pos] = parent pos = parentpos continue break heap[pos] = newitem def _siftup(heap, pos, endpos): startpos = pos newitem = heap[pos] childpos = 2 * pos + 1 while childpos < endpos: rightpos = childpos + 1 if rightpos < endpos and not heap[childpos] < heap[rightpos]: childpos = rightpos heap[pos] = heap[childpos] pos = childpos childpos = 2 * pos + 1 heap[pos] = newitem _siftdown(heap, startpos, pos) def heapify(x): n = len(x) for i in reversed(range(n // 2)): _siftup(x, i, n)
a = int(input()) next = a+1 prev = a-1 print("The next number for the number %i is %i." % (a,next)) print("The previous number for the number %i is %i." % (a,prev))
import re import sys STRIPPING_REGEX = r'[A-Za-z].+' def strip_it(line): test = re.findall(STRIPPING_REGEX, line) if test: return test[0] def main(): file_names = sys.argv[-2:] if len(file_names) > 2: print 'Too many files' exit(-1) elif len(file_names) < 2: print 'Too few files' exit(-2) elif filter(lambda x: '.' not in x, file_names): print 'Need to have file extensions for both files' exit(-3) with open(file_names[0], 'r') as f, open(file_names[1], 'r') as g: first_file = filter(lambda x: x and x != '\n', f.readlines()) second_file = filter(lambda x: x and x != '\n', g.readlines()) for line in reversed(first_file): if line in second_file: del first_file[first_file.index(line)] del second_file[second_file.index(line)] with open(file_names[0].replace('.', '_diffs.'), 'w') as f, open(file_names[1].replace('.', '_diffs.'), 'w') as g: f.writelines(map(lambda x: x + '\n', first_file)) g.writelines(map(lambda x: x + '\n', second_file)) if __name__ == '__main__': main()
def pascal_triangle(n): tri = [[1]] while (len(tri) < n): prev = [0] + tri[-1] + [0] a = [] for i in range(len(prev)-1): a.append(prev[i] + prev[i+1]) tri.append(a) return tri[-1] def lattice_path(n): # solution for n x n square return max(pascal_triangle((n*2) + 1)) print "Answer:", lattice_path(20)
def digit_sum(n): if n == 0: return 0 return (n % 10) + digit_sum(int(n / 10)) maxA = 1 maxB = 1 max = 1 for a in range(100): for b in range(100): s = digit_sum(a**b) if (max < s): maxA = a maxB = b max = s print "Answer:", "a =", maxA, "b =", maxB, "sum =", max
import math r = 1.0 l_sect = ((2 * r * 2 * r) - (math.pi * r * r)) / 4 def solve_for_x(n): # find the x coordinate where the line between the # lower left corner of the 1st sqaure and the upper # right corner of thenth square intersects with the # circle in the 1st square n = 1.0 * n return ((2 + (2 / n)) - math.sqrt(((-2 - (2 / n)) ** 2) - (4 + (4/(n * n))))) / (2 * (1 + (1 / (n * n)))) def solve_for_y(x, n): # find the y coordinate where the line between the # lower left corner of the 1st sqaure and the upper # right corner of thenth square intersects with the # circle in the 1st square return (1.0 / n) * x def div_sect(n): # find the area of the segment x = solve_for_x(n) y = solve_for_y(x, n) tri_area = 0.5 * r * y c = math.hypot(y, 1.0 - x) theta = 2.0 * math.asin(c / (2.0 * r)) arc_area = (r / 2.0) * (theta - math.sin(theta)) return tri_area - arc_area n = 1 while (True): ratio = div_sect(n) / l_sect print "{0} - {1}\r".format(n, ratio), if ratio < 0.001: break n += 1 print print "Answer:", n
# Learn python at python_coderz_ def A(char): print("") for i in range(7): for j in range(5): if ((j == 0 or j == 4) and i != 0) or ((i == 0 or i == 3) and (j > 0 and j < 4)): print("*", end=" ") else: print(" ", end=" ") print("") def B(char): print("") for i in range(7): for j in range(5): if (j == 0) or (j == 4 and (i != 0 and i != 3 and i != 6)) or ((i == 0 or i == 3 or i == 6) and (j > 0 and j < 4)): print("*", end=" ") else: print(" ", end=" ") print("") def C(char): print("") for i in range(7): for j in range(5): if (j == 0 and (i != 0 and i != 6)) or ((i == 0 or i == 6) and (j < 4 and j > 0)): print("*", end=" ") else: print(" ", end=" ") print("") def D(char): print("") for i in range(7): for j in range(5): if (j == 0) or (j == 4 and (i != 0 and i != 6)) or ((i == 0 or i == 6) and (j > 0 and j < 4)): print("*", end=" ") else: print(" ", end=" ") print("") def E(char): print("") for i in range(7): for j in range(5): if j == 0 or i == 0 or i == 3 or i == 6: print("*", end=" ") else: print(" ", end=" ") print("") def F(char): print("") for i in range(7): for j in range(5): if j == 0 or i == 0 or i == 3: print("*", end=" ") else: print(" ", end=" ") print("") def G(char): print("") for i in range(7): for j in range(6): if j == 0 or (j == 4 and (i !=1 and i != 2)) or ((i == 0 or i == 6) and (j > 0 and j < 5)) or (i == 3 and (j != 1 and j != 2)): print("*", end=" ") else: print(" ", end=" ") print("") def H(char): print("") for i in range(7): for j in range(5): if (j == 0 or j == 4) or i == 3: print("*", end=" ") else: print(" ", end=" ") print("") def I(char): print("") for i in range(7): for j in range(5): if j == 2 or ((i == 0 or i == 6) and j != 2): print("*", end=" ") else: print(" ", end=" ") print("") def J(char): print("") for i in range(7): for j in range(5): if j == 2 or i == 0 or (j == 1 and i == 6) or (j == 0 and (i == 5 or i == 4)): print("*", end=" ") else: print(" ", end=" ") print("") def K(char): print("") for i in range(7): for j in range(5): if j == 0 or (j == 1 and i == 3) or (j == 2 and (i == 2 or i == 4)) or (j == 3 and (i == 1 or i == 5)) or (j == 4 and (i == 0 or i == 6)): print("*", end=" ") else: print(" ", end=" ") print("") def L(char): print("") for i in range(7): for j in range(5): if j == 0 or i == 6: print("*", end=" ") else: print(" ", end=" ") print("") def M(char): print("") for i in range(6): for j in range(5): if j == 0 or j == 4 or (i == 1 and (j == 1 or j == 3)) or (i == 2 and j == 2): print("*", end=" ") else: print(" ", end=" ") print("") def N(char): print("") for i in range(6): for j in range(6): if (j == 0 or j == 5) or ((i == 1 and j == 1) or (i == 2 and j == 2) or (i == 3 and j == 3) or (i == 4 and j == 4) or (i == 5 and j == 5)): print("*", end=" ") else: print(" ", end=" ") print("") def O(char): print("") for i in range(7): for j in range(5): if ((j == 0 or j == 4) and (i != 0 and i != 6)) or ((i == 0 or i == 6) and (j < 4 and j > 0)): print("*", end=" ") else: print(" ", end=" ") print("") def P(char): print("") for i in range(7): for j in range(5): if j == 0 or ((i == 0 or i == 3) and (j != 4)) or ((j == 4) and (i == 1 or i == 2)): print("*", end=" ") else: print(" ", end=" ") print("") def Q(char): print("") for i in range(8): for j in range(6): if ((j == 0 or j == 4) and (i > 0 and i < 6)) or ((i == 0 or i == 6) and (j < 4 and j > 0)) or (i == 5 and j == 2) or (i == 7 and j == 4): print("*", end=" ") else: print(" ", end=" ") print("") def R(char): print("") for i in range(8): for j in range(5): if j == 0 or ((i == 0 or i == 3) and (j != 4)) or ((j == 4) and (i == 1 or i == 2)) or (i == 4 and j == 1) or (i == 5 and j == 2) or (i == 6 and j == 3) or (i == 7 and j == 4): print("*", end=" ") else: print(" ", end=" ") print("") def S(char): print("") for i in range(7): for j in range(5): if (i == 0 and j != 0) or (j == 0 and (i == 1 or i == 2)) or (i == 3 and (j != 0 and j != 4)) or (j == 4 and (i == 4 or i == 5)) or (i == 6 and j != 4): print("*", end=" ") else: print(" ", end=" ") print("") def T(char): print("") for i in range(7): for j in range(5): if j == 2 or i == 0: print("*", end=" ") else: print(" ", end=" ") print("") def U(char): print("") for i in range(7): for j in range(5): if ((j == 0 or j == 4) and i != 6 ) or (i == 6 and (j > 0 and j < 4)): print("*", end=" ") else: print(" ",end=" ") print("") def V(char): print("") for i in range(5): for j in range(9): if (i == 0 and (j == 0 or j == 8)) or (i == 1 and (j == 1 or j == 7)) or (i == 2 and (j == 2 or j == 6)) or (i == 3 and (j == 3 or j == 5)) or (i == 4 and (j == 4)): print("*", end=" ") else: print(" ", end=" ") print("") def W(char): print("") for i in range(6): for j in range(5): if j == 0 or j == 4 or (i ==4 and (j == 1 or j == 3)) or (i == 3 and j == 2): print("*", end=" ") else: print(" ", end=" ") print("") def X(char): print("") for i in range(7): for j in range(7): if (i == 0 and (j == 0 or j == 6)) \ or (i == 1 and (j == 1 or j == 5)) \ or (i == 2 and (j == 2 or j == 4)) \ or (i == 3 and j == 3) \ or (i == 4 and (j == 2 or j == 4)) \ or (i == 5 and (j == 1 or j == 5)) \ or (i == 6 and (j == 0 or j == 6)): print("*", end=" ") else: print(" ", end=" ") print("") def Y(char): print("") for i in range(8): for j in range(7): if (j == 3 and (i != 0 and i != 1 and i != 2)) or (i == 0 and (j == 0 or j == 6)) or (i == 1 and (j == 1 or j == 5)) or (i == 2 and (j == 2 or j == 4)): print("*", end=" ") else: print(" ", end=" ") print("") def Z(char): print("") for i in range(6): for j in range(6): if (i == 0 or i == 5) or (i == 1 and j == 4) or (i == 2 and j == 3) or (i == 3 and j == 2) or (i == 4 and j == 1) or (i == 5 and j == 1): print("*", end=" ") else: print(" ", end=" ") print("") name = input("enter your name: ") print('Program Developed By Shailendra:-') char = [] for i in name: char.append(i.upper()) for j in char: if j == "A": A(char) if j == "B": B(char) if j == "C": C(char) if j == "D": D(char) if j == "E": E(char) if j == "F": F(char) if j == "G": G(char) if j == "H": H(char) if j == "I": I(char) if j == "J": J(char) if j == "K": K(char) if j == "L": L(char) if j == "M": M(char) if j == "N": N(char) if j == "O": O(char) if j == "P": P(char) if j == "Q": Q(char) if j == "R": R(char) if j == "S": S(char) if j == "T": T(char) if j == "U": U(char) if j == "V": V(char) if j == "W": W(char) if j == "X": X(char) if j == "Y": Y(char) if j == "Z": Z(char)
from argparse import ArgumentParser import json def main(): # hi test = False # num_found = {selector_name : selector_count} num_found = {} # get local json file as command line args parser = ArgumentParser(description='get json for input') parser.add_argument('input', type=str, help="json file") args = parser.parse_args() # load the json file into a dictionary views with open(args.input, 'r') as f: views = json.load(f) # get selector from user print('class e.g. StackView, classNames e.g. .container, identifier e.g. #videoMode') selector = input('Enter selector: ') while selector: # enter nothing to exit # get attribute type from prefix if selector[0] == '.': attrib = 'classNames' selector = selector[1:] elif selector[0] == '#': attrib = 'identifier' selector = selector[1:] else: attrib = 'class' # for implementing the bonus questions i was thinking of splitting # the input and running the first token to generate a list of views or roots, # num_found = {compound_selector_name : [list of json views]} # then i could call the 2nd selector on each one of those json views to # see if it is a child # store the number found num_found = {selector : 0} search_json(views, selector, attrib, num_found, test) print('{} found {} views'.format(selector, num_found[selector])) # select another item selector = input('Enter selector: ') # begin test # not sure if you wanted an assertion statement # or just the number printed on the screen as above test = True attrib = 'class' num_found['Input'] = 0 search_json(views, 'Input', attrib, num_found, test) assert num_found['Input'] == 26, 'Input should return 26 items. returned {}'.format(num_found['Input']) print('All Done..\n') # print the children starting from the root in json format, if in test, do not # print anything def print_children(root, test): if test: return print('{}\n'.format(json.dumps(root, indent=4))) # recursively iterate through the dictionary, if search term is found, print # children using the term's container as the root, and track the count for # each earch term in a table def search_json(json_obj, term, attrib, num_found, test): if isinstance(json_obj, dict): for k, v in json_obj.items(): # check if a className is in a list of ClassNames # if so, print the view if k == attrib and isinstance(v, list): for item in v: if item == term: num_found[term] +=1 print_children(json_obj, test) # if the value matches the search term, print view elif v == term and k == attrib: num_found[term] +=1 print_children(json_obj, test) else: search_json(v, term, attrib, num_found, test) elif isinstance(json_obj, list): for value in json_obj: search_json(value, term, attrib, num_found, test) if __name__ == '__main__': main()
class Employee: no_of_leaves = 8 def __init__(self,name,salary,role): self.name = name self.salary = salary self.role = role def printdetails(self): return f"name is {self.name}. salary is {self.salary}. and role is {self.role}" classmethod def change_leaves(cls, newleaves): cls.no_of_leaves = newleaves murat = Employee("Murat",4500,"Instructor") ahaan = Employee("Ahaan",4554,"Student") murat.change_leaves(34) # print(murat.printdetails()) print(murat.no_of_leaves)
class Employee: no_of_leaves = 8 def __init__(self, name, salary, role): #Dunder method self.name = name self.salary = salary self.role = role def printdetails(self): return f"name is {self.name}. salary is {self.salary}. and role is {self.role}" @classmethod def change_leaves(cls, newleaves): cls.no_of_leaves = newleaves def __add__(self, other): #used for operator overloading return self.salary + other.salary def __truediv__(self, other): return self.salary / other.salary def __repr__(self): return f"Employee ({self.name}, {self.salary}, {self.role})" def __str__(self): return f"name is {self.name}. salary is {self.salary}. and role is {self.role}" emp1 = Employee("Murat", 956, "student") # emp2 = Employee("Doruk", 756, "Programmer") print(emp1) # mapping operator google
f1 = open("twinkle.txt") try: f = open("does2.txt") except Exception as e: print(e) except EOFError as e: print("Print eof error aa gaya hai", e) except IOError as e: print("Print IO error aa gaya hai", e) else: print("This will run only if except is not running") finally: print("Run this anyway....") # f.close() f1.close() print("Important Stuff")
import random n = int(input("Enter the number of friends \n")) name_list = input(f"Enter the name of your {n} friends \n")
n = int(input("")) sum = 0 while n > 0: sum = sum+m n = n-1 print sum
# your code goes here def isIsogram(n): charMap={} for h in n: if h in charMap: return False else: charMap[c]=1 return True n=raw_input().rstrip() print("Yes" if isIsogram(n) else "No")
# your code goes here n=int(input("")) count=0 while(n>0): count=count+1 n=n//10 print("the number of digits in the given number:",count)
num = int(input("enter the number")) if num < 0: print("the number is negative") elif num == 0: print("the number is zero") else: print("the given number is positive")
s = int(raw_input()) if(s < = 10): print ("yes") else: print("no")
n = int(raw_input()) reverse = 0 while(n > 0): remainder = n % 10 reverse = reverse* 10 + remainder n = n/10 print reverse
class TreeNode: def __init__(self, val, left=None, right=None, parent=None): self.left = left self.right = right self.parent = parent self.val = val def __repr__(self): return str(self.val) root = TreeNode(6) l1 = TreeNode(5) l11 = TreeNode(2) l12 = TreeNode(5) l2 = TreeNode(7) l22 = TreeNode(8) root.left = l1 root.right = l2 l1.parent = root l2.parent = root l1.left = l11 l1.right = l12 l2.right = l22 l11.parent = l1 l12.parent = l1 l22.parent = l2 s = [] def inorder_traversal(r: TreeNode): x = r while x is not None: s.append(x) x = x.left while len(s) > 0: x = s.pop() print(x) x = x.right while x is not None: s.append(x) x = x.left inorder_traversal(root)
from sort import heapsort, quicksort, insertion_sort, reverse, add_integers, counting_sort, radix_sort import unittest class TestSort(unittest.TestCase): def test_heap_sort(self): x = [4, 8, 2, 1, 0] self.assertEqual(heapsort(x)[::-1], [0, 1, 2, 4, 8]) def test_quicksort(self): x = [4, 8, 2, 1, 0] self.assertEqual(quicksort(x), [0, 1, 2, 4, 8]) def test_counting_sort(self): x = [4, 8, 2, 1, 0] self.assertEqual(counting_sort(x, 0, 8), [0, 1, 2, 4, 8]) def test_radix_sort(self): a = [1,9,5,3] b = [0, 5] with self.assertRaises(ValueError): radix_sort([a,b]) a = [1,9,5,3] b = [1,9,7,2] c = [2,0,0,2] d = [2,1,2,2] e = [0,1,2,2] f = [0,0,3,9] out = radix_sort([f, b, c, a, d, e]) self.assertEqual(out, [(0, 0, 0, 2), (0, 0, 2, 2), (1, 1, 2, 2), (1, 1, 3, 2), (2, 9, 5, 3), (2, 9, 7, 9)]) def test_insertion_sort(self): x = [4, 8, 2, 1, 0] self.assertEqual(insertion_sort(x), [0, 1, 2, 4, 8]) def test_merge_sort(self): x = [4, 8, 2, 1, 0] self.assertEqual(insertion_sort(x), [0, 1, 2, 4, 8]) def test_reverse(self): x = [4, 8, 2, 1, 0] self.assertEqual(reverse(x), [0, 1, 2, 8, 4]) def test_add_integers(self): a = [7, 4, 5, 3] b = [6, 4, 3, 2] self.assertEqual(add_integers(a, b), [1, 3, 8, 8, 5]) if __name__ == '__main__': unittest.main()
if __name__ == "__main__": Enviroment = object from board import Board O = "O" X = "X" P1 = 1 P2 = -1 else: from ..environment import Environment, P1, P2 from .board import Board from . import O, X class TicTacToe(Environment): def __init__(self, board = None): if board is None: self.board = Board() else: self.board = board self.turn = P1 def get_turn(self): return self.turn def get_action_size(self): return 9 def playout(self, action): my_symbol = O if self.turn == P1 else X self.board.state[action] = my_symbol self.turn = -self.turn def get_state_size(self): return len(self.board.state) + 1 def get_state(self): def to_number(s): if s == O: return 1 elif s == X: return -1 else: return 0 return [to_number(s) for s in self.board.state] + [self.get_turn()] def valid_actions(self): return [i for i, s in enumerate(self.board.state) if s is None] def is_complete(self): return (None not in self.board.state) or self.winner() is not None def winner(self): def player(s): if s == O: return P1 else: return P2 s = self.board.state for i in range(0,3): # horizontal j = i * 3 if s[j] is not None and s[j] == s[j + 1] and s[j] == s[j + 2]: return player(s[j]) for i in range(0,3): # verticle if s[i] is not None and s[i] == s[i + 3] and s[i] == s[i + 6]: return player(s[i]) # diagonal if s[0] is not None and s[0] == s[4] and s[0] == s[8]: return player(s[0]) if s[2] is not None and s[2] == s[4] and s[2] == s[6]: return player(s[2]) if None not in self.board.state: return 0 return None # still playable # score in respect to the player def evaluate(self, player): winner = self.winner() if winner == player: return 1 elif winner == -player: return -1 else: return winner # 0 or None def copy(self): env_copy = TicTacToe(self.board.copy()) env_copy.turn = self.turn return env_copy def __str__(self): return str(self.board) def reset(self): self.board = Board() def heuristic(self, *args): return 0
def fib(n): """returns the nth Fibonacci number""" sequence = [0, 1] for i in range(n + 1): value = sequence[-2] + sequence[-1] sequence.append(value) return sequence[n]
# @Time : 2018/11/5 14:41 # @Author : Yanlin Wang # @Email : [email protected] # @File : 8. WORKING WITH TEXT DATA.py from time import clock import pandas as pd import numpy as np start = clock() s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat']) """ # 对序列进行操作 s.str.lower() s.str.upper() s.str.len() # 字符串操作 s.str.strip() # 删除序列字符串前后的空格 idx.str.rstrip() idx.str.lstrip() # 删除序列左右的空格 """ df = pd.DataFrame(np.random.randn(3, 2), columns=[' Column A ', ' Column B '], index=range(3)) """ dataframe进行操作 df.columns.str.strip() """ df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_') print(df.head()) end = clock() print('time: {:.8f}s'.format(end - start))
# @Time : 2018/9/25 22:29 # @Author : Yanlin Wang # @Email : [email protected] # @File : TempConvert.py def temp_convert(temp_str): """ 华氏温度F,和摄氏温度C互相转换 :param temp_str: 输入的温度,华氏(F)or摄氏(C) :return: 转换后的温度 """ # temp_str = input("input your temp") if temp_str[-1] in ['F', 'f']: C = (eval(temp_str[0:-1]) - 32) / 1.8 # Python 切片不包括右侧, Python小数除法 print("摄氏温度是 {0:.2f}C".format(C)) return C elif temp_str[-1] in ['c', 'C']: F = 1.8 * eval(temp_str[0:-1]) + 32 # string eval to number print("华氏温度是 {0:.2f}F".format(F)) return F print("请输入带有符号的温度值:") return "input wrong" if __name__ == "__main__": temp_str = input("input temperature: ") # return a string temp_convert(temp_str) """ in 配合切片,定点筛查 not in ['n', 'N'] """
# @Time : 2018/9/25 22:21 # @Author : Yanlin Wang # @Email : [email protected] # @File : print_input_format.py print("hello,world") # print 中间分隔符 sep print('www', 'python', 'org', sep='.') # 以 . 分割 print('www', 'python', 'org', sep='\n') # 以 换行 分割 # print 结束符end= 默认是结束后换行, 可以改为空,则连续输出 print('hello, world', end='') print("hello,world") print('hello, world', end='***\n') # 同步赋值 x = 1 y = 2 print("x is {0}, y is {1}".format(x, y)) x, y = y, x print("x is {0}, y is {1}".format(x, y)) # input, return a string, use function eval(); """ TempStr = input("Please input your number: ") """ # eval() 函数 """ eval(<字符串>) 函数是Python 语言中一个重要的函数 它能够以Python表达式的方式解析并执行字符串,并将返回结果输出 将输入的字符串变成Python语句 x = 1 eval("x + 1") # 2 eval("1.1 + 2.2") # 3.3 解析并执行语句 TempStr = "102C" eval(TempStr[0:-1]) # 102 去掉最后一个字符,结果执行为一个数字 eval("hello") # 默认将字符串执行为 变量 name 'hello' not defined """ # 命名规范 """ 文件名,包:全部小写,可使用下划线 函数名,变量名全部小写,myfunction, my_example 类: 首字母大写单词串 MyTime 常量名所有字母大写 """ # Python 格式化输出 {}.format() """ Python格式化输出和C真是非常的相似 1. 打印字符串 >>> a='AAAA' >>> b='BBBB' >>> print('a=%s b=%s' %(a,b)); a=AAAA b=BBBB 2.打印整数 >>> a=10 >>> b=20 >>> print('a=%d b=%d' %(a,b)); a=10 b=20 >>> 3.打印浮点数 >>> a=1.1234 >>> b=3.14159; >>> print('a=%d b=%d' %(a,b)); a=1 b=3 >>> print('a=%f b=%f' %(a,b)); a=1.123400 b=3.141590 >>> python2.5 python3.5默认浮点数都保留6位小数 4.打印浮点数(指定保留小数点位数) >>> a=1.1234 >>> b=3.14159; >>> print('a=%.2f b=%.3f' %(a,b)); a=1.12 b=3.142 %f里指定保留小数位数时具有自动四舍五入的功能,比如b=3.14159 使用%.3f格式化之后输出的结果变成了b=3.142 5.指定占位符宽度 >>> a='ABC' >>> b='DEFF' >>> print('a=%4s b=%6s' %(a,b)); a= ABC b= DEFF 还可以指定特定的占位符 >>> a='ABC' >>> b='DEFF' >>> d=125 >>> print('a=%4s b=%6s d=%04d' %(a,b,d)); a= ABC b= DEFF d=0125 指定输出d使用4个字符宽度,如果不够在前面补零,输出字符串时,默认右对齐,其实可以调整的 6.指定占位符宽度,指定对其方式 >>> a='ABC' >>> b='DEFF' >>> d=125 >>> print('a=%-4s b=%-6s d=%-06d' %(a,b,d)); a=ABC b=DEFF d=125 """ """ Python format print "{:.2f}".format(3.1415926) #3.14,保留小数点后两位 print "{:+.2f}".format(3.1415926) #+3.14 带符号保留小数点后两位 print "{:+.2f}".format(-10) #-10.00 带符号保留小数点后两位 print "{:+.0f}".format(-10.00) #-10 不带小数 print "{:0>2d}".format(1) #01 数字补零 (填充左边, 宽度为2) print "{:x<2d}".format(1) #1x 数字补x (填充右边, 宽度为4) print "{:x<4d}".format(10) #10xx 数字补x (填充右边, 宽度为4) print "{:,}".format(1000000) #1,000,000 以逗号分隔的数字格式 print "{:.2%}".format(0.12) #12.00% 百分比格式 print "{:.2e}".format(1000000) #1.00e+06 指数记法 print "{:<10d}".format(10) #10 左对齐 (宽度为10) print "{:>10d}".format(10) # 10 右对齐 (默认, 宽度为10) print "{:^10d}".format(10) # 10 中间对齐 (宽度为10) 1.格式符 ‘f’表示浮点数 ‘d’表示十进制整数. 将数字以10为基数进行输出 ‘%’表示百分数. 将数值乘以100然后以fixed-point(‘f’)格式打印, 值后面会有一个百分号 ‘e’表示幂符号. 用科学计数法打印数字, 用’e’表示幂. 2.对齐与填充 ^、<、>分别是居中、左对齐、右对齐,后面带宽度 :后面带填充字符,只能是一个字符,不指定的话默认就是空格。 """ # 字符串格式化 print('%s,eggs, and %s' % ('spam', 'spam!'))
""" Where's That Word? functions. """ # The constant describing the valid directions. These should be used # in functions get_factor and check_guess. UP = 'up' DOWN = 'down' FORWARD = 'forward' BACKWARD = 'backward' # The constants describing the multiplicative factor for finding a # word in a particular direction. This should be used in get_factor. FORWARD_FACTOR = 1 DOWN_FACTOR = 2 BACKWARD_FACTOR = 3 UP_FACTOR = 4 # The constant describing the threshold for scoring. This should be # used in get_points. THRESHOLD = 5 BONUS = 12 # The constants describing two players and the result of the # game. These should be used as return values in get_current_player # and get_winner. P1 = 'player one' P2 = 'player two' P1_WINS = 'player one wins' P2_WINS = 'player two wins' TIE = 'tie game' # The constant describing which puzzle to play. Replace the 'puzzle1.txt' with # any other puzzle file (e.g., 'puzzle2.txt') to play a different game. PUZZLE_FILE = 'puzzle1.txt' # Helper functions. def get_column(puzzle: str, col_num: int) -> str: """Return column col_num of puzzle. Precondition: 0 <= col_num < number of columns in puzzle >>> get_column('abcd\nefgh\nijkl\n', 1) 'bfj' """ puzzle_list = puzzle.strip().split('\n') column = '' for row in puzzle_list: column += row[col_num] return column def get_row_length(puzzle: str) -> int: """Return the length of a row in puzzle. >>> get_row_length('abcd\nefgh\nijkl\n') 4 """ return len(puzzle.split('\n')[0]) def contains(text1: str, text2: str) -> bool: """Return whether text2 appears anywhere in text1. >>> contains('abc', 'bc') True >>> contains('abc', 'cb') False """ return text2 in text1 def get_current_player(player_one_turn: bool) -> str: """Return 'player one' iff player_one_turn is True; otherwise, return 'player two'. >>> get_current_player(True) 'player one' >>> get_current_player(False) 'player two' """ if player_one_turn: return P1 else: return P2 def get_winner(player_one_score: int, player_two_score: int) -> str: """Return 'player one wins' iff player_one_score is greater than player_two_score; otherwise, Return 'player two wins' iff player_two_score is greater than player_one_score; otherwise, return 'tie game'. >>> get_winner(6, 5) 'player one wins' >>> get_winner(6,6) 'tie game' """ if player_one_score > player_two_score: return P1_WINS elif player_one_score < player_two_score: return P2_WINS else: return TIE def reverse(line: str) -> str: """Return the reverse copy of line. >>> reverse('zohaib') 'biahoz' >>> reverse('python') 'nohtyp' """ return line[::-1] def get_row(puzzle: str, row_num: int) -> str: """Return row row_num of puzzle. Precondition: 0 <= row_num < number of rows in puzzle >>>get_row('abcd\nefgh\nijkl\n', 2) 'ijkl' >>>get_row('abcde\nfghij\nklmno\n', 1) 'fghij' """ row_length = get_row_length(puzzle) first_index = (row_length + 1) * row_num last_index = first_index + row_length return puzzle[first_index : last_index] def get_factor(direction: str) -> int: """Return the multiplicative factor associated with the direction. >>>get_factor(UP) 4 >>>get_factor(DOWN) 2 """ if direction == UP: return UP_FACTOR elif direction == DOWN: return DOWN_FACTOR elif direction == FORWARD: return FORWARD_FACTOR else: return BACKWARD_FACTOR def get_points(direction: str, words_left: int) -> int: """Return the points earned towards the direction when words_left number of words are left. >>>get_points(BACKWARD, 5) 15 >>>get_points(BACKWARD, 1) 39 """ factor = get_factor(direction) if words_left >= THRESHOLD: points = THRESHOLD * factor else: points = (2 * THRESHOLD - words_left) * factor if words_left == 1: points += BONUS return points def check_guess(puzzle: str, direction: str, guessed_word: str, row_or_col_num: int, words_left: int) -> int: """Return the number of points earned when a guessed_word in found towards the direction in a row_or_col_num row or column of the puzzle when words_left number of words are left. Precondition: 0 <= row_or_col_num < number of rows or columns in puzzle >>>check_guess('abcd\nefgh\nijkl\n', BACKWARD, 'hgf', 1, 1) 39 >>>check_guess('abcd\nefgh\nijkl\n', BACKWARD, 'kji', 2, 5) 15 """ if direction == DOWN and contains(get_column(puzzle, row_or_col_num), guessed_word): return get_points(direction, words_left) elif direction == UP and contains(reverse(get_column(puzzle, row_or_col_num)), guessed_word): return get_points(direction, words_left) elif direction == FORWARD and contains(get_row(puzzle, row_or_col_num), guessed_word): return get_points(direction, words_left) elif direction == BACKWARD and contains(reverse(get_row(puzzle, row_or_col_num)), guessed_word): return get_points(direction, words_left) else: return 0
def calcReimburse(rate, startMileage, endMileage): return eval(f"{rate} * ({endMileage} - {startMileage}) / 100") # evaluates string representation of expression def readFile(fileName): with open(fileName, 'r') as file: # read in contents of file lines = file.read().split("\n") # lines is a list of lines of the file data = [[], []] # data[0] will hold subtitles # data[1] will hold list of lists of car data for line in lines: tokens = line.split(',') # tokens obtained using comma delimiter if not line == lines[0]: # if line is not equal to the heading line data[1].append(tokens) if line == lines[0]: data[0] = tokens for carData in data[1]: # for each car data list, calculate the reimbursement val_reimb = calcReimburse(carData[1], carData[2], carData[3]) carData.append(val_reimb) # add the reimbursement amount to the appropriate car data list return data def writeFile(data, fileName): with open(fileName, 'w') as file: # open file for writing for subtitle in data[0]: # write subtitles to file first and newline if not subtitle == data[0][-1]: # if not last element, include a comma file.write(subtitle + ",") else: file.write(subtitle) file.write("\n") # newline after subtitles for carData in data[1]: # write car data to file for item in carData: if not item == carData[-1]: # if not last element, include a comma file.write(str(item) + ",") else: file.write(str(item)) file.write("\n") # newline after each car's data is done being written to file def main(): data = readFile("dataIn.csv") writeFile(data, "dataOut.csv") if __name__ == '__main__': main()
#Write a function reverseArray(A) that takes in an array A and reverses it, #without using another array or collection data structure; in-place. def reverseArray(A): if ( not A ) or ( A == 0 ): exit("The array can not be empty") #Begining of the index start_index = 0 #End of the index - 1 end_index = len(A) - 1 #Swamp elements while end_index > start_index: A[start_index], A[end_index] = A[end_index], A[start_index] start_index += 1 end_index -= 1 return(A) A = [10, 5, 6, 9, 10, 3, 1, 8] print("The original list") print(A) print("") print("The reverse list") print(reverseArray(A))
import pandas as pd import json #将每条评论放入list 中 def get_data(contents_all): contents = [] for content_data in contents_all: c = content_data.split('。') contents.append(c) return contents #将评论分行写入txt 文件中 def totxt(contents): f = open("raw data/contents.txt","w+") for content in contents: for c in content: f.writelines(c+"\n") f.close() if __name__ == '__main__': #读取csv 中所有新闻所有评论 excelFile = 'raw data/data_new.csv' df = pd.DataFrame(pd.read_excel(excelFile)) contents_all = df['content'].values contents = get_data(contents_all) # print(content[1]) totxt(contents)
# Uses python2 def calc_fib(n): fib=[] fib.append(0) fib.append(1) if(n>=2): for i in xrange(2,n+1): fib.append(fib[i-1]+fib[i-2]) return fib[i] elif(n==1): return 1 else: return 0 n = int(input()) print(calc_fib(n))
import random def split(L): p = random.choice(L) l, r = [], [] m = 0 for e in L: if e < p: l.append(e) elif e > p: r.append(e) else: m += 1 return l, [p] * m, r def quickSort(L): if len(L) <= 1: return L l, m, r = split(L) return quickSort(l) + m + quickSort(r) def quickSearch(L, pos): if len(L) <= 1: return L l, m, r = split(L) if len(l) > pos: # In l return quickSearch(l, pos) elif len(l) + len(m) > pos: # In m return m[0] else: # In r return quickSearch(r, pos - (len(l) + len(m)))
# modified to be able to store ids and values in heap. # Heap shortcuts def left(i): return i * 2 + 1 def right(i): return i * 2 + 2 def parent(i): return (i - 1) / 2 def root(i): return i == 0 def leaf(L, i): return right(i) >= len(L) and left(i) >= len(L) def one_child(L, i): return right(i) == len(L) def val_(pair): return pair[0] def swap(heap, old, new, location): location[heap[old]] = new location[heap[new]] = old (heap[old], heap[new]) = (heap[new], heap[old]) # Call this routine if the heap rooted at i satisfies the heap property # *except* perhaps i to its children immediate children # # # location is a dictionary mapping an object to its location # in the heap def down_heapify(heap, i, location): # If i is a leaf, heap property holds while True: l = left(i) r = right(i) # see if we don't have any children if l >= len(heap): break v = heap[i][0] lv = heap[l][0] # If i has one child... if r == len(heap): # check heap property if v > lv: # If it fails, swap, fixing i and its child (a leaf) swap(heap, i, l, location) break rv = heap[r][0] # If i has two children... # check heap property if min(lv, rv) >= v: break # If it fails, see which child is the smaller # and swap i's value into that child # Afterwards, recurse into that child, which might violate if lv < rv: # Swap into left child swap(heap, i, l, location) i = l else: # swap into right child swap(heap, i, r, location) i = r # Call this routine if whole heap satisfies the heap property # *except* perhaps i to its parent def up_heapify(heap, i, location): # If i is root, all is well while i > 0: # check heap property p = (i - 1) / 2 if heap[i][0] < heap[p][0]: swap(heap, i, p, location) i = p else: break # put a pair in the heap def insert_heap(heap, v, location): heap.append(v) location[v] = len(heap) - 1 up_heapify(heap, len(heap) - 1, location) # build_heap def build_heap(heap): location = dict([(n, i) for i, n in enumerate(heap)]) for i in range(len(heap) - 1, -1, -1): down_heapify(heap, i, location) return location # remove min def heappopmin(heap, location): # small = heap[0] val = heap[0] new_top = heap.pop() del location[val] if len(heap) == 0: return val location[new_top] = 0 heap[0] = new_top down_heapify(heap, 0, location) return val def decrease_val(heap, location, old_val, new_val): i = location[old_val] heap[i] = new_val # is this the best way? del location[old_val] location[new_val] = i up_heapify(heap, i, location) def _test_location(heap, location): for n, i in location.items(): assert heap[i] == n def _test_heap(): h = [(1, 'a'), (4, 'b'), (6, 'c'), (8, 'd'), (9, 'e'), (1, 'f'), (4, 'g'), (5, 'h'), (7, 'i'), (8, 'j')] location = build_heap(h) _test_location(h, location) old_min = (-float('inf'), None) while len(h) > 0: new_min = remove_min_heap(h, location) _test_location(h, location) assert val_(old_min) <= val_(new_min) old_min = new_min def _test_add_and_modify(): h = [(1, 'a'), (4, 'b'), (6, 'c'), (8, 'd'), (9, 'e'), (1, 'f'), (4, 'g'), (5, 'h'), (7, 'i'), (8, 'j')] location = build_heap(h) insert_heap(h, (-1, 'k'), location) assert (-1, 'k') == remove_min_heap(h, location) decrease_val(h, location, (6, 'c'), (-1, 'c')) assert (-1, 'c') == remove_min_heap(h, location) _test_location(h, location)
# # Given a list of numbers, L, find a number, x, that # minimizes the sum of the absolute value of the difference # between each element in L and x: SUM_{i=0}^{n-1} |L[i] - x| # # Your code should run in Theta(n) time # import random def split(L): p = random.choice(L) l, r = [], [] m = 0 for e in L: if e < p: l.append(e) elif e > p: r.append(e) else: m += 1 return l, [p] * m, r def quickSort(L): if len(L) <= 1: return L l, m, r = split(L) return quickSort(l) + m + quickSort(r) def quickSearch(L, pos): if len(L) <= 1: return L l, m, r = split(L) if len(l) > pos: # In l return quickSearch(l, pos) elif len(l) + len(m) > pos: # In m return m[0] else: # In r return quickSearch(r, pos - (len(l) + len(m))) def minimize_absolute(L): return quickSearch(L, len(L) / 2)
""" Python script that contains Grid and Node class definitions. Grid class is a two dimensional collection of Nodes that allows for a graphical and interactive representation of the A* pathfinding algorithm. Node class represents a single unit of the two-dimensional grid with varying states to represent different phases of the A* pathfinding algorithm. """ import pygame import MinPriorityQueue class Grid: """ Represents the arrangment of nodes/cells in the two-dimensional array. Attributes: surface: the surface object on which to draw the grid onto nodes: the two-dimensional list arrangment of nodes that makes up the grid Constants: VERT_HORZ_COST: Cost of vertical/horizontal path movement DIAG_COST: Cost of diaginal path movement COLUMNS: Number of columns in grid ROWS: Number of rows in grid """ VERT_HORZ_COST = 10 DIAG_COST = 14 PATHFIND_TIMEDELAY = 50 DEFAULT_START_ROW = 9 DEFAULT_START_COL = 4 DEFAULT_TARGET_ROW = 9 DEFAULT_TARGET_COL = -5 def __init__(self, surface, rect, columns, rows): """ Initializes an instance of the Grid class. """ self.__surface = surface self.__rect = rect self.__columns = columns self.__rows = rows self.__width = rect.width self.__height = rect.height self.__nodes = [] self.__start = None self.__target = None self.create_grid() self.set_start_node() self.set_target_node() self.__solved = False def create_grid(self): """ Initializes the arrangment of grid nodes. Nodes are initialized and stored in the two-dimensional list attribute self.__nodes. There are no obstacle nodes at initialization. All nodes except start and target nodes are walkable. """ self.__solved = False self.__nodes = [] width = self.__width // self.__columns height = self.__height // self.__rows for row_index in range(self.__rows): row = [] for column_index in range(self.__columns): node = Node(column_index, row_index, width, height) node.draw() row.append(node) self.__nodes.append(row) def draw(self): """ Draws the grid object. Draws the grid object by drawing all nodes in self.__nodes. """ for row in self.__nodes: for node in row: node.draw() def set_as_obstacle(self, mouse_pos, selected_nodes): """ Handles click event on a grid node. Determines which node was selected. If selected node was UNDISCOVERED, it is changed to OBSTACLE, and vice versa. Args: mouse_pos: position of the mouse cursor when event occurred selected_nodes: set of Nodes that have been selected in current continous mouse-key-down Returns: Node that has toggled, or None if no Node was toggled """ node = self.get_node(mouse_pos) if node not in selected_nodes: node.toggle_obstacle() return node def collidepoint(self, point): """ Tests if a point is inside the Grid area. Args: point: the (x, y) coordinates of the point Returns: True if point is on Grid area, False otherwise """ return self.__rect.collidepoint(point) def set_start_node(self, node=None): """ Sets the start node of the Grid. Args: node: The Node object to be set as the start node. (If no argument given, the node is set to the default.) """ # Set to default if no optional paramater given if node is None: node = self.__nodes[Grid.DEFAULT_START_ROW][Grid.DEFAULT_START_COL] # Let node be start node only if given node is not already target node if self.__target != node: if self.__start is not None: self.__start.make_undiscovered() node.set_start() self.__start = node def set_target_node(self, node=None): """ Sets the target node of the Grid. Args: node: The Node object to be set as the target node. (If no argument given, the node is set to the default.) """ # Set to default if no optional paramater given if node is None: node = self.__nodes[Grid.DEFAULT_TARGET_ROW][Grid.DEFAULT_TARGET_COL] # Let node be target node only if given node is not already start node if self.__start != node: if self.__target is not None: self.__target.make_undiscovered() node.set_target() self.__target = node def get_node(self, pos): """ Gets the node at a given position on the surface. It is assummed that the position has already been checked to be a valid point that lies on the Grid. This can be checked with the Grid.collidepoint method. Args: pos: The (x, y) position to be checked Returns: The node at the given (x, y) position """ x, y = pos j = x // (self.__width // self.__columns) i = y // (self.__height // self.__rows) return self.__nodes[i][j] # ------------------------------------------- # Methods related to A* pathfinding algorithm # ------------------------------------------- def solve(self, show_steps=True): """ Solves the current Grid layout. Solves the current Grid layout by finding a shortest path from the start node to the target node using the A* pathfinding algorithm. The path can be found with or without a visual demonstration of each step. Args: show_steps: bool that determines if steps should be shown """ if self.__start is None or self.__target is None: raise AttributeError("Start Node and Target Node are not set.") try: if show_steps: self.find_path() else: self.find_path_nonvisual() except IndexError: self.print_no_solution() else: self.print_path() def find_path(self): """ Find a path from start position to target position. Given the start and target attributes, finds the cheapest path from the start node to the target node using the A* pathfinding algorithm. Steps in the algorithm are shown graphically with time delays to show path progression. """ opened = MinPriorityQueue.MinPriorityQueue() closed = set() self.calculate_all_h_costs() self.__start.relax_g_cost(0) opened.insert(self.__start.get_f_cost(), self.__start) current = None path_found = False while not path_found: pygame.time.delay(Grid.PATHFIND_TIMEDELAY) # Select node with smallest f_cost from opened current = opened.extract_min() # If found target, break the loop if current is self.__target: path_found = True self.__solved = True # If target not found, add neighbours to opened else: vh_neighbours = self.get_vert_horz_neighbours(current) d_neighbours = self.get_diag_neighbors(current) for node in vh_neighbours: if node.relax_g_cost(current.get_g_cost() + Grid.VERT_HORZ_COST): node.set_prev(current) if opened.element_exists(node): opened.decrease_key(node, node.get_f_cost()) else: opened.insert(node.get_f_cost(), node) node.make_open() for node in d_neighbours: if node.relax_g_cost(current.get_g_cost() + Grid.DIAG_COST): node.set_prev(current) if opened.element_exists(node): opened.decrease_key(node, node.get_f_cost()) else: opened.insert(node.get_f_cost(), node) node.make_open() # Finish with current closed.add(current) current.close() # Update UI, handle QUIT if necessary for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() self.draw() pygame.display.update() def find_path_nonvisual(self): """ Find a path from start position to target position. Given the start and target attributes, finds the cheapest path from the start node to the target node using the A* pathfinding algorithm. """ opened = MinPriorityQueue.MinPriorityQueue() closed = set() self.calculate_all_h_costs() self.__start.relax_g_cost(0) opened.insert(self.__start.get_f_cost(), self.__start) current = None path_found = False while not path_found: # Select node with smallest f_cost from opened current = opened.extract_min() # If found target, break the loop if current is self.__target: path_found = True self.__solved = True # If target not found, add neighbours to opened else: vh_neighbours = self.get_vert_horz_neighbours(current) d_neighbours = self.get_diag_neighbors(current) for node in vh_neighbours: if node.relax_g_cost(current.get_g_cost() + Grid.VERT_HORZ_COST): node.set_prev(current) if opened.element_exists(node): opened.decrease_key(node, node.get_f_cost()) else: opened.insert(node.get_f_cost(), node) for node in d_neighbours: if node.relax_g_cost(current.get_g_cost() + Grid.DIAG_COST): node.set_prev(current) if opened.element_exists(node): opened.decrease_key(node, node.get_f_cost()) else: opened.insert(node.get_f_cost(), node) # Finish with current closed.add(current) def is_solved(self): """ Gets if Grid has been solved. Returns: True is solved, False otherwise """ return self.__solved def calculate_all_h_costs(self): """ Initialize the h_costs of all nodes for an execution of find_path. Sets the heuristic h_cost for all nodes in Grid at the beginning of an execution of find_path. """ for row in self.__nodes: for node in row: # Calculate direct distance from node to target vdist = abs(node.get_row() - self.__target.get_row()) hdist = abs(node.get_col() - self.__target.get_col()) diag = min(vdist, hdist) updown = max(vdist, hdist) - min(vdist, hdist) dist = diag * Grid.DIAG_COST + updown * Grid.VERT_HORZ_COST node.set_h_cost(dist) def get_vert_horz_neighbours(self, node): """ Gets all walkable nodes that are directly above, below, left or right of the given node. Args: node: the Node object Returns: adjacent: list of Node objects that are vertically/horizontally adjacent to given node and walkable. """ adjacent = [] # Get the row and column of the node x, y = node.get_pos() col = x // (self.__width // self.__columns) row = y // (self.__height // self.__rows) for i, j in (-1, 0), (1, 0), (0, -1), (0, 1): if row + i >= 0 and col + j >= 0: try: adj = self.__nodes[row+i][col+j] if not adj.is_obstacle(): adjacent.append(adj) except IndexError: pass return adjacent def get_diag_neighbors(self, node): """ Gets all walkable nodes that are adjacent and diagonal to the given node. Args: node: the Node object Returns: adjacent: list of Node objects that are vertically/horizontally adjacent to given node and walkable. """ adjacent = [] # Get the row and column of the node x, y = node.get_pos() col = x // (self.__width // self.__columns) row = y // (self.__height // self.__rows) for i, j in (-1, -1), (1, -1), (-1, 1), (1, 1): if row + i >= 0 and col + j >= 0: try: adj = self.__nodes[row+i][col+j] if not adj.is_obstacle(): adjacent.append(adj) except IndexError: pass return adjacent def print_path(self): """ Changes state of all nodes in solution path. For every node that has been identified to be part of the optimal solution path, changes the state of the node. It is assumed that find_path has been executed and a solution has been found. """ if self.__solved: current = self.__target.get_prev() while current is not self.__start: current.add_to_solution() current = current.get_prev() def print_no_solution(self): """ Displays pathfinding result when there is no solution. """ self.__target.set_no_sol_target() class Node: """ Object which represents a unit on the two-dimensional grid. A node object has represents a single unit on a two dimensional grid. A node can be in one of several states. The state defines how the node is to be graphically represented and determines how it can interact with surrounding nodes on the grid. Possible Node states : UNDISCOVERED : Node is walkable and not directly accessable by an adjacent closed Node OPENED : Node is walkable and directly accessable by an adjacent closed Node CLOSED : Node is no longer walkable, was opened and all handling on Node has been completed START : Node is designated as the start position of the path TARGET : Node is designated as the target position of the path OBSTACLE : Node is not walkable SOLUTION : Node has been identified to be part of solution path Attributes : rect : the Rect object that graphically represents the Node pos : tuple representing the x-y position of the node on the surface prev : reference to the Node that opened current Node in the execution of path finding state : int representing the current state of the node """ pygame.font.init() FONT = pygame.font.SysFont("Arial", 20, True) FONT_COLOR = pygame.Color('white') UNDISCOVERED = 'UNDISCOVERED' OPENED = 'DISCOVERED' CLOSED = 'CLOSED' START = 'START' TARGET = 'TARGET' OBSTACLE = 'OBSTACLE' SOLUTION = 'SOLUTION' NO_SOL_TARGET = 'NO_SOL_TARGET' BG_COLORS = { UNDISCOVERED : pygame.Color("white"), OPENED : pygame.Color('yellow'), CLOSED : pygame.Color('red'), START : pygame.Color("blue"), TARGET : pygame.Color("blue"), OBSTACLE : pygame.Color("black"), SOLUTION : pygame.Color("green"), NO_SOL_TARGET : pygame.Color("red") } BORDER_COLOR = pygame.Color("black") BRDER_WIDTH = 1 surface = None @classmethod def set_surface(cls, surface): """ Sets the pygame drawing surface for all node objects. """ cls.__surface = surface def __init__(self, col, row, width, height): """ Initializes an instance of the Node class. """ self.__row = row self.__col = col self.__width = width self.__height = height self.__pos = (self.__width*self.__col, self.__height*self.__row) self.__rect = pygame.Rect(self.__pos, (width, height)) self.__prev = None self.__state = Node.UNDISCOVERED self.__h_cost = None self.__g_cost = None def draw(self): """ Draws the node on the surface. Draws the node on the surface given as instance attribute. A node is drawn in accordance with its state. """ pygame.draw.rect(self.__surface, Node.BG_COLORS[self.__state], self.__rect) if self.__state == Node.START: self.draw_node_text("S") if self.__state == Node.TARGET or self.__state == Node.NO_SOL_TARGET: self.draw_node_text("T") # if self.__state == Node.OPENED or self.__state == Node.CLOSED or self.__state == Node.SOLUTION: # self.draw_g_cost() # self.draw_h_cost() # self.draw_f_cost() pygame.draw.rect(self.__surface, self.BORDER_COLOR, self.__rect, Node.BRDER_WIDTH) def draw_node_text(self, text): """ Draws text centered in the current node. """ text_image = self.FONT.render(text, True, self.FONT_COLOR) x = self.__pos[0] + (self.__rect.width//2) - (text_image.get_width()//2) y = self.__pos[1] + (self.__rect.height//2) - (text_image.get_height()//2) self.__surface.blit(text_image, (x, y)) def draw_g_cost(self): """ Draws the g_cost of the node in the upper left corner of the Node rect. """ text_image = self.FONT.render(str(self.__g_cost), True, self.BORDER_COLOR) x = self.__pos[0] + Node.BRDER_WIDTH y = self.__pos[1] self.__surface.blit(text_image, (x, y)) def draw_h_cost(self): """ Draws the h_cost of the node in the upper right corner of the Node rect. """ text_image = self.FONT.render(str(self.__h_cost), True, self.BORDER_COLOR) x = self.__pos[0] + self.__width - text_image.get_width() - Node.BRDER_WIDTH y = self.__pos[1] self.__surface.blit(text_image, (x, y)) def draw_f_cost(self): """ Draws the f_cost of the node in the center of the Node rect. """ text_image = self.FONT.render(str(self.__h_cost+self.__g_cost), True, self.BORDER_COLOR) x = self.__pos[0] + (self.__rect.width//2) - (text_image.get_width()//2) y = self.__pos[1] + (self.__rect.height//2) - (text_image.get_height()//2) self.__surface.blit(text_image, (x, y)) def toggle_obstacle(self): """ Toggles node between undiscovered and obstacle states. If a node is currently undiscovered and not the target node, the node state will be changed to obstacle. If a node is currently an obstacle and not the start node, the node change will be changes to walkable. """ if self.__state == Node.UNDISCOVERED: self.__state = Node.OBSTACLE elif self.__state == Node.OBSTACLE: self.__state = Node.UNDISCOVERED def set_start(self): """ Sets node to be the start node. """ self.__state = Node.START def set_target(self): """ Sets node to be the target node. """ self.__state = Node.TARGET def set_no_sol_target(self): """ Identified Node as an unreachable target Node. """ self.__state = Node.NO_SOL_TARGET def make_undiscovered(self): """ Changes the state of the node to OPEN. """ self.__state = Node.UNDISCOVERED def make_open(self): """ Changes the state of the node to OPEN. """ if self.__state != Node.START and self.__state != Node.TARGET: self.__state = Node.OPENED def close(self): """ Changes the state of the node to CLOSED. """ if self.__state != Node.START and self.__state != Node.TARGET: self.__state = Node.CLOSED def is_obstacle(self): """ Returns true if node state is obstacle """ return self.__state == Node.OBSTACLE def add_to_solution(self): """ Identifies node state as part of solution. """ self.__state = Node.SOLUTION def set_h_cost(self, h_cost): """ Initializes the h cost of the node. """ assert isinstance(h_cost, int) self.__h_cost = h_cost def relax_g_cost(self, cost): """ Relaxes the g_cost of the current node. If the current g_cost is None or higher than the given cost, then cost is assigned to g_cost. Args: cost: The new potential g_cost for the Node Raises: AssertionError: cost paramater is not an int Returns: True if g_cost was relaxed/modified, False otherwise """ assert isinstance(cost, int), "Cost must be an int" if self.__g_cost is None or cost < self.__g_cost: self.__g_cost = cost return True else: return False def get_g_cost(self): """ Gets the g cost of the node. """ return self.__g_cost def get_f_cost(self): """ Gets the f cost of the node. """ return self.__h_cost + self.__g_cost def set_prev(self, prev_node): """ Sets the prev attribute of the current node. Args: prev_node: Node object to set to the prev of this Node Raises: TypeError: prev_node is not of type Node """ if not isinstance(prev_node, Node): raise TypeError('prev_node must be of type Node') self.__prev = prev_node def get_prev(self): """ Gets the prev node for the Node.""" return self.__prev def get_row(self): """ Gets the row of the node. """ return self.__row def get_col(self): """ Gets the column of the node. """ return self.__col def get_pos(self): """ Gets the position of the Node. """ return self.__pos def __repr__(self): """ Returns representation of Node object. """ return { "Row":self.__row, "Column":self.__col, "F-cost":self.get_f_cost() }
class Animal(object): def __init__(self, name): self.name = name self.health = 100 def Walk(self): print 'Walking' self.health -= 1 return self def Run(self): print 'Running' self.health -= 5 return self def Display_health(self): print 'My name is: ' + str(self.name) print 'My current health is: '+ str(self.health) animal = Animal('Cat') animal.Walk() animal.Walk() animal.Walk() animal.Run() animal.Run() animal.Display_health() # or animal = Animal('Dog') animal.Walk().Walk().Walk().Run().Run().Display_health() class Dog(Animal): def __init__(self, name): super(Dog,self).__init__(name) self.health = 150 def pet(self): print 'Get pets' self.health += 5 return self dog = Dog('Sophie') dog.Walk().Walk().Walk().Run().Run().pet().Display_health() class Dragon(Animal): def __init__(self, name): super(Dragon,self).__init__(name) self.health = 170 def fly(self): print 'Flying and seeking prey' self.health -= 10 return self def Display_health(self): print "I am THE Dragon you fear" super(Dragon, self).Display_health() dragon = Dragon('Nightfury') dragon.fly().Display_health() class Horse(Animal): def __init__(self, name): super(Horse,self).__init__(name) self.health = 125 horse = Horse('Carl') horse.Display_health()
# Nettoyer la console avant le demarrage du programme # import os os.system('clear') ####################################################### ################## # counting FIZZBUZZ # ################# num = 1 fizzes = 0 buzzes = 0 fizzbuzzes = 0 fizval = [] buzval = [] fizbuzval = [] while num <= 1000: if ((num % 3) == 0) and ((num % 5) == 0): print("FIZZBUZZ " + str(num) + " est divisible par 3 et 5") fizzbuzzes += 1 fizbuzval.append(num) elif (num % 5) == 0: print("BUZZ " + str(num) + " est divisible par 5") buzzes += 1 buzval.append(num) elif (num % 3) == 0: print("FIZZ " + str(num) + " est divisible par 3") fizzes += 1 fizval.append(num) else: print(num) num += 1 print("\nFizzes = " + str(fizzes)) print("All Fizzes : " + str(fizval)) print("\nBuzzes = " + str(buzzes)) print("All Buzzes : " + str(buzval)) print("\nFizzbuzzes = " + str(fizzbuzzes)) print("All Fizzbuzzes : " + str(fizbuzval))
# I want to be able to call capitalize_nested from main w/ various lists # and get returned a new nested list with all strings capitalized. # Ex. ['apple', ['bear'], 'cat'] # Verify you've tested w/ various nestings. # In your final submission: # - Do not print anything extraneous! # - Do not put anything but pass in main() ############################################################################## # Write a list of first and last names #[First Last, First Last, etc] # def capitalize_nested(list_): # return_list = [] # for thing in list_: # if isinstance(thing, list): # return_list.append(capitalize_nested(thing)) # else: # return_list.append(thing[0].upper() + thing[1:]) # return return_list def capitalize_nested(list_): return[capitalize_nested(thing) if isinstance(thing, list) else thing.capitalize() for thing in list_] ############################################################################## def main(): # list1 = ['apple', ['bear'], 'cat'] # print_list = capitalize_nested(list1) # print print_list pass if __name__ == '__main__': main()
import socket, sys from pynput.keyboard import Key, Listener #Create socket (allows two computers to connect) def create_socket(): try: global host global port global s host = "10.1.10.162" port = 9999 s = socket.socket() except socket.error as msg: print("Socket Creation Error:", str(msg)) #bind socket to port (host and port communication will take place def bind_socket(): try: global host global port global s print("Binding socket to port", str(port)) s.bind((host, port)) s.listen(5) except socket.error as msg: print("Socket Binding Error", str(msg)) print("Retrying...") bind_socket() #establish connection from client to server (socket must be binded) def established_connection(): conn, addr = s.accept() print("Connection Established: ") print("IP: ", addr[0]) print("Port: ", addr[1]) #send command to client send_command(conn) #Close The Connection conn.close() #Send commands to user/client #Record Keystrokes on client computer #Must pass in the users IP Address/Connection def send_command(conn): while True: send = input("Insert Command:") cmd = str.encode(send) if len(cmd) > 0: conn.send(cmd) client_response = str(conn.recv(1024), "utf-8") print(client_response, end="") def main(): create_socket() bind_socket() established_connection() send_command() #run program main()
from collections import Counter def vowel_count(phrase): """Return frequency map of vowels, case-insensitive. >>> vowel_count('rithm school') {'i': 1, 'o': 2} >>> vowel_count('HOW ARE YOU? i am great!') {'o': 2, 'a': 3, 'e': 2, 'u': 1, 'i': 1} """ vowels = 'aeiou' phrase = phrase.lower() vow_count = {} char_count = Counter(phrase) for vowel in vowels: if not char_count[vowel] == 0: vow_count[vowel] = char_count[vowel] return vow_count print(vowel_count('HOW ARE YOU? i am great!'))
# -*- coding: utf-8 -*- """ Created on Fri Feb 19 09:35:43 2021 @author: yerminal @website: https://github.com/yerminal """ import numpy as np mu, sigma = 0, 0.1 # mean and standard deviation s = np.random.normal(mu, sigma, 100) print("Mean Difference:",abs(mu - np.mean(s))) print("STD Difference:",abs(sigma - np.std(s, ddof=1))) """ The standard deviation is the square root of the average of the squared deviations from the mean, i.e., std = sqrt(mean(x)), where x = abs(a - a.mean())**2. The average squared deviation is typically calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of the variance of the infinite population. ddof=0 provides a maximum likelihood estimate of the variance for normally distributed variables. The standard deviation computed in this function is the square root of the estimated variance, so even with ddof=1, it will not be an unbiased estimate of the standard deviation per se. Reference: https://numpy.org/doc/stable/reference/generated/numpy.std.html """
# python3 import sys, threading sys.setrecursionlimit(10**6) # max depth of recursion threading.stack_size(2**27) # new thread will get stack of such size class TreeOrders: def read(self): self.n = int(sys.stdin.readline()) self.key = [0 for i in range(self.n)] self.left = [0 for i in range(self.n)] self.right = [0 for i in range(self.n)] for i in range(self.n): [a, b, c] = map(int, sys.stdin.readline().split()) self.key[i] = a self.left[i] = b self.right[i] = c self.in_order = [] self.pre_order = [] self.post_order = [] def inOrder(self, tree=0): if tree == -1: return self.inOrder(self.left[tree]) self.in_order.append(self.key[tree]) self.inOrder(self.right[tree]) def preOrder(self, tree=0): if tree == -1: return self.pre_order.append(self.key[tree]) self.preOrder(self.left[tree]) self.preOrder(self.right[tree]) def postOrder(self, tree=0): if tree == -1: return self.postOrder(self.left[tree]) self.postOrder(self.right[tree]) self.post_order.append(self.key[tree]) def main(): tree = TreeOrders() tree.read() tree.inOrder() tree.preOrder() tree.postOrder() print(" ".join(str(x) for x in tree.in_order)) print(" ".join(str(x) for x in tree.pre_order)) print(" ".join(str(x) for x in tree.post_order)) threading.Thread(target=main).start() # 5 # 4 1 2 # 2 3 4 # 5 -1 -1 # 1 -1 -1 # 3 -1 -1
# P-1.29 Write a Python program that outputs all possible strings # formed by using the characters 'c' , 'a' , 't' , 'd' , 'o' , and 'g' # exactly once. from typing import Dict, List def permutate(input: str) -> None: """ prints out all permutations of input Taking a recursive approach the algorithm will use a frequency table that of the input string and methodically exhaust the decision space by removing character from it one by one and adding them to the result, always backtracking when the possibilities for a certain variation are done. This algorithm also works with repeating characters in the input and will output the result in lexicographically correct order. Time complexity: O(!n) where n == len(input); Note: if input has repeated characters, the time complexity will decrease, e.g. for input == "AABB" it'll be !4/(!2*!2) Space complexity: O(n) where n == len(input), since we're just printing the results and don't store them, otherwise it would be O(n*!n) """ # Create a frequency table for the characters fTable = {} for c in input: if c in fTable: fTable[c] += 1 else: fTable[c] = 1 keys = sorted(fTable.keys()) string = [] count = [] for key in keys: string.append(key) count.append(fTable[key]) result = ["" for i in range(len(input))] permuteUtil(string, count, result, 0) counter = 0 def permuteUtil(string: [str], count: [int], result: List[str], level: int) -> None: if level == len(result): global counter counter += 1 print(counter, "".join(result)) return for i in range(len(result)): if count[i] == 0: continue result[level] = string[i] count[i] -= 1 permuteUtil(string, count, result, level+1) count[i] += 1 permutate("catdog")
# R-2.6 If the parameter to the make_payment method of the CreditCard class # were a negative number, that would have the effect of raising the balance # on the account. Revise the implementation so that it raises a ValueError if # a negative value is sent. class CreditCard: """A consumer credit card.""" def __init__(self, customer: str, bank: str, acnt: str, limit: float): """ Create a new credit card instance. The initial balance is zero. customer the name of the customer (e.g., John Bowman ) bank the name of the bank (e.g., California Savings ) acnt the acount identifier (e.g., 5391 0375 9387 5309 ) limit credit limit (measured in dollars) """ self.customer = customer self.bank = bank self.account = acnt self.limit = limit self.balance = 0 def get_customer(self) -> str: """Return name of the customer.""" return self.customer def get_bank(self) -> str: """Return the bank s name.""" return self.bank def get_account(self) -> str: """Return the card identifying number (typically stored as a string).""" return self.account def get_limit(self) -> float: """Return current credit limit.""" return self.limit def get_balance(self) -> float: """Return current balance.""" return self.balance def charge(self, price: float) -> bool: """ Charge given price to the card, assuming sufficient credit limit. Return True if charge was processed; False if charge was denied. """ if not isinstance(price, (int, float)): raise TypeError("Price must be numeric!") if price + self.balance > self.limit: # if charge would exceed limit, return False # cannot accept charge else: self.balance += price return True def make_payment(self, amount: float): """Process customer payment that reduces balance.""" if not isinstance(amount, (int, float)): raise TypeError("Amount must be numeric!") if amount < 0: raise ValueError("Amount can't be less than zero!") self.balance -= amount # Overriding builtin methods def __str__(self): return f""" {self.get_customer()} has account {self.get_account()} with {self.get_bank()}. The account has a balance of {self.get_balance()} and a limit of {self.get_limit()}. ********************************************************************************* """ if __name__ == "__main__": card = CreditCard("azgh", "some Bank", "666 999 333", 1000) print(card) card.charge(100) print(card) card.make_payment(50) print(card) # card.make_payment(-10) # raise ValueError
# C-1.23 Give an example of a Python code fragment that attempts to write an ele- # ment to a list based on an index that may be out of bounds. If that index # is out of bounds, the program should catch the exception that results, and # print the following error message: # “Don’t try buffer overflow attacks in Python!” from typing import List def throwsOutOfBoundsException(data: List): try: for i in range(len(data)+1): print(data[i]) except IndexError: print("Don't try buffer overflow attacks in Python!") data = [1, 3, 4, 6, 7] throwsOutOfBoundsException(data)
import sys def print_odd_numbers(): """ :rtype: None """ for x in range(1, 101): if x % 2: print x def print_mult_tables(): for x in range(1, 13): result = "" for y in range(1, 13): result += str(x * y) + ' ' print '{0} {1}'.format(x, result) def main(args): """ :param args: args from main :rtype: None """ #print_odd_numbers() print_mult_tables() if __name__ == '__main__': main(sys.argv[1:])
""" SOURCE: https://stackoverflow.com/questions/53975717/pytorch-connection-between-loss-backward-and-optimizer-step """ import torch x = torch.tensor([1.0], requires_grad=True) y = torch.tensor([2.0], requires_grad=True) z = 3*x**2+y**3 print("x.grad: ", x.grad) print("y.grad: ", y.grad) # print("z.grad: ", z.grad) # # print result should be: # x.grad: None # y.grad: None # z.grad: None # calculate the gradient z.backward() print("x.grad: ", x.grad) print("y.grad: ", y.grad) # print("z.grad: ", z.grad) # # print result should be: # x.grad: tensor([6.]) # y.grad: tensor([12.]) # z.grad: None # create an optimizer, pass x,y as the paramaters to be update, sutting the learning rate lr=0.1 optimizer = torch.optim.SGD([x, y], lr=0.1) # executing an update step optimizer.step() # print the updated values of x and y print("x:", x) print("y:", y) # print result should be: # x: tensor([0.4000], requires_grad=True) # y: tensor([0.8000], requires_grad=True)
#coding=utf-8 d=lambda x:x+1 if x > 0 else 'Error' g = lambda x:[(x,i) for i in xrange(0,10)] print g(0) print 'x'*10 print d(9) print d(10) def e(x): return x+1 print e(12) print d(-0) # 函数的参数总结 # 1、位置匹配 def func(arg1,arg2): return arg1,arg2 print func(1,2) #2、关键字匹配 def func1(k1='',k2='None',k3=''): return k1,k2,k3 print func1(k1='2',k3='5') print func1(k3='5',k1='2') print func1(k1='2',k2='3',k3='5') '''' #3、收集匹配 1)、元组收集 2)、字典收集 ''' def func3(a,b,u,*kargs,**kwargs): return kargs print func3('w','e','t',1,2,3,4,5,{'d':1,'u':2}) #位置参数 先是位置匹配的参数 再是关键字匹配的参数 收集匹配的元组的参数 收集匹配的字典的参数 ********Next 递归*********
''' 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。 注意:答案中不可以包含重复的三元组。 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ] ''' class Solution: #全部组合 def threeSum(self, nums): list1=[] for i in range(len(nums)-2): for j in range(i+1,len(nums)-1): for k in range(i+2,len(nums)): if(nums[i]+nums[j]+nums[k]==0): list1.append([nums[i],nums[j],nums[k]]) return list1 def threeSum1(self,nums): list1=[] d1={} for i in range(len(nums)-2): for j in range(i+1,len(nums)-1): if nums[j] in d1: print(nums[j]) print(d1[nums[j]]) temp = d1[nums[j]].copy() temp.append(nums[j]) list1.append(temp) else: d1[-nums[i]-nums[j]]=[nums[i],nums[j]] return list1 def threeSum2(self,nums): list1=[] nums=sorted(nums) print(nums) for i in range(1,len(nums)-1): # if(i>1): # if(nums[i]==nums[i-1]): # continue k=0 j=len(nums)-1 while(i<j and i>k): if(nums[i]+nums[j]+nums[k]==0): print('append') print(i,j,k) list1.append([nums[i],nums[j],nums[k]]) if(nums[i]+nums[j]+nums[k]<=0 and k<i): print(i,j,k) k+=1 while(nums[k]==nums[k-1]): print('<'+str(k)) k+=1 elif(nums[i]+nums[j]+nums[k]>=0 and i<j): print(i,j,k) j-=1 while(nums[j]==nums[j+1]): print('>'+str(j)) j-=1 else: break return list1 if __name__ == '__main__': nums = [-1, 0, 1, 2, -1, -4] nums #print(Solution().threeSum(nums)) #print(Solution().threeSum1(nums)) print(Solution().threeSum2(nums))
#coding:UTF-8 ''' Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. ''' class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ dict2={'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'} if not digits: return [] listAll=[''] # for digit in digits: # digit_letter = dict2[digit] # res_temp=[] # for item in digit_letter: # res_temp+=[x+item for x in listAll] # listAll=res_temp for digit in digits: listAll=[x+y for x in listAll for y in dict2[digit]] return listAll # for i in digits: # list1.append(dict2[i]) # print(list1) # listAll=[] # listAll.append('') # for item in list1: # listAll=self.addStr(listAll,item) # return listAll def addStr(self,str1,str2): listAll=[] for x in str1: for y in str2: listAll.append(x+y) return listAll if __name__ == '__main__': print('hello') nums = '23' print(Solution().letterCombinations(nums))
# blocks a list of sites import time from datetime import datetime as dt # siteblocker.py # accesses a hostfile and edits it based on the time of day. # # TODO # does not yet run as a daemon/cron (back burner) hosts_temp = "/Users/DM-Alt/Software Dev/Python/siteblock/hosts" hosts_path = "/etc/hosts" redirect = "127.0.0.1" website_list = ['www.facebook.com', 'facebook.com', 'news.google.com', 'jalopnik.com', 'macrumors.com',\ 'daringfireball.com', 'reddit.com','www.reddit.com',\ 'nytimes.com','kottke.org'] # =================================================== print(dt.now().weekday()) # syntax for printing day of week while True: # today is Tuesday (1) so we use another number for testing (0) # ---------------------------------- # ATTEMPTS # 1: # if (dt.today().weekday()) in range [0:4]: # 2: # weekday = int(dt.today().weekday()) # if weekday not in range [0:4]: # # 3: # if dt.today().weekday < 5: # # 4: # print(int(dt.now().weekday())) # # -- we need a range that is 0,1,2,3,4 for M-F but it seems datetime is not subscriptable in a range like this. # solved by not using a range but rather < 5 if int(dt.now().weekday()) < 5: if dt(dt.now().year, dt.now().month, dt.now().day, 8) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day, 18): # ----------------- # original: # if dt(dt.now().year, dt.now().month, dt.now().day, 8) < dt.now() \ # < (dt.now().year, dt.now().month, dt.now().day, 16): # ^^^^^^ ERROR: yes, in fact, the entire thing fell apart # because the last item was not in dt(). ... # # ----------------- print("Working hours.") with open(hosts_path, 'r+') as file: content = file.read() # store file content in a variable. # iterate through website list -------------------- for website in website_list: # for each site if website in content: # if website is already in memory copy ----------- pass else: # write the website. # take care to add the newline char \n at the end. file.write(redirect + " " + website + "\n") else: # if it's nonworking hours: with open(hosts_path, 'r+') as file: content=file.readlines() file.seek(0) # move to the start of the file for line in content: # for each line if not any(website in line for website in website_list): # if each item in the site list # is not seen on line [i], then file.write(line) file.truncate() #remove everything that comes after # still not sure why: # - we write file lines when in fact we want to remove them # - how if not any(website in line for website in website_list) works print("you are free.") # else: # # REMOVE BELOW AFTER TESTING------------- # # (TEST) if the day of the week is't right # print("Day Of Week Was 0 or 7.") # -------------------------- time.sleep(320)
import sys import datetime import locale as _locale __all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday", "firstweekday", "isleap", "leapdays", "weekday", "monthrange", "monthcalendar", "prmonth", "month", "prcal", "calendar", "timegm", "month_name", "month_abbr", "day_name", "day_abbr"] # Exception raised for bad input (with string parameter for details) error = ValueError # Exceptions raised for bad input class IllegalMonthError(ValueError): def __init__(self, month): self.month = month def __str__(self): return "bad month number %r; must be 1-12" % self.month class IllegalWeekdayError(ValueError): def __init__(self, weekday): self.weekday = weekday def __str__(self): return "bad weekday number %r; must be 0 (Monday) to 6 (Sunday)" % self.weekday # Constants for months referenced later January = 1 February = 2 # Number of days per month (except for February in leap years) mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] class Calendar(object): """ Base calendar class. This class doesn't do any formatting. It simply provides data to subclasses. """ def __init__(self, firstweekday=0): self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday def getfirstweekday(self): return self._firstweekday % 7 def setfirstweekday(self, firstweekday): self._firstweekday = firstweekday firstweekday = property(getfirstweekday, setfirstweekday) def iterweekdays(self): """ Return a iterator for one week of weekday numbers starting with the configured first one. """ for i in range(self.firstweekday, self.firstweekday + 7): yield i%7 #==================================================================================== # Day of the week...starting at 1 for monday #==================================================================================== def datetoday(self, day, month, year): d = day m = month y = year if m < 3: z = y-1 else: z = y dayofweek = ( 23*m//9 + d + 4 + y + z//4 - z//100 + z//400 ) if m >= 3: dayofweek -= 2 dayofweek = dayofweek%7 return dayofweek def itermonthdatesdays(self, year, month, theday): """ Return an iterator for one month. The iterator will yield datetime.date values and will always iterate through complete weeks, so it will yield dates outside the specified month. """ date = datetime.date(year, month, 1) # Go back to the beginning of the week days = (date.weekday() - self.firstweekday) % 7 date -= datetime.timedelta(days=days) oneday = datetime.timedelta(days=1) while True: if date.month == month: if self.datetoday(date.day, date.month, date.year) == theday: yield date try: date += oneday except OverflowError: # Adding one day could fail after datetime.MAXYEAR break if date.month != month and date.weekday() == self.firstweekday: break if __name__ == "__main__": #main(sys.argv) c = Calendar() #for i in c.itermonthdatesdays(2012, 11, 3): # print i for t in c.itermonthdatesdays(2012, 2, 3): print t
an_int = 5 a_float = 10 a_string = "hello" a_bool = True message = "hello aa " print(an_int + a_float) print (str(an_int) + a_string) print(a_string + str(a_bool)) print(str(a_float) +"\n" + message )
x = int(input("mantepse ton ari8mo")) number = 0 pro = 0 while number != x and pro <=5 : if number > x: number = int(input(("dwse ari8mo mikrotero :"))) pro += 1 else: number = int(input(("dwse ari8mo megalutero :"))) pro += 1 if number == x : print("to vrhkes!! einai to : " + str(number)) print("ekanes" + str(pro) + "prospa8eies") else: print("exases")
#Author: AMARACHI IWUH print("******THE HANGMAN!!!!********") print("Instructions:") print("1. For the default mode, a hardcoded word will be used to generate the empty spaces.") print("2. For the human against human game, a user will type in a random word, the computer will hide it and the opponent will try and figure it out") print("3. For the human against computer game, the most difficult of all, the computer prints dashes to hide the mystery word and the user is made to figure the word out") print("If a letter is repeated and the word has no duplicate of the letter, the user will be asked for a new guess") print("These challenges are only for the FEARLESS!") print("*the guesser has only 6 guesses. Use wisely") print("For the default mode, press 1") print("For the human against human game, press 2") print("For the human against computer game, press 3") print() while True: decision = int(input("enter decision: ")) if decision == 1: print() from first_mode import first_mode print(first_mode()) break elif decision == 2: print() from human_human_games import human_human_games print(human_human_games()) break elif decision == 3: print() from third_mode import third_mode print(third_mode()) break else: continue
import numpy as np def Swap(data,f,s): reg = data[f] data[f] = data[s] data[s] = reg def Sort(data,f,e): pivot = data[e] j = f if(f<e): for i in range(f,e): if((data[i]< pivot) and (i!=j)): Swap(data,i,j) j+=1 elif(data[i]< pivot): j+=1 Swap(data,j,e) print(data) Sort(data,f,j-1) Sort(data,j+1,e) #data= [63,15,7,21,8,14,25,45] data= [63,15,7,14,45,21,8,25] print(data) Sort(data,0,len(data)-1) print("result = ",data)
""" Node class has the data and a pointer that is used to point to the next Node object. """ class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next_node = next_node def get_data(self): return self.data def get_next(self): return self.next_node def set_next(self, next_node): self.next_node = next_node class LinkedList(object): def __init__(self, head=None): self.head = head def insertFront(self, data): new_node = Node(data) new_node.set_next(self.head) self.head = new_node def append(self, data): new_node = Node(data) if self.head == None: self.head = new_node else: current = self.head while current.get_next(): current = current.get_next() current.set_next(new_node) def size(self): current = self.head count = 0 while current: count += 1 current = current.get_next() return count def search(self, data): current = self.head if current == None: return "No elements present to search. Please insert elements first." found = False while current and found == False: if current.get_data() == data: found = True else: current = current.get_next() if current == None: return "Value not found" return "Match Found" def delete(self, data): current = self.head if current == None: return "No elements present to delete. Please insert elements first." found = False prev = None while current and found == False: if current.get_data() == data: found = True else: prev = current current = current.get_next() if current == None: return "Value not found" if prev == None: self.head = current.get_next() else: prev.set_next(current.get_next()) return "Successfully deleted " + str(data) def printElements(self): current = self.head if current == None: print "No elements present. Please insert elements." return while current: print current.get_data() current = current.get_next() #Test list = LinkedList() list.printElements() print list.delete(5) list.append(4) list.append(5) list.append(6) list.append(7) list.printElements() print list.delete(7) list.printElements() print list.size()
""" The longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, length of LIS for { 10, 22, 9, 33, 21, 50, 41, 60, 80 } is 6 and LIS is {10, 22, 33, 50, 60, 80} The program's time complexity is nlogn. """ class LongestIncreasingSubsequence(object): def __init__(self, arr): self.arr = arr self.arrLength = len(self.arr) self.tail = [0]*self.arrLength def ceilIndex(self, low, high, entry): while (high-low)>1: mid = low + (high-low)/2 if self.tail[mid] >= entry: high = mid else: low = mid return high def findLength(self): if self.arrLength == 0: return 0 tailLength = 1 self.tail[0] = self.arr[0] for i in range(1, self.arrLength): if self.arr[i] < self.tail[0]: self.tail[0] = self.arr[i] elif self.arr[i] > self.tail[tailLength-1]: self.tail[tailLength] = self.arr[i] tailLength += 1 else: self.tail[self.ceilIndex(-1, tailLength-1, self.arr[i])] = self.arr[i] return tailLength #Test arr = [2, 5, 3, 7, 11, 8, 10, 13, 6] longest = LongestIncreasingSubsequence(arr) print "Length of longest increasing subsequence in nlogn time complexity is " + str(longest.findLength())
""" There are 2 sorted arrays A and B of size n each. Write an algorithm to find the median of the array obtained after merging the above 2 arrays (i.e. array of length 2n). The complexity should be O(log(n)) 1) Calculate the medians m1 and m2 of the input arrays ar1[] and ar2[] respectively. 2) If m1 and m2 both are equal then we are done. return m1 (or m2) 3) If m1 is greater than m2, then median is present in one of the below two subarrays. a) From first element of ar1 to m1 (ar1[0...|_n/2_|]) b) From m2 to last element of ar2 (ar2[|_n/2_|...n-1]) 4) If m2 is greater than m1, then median is present in one of the below two subarrays. a) From m1 to last element of ar1 (ar1[|_n/2_|...n-1]) b) From first element of ar2 to m2 (ar2[0...|_n/2_|]) 5) Repeat the above process until size of both the subarrays becomes 2. 6) If size of the two arrays is 2 then use below formula to get the median. Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2 """ def median(arr, n): if n % 2 == 0: # If even elements return (arr[n/2] + arr[n/2-1])/2 else: return arr[n/2] def getMedian(arr1, arr2, n): if n == 1: return (arr1[0] + arr2[0])/2 if n == 2: return (max(arr1[0],arr2[0])+min(arr1[1],arr2[1]))/2 #If N is greater than 2 m1 = median(arr1, n) m2 = median(arr2, n) # If both medians are equal, then we're done if m1 == m2: return m1 # If m1<m2, Case 4 from the above explanation elif m1<m2: if n%2 == 0: # If even elements return getMedian(arr1[n/2-1:], arr2, n-n/2+1) else: return getMedian(arr1[n/2:], arr2, n-n/2) elif m1>m2: if n%2 == 0: # If even elements return getMedian(arr1, arr2[n/2-1:], n-n/2+1) else: return getMedian(arr1, arr2[n/2:], n-n/2) arr1 = [1, 2, 3, 6] arr2 = [4, 6, 8, 10] n = len(arr1) print getMedian(arr1, arr2, n)
""" Given a string, find the longest possible palindromic substring. The algorithm is solved using Dynamic Programming. Time complexity is O(n^2) and space complexity is O(n^2). This is much better than the Brute force logic with O(n^3) time complexity. """ def longestPalindromicSubString(string): arr = list(string) arr_len = len(arr) dpArray = [[False for i in range(arr_len)] for j in range(arr_len)] for i in range(arr_len): dpArray[i][i] = True maxLength = 0 indexStart = -1 for l in range(2,arr_len+1): for i in range(arr_len-l+1): j = i+l-1 if arr[i] == arr[j] and dpArray[i+1][j-1] is True: dpArray[i][j] = True maxLength = l indexStart = i if maxLength != 0: return "substring of " + str(maxLength) + " found starting from index " + str(indexStart) else: return "No such substring found" # Test string = "banana" print longestPalindromicSubString(string)
""" Given a graph with or without cycles, a source vertex s and a destination vertex d, print all paths from given s to d. The algorithm follows DFS or Depth first search strategy """ def all_paths_dfs(graph, start, goal): queue = [(start, [start])] visited = {} visited[start] = True paths = [] while queue: (vertex, path) = queue.pop() nodes = graph[vertex] for i in range(len(nodes)): next_node = nodes[i] if next_node not in visited or visited[next_node] is False: visited[next_node] = True if next_node == goal: paths.append(path + [next_node]) visited[next_node] = False # Since we want all paths to this node else: queue.append((next_node, path + [next_node])) return paths # Test graph = {'A': ['A','B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E']} print all_paths_dfs(graph, 'C', 'F')
""" A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. The rat can move in only 2 directions, either bottom or right. In the maze matrix, 0 means the block is dead end and 1 means the block can be used in the path from source to destination. """ def findPath(maze): n = len(maze) sol = [[0 for i in range(n)] for j in range(n)] if bactrack(maze, n, sol, 0, 0) == False: return False else: return sol def bactrack(maze, n, sol, row, col): if row == n-1 and col == n-1: sol[row][col] = 1 return True if isSafe(row, col, n): sol[row][col] = 1 if bactrack(maze, n, sol, row+1, col): return True # Bottom if bactrack(maze, n, sol, row, col+1): return True # Right sol[row][col] = 0 return False def isSafe(row, col, n): if (row >=0) and (row < n) and (col >=0) and (col < n) and maze[row][col] == 1: return True return False # Test maze = [[1,0,0,0],[1,0,0,1],[0,1,0,0],[1,1,1,1]] path = findPath(maze) if path: print path else: print "No such path"
""" Write a Python program to count the occurrences of each word in a given sentence. """ def wordFrequency(input_string): # Initiating empty Dictionary input_word = input_string.split(' ') dict = {} for n in input_word: keys = dict.keys() # if key exists increase by 1 if n in keys: dict[n] += 1 else: dict[n] = 1 return dict print(wordFrequency('Write a Python program to count the occurrences of each word in a given sentence.'))
""" Write a Python program to sum all the items in a list. """ def sumListItem(input_list): total = 0 for i in range(0, len(input_list)): total = total + input_list[i] return 'Sum of all items in the list : %s' % total print(sumListItem([1, 2, 3, 4, 5]))