text
stringlengths
37
1.41M
def solution(inp: str) -> str: total: int = 0 for n in inp: total += int(n) if total % 9 == 0: return "Yes" else: return "No" inp: str = str(input()) print(solution(inp))
def write_string_to_disk_and_close(path, string): """ Write a string to the given path and close the file. """ with open(path, 'wb+') as destination: destination.write(string) destination.close() def write_file_to_disk_and_close(path, w_file): """ Write the file to the given path and close the file. Handle file in a memory efficient way. """ with open(path, 'wb+') as destination: for chunk in w_file.chunks(): destination.write(chunk) destination.close() w_file.close()
##total = 0 ##for number in range(1, 10 + 1): ## print(number) ## total = total + number ##print(total) def add_number(): total = 0 for number in range(1, 10 + 1): print(number) total = total + number return(total) new_answer=total+10 answer=add_number() new_answer=answer+8 print(new_answer) #print(answer)
def isUniqieChars1(string): ''' Apprach 1 ''' for i in range(0, len(string)): for j in range(len(string), 0, -1): if i!=j and string[i]==string[j]: return False return True def isUniqueChars2(string): '''Approach 2 - This is a slight variation to the approach explained''' uniqueChars = [] for i in range(0, len(string)): if string[i] not in uniqueChars: uniqueChars.append(string[i]) else: return False return True def isUniqueChars3(string): '''Approach 3 - Slight variation:- Instead of using 0 and 1, I used False and True''' if len(string) > 256: return False alphabet = [False]*256 for i in range(0, len(string)): index = ord(string[i]) if (alphabet[index]): return False else: alphabet[index] = True return True
def loadarray(): arrayFile = open("Integerarray.txt", "r") array = [] for i in arrayFile: array.append(int(i[:-1])) return array def sortCount(array): #Divide n = len(array) if n == 1: return array else: array1 = array[:n/2] array2 = array[n/2:] #Recursive Call array1 = sortCount(array1) array2 = sortCount(array2) #Merge global counter j = 0 k = 0 i = 0 Output = [] while i < (len(array1) + len(array2)): if j==len(array1): Output.append(array2[k]) k += 1 elif k==len(array2): Output.append(array1[j]) j += 1 elif array1[j] <= array2[k]: Output.append(array1[j]) j += 1 elif array1[j] > array2[k]: Output.append(array2[k]) counter += (len(array1) - j) k += 1 i += 1 return Output array = loadarray() counter = 0 sortCount(array) print counter
## write linked list class LinkedList: def __init__(self): self.first = None def append(self, node): if self.first == None: self.first = node else: cur = self.first while cur.next != None: cur = cur.next cur.next = node def __repr__(self): cur = self.first print "first:", cur.value print "next val", cur.next.value i = 0 output = "" while cur != None: output += "Node%s: %s \n" % (i, cur.value) i += 1 cur = cur.next return output def __len__(self): cur = self.first i = 0 while cur != None: i += 1 cur = cur.next return i class LLNode: def __init__(self, value): self.value = value self.next = None def reverse(ll): ll_len = len(ll) print "length:", len(ll) if ll_len <= 1: return ll prev = ll.first redirect = prev.next next = redirect.next while redirect != None: # redirect redirect.next = prev # increment prev = redirect redirect = next if next != None: next = next.next else: next = None ll.first.next = None ll.first = prev print ll return ll if __name__ == '__main__': ll = LinkedList() for i in range(12): ll.append(LLNode(i)) # ll.append(LLNode(3)) # ll.append(LLNode(5)) # ll.append(LLNode(8)) print ll reverse(ll)
# # Bin Organizer # Jeff Shea, 2014 # # Python 2.7.6 # """Organizes pharmacy will-call bin structure based on number of name occurrences. Reads <filename>.csv as source data. Final sorted list will be output to BinOrder.txt in the local directory.""" import os import sys src = open( 'MOCK_DATA.csv' , mode='r' ).readlines() srcList = [] def printList(list): # Prints data in a readable format print 'Name: ' , list[0] , list[1] print 'Phone: ' , list[2][3:6] + '-' + list[2][7:10] + '-' + list[2][11:15] print 'Rx# ' , list[3] print 'Days in Bin: ' , list[4] print '' def emptyDict(d): # Creates an empty dictonary with two-letter prefices as keys key1 = 'A' while( key1 <= 'Z' ): key2 = 'a' while( key2 <= 'z' ): d[(key1+key2)] = 0 key2 = chr(ord(key2) + 1) key1 = chr(ord(key1) + 1) def getTotals( l , d ): for i in range(len(l)): lookup = l[i][1][0] + l[i][1][1] d[lookup] += 1 def main(): # Create the output text file try: os.remove('BinOrder.txt') except OSError: pass nBin = input( "Input the number of available bins to use: " ) # Generate table from source file for i in range(len(src)): curRecord = src[i] curRecord = curRecord.split(',') srcList.append(curRecord) srcList[i][4] = int(srcList[i][4]) # # Print source list # srcList.sort(key=lambda x: x[1]) # srcList.sort(key=lambda x: x[4] , reverse=True) # # for i in range(len(srcList)): # printList(srcList[i]) mList = {} emptyDict(mList) getTotals( srcList , mList ) total = float(sum( mList.values() )) maxPerBin = total/nBin #combine = raw_input("Combine names that start with different letters? (y/n): ") # Prints list of name ranges that will fit into bins evenly sys.stdout = open( 'BinOrder.txt' , 'w' ) key1 = 'A' bagCount = 0 while( key1 <= 'Z' ): key2 = 'a' print key1 + key2 while( key2 <= 'z' ): #print key1 + key2 if(mList[(key1+key2)] != 0 ): #print mList[ ( key1 + key2 ) ] curKey = mList[ ( key1 + key2 ) ] bagCount = bagCount + curKey if( bagCount >= maxPerBin ): print key1 + key2 print "-----" print key1 + chr(ord(key2) + 1) bagCount=0 if( key2 == 'z' ): print key1 + key2 key2 = chr(ord(key2) + 1) key1 = chr(ord(key1) + 1) print "=====" bagCount = 0 print total , "scripts total across" , nBin , "bins\n\n" if __name__ == '__main__': main()
#!/usr/bin/env python3 ####### Adapted from code by Pleuni Pennings https://github.com/pleunipennings/PlotNumWomenCongress ######## matplotlib import matplotlib.pyplot as plt import csv def get_data(): list_years = [] #create an empty list to store years list_num =[] #create an empty list to store the number of women linenum=0 #create a variable to count the lines, with open("https://raw.githubusercontent.com/GWC-DCMB/codeDemos/master/data/WomenCongress.csv") as file: #open the file with the data for line in file: #for each line data = line.split(",") #split the line at the commas (bc it is a csv file) year = data[1][0:4] #take the first 4 characters from the second column as the year if linenum>0: #do this, but not for the very first line list_years.append(int(year)) #append the year to the list of years list_num.append(int(data[2])) #append the number of women to the list for that linenum+=1 #update the counter for the number of lines return list_years,list_num # return the list for the years and the list for the number of women list_years,list_num=get_data() #use the get_data function to get the list of years and the list of the number of women in congress print(list_years[0]) #print statement to make sure it worked plt.plot(list_years, list_num, 'o') #plot year vs the number of women plt.plot(list_years[-1], list_num[-1], 'ro') #Highlight the last year (2019) in red plt.suptitle('Number of Women in the US Congress', fontsize=16) #add a title plt.show() # show the plot ############# pandas and dictionaries import pandas as pd #CSV to data frame df=pd.read_csv("https://raw.githubusercontent.com/GWC-DCMB/codeDemos/master/data/WomenCongress.csv") df.head() #Series vs Data Frame type(df[["Congress"]]) #data frame type(df["Congress"]) #series type(df["Congress"][0]) df["Congress","Years"] #2 columns can't be a series, throws error df[["Congress","Years"]] # 2 columns is a data frame #iloc vs loc df.iloc[0] #first row (this is a series) df.iloc[0,0] #first row, first column (this is a string) df.iloc[-1] #last row #pandas data frame to dictionary my_dict=df.to_dict() my_dict.keys() my_dict['Congress'] my_dict['Congress'][0]
#!/usr/bin/env python # coding: utf-8 # #Implementation of DFS(Depth First Search) using Recursion # In[1]: #!/usr/bin/python36 import os import subprocess as sp import math from random import randint, randrange from string import ascii_letters, ascii_lowercase, ascii_uppercase from collections import Counter from heapq import heapify, heappush, heappop from itertools import permutations, combinations, combinations_with_replacement from bisect import bisect, bisect_left, bisect_right # In[2]: class Node: def __init__(self,vertex): self.vertex = vertex self.visited = False self.adjacencyList = [] # In[6]: class DFS: def dfs(self,s): s.visited = True print(s.vertex) for neighbour in s.adjacencyList: if neighbour.visited != True: self.dfs(neighbour) # In[7]: demo = DFS() a = Node(1) b = Node(2) c = Node(3) d = Node(4) a.adjacencyList.append(b) a.adjacencyList.append(d) b.adjacencyList.append(a) b.adjacencyList.append(c) b.adjacencyList.append(d) demo.dfs(a) # In[ ]: ###Contributed by NobleBlack
#!/usr/bin/env python # coding: utf-8 # Implementation of BFS(Breadth First Search) # # # In[1]: #!/usr/bin/python36 import os import subprocess as sp import math from random import randint, randrange from string import ascii_letters, ascii_lowercase, ascii_uppercase from collections import Counter from itertools import permutations, combinations, combinations_with_replacement from bisect import bisect, bisect_left, bisect_right from heapq import heapify, heappush, heappop from decimal import Decimal # In[2]: class Node: def __init__(self, vertex): self.vertex = vertex self.adjacencyList = [] self.predecessor = None # In[3]: class BFS: def bfs(self,startNode): level = {startNode : 0} parent = {startNode : None} frontier = [startNode] startNode.predecessor = parent[startNode] i = 1 print(startNode.vertex) while frontier: next = [] for vertex in frontier: for neighbours in vertex.adjacencyList: if neighbours not in level: print(neighbours.vertex) level[neighbours] = i parent[neighbours] = vertex neighbours.predecessor = parent[neighbours] next.append(neighbours) frontier = next i += 1 # In[5]: a = Node('a') b = Node('b') c = Node('c') abc = BFS() a.adjacencyList.append(b) a.adjacencyList.append(c) abc.bfs(a) # In[ ]: ###Contributed by NobleBlack
#!/usr/bin/env python # coding: utf-8 # #Implementation of PowerSet Using Iteration # In[1]: #!/usr/bin/python36 import os import subprocess as sp import math from random import randint, randrange from itertools import permutations, combinations, combinations_with_replacement from collections import Counter, deque from heapq import heapify, heappush, heappop from string import ascii_letters, ascii_lowercase, ascii_uppercase from bisect import bisect, bisect_left, bisect_right # In[7]: def powerSet(arr): for i in range(0,2**len(arr)): count = "" for j in range(0,len(arr)): if (i & (1 << j)) : count += arr[j] print(count, end = ", ") powerSet("abc") # In[ ]: ###Contributed by NobleBlack
#!/usr/bin/python36 print("content-type: text/html") print("") ###input m1=int(input("input no of rows for first matrix")) n1=int(input("input no of columns for first matrix")) m2=int(input("input no of rows for second matrix")) n2=int(input("input no of columns for second matrix")) ############################################################################################################### ###list initialization for matrix input matrix1=[[0 for i in range(n1)] for j in range(m1)] matrix2=[[0 for i in range(n2)] for j in range(m2)] ################################################################################################################ ###input for matrices print('\t\t',"matrix1 input") for i in range(m1): for j in range(n1): matrix1[i][j]=int(input("input values for matrix1")) print('\t\t',"matrix2 input") for i in range(m2): for j in range(n2): matrix2[i][j]=int(input("input values for matrix2")) ################################################################################################################ ###matrices output print('\t','\t',"MATRIX:1") for i in range(m1): for j in range(n1): print(matrix1[i][j],'\t',end='') print("") print('\t','\t',"MATRIX:2") for i in range(m2): for j in range(n2): print(matrix2[i][j],'\t',end='') print("") ################################################################################################################ ###matrix multiplication if n1==m2: matrix3= [[0 for i in range(n2)]for j in range(m1)] for i in range(m1): for j in range(n2): sum=0 for k in range(n1): ###n1==m2 sum+=matrix1[i][k]*matrix2[k][j] matrix3[i][j]=sum else: print("matrix multiplication can not be done") ################################################################################################################ ###matrix multiplication output print('\t\t',"MATRIX:3") for i in range(m1): for j in range(n2): print(matrix3[i][j],'\t',end='') print("") ################################################################################################################ ###matrices transpose print('\t\tMATRIX:1 TRANSPOSE') matrix4=[[0 for i in range(m1)]for j in range(n1)] for i in range(n1): for j in range(m1): matrix4[i][j]=matrix1[j][i] print(matrix4[i][j],'\t',end='') print("") print('\t\tMATRIX:2 TRANSPOSE') matrix5=[[0 for i in range(m2)]for j in range(n2)] for i in range(n2): for j in range(m2): matrix5[i][j]=matrix2[j][i] print(matrix5[i][j],'\t',end='') print("") ################################################################################################################
#! /usr/bin/env python3 """ Read stdin, turn input into 8 bit binary, output binary to stdout """ import sys import argparse import itertools import signal def parse_arguments(args): parser = argparse.ArgumentParser(description="Convert an input stream into binary") parser.add_argument( "in_file", nargs="?", type=argparse.FileType("r"), default=sys.stdin, help="Input file (default stdin)", ) parser.add_argument( "out_file", nargs="?", type=argparse.FileType("w"), default=sys.stdout, help="Output file (default stdout)", ) parser.add_argument( "-w", "--width", type=int, default=8, help="Number of columns (default 8)" ) return parser.parse_args(args) def chunks(iterable, size): return iter(itertools.zip_longest(*([iter(iterable)] * size))) def byte_to_binary(byte): return f"{byte:08b}" def byte_stream_iter(input_stream, chunk_size=8): b = input_stream.buffer.read(chunk_size) while b: yield b b = input_stream.buffer.read(chunk_size) def bytes_to_binary(input_stream, output_stream, width): for bytes_ in byte_stream_iter(input_stream, width): output_stream.write(" ".join(byte_to_binary(byte) for byte in bytes_)) output_stream.write("\n") def main(argv): args = parse_arguments(argv[1:]) bytes_to_binary(args.in_file, args.out_file, args.width) return 0 if __name__ == "__main__": signal.signal(signal.SIGPIPE, signal.SIG_DFL) sys.exit(main(sys.argv))
''' Input: an integer Returns: an integer ''' def eating_cookies(n, memory=None): if memory == None: memory = [0] * (n + 1) if n <= 1: memory[n] = 1 elif n == 2: memory[n] = 2 elif memory[n] == 0: memory[n] = eating_cookies(n - 1, memory) + eating_cookies(n - 2, memory) + eating_cookies(n - 3, memory) return memory[n] if __name__ == "__main__": # Use the main function here to test out your implementation for i in range(10): num_cookies = i print(f"There are {eating_cookies(num_cookies)} ways for Cookie Monster to eat {num_cookies} cookies")
# Psuedocode: # # x = //user input # if x > 0: //this will allow us account for positive ints - else statement at end of loop will account for negative input # # for square_root in range (abs(x) + 1): //runs from 0 up to absolute value of x+1. (allows exhaustive emuneration) # if square_root **2 >= abs(x): // if square root squared is greater than the absolute value of x break loop. # break //kicks program out of loop # # if square_root **2 == abs(x): #if the square root value ^2 is equal to the absolute value of x # print('Square root of', x, 'is', square_root) //print the squared root of variable is 'value' # else: # print(x, 'is not a perfect square.') //otherwise print the inputted value is not a perfect square. # #else: # print('negative int deteceted - program end') //print alert that negative int was enetered and close program x = int(input("Please insert Int:")) if x > 0: for square_root in range (abs(x) + 1): if square_root **2 >= abs(x): break if square_root **2 == abs(x): print('Square root of', x, 'is', square_root) else: print(x, 'is not a perfect square.') else: print('negative int deteceted - program end')
# Psuedocode # for number in range (2,20) # let the variable x = 1 // this will act as a semaphore # for i in range (2,number): # if number has no remainder: # print number equal to number 1 by number 2 # let x = 0 //switch semaphore state - forces program to run though entire range first. # else # if semaphore value is 1... # print its a prime number # # print finished at end of program. # for number in range (2,20): x = 1 for i in range (2,number): if number %i == 0: print(number, 'equals', i, '*', number//i) x = 0 else: if x == 1: print(number, 'is a prime number') print ('Finished!')
euro_currency = float (input('Enter the number of Euro(s) to convert: ')) euro_to_pound = float (0.86) conversion = euro_currency * euro_to_pound if euro_currency <= 0: print("Amount must be >= 0. Please try again.") else: print('€' , euro_currency , 'converted to pounds = ' , '£' , conversion)
x = int (input('Please enter first int: ')) y = int (input('Please enter second int:')) z = int (input('Please enter third int:')) if (x%2 == 1 or y%2 == 1 or z%2 == 1): if (x>y and x>z): print(x, 'is the largest odd number'); elif (y>x and z>x): print(y, 'is the largest odd number'); else: print(z, ' is the largest odd number'); if(x%2 == 0 and y%2 == 0 and z%2 == 0): print('All numbers are positive');
tableSize = int (input ('Please insert table size:')) i = 0 while i < 21: print (i, i*tableSize) i+=1
# Psuedocode # #def findDivisors(num1,num2): //define function that takes 2 argumets # divisors = (1,min(num1,num2)) //divisors initialised with 1,and min of the two x/y user input values. # for i in range (2, (min(num1,num2)+1)//2): //modified range between 2 and half of the number # if num1 % i == 0 and num2 % i == 0: //for loop will check divisors of both numbers and add them to divisors. # divisors += (i,) # return divisors //returns divisors # #x = user input // takes user input for x value #y = user input // takes user input for y value # #if x <= 0 or y <= 0: # print('Numbers should be > 0.') //check to ensure numbers entered are positive #else: # divisors = findDivisors(x,y) //assigns divisors the values of the user input # print('The common divisors of', x, 'and', y, 'are', divisors) //prints out divisors of the user input. # def findDivisors(num1,num2): ''' program to get the common divisors of two positive integers supplied ''' divisors = (1,min(num1,num2)) for i in range (2, (min(num1,num2)+1)//2): if num1 % i == 0 and num2 % i == 0: divisors += (i,) return divisors x = int(input('Please insert x value: ')) y = int(input('Please insert y value:')) if x <= 0 or y <= 0: print('Numbers should be > 0.') else: divisors = findDivisors(x,y) print('The common divisors of', x, 'and', y, 'are', divisors)
animals = 'herd of elephants' x=2 y=2 seg = animals [x:y] #prints result when x and y are the same (blank returned) print ('Segment is:',seg) x=7 y=3 seg = animals[x:y] #prints result when x is greater than y (blank returned) print ('Segment is:',seg) x=5 y=6 seg = animals[:y] #what happens when x is omitted ('herd o' returned - string represented by y) print ('Segment is:',seg) x=5 y=5 seg = animals[x:] #what happens when y is omitted ('of elephants' returned - string represented by x) print ('Segment is:',seg) x=5 y=5 seg = animals[:] #what happens when x and y are omitted ('herd of elephants returned' - full string returned) print ('Segment is:',seg)
x = raw_input("Please enter a random genre.") if x != "": print "Thank You!" x = raw_input("Please enter a random artist.") if x != "": print "Thank You!" x = raw_input("Please enter a random song.") if x != "": print "Thank You!" print ("It means a lot, thank you sooooo much.")
#Exercício Python 006: Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada. num = int(input("Digite um número: ")) dobro = num*2 triplo = num*3 raiz = num**(1/2) print("O dobro de {} é {}.\nO triplo de {} é {}.\nA raiz de {} é {}.".format(num,dobro,num,triplo,num,round(raiz,2)))
#Exercício Python 017: Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo. Calcule e mostre o comprimento da hipotenusa. from math import hypot oposto = float(input("Comprimento do cateto oposto: ")) adjacente = float(input("Comprimento do cateto adjacente: ")) print("A hipotenusa vai medir {:.2f}".format(hypot(oposto,adjacente))) #O cálculo é: (oposto**2 + adjacente**2) ** (1/2)
# Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado. def porcentagem (num, porcent): resultado = num * porcent / 100 return resultado valorCasa = float(input("Valor da casa: R$")) salario = float(input("Salário do comprador: R$")) anos = int(input("Quantos anos de financiamento?: ")) qtdPrestacoes = 12 * anos valorPrestacoes = valorCasa / qtdPrestacoes porcentagemSalario = porcentagem(salario, 30) print("Para pagar uma casa de R${:.2f} em {} anos, a prestação será de R${:.2f}".format(valorCasa,anos,valorPrestacoes)) if (valorPrestacoes > porcentagemSalario): print("Empréstimo NEGADO!") else: print("Empréstimo pode ser CONCEDIDO!")
# Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade, se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do prazo. from datetime import date dataAtual = date.today() anoAtual = dataAtual.year nasc = int(input("Ano de nascimento: ")) idade = anoAtual-nasc print("Quem nasceu em {} tem {} anos em {}".format(nasc, idade, anoAtual)) if (idade < 18): print("Ainda faltam {} anos para o alistamento.\nSeu alistamento será em {}.".format( 18-idade, nasc+18)) elif (idade > 18): print("Você já deveria ter se alistado a {} anos.\nSeu alistamento foi em {}.".format( idade-18, nasc+18)) elif (idade == 18): print("Você tem que se alistar IMEDIATAMENTE!")
class A: x = 4 y = 'kadabra' def __init__(self, a: int, b: int): print('konstruktor uruchomiony') self.x = a + b def square_x(self): print('podnoszę x do potęgi 2') self.x **= 2 def gg(n): g = [i * i for i in range(n)] return g w = [1, 2, 3] x = 12 w.append(x) w.extend(gg(15)) instance1 = A(2, 5) instance2 = A(2, 3) print(instance1) print(instance2) print(instance1.x) print(instance2.x) print('---------') instance1.square_x() print(instance1.x) print(instance2.x)
from dataclasses import dataclass @dataclass class Employee: name: str role: str vacation_days: int = 25 e = Employee(name="Joe", role="admin") print(e) # output: # Employee(name="Joe", role="admin", vacation_days=25) """ above example is equivalent of the following: """ class Employee: def __init__(self, name, role, vacation_days=25): self.name = name self.role = role self.vacation_days = vacation_days def __repr__(self): return f"{type(self).__name__}(name='{self.name}', role='{self.role}', vacation_days={self.vacation_days})" e = Employee(name="Joe", role="admin") print(e) # output: # Employee(name="Joe", role="admin", vacation_days=25)
print("包含中文的str") #获取字符的整数表示 print(ord('A')) print(ord('中')) #编码转化为对应的字符 print(chr(66)) print(chr(25991)) print(len('ABC')) print(len('中文')) print('Hello,%s' % 'world') print('Hi, %s, you have $%d.' % ('Michael', 1000000))
# # #1- Girilen bir sayının 0-100 arasında olup olmadıgını kontrol ediniz. # sayi1 = int(input("Bir sayi giriniz: ")) # result = (sayi1 >= 0) and (sayi1 <= 100) # print(f"Sayi 0 ile 100 arasındamı? : {result}") # # #2- Girilen bir sayının pozitif çift sayı olup olmadıgını kontrol ediniz. # sayi2 = int(input("Bir sayi giriniz: ")) # result = (sayi2 > 0) and (sayi2%2==0) # print(f"Girilen sayi pozitif çift sayimidir? : {result}") # # #3- Email ve parola bilgileri ile giriş kontrolü yapınız. # emailUser = "[email protected]" # passwordUser = "ab1234" # user2 = input("Bir mail girin: ") # user3 = input("Bir şifre girin: ") # result = (emailUser==user2) and (passwordUser==user3) #######DAAAAAAYUM IM GOOOD # print(f"Uygulamaya giriş başarılı oldu mu? : {result}") # # # 4- Girilen 3 sayıyı büyüklük olarak karşılaştırınız. # a = int(input("1.sayiyi giriniz: ")) # b = int(input("2.sayiyi giriniz: ")) # c = int(input("3.sayiyi giriniz: ")) # result = (a > b) and (a > c) # print(f"A en büyük sayımıdır? {result}") # result = (b>a) and (b>c) # print(f"B en büyük sayımıdır? {result}") # result = (c>a) and (c>b) # print(f"C en büyük sayımıdır? {result}") # # #5-Kullanıcıdan 2vize(%60) ve final(%40) notunu alıp ortalama hesaplayınız # # # Eğer ortalama 50 ve üstündeyse geçti değilse kaldı yazdırın. # # # a- ortalama 50 olsa bile final notu en az 50 olmalıdır. # # # b- finalden 70 alındıgında ortalamanın önemi olmasın (ortalama >= 50) or (final >= 70) # vize1 = int(input("1.Vizenizi girin: ")) ##### MEMO eğer else-if gibi komutlar kullanmıyorsan yazdırmak için fstring ya da .format falan kullan bunu unutma bu önemli !!! # vize2 = int(input("2.Vizenizi girin: ")) # final = int(input("Final notunuzu girin: ")) # ortalama = (vize1*30/100 + vize2*30/100) + (final*40/100) # print(f"not ortalamanız: {ortalama} ve dersten geçme durumunuz: {((ortalama >= 50) and (final >= 50)) or (final >= 70)}") #a koşulu için; # result = (ortalama >= 50) and (final >= 50) # #b koşulu için; # result = ((ortalama >= 50) and (final >= 50)) or (final >= 70) ####### NAAAAAYYYSSS XD # # #6- Kişinin ad, kilo ve boy bilgilerini alıp kilo indekslerini hesaplayınız. # # #Formül: (Kilo / boy uzunluğunun karesi) # # #Aşağıdaki tabloya göre kişi hangi gruba girmektedir. # # #0-18.4 => zayıf # # #18.5-24.9 => normal # # #25.0-29.9 => fazla kilolu # # #30.0-34.9 => şişman name = input ("İsminizi cisminizi giriniz: ") kg = float(input("Kaç okka çekiyon: ")) hg = float(input("Boy kaç yiğeen: ")) formula = (kg) / (hg**2) zayif = (formula >= 0) and (formula <= 18.4) normal = (formula > 18.4) and (formula <= 24.9) fazlakilo = (formula > 24.9) and (formula <= 29.9) obez = (formula > 29.9) and (formula <= 34.9) print(f"{name} isimli kişinin kilo indeksi: {formula} ve kilo değerlendirmen: {zayif}") print(f"{name} isimli kişinin kilo indeksi: {formula} ve kilo değerlendirmen: {normal}") print(f"{name} isimli kişinin kilo indeksi: {formula} ve kilo değerlendirmen: {fazlakilo}") print(f"{name} isimli kişinin kilo indeksi: {formula} ve kilo değerlendirmen: {obez}")
#### ---- range metodu # for item in range(10): ### 0-10 a kadar olan sayilari range ile kısıtlayıp yazdırıyorum # print(item) # for item in range(2,10): ### 2 baslangic 10 bitis diyorum ve arasındaki sayilari istiyorum # print(item) # for item in range(2,10,2): ### 2 den 10 a kadar 2 ser atlayarak devam et diyorum. # print(item) # print(list(range(50,100,20))) ### direk olarak listeye aldım (mesafeyi belirledim o mesafe arasındaki verileri) # # ------------------------- ####-----enumerate metodu # index = 0 ###---> for döngüsünde indeks numarasına ihtiyacımız olursa bu kullanılabilir. # greeting = "Hello There. said obiwan" ##enumeratesiz! # for letter in greeting: # print(f"letter: {letter}, index:{index}") ## fstringde index yazmanın alternatifide {greeting[index]} olabilir. # index += 1 ###-------------------------------------- # greeting = "Hello" # for index,letter in enumerate(greeting): ### index,letter yerine item yazıp direk print(item) şeklindede yazabilirz böylelikle liste şeklinde elde edilebilir.key-value sistemi vardır. # print(f"letter: {letter}, index:{index}") ## fstringde index yazmanın alternatifide {greeting[index]} olabilir. ####-----zip metodu ### bir kaç ayrı listeyi birleştirip tek liste olarak cıkartabiliriz.1-a-100,2-b-200 seklinde list1 = [1,2,3,4,5] list2 = ["a","b","c","d","e"] list3 = [100,200,300,400,500] print(list(zip(list1,list2,list3))) for item in zip(list1,list2,list3): print(item) for a,b,c in zip(list1,list2,list3): ### burda listelerin içindeki verileri göstermek istedik ! listeden çıkararak.. print(a,b,c)
""" Modül Hakkında Bilgilendirme; """ print("Modül Eklenmiştir.") number = 10 numbers = [1,2,3] person = { "Name" : "Ali", "Age" : "24", "City" : "İstabul" } def func(x): """ Fonksiyon Hakkında Bilgilendirme; """ print(f"X: {x}") class Person: def speak(self): print("I am speaking...")
# method list = [1,2,3] list.append(4) list.pop() print(type(list)) print(list) myString = "Hello" myString.upper() print(myString.upper()) print(type(myString)) #fonksiyon--> class bünyesinden değerlendirilmez! ##
## def sayWhat(name = ", boş bırakırsan böyle olur"): print("nerdesin def"+ name) sayWhat(", görüpde baktığın her yerde moruk") sayWhat(", 1 saat sonra halısahada") sayWhat() ###### def sayHello(name = "user"): return "hello " + name message = sayHello() message = sayHello("Mehmet") print(message) ##### def total(num1 , num2): return num1 + num2 result = total(10,20) print(result) ###### def yasHesap(dogumYili): return 2021 - dogumYili ageMert = yasHesap(2000) ageBilge = yasHesap(1995) print(ageBilge,ageMert) def emekliligeKacYildKaldi(dogumYili, isim): """ DOCSTRING: Dogum yiliniza gore emekliliginize kac yil kaldi. INPUT: Dogum yili OUTPUT: Emeklilik yili bilgisi """ yas = yasHesap(dogumYili) emeklilik = 65 - yas if emeklilik > 0: print(f"{isim}in , Emekliliğe daha {emeklilik} kadar yiliniz var.") else: print(f"Emeklisin zaten. {isim} " ) emekliligeKacYildKaldi(1983,"kemal") emekliligeKacYildKaldi(1940,"suna") print(help(emekliligeKacYildKaldi)) #### içinde neler oldugunu kullanım şekli vs. help() #####
names = ["Ali","Yağmur","Hakan","Deniz"] years = [1998, 2000, 1998, 1987] #1- "Cenk" ismini listenin sonuna ekleyiniz. result = names.append("Cenk") result = names #2- "Sena" değerini listenin başına ekleyiniz. result = names.insert(0,"Sena") result = names #3- "Deniz" ismini listeden siliniz. result = names.remove("Deniz") result = names #4- "Deniz" isminin indeksini nedir? # result = names.index("Deniz") #5- "Ali" listenin bir elemanımıdır ? result = "Ali" in names #6- "Liste elemanlarını ters çeirin" # names.reverse() # print(names) # years.reverse() # print(years) #7- Liste elemanlarını alfabetik olarak sıralayın. # names.sort() # print(names) # years.sort() # print(years) #8- years listesini rakamsal büyüklüğe göre sıralayın # years.sort() # years.reverse() # print(years) #9- str = "Chevrolet,Dacia" karakter dizisini listeye çeviriniz. # model = ["Şevo", "Dacia"] # str = "Chevrolet,Dacia" # print(model) #result = str.split(",") #10- years dizisinin en büyük ve en küçük elemanı nedir # max = max(years) # min = min(years) # print(max , min) # #11 -years dizisinde kaç tane 1998 değeri vardır # result = years.count(1998) #12- years dizisinin tüm elemanlarını siliniz. # years.clear() # print(years) # #13- kullanıcıdan alacağını 3 tane marka bilgisini bir listede saklayınız. markalar = [] marka = input("Marka adi: ") ### 3kere ekledim cunku henuz döngü kısmına gelmedim.!! markalar.append(marka) #şimdi burda mantık şu markalar boş listesi oluşturdun ; kullanıcıdan istediğim için input ile marka ismi aldım ve kullanıcının verdiğini markalar listesine ekledim tekrar marka'ya döndüm aynı işlem devam ettikçe istenilen sayıda marka oluşturdum. marka = input("Marka adi: ") markalar.append(marka) marka = input("Marka adi: ") markalar.append(marka) print(markalar) print(result)
# # for ve while döngüsüne alternatif olarak kullanabileceğimz bir yöntem # for x in range(10): # print(x) # ##----------------------------------- # numbers = [x for x in range(10)] # print(numbers) # ##----------------------------------- # numbers = [] # for x in range(10): # numbers.append(x) # print(numbers) # ###-------yukarıda ki işlemi comprehensionsla yapınca; # numbers = [x for x in range(10)] # print(numbers) # ##--------- # for x in range (10): # print(x**2) # ###---------------- # numbers = [x**2 for x in range(10)] # print(numbers) # ###------------- # numbers = [x*x for x in range(10) if x%3==0] # print(numbers) # ##----- # myString = "hello" # myList = [] # for letter in myString: # myList.append(letter) # print(myList) # ###-------yukarıda ki işlemi comprehensionsla yapınca; # myList = [letter for letter in myString] # print(myList) # ####-------- # years = [1983,1999,2008,1956,1996] # ages = [2021-year for year in years] # print(ages) # ##------------- # results = [x if x%2==0 else "Teksayi" for x in range(1,10)] # print(results) # ##------------- # result = [] #####sunu acıklayayım ilk döngü ikinci döngüyü döndürcek ve ikinci döngü tamamlandıgında birinci döngü 1 kademe atlıcak ve tekrar y döngüsünü döndürcek işlem bitene kadar # for x in range (3): # for y in range(3): # result.append((x,y)) # print(result) # ###---------aynı işlemi comprehensionsla yapmak istersek;; # numbers = [(x,y,z) for x in range(3) for y in range(3) for z in range (3)] # print(numbers)
""" 1-100 arasında rastgele üretilecek bir sayıyı aşağı yukaru ifadeleri ile buldurmaya çalışın. ** "random modülü" için "python random" şeklinde arama yapın ** 100 üzerinden puanlama yapın her soru 20 puan. ** hak bilgisini kullanıcıdan alın ve her soru belirtilen can sayısı üzerinden hesaplansın. """ # import random # sayi = random.randint(0,100) # hak_sayisi = int(input("Soruları bilmek için kaç hakkınız olsun?:(En az 5 giriniz!) ")) # print(f"Hak sayınızı {hak_sayisi} olarak belirlediniz.") # for i in range(hak_sayisi): # cevap = input("1.Sorunuz Türkiyenin başkenti neresidir? : ") # if cevap == "ankara": # print(f"Verdiğiniz cevap doğru 2.soruya geçebilirsiniz.") # break # else: # hak = (hak_sayisi-1) - i # print(f"Verdiğiniz cevap yanlış {hak} hakkınız kaldı.") # ------------------------------------------------------------------------------------- import random sayi = random.randint(1,30) sayac = 0 hak_sayisi = int(input("Soruları bilmek için kaç hakkınız olsun? ")) can = hak_sayisi print(f"Doğru cevabı bulabilmek için {hak_sayisi} hakkınız var...") print(sayi) while hak_sayisi>0: hak_sayisi-=1 sayac+=1 sayig = int(input("1-100 arasında bir sayi giriniz (0'oyundan çıkar): ")) if sayig==0: print("Oyunu iptal ettiniz.") break elif sayig < sayi: print("Girdiğin sayi daha aşağıda...Yukarı") continue elif sayi == sayig: print(f"Tebrikler...{100 - (100/hak_sayisi) * (sayac+1)}") break else: print("Girdiğin sayi daha yukarıda...Aşağı") continue print(f"Maalesef hakkınız bitti... {sayac} kere denediniz.")
#Dicionários #Criando dicionários dicionario = {} dicionario = dict () dicionario = {'nome': 'Grazi', 'idade': 35, 'altura':1.74} print(dicionario['idade']) print(dicionario) #Adicionando elementos em um dicionário dicionario['Analista de Dados'] = True print(dicionario) dicionario['altura'] = 1.75 print(dicionario) #Iterando sobre um dicionário for chave in dicionario: print(chave, dicionario[chave]) # Testando a existência de uma chave print('peso' in dicionario) print('altura' in dicionario)
''' This is is a very basic stdio handler script. This is used by python.py example. ''' import time # Read an integer from the user: print('Give a small integer: ', end='') num = input() # Wait the given time for i in range(int(num)): print('waiter ' + str(i)) time.sleep(0.2) # Ask the name of the user to say hello. print('Give your name: ', end='') name = input() print('Hello ' + str(name), end='')
import time import random def random_choice(): list = ["Mumbai", "Hyderbad", "Delhi", "Kolkata", "Calicut", "Chennai"] city = random.choice(list) print_pause("He has his hidden research lab somewhere here.So he will be" + " somewhere here in "+city+"'s dumpward.") print_pause("Now we are in "+city+" dumpward.") def print_pause(text): print(text) time.sleep(2) def intro(): print_pause("You are Kahil and you are in so angry and diappointment mood" + " " + "that your parents were kidnapped recently.") print_pause("World's one of most smartest person kidnapped them.") print_pause("So to find them you want to take the help of Rabath.") print_pause("Rabath is the only smarter and intelligent guy who" + " can help you,he's the angry guy too....") random_choice() print_pause("SO,LET'S FIND RABATH"+"!!"+" and convince him....") def after_end(): while True: play_again = input("DO you want to play again y/n\n").lower() if play_again == "y": print_pause("Loading your game....") return "y" elif play_again == "n": print_pause("GOOD BYE"+"!!") return "n" else: print_pause("I did not get you....") def game(): while True: intro() while True: print_pause("It's dark here.\n1.Will you find torch.\n2.Or will" + " you directly enter the dumpward.") response1 = input("Please enter the number:") if response1 == "1": print_pause("There's a box right side of you search in that." + " You will get it and enter the dumpward" + " silently.") print_pause("THAD, THAD, THAD, THAD....\nThere's a sound from" + " middle of the dumpward..") while True: print_pause("1.Do you want to go there to check out\n" + "2.Or wait for a while to see what happens?") response2 = input("Pleas enter the number:") if response2 == "1": print_pause("Ohhhh"+"!!!!"+" finally we found Rabath.." + "HE SAY YOU AND HE IS IN ANGRY MOOD") print_pause("Thinking of someone, he shot you with" + " laser gun in his hand"+"!!!!!!!!!") print_pause("THANKGOD IT MISSED YOU...") print_pause("WAAAAHHHH,WAAAAHHH,WAAAAAAHHHH...." + "Police siren") print_pause("Because of that gun sound, Police are" + " on the way, if run back they may get" + " you.") while True: print_pause("1.Do you want to stay there praise" + " him....convincingly tell him your" + " story.") print_pause("2.Or run back.") response3 = input("Please enter the number:") if response3 == "1": print_pause("LUCKILY"+"!!"+" He got convinced" + " with your story....") print_pause("And he promised that he will help" + " you to find your parents....") break elif response3 == "2": print_pause("You ran back and police" + " cought you") print_pause("You lost your chance of" + " finding your parents....") break else: print_pause("I did not get you....") after_end() break elif response2 == "2": print_pause("It's waste of waiting here...") print_pause("Sound keeps on getting louder...its" + " better to go there...") else: print_pause("I did not get you....") break elif response1 == "2": print_pause("If you are in so hurry and confident go head" + "!!") print_pause("OHHhh....Here's a pit...You fell in " + "that and died") print_pause("Better Luck Next time"+"!!") after_end() break else: print_pause("I did not get you....") if after_end() == "n": break game()
""" Utility module Module used as a library of functions with an utility scope. No class are needed. """ def word_checker(user_input, possible_choices): """ Word in String Checker A simple way of checking what element of the possible choices list is more similar to the user input, in order to have a standard string that will be used as a standard. Args: user_input (string): user's input string. possible_choices ([string]): all possible choices that must be compared. Returns: possible_element (int): the element of possible choices that are similar to the user input. The default, if no match occurs, is the first element of the possible choices list. """ user_input = user_input.lower() for possible_element in possible_choices: if user_input in possible_element: return possible_element # Default return of first element in the list return possible_choices[0]
""" Game module Game: this class is the game built with a specified characteristic function type and an adjacency matrix. """ from GAME.CHARACTERISTIC_FUNCTIONS.centrality_type_dictionary import TYPE_TO_CLASS class Game: """ Game Class This class has the basic information of the game created. Attributes: characteristic_function (group_centrality_measure): the type of the characteristic function used. """ def __init__(self, matrix, characteristic_function): """ Classical __init__ python method The method initialize the instance of the class. Args: self: the instance of the class itself. matrix (matrix): the adjacency matrix previously uploaded. characteristic_function (group_centrality_measure): the characteristic function type. Returns: no return is needed. """ self.matrix = matrix self.length = len(matrix) self.characteristic_function = TYPE_TO_CLASS[characteristic_function](matrix) self.item, \ self.item_class, \ self.neutral, \ self.positive, \ self.positive_relation, \ self.negative_relation, \ self.neutral_relation = \ self.characteristic_function.data_preparation()
from .model_base import Model import numpy as np class LinearRegressionModel(Model): """ A model for Linear Regression. Arguments: input_features (int) output_features (int) normalize (bool) """ def __init__(self, input_features, output_features, normalize=False): self.input_features = input_features self.output_features = output_features self.weights = np.zeros((input_features + 1, output_features)) self.normalize = normalize if normalize: self.std = np.zeros(input_features) self.mean = np.zeros(input_features) @staticmethod def design_matrix(X): """Take dataset X and return the design-matrix (dm_X)""" return np.c_[np.ones(X.shape[0]), X] def normalize_matrix(self, X, fit): """Take dataset X and return the normalize matrix""" if fit: self.mean = X.mean(axis=0) self.std = X.std(axis=0) if 0 in self.std: raise ValueError( 'The variance of the data is 0, meaning prediction has no meaning.') return (X - self.mean) / self.std def predict(self, X): """Predict the output after training by given dataset X""" if self.normalize: return self.design_matrix(self.normalize_matrix(X, False)) @ self.weights # Predict without normalization return self.design_matrix(X) @ self.weights def fit(self, X, Y, epochs=None, learn_rate=None): """ Training the model by dataset X and the true values of Y. Arguments: X (np.ndarray): Dataset. Y (np.ndarray): True values. Arguments for 'Gradient Descent' method: epochs (int): Num of iteration on GD function. learn_rate (float): The rate of the learning of the model. """ if self.normalize: # Normalize the matrix dm_X = self.design_matrix(self.normalize_matrix(X, True)) else: dm_X = self.design_matrix(X) # 'Gradient Descent' method if learn_rate and epochs was given if learn_rate and epochs: for _ in range(epochs): # Calculate the new weights by vectorization approach self.weights -= (learn_rate / Y.shape[0]) * dm_X.T @ (dm_X @ self.weights - Y) # 'Normal equation' method if learn_rate or epochs wasn't given else: self.weights = np.linalg.inv(dm_X.T @ dm_X) @ dm_X.T @ Y def loss(self, Y_prediction, Y_true): """ Mean Squared Error (MSE) loss. 1 MSE(Y, Y') = --- sum(i=0,N) ||y_i - y_i'||^2 2N Where ||x|| is the L2 norm of a vector 'x' of dimension C, y_i, y_i' are i-th samples from the batches Y, Y' respectively. This simplifies to: 1 MSE(Y, Y') = --- sum(i=0,N) sum(k=1,C) (y[i,k] - y'[i,k])^2 2N """ batch_size = Y_true.shape[0] return 1 / (2*batch_size) * np.sum((Y_true - Y_prediction)**2) class LogisticRegressionModel(Model): """ A model for Logistic Regression i.e. classification. Arguments: input_features (int) normalize (bool) """ def __init__(self, input_features, normalize=False): self.input_features = input_features self.weights = np.zeros((input_features + 1, 1)) self.normalize = normalize if normalize: self.std = np.zeros(input_features) self.mean = np.zeros(input_features) @staticmethod def design_matrix(X): """Take dataset X and return the design-matrix (dm_X)""" return np.c_[np.ones(X.shape[0]), X] @staticmethod def sigmoid_fn(z): """Calculate the Sigmoid-function of an array or a scalar""" return 1/(1+np.exp(-z)) def normalize_matrix(self, X, fit): """Take dataset X and return the normalize matrix""" if fit: self.mean = X.mean(axis=0) self.std = X.std(axis=0) if 0 in self.std: raise ValueError( 'The variance of the data is 0, meaning prediction has no meaning.') return (X - self.mean) / self.std def predict(self, X, prob=False): """ Predict the output after training by given dataset X Arguments: X (np.ndarray): dataset. prob (bool): True - return the probability of each case to be true (1). False - return the prediction of each case 1 or 0. """ if self.normalize: # Normalize the matrix dm_X = self.design_matrix(self.normalize_matrix(X, False)) else: dm_X = self.design_matrix(X) # Calculate the probability of each case to be True (1) prob_matrix = self.sigmoid_fn(dm_X @ self.weights) # Return 1 if probability > 0.5 else 0 return prob_matrix if prob else np.round(prob_matrix) def fit(self, X, y, epochs=None, learn_rate=None): """ Training the model by dataset X and the true values of y. Arguments: X (np.ndarray): Dataset. Y (np.ndarray): True values. epochs (int): Num of iteration on GD function. learn_rate (float): The rate of the learning of the model. """ if self.normalize: # Normalize the matrix dm_X = self.design_matrix(self.normalize_matrix(X, True)) else: dm_X = self.design_matrix(X) # 'Gradient Descent' method if learn_rate and epochs: for _ in range(epochs): # Calculate the new weights by vectorization approach self.weights -= (learn_rate / y.shape[0]) * dm_X.T @ (self.sigmoid_fn(dm_X @ self.weights) - y) def loss(self, y_prediction, y_true): """ Cross entropy loss i.e. logistic loss.""" return -np.mean(y_true * np.log(y_prediction) + (1-y_true) * np.log(1-y_prediction))
################################################################################ # Project Euler # Problem 4: Largest Palindrome Product # Description: Find the largest palindrome product of two 3-digit numbers ################################################################################ def getLargestPalindromeProduct(factor1, factor2): f1 = factor1 f2 = factor2 palindromeMax = -1 while f1 > 100: while f2 > 100: product = f1 * f2 if isPalindrome(product) and product > palindromeMax: palindromeMax = product f2 = f2 - 1 f1 = f1 - 1 f2 = f1 return palindromeMax def isPalindrome(x): stringVal = str(x) stringReverse = stringVal[::-1] for char1, char2 in zip(stringVal, stringReverse): if char1 != char2: return False return True print(getLargestPalindromeProduct(999, 999))
TERM = 600851475143 currentNum = TERM divisible = False while (not divisible) and (currentNum > 1): print("currentNum is: " + str(currentNum)) # check if currentNum divides TERM if TERM % currentNum == 0: print("currentNum divides evenly: " + str(currentNum)) # check if currentNum is prime prime = True factor = currentNum - 1 while prime and (factor > 1): if currentNum % factor == 0: prime = False factor = factor - 1 print(str(currentNum) + " is prime: " + str(prime)) # found prime factor if prime == True: divisible = True currentNum = currentNum - 1 print(currentNum + 1)
#object oriented #(1)python class #when we write funtion in a class, it called method #when we write variable in class, it called attribute class User: name = '' email = '' password = '' login = False def login(self): email= input("enter email: ") password= input("enter password: ") if email == self.email and password == self.password: login = True print("login successfull!!") else: print("login failed!!") #use of constructor def __init__(self, name, email, password): self.name = name self.email = email self.password = password def logout(self): login = False print("logged out!") def isLoggedIn(self): if self.login: return True else: return False def profile(self): if self.isLoggedIn(): print(self.name, "\n", self.email) else: print("user is not logged in") #make an object of a class user1= User("Maynul islam", "maynulislam3", "12345") '''user1.name = "Maynul Islam" user1.email= "maynulislam3" user1.password= "12345"''' user1.login() user1.profile() hello = input()
# 131、132 分割回文串 # 给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。 # 回文串 是正着读和反着读都一样的字符串。 # https://leetcode-cn.com/problems/palindrome-partitioning/ # 回溯法: 是一种算法思想,而递归是一种编程方法,回溯可以用递归来实现 class Solution: # 判断字符串是否为回文 def is_palindrome(self, p): return p == p[::-1] def partition(self, s): # self.isPalindrome = lambda s: s == s[::-1] res = [] self.backtrack(s, res, []) return res def backtrack(self, s, res, path): if not s: res.append(path) return for i in range(1, len(s) + 1): r = self.is_palindrome(s[:i]) if r: self.backtrack(s[i:], res, path + [s[:i]]) def minCut(self, s: str) -> int: n = len(s) dp = [n] * n for i in range(n): if self.is_palindrome(s[0: i + 1]): dp[i] = 0 continue for j in range(i): if self.is_palindrome(s[j + 1: i + 1]): dp[i] = min(dp[i], dp[j] + 1) return dp[n - 1]
# Generates a key # Created by JPCatarino - 28/10/2020 from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.backends import default_backend import random import string # Generates a random string with letters and numbers # Taken from pynative.com/python-generate-random-string/ def get_random_alphanumeric_string(length): letters_and_digits = string.ascii_letters + string.digits result_str = ''.join((random.choice(letters_and_digits) for i in range(length))) return result_str # The PBKDF2 generator receives as input the number of bytes to generate instead of bits def generate_key(pwd): salt = b'\x00' kdf = PBKDF2HMAC(hashes.SHA1(), 16, salt, 1000, default_backend()) key = kdf.derive(bytes(pwd, 'UTF-8')) return key
def function(): spisok_stud = ["Никита", "Рома", "Катя", "Лена", "Богдан", "Диасдастан", "Влад", "Стас", ] x = input("Добавьте человека") spisok_stud.append(x) print(spisok_stud) function()
from calculos import Calculos from comodo import Comodo calc = Calculos() def montando_comodo(vez): print(f"Vamos para o {vez}º comodo.\n") comprimento = float(input("Qual o comprimento do comodo em metros? ")) largura = float(input("E a largura? ")) comod = Comodo(comprimento, largura) print(f"\nA área das paredes são de {calc.calcular_parede(comprimento, comod.parede_altura):.2f}m².") print(f"A área do teto é de {calc.calcular_teto(comprimento, largura):.2f}m².") tinta = calc.tinta_gasta() print(f"Seu gasto de tinta será de {tinta:.2f}l.\n") def pintar(n): i = 1 while i <= n: montando_comodo(i) i += 1 else: print("Belo trabalho, por hoje terminamos por aqui!") if __name__ == "__main__": n_comodos = int(input("Quantos comodos iremos pintar? ")) pintar(n_comodos)
# Prompts user to enter file, reads file, and prints the file to the screen. fileName = input('Enter file name to be printed to screen: ') file_handle = open(fileName,'r') text = file_handle.read() print(text) file_handle.close()
m = int(input('Start from: ')) n = int(input('End on: ')) + 1 for i in range(m, n): print(i)
class Person: """ Person class saves names, emails, phone numbers, and friends to an object. Method greet() greets one person from another. Method print_contact_info prints objects email & phone number. """ def __init__(self, name, email, phone): friends = [] count = 0 self.name = name self.email = email self.phone = phone self.friends = friends self.count = count def greeting_count(self): self.count += 1 def greet(self, other_person): print('Hello {}, I am {}!'.format(other_person.name, self.name)) self.greeting_count() def print_contact_info(self): print(self.name, "'s email: ", self.email, ' ', self.name, "'s phone: ", self.phone, sep='') def add_friends(self, addFriend): self.friends.append(addFriend) def __str__(self): return 'Person: {} {} {}'.format(self.name, self.email, self.phone) sonny = Person('Sonny', '[email protected]', '222-333-4455') jordan = Person('Jordan', '[email protected]', '999-444-6677') sonny.print_contact_info() jordan.print_contact_info() jordan.add_friends(sonny) sonny.add_friends(jordan) print(len(jordan.friends)) print(len(sonny.friends)) sonny.greet(jordan) jordan.greet(sonny) sonny.greet(jordan) print(sonny.count) sonny.greet(jordan) print(sonny.count) jordan.greet(sonny) print(jordan.count) print(jordan) print(str(jordan)) class Vehicle: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def print_info(self): print(self.year, self.make, self.model) car = Vehicle('Nissan', 'Leaf', '2015') car.print_info()
import random que = 'n' while True: my_random_number = random.randint(1, 10) print('Random', my_random_number) count = 5 print('I am thinking of a number from 1 to 10.') print('You have', count, 'guesses left.') while True: prompt = int(input("What's the number? ")) if prompt < my_random_number: print(prompt, 'is too low.') elif prompt > my_random_number: print(prompt, 'is too high.') elif prompt == my_random_number: print('Yes! You Win!') que = input('Do you want to play again? (Y or N) ') break print('You have', count, 'guesses left.') count -= 1 if count == 0: print('You ran out of guesses!') que = input('Do you want to play again? (Y or N) ') if que != 'y': break
# Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta # necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2 metros quadrados. largura = float(input('Largura da parede: ')) altura = float(input('Altura da parede: ')) area = largura * altura tinta = area / 2 print(f'A área da parede mede {area}m²') print(f'Precisa de {tinta}l de tinta.')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- X_PLAYER = 1 O_PLAYER = -1 import numpy as np class TTTBoard: """ represents a tic tac toe board for the board """ def __init__(self, pos = [0 for _ in range(9)]): self.pos = pos def checkPos(self, pos): assert self.isValid(pos) return self.pos[pos] def valiateBoard(self): assert len(self.pos) == 9 assert max(self.pos) < 2, self.pos assert min(self.pos) > -2, self.pos def tryReward(self, player = X_PLAYER): cols = [[self.checkPos(loc) for loc in triple] for triple in ((range(col, 9, 3)) for col in range(3))] rows = [[self.checkPos(loc) for loc in triple] for triple in ((range(row, row + 3)) for row in range(0, 9, 3))] diags = [[self.checkPos(loc) for loc in triple] for triple in ((0, 4, 8), (2, 4, 6))] found_fail = False for pair in cols + rows + diags: if sum(pair) in [3, -3]: if pair[0] == player: return 1 found_fail = True # OR SHOULD IT BE X_PLAYER if found_fail: return 0 return None def isValid(self, loc): return loc in range(0, 9) def isEmpty(self, loc): self.isValid(loc) return self.checkPos(loc) == 0 def adjacents(self, loc): assert self.isValid(loc) col = loc % 3 row = loc // 3 return [adj for adj in range(9) if (adj // 3) in range(row - 1, row + 2) and (adj % 3) in range(col - 1, col + 2) and self.isValid(adj) and adj != loc] def emptyAdjacents(self, loc): assert self.isValid(loc) return [adj for adj in self.adjacents(loc) if self.isEmpty(adj) == 0] def allEmpties(self): return [empty for empty in range(9) if self.isEmpty(empty)] def stateAt(self, location, playerSide): self.valiateBoard() assert playerSide in [-1, 1] assert self.isEmpty(location) new = [i for i in self.pos] new[location] = playerSide return TTTBoard(new) def posVector(self): self.valiateBoard() pos = np.array(self.pos) pos = np.reshape(pos, (1, 9, 1)) assert len(pos.shape) == 3 return pos def flipPieces(self): self.pos *= -1
print("Im asking for the first and the last numbers of a range.") while True: try: x = int(input("Please give me the first number:")) y = int(input("Please give me the last number:")) if(x > y): print(x,"is greater than",y,"! Please give me the right order.") elif(x == y): print("Please, give me different values.") else: suma = 0 for n in range(x,y+1): suma = suma + n print ("The sum from",x,"to",y,"is:",suma) break except ValueError: print("Don't you dare! (Please enter an integer).")
from math import * def distance(x1,y1,x2,y2): d = sqrt((x2 - x1)**2+(y2 - y1)**2) return(d) print(distance(2,3,5,6))
"""Floyd-Warshall algorithm for finding shortest path between all vertices in a graph. Works both undirected and directed graphs as long as all edges have property 'weight'. The only limitation is that graph may not contain negative cycles so undirected graphs with negative weights are not allowed. Time complexity: O(V^3) For more information see Wikipedia: https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm """ def floyd(graph): """Floyd-Warshall algorithm for finding shortest path between all vertices in a weighted graph. Args: graph: Weighted graph, directed or undirected but may not contain negative cycles. Returns: Dictionary of dictionaries where d[source][dest] is distance between two vertices. In case there's no path between vertices the distance is float('inf'). """ default = {'weight': float('inf')} res = {x: {y: graph[x].get(y, default)['weight'] if x != y else 0 for y in graph.vertices} for x in graph.vertices} for k in graph.vertices: for i in graph.vertices: for j in graph.vertices: res[i][j] = min(res[i][j], res[i][k] + res[k][j]) return res
"""Hash-table that uses open addressing where collisions are solved by storing the item to next free slot. """ from itertools import chain, islice # Sentinel object used to mark unused slots SENTINEL = object() # Default size INITIAL_SIZE = 7 # Max load factor, once this is reached table will be grown LOAD_FACTOR = 0.7 # Growth factor GROW = 2 class Hash(object): """Hash table that uses open addressing. Attributes: table: Table storing items, uses SENTINEL to mark unused slots size: Number of items in the table """ def __init__(self, it=None): """Initializer, initializes Hash from given iterable. Args: it: Optional iterable which contents are added to table. """ self.table = [SENTINEL] * INITIAL_SIZE self.size = 0 self.extend(it or []) def __str__(self): return 'Hash({})'.format(list(self)) def __len__(self): return self.size def __iter__(self): for x in self.table: if x is not SENTINEL: yield x @staticmethod def __index_from_item(item, table): """Iterates over indexes in table starting from given item. First free index should be used to store the item. Args: item: Item to hash table: Table containing items Yields: Indexes where item should be stored in preference order """ size = len(table) start = hash(item) % size for i in range(start, start + size): yield i % size @staticmethod def __add(table, item): """Adds given item to table. Args: table: Table to add the item item: Item to add Returns: 1 if item was added, 0 if it wasn't (it was already in the table) """ for i in Hash.__index_from_item(item, table): if table[i] is SENTINEL: table[i] = item return 1 elif table[i] == item: break # Never reached without break return 0 def add(self, item): """Adds item to hash table Args: item: Item to add """ if self.size == int(len(self.table) * LOAD_FACTOR): # Rehash whole table table = [SENTINEL] * (GROW * len(self.table)) for x in self.table: if x is not SENTINEL: Hash.__add(table, x) self.table = table self.size += Hash.__add(self.table, item) def extend(self, it): """Adds items from given iterable to hash table. Args: it: Itertable containing items """ for x in it: self.add(x) def __find(self, item): """Searches index of an item in the hash table. Args: item: Item to search Returns: Index where the item is stored, -1 if not found """ for i in Hash.__index_from_item(item, self.table): x = self.table[i] if x is SENTINEL: break elif x == item: return i # Never reached without break return -1 def __contains__(self, item): return self.__find(item) != -1 def isdisjoint(self, other): """Check if two hashtables are disjoint (=don't contain the same item). Args: other: Other hash table Returns: True if hashtables are disjoint, False if not """ small, big = sorted((self, other), key=len) return all(x not in big for x in small) def __le__(self, other): return len(self) <= len(other) and all(x in other for x in self) def __lt__(self, other): return len(self) < len(other) and all(x in other for x in self) def __eq__(self, other): return len(self) == len(other) and all(x in other for x in self) def __ge__(self, other): return len(self) >= len(other) and all(x in self for x in other) def __gt__(self, other): return len(self) > len(other) and all(x in self for x in other) def __ne__(self, other): return len(self) != len(other) or any(x not in other for x in self) def __and__(self, other): small, big = sorted((self, other), key=len) return Hash(x for x in small if x in big) def __or__(self, other): return Hash(chain(self, other)) def __sub__(self, other): return Hash(x for x in self if x not in other) def __xor__(self, other): res = Hash(x for x in self if x not in other) res.extend(x for x in other if x not in self) return res def clear(self): """Removes all items from the hashtable.""" self.table = [SENTINEL] * INITIAL_SIZE self.size = 0 def __remove(self, index): """Removes item from hashtable. Args: index: Index of the item """ # In open addressing scheme all the items immediately following the # removed item need to be hashed. Collect all them to rehash. rehash = [] length = len(self.table) for i in range(index, index + length): i %= len(self.table) if self.table[i] == SENTINEL: break rehash.append(self.table[i]) self.table[i] = SENTINEL self.size -= 1 # Insert back all except the one that needed to be removed self.extend(islice(rehash, 1, None)) def pop(self): """Removes random item from hashtable and returns it. Returns: Removed item Raises: KeyError in case hashtable is empty """ # If items would be stored to doubly linked list time complexity # would be O(1) for i in range(len(self.table)): x = self.table[i] if x != SENTINEL: self.__remove(i) return x raise KeyError def discard(self, item): """Removes given item from hash, Args: item: Item to remove """ index = self.__find(item) if index != -1: self.__remove(index) def remove(self, item): """Removes given item from hash. Args: item: Item to remove Raises: KeyError if item is not present """ index = self.__find(item) if index == -1: raise KeyError self.__remove(index) def __ior__(self, other): for x in other: self.add(x) return self def __iand__(self, other): for i, x in enumerate(self.table): if x not in other: self.table[i] = SENTINEL self.size -= 1 return self def __isub__(self, other): for x in other: self.discard(x) return self def __ixor__(self, other): self.__isub__(self & other) return self
"""Directed graph that doesn't have multi-edges but may contain loops. Both vertices and edges may have associated properties. Vertices as stored as an adjacency matrix using dicts and as a separate dict that maybe iterated over. Time complexity of the operations: - check if edge (x, y) exists: O(1) - check degree of vertex: O(1) - insert/delete edge: O(1) - insert vertex: O(1) - delete vertex: O(number of connected edges) - iterate vertices/edges: O(n) Interface is loosely based on NetworkX (http://networkx.github.io/). """ from collections import defaultdict class Directed(object): """Directed graph which may contain loops but not multiple edges. Attributes: vertices: Dictionary of vertices where keys are vertex names and values are dictionary of vertex properties. edges: Dictionary of edges where keys are tuples of vertex pairs (from, to) and values are dictionary of edge properties. _outgoing: Three level dictionary of outgoing edges where the first level key is source vertex, second level key is destination vertex and third level is edge properties. incoming: Three level dictionary of incoming edges where the first level key is destination vertex, second level key is source vertex and third level is edge properties. """ def __init__(self): """Initializer, initializes empty graph.""" self.vertices = {} self.edges = {} self._outgoing = defaultdict(dict) self.incoming = defaultdict(dict) @property def directed(self): """Returns boolean value telling if graph is directed or not. Returns: Always True. """ return True def insert_vertex(self, name, **kwargs): """Inserts vertex to graph. Args: name: Vertex name, any hashable object **kwargs: Optional properties, if vertex already exists then given properties will be used to update existing ones. """ kwargs.update(self.vertices.get(name, {})) self.vertices[name] = kwargs self._outgoing.setdefault(name, {}) self.incoming.setdefault(name, {}) def remove_vertex(self, name): """Removes vertex from graph. Removes also all the edges the vertex is part of. Args: name: Name of the vertex. """ del self.vertices[name] # Remove edges without copying the keys while self._outgoing[name]: self.remove_edge(name, next(iter(self._outgoing[name]))) while self.incoming[name]: self.remove_edge(next(iter(self.incoming[name])), name) del self._outgoing[name] del self.incoming[name] def insert_edge(self, source, dest, **kwargs): """Inserts edge to graph. If vertices don't exist they are created. Args: source: Source vertex. dest: Destination vertex. **kwargs: Optional properties for the edge """ self.vertices.setdefault(source, {}) self.vertices.setdefault(dest, {}) kwargs.update(self.edges.get((source, dest), {})) self._outgoing[source][dest] = kwargs self.incoming[dest][source] = kwargs self.edges[(source, dest)] = kwargs def remove_edge(self, source, dest): """Removes edge from graph. Args: source: Source vertex. dest: Destination vertex. """ del self.edges[(source, dest)] del self._outgoing[source][dest] del self.incoming[dest][source] def connected(self, source, dest): """Returns boolean value telling if given vertices are connected by an edge. Args: source: Source vertex. dest: Destination vertex. Returns: True if vertices are connected by edge, False if not """ return (source, dest) in self.edges def edges_between(self, source, dest): """Returns iterator iterating over edges between given nodes. Note that with graph like this which doesn't allow multiple edges between the same nodes this doesn't make much sense but if multi-edge graphs are supported then easier to expose similar interface. Args: source: First vertex. dest: Second vertex. Returns: Iterator iterating over all the edges between given vertices. """ if dest in self._outgoing[source]: yield (source, dest) def edges_from(self, vertex): """Returns iterator iterating over all the outgoing edges of given vertex. Args: vertex: Edge start vertex.. Returns: Iterator iterating over all the outgoing edges of given vertex. Iterator returns (edge key, destination vertex) tuples where edge key can be used to index Undirected.edges. """ for neighbor in self._outgoing[vertex]: yield (vertex, neighbor), neighbor def __getitem__(self, item): return self._outgoing[item] def degree_in(self, vertex): """Returns in degree of given vertex. Args: vertex: Vertex. Returns: In degree. """ return len(self.incoming[vertex]) def degree_out(self, vertex): """Returns out degree of given vertex. Args: vertex: Vertex. Returns: Out degree. """ return len(self._outgoing[vertex]) def __eq__(self, other): return isinstance(other, Directed) and \ self.edges == other.edges and \ self.vertices == other.vertices def __ne__(self, other): return not self == other def __copy__(self): other = Directed() for vertex, properties in self.vertices.items(): other.insert_vertex(vertex, **properties) for (x, y), properties in self.edges.items(): other.insert_edge(x, y, **properties) return other copy = __copy__
"""Insertion sort.""" def sort(lst): """In-place insertion sort. Args: lst: List to sort """ for i in range(1, len(lst)): for j in range(i, 0, -1): if lst[j - 1] <= lst[j]: break lst[j - 1], lst[j] = lst[j], lst[j - 1]
#!/usr/bin/env python # Given the variable countries defined as: # Name Capital Populations (millions) countries = [['China','Beijing',1350], ['India','Delhi',1210], ['Romania','Bucharest',21], ['United States','Washington',307]] # Write code to print out the capital of India # by accessing the array. print countries[1][1] print countries[0][2] / countries[2][2] # We defined: stooges = ['Moe','Larry','Curly'] # but in some Stooges films, Curly was # replaced by Shemp. # Write one line of code that changes # the value of stooges to be: ['Moe','Larry','Shemp'] # but does not create a new List # object. stooges[2] = 'Shemp' print stooges # Define a procedure, replace_spy, that takes as its input a list of # three numbers, and modifies the value of the third element in the # input list to be one more than its previous value. spy = [0,0,7] def replace_spy(p): p[2] = p[2] + 1 # In the test below, the first line calls your procedure which will change spy, and the # second checks you have changed it. replace_spy(spy) print spy #>>> [0,0,8] speed_of_light = 299792458. # meters per second meter = 1 kilometer = 1000 nanosecond = 1.0/1000000000 # one billionth of a second millasecond = 1.0/1000000 cycles_per_second = 2700000000.0 #2.7 GHz cycle_distance = speed_of_light / cycles_per_second print speed_of_light / kilometer print speed_of_light * (0.4 * nanosecond) print speed_of_light * (12 * nanosecond) print speed_of_light * (7 * millasecond) bit = 8.79609e12 dollar_per_bit = 100 / bit nanodollar = 1/1000000000. print dollar_per_bit / nanodollar
#!/usr/bin/env python def bad_hash_string(keyword,buckets): return ord(keyword[0]) % buckets def test_hash_function(func, keys, size): results = [0] * size keys_used = [] for w in keys: hv = func(w,size) results[hv] += 1 keys_used.append(w) return results #.split() and then len(words) def hash_string(keyword, buckets): for char in keyword: location = ord(char) % buckets
#!/usr/bin/env python def find_element(alist,value): for index in range(len(alist)): element = alist[index] if element == value: return index return - 1 print find_element([1,2,3],3) print find_element(['alpha','beta'],'gamma')
# 리스트 안의 동명이인을 찾아 집합으로 반환하시오. name = ["Booki", "Jeeeun", "Jungwoo", "Booki"] name2 = ["Booki", "Jeeeun", "Jungwoo", "Booki", "Jeeeun"] def find_namesake(a): n = len(a) result = set() for i in range(0, n - 1): for j in range(i + 1, n): if a[i] == a[j]: result.add(a[i]) return result print(find_namesake(name)) print(find_namesake(name2)) # n명 중 두 명을 뽑아 짝을 짓는다고 가정할 때 짝을 지을 수 있는 모든 조합을 출력하시오. (중복 이름은 제외하시오.) name3 = ["Chad", "Nick", "Matt", "Booki", "Jeeeun", "Nick", "Booki", "Chad"] def match_two(a): l = list(set(a)) n = len(l) for i in range(0, n - 1): for j in range(i + 1, n): if not a[i] == a[j]: print(a[i] + " - " + a[j]) match_two(name3)
class MaxPriorityQueue: # A Priority Queue where the maximum element is removed first. # Implemented using a Heap. # TODO Add in place heap creation. def __init__(self): self.heap = [] self.size = 0 def insert_max(self, value): self.heap.append(value) self.bubble_up_max(len(self.heap)-1) def extract_max(self): value = self.heap[0] self.heap[0] = self.heap[-1] self.heap.pop(len(self.heap) - 1) self.bubble_down_max(0) return value def bubble_up_max(self, index): currentIndex = index while self.get_parent(currentIndex) != -1: parent = self.get_parent(currentIndex) if self.heap[parent] < self.heap[currentIndex]: temp = self.heap[parent] self.heap[parent] = self.heap[currentIndex] self.heap[currentIndex] = temp currentIndex = parent else: currentIndex = -1 def bubble_down_max(self, index): left = self.get_left(index) right = self.get_right(index) largest = -1 if left != -1 and right != -1: if self.heap[left] > self.heap[right]: largest = left else: largest = right elif right != -1: if self.heap[right] > self.heap[index]: largest = right elif left != -1: if self.heap[left] > self.heap[index]: largest = left if largest != -1 and self.heap[largest] > self.heap[index]: self.swap(index, largest) self.bubble_down_max(largest) def swap(self, index1, index2): temp = self.heap[index1] self.heap[index1] = self.heap[index2] self.heap[index2] = temp def get_parent(self, index): parent = index//2 if index == 0: return -1 return parent def get_right(self, index): right = 2*index + 1 if right >= len(self.heap): return -1 return right def get_left(self, index): left = 2*index if left >= len(self.heap): return -1 return left def getLayerOfElement(self, n): counter = 1 currentLayer = 0 while(True): if(counter >= n): return currentLayer currentLayer += 1 counter = counter*2 class MinPriorityQueue: # A Priority Queue where the minimum element is removed first. # Implemented using a Heap. # TODO Add in place heap creation. def __init__(self): self.heap = [] self.size = 0 def insert_min(self, value): self.heap.append(value) self.bubble_up_min(len(self.heap)-1) def extract_min(self): self.size += 1 value = self.heap[0] self.heap[0] = self.heap[-1] self.heap.pop(len(self.heap) - 1) self.bubble_down_min(0) return value def bubble_up_min(self, index): currentIndex = index while self.get_parent(currentIndex) != -1: parent = self.get_parent(currentIndex) if self.heap[parent] > self.heap[currentIndex]: temp = self.heap[parent] self.heap[parent] = self.heap[currentIndex] self.heap[currentIndex] = temp currentIndex = parent else: currentIndex = -1 def bubble_down_min(self, index): left = self.get_left(index) right = self.get_right(index) smallest = -1 if left != -1 and right != -1: if self.heap[left] < self.heap[right]: smallest = left else: smallest = right elif right != -1: if self.heap[right] < self.heap[index]: smallest = right elif left != -1: if self.heap[left] < self.heap[index]: smallest = left if smallest != -1 and self.heap[smallest] < self.heap[index]: self.swap( index, smallest) self.bubble_down_min(smallest) def swap(self, index1, index2): temp = self.heap[index1] self.heap[index1] = self.heap[index2] self.heap[index2] = temp def get_parent(self, index): parent = index//2 if index == 0: return -1 return parent def get_right(self, index): right = 2*index + 1 if right >= len(self.heap): return -1 return right def get_left(self, index): left = 2*index if left >= len(self.heap): return -1 return left def getLayerOfElement(self, n): counter = 1 currentLayer = 0 while(True): if(counter >= n): return currentLayer currentLayer += 1 counter = counter*2
import torch import math import matplotlib.pyplot as plt class KMeans: """ Implementation of KMeans clustering in pytorch Parameters: n_clusters : number of clusters (int) max_iter : maximum number of iteration (int) tol : tolerance (float) Attributes: centroids : cluster centroids (torch.Tensor) """ def __init__(self, n_clusters, max_iter=100, tol=0.0001, verbose=0): self.n_clusters = n_clusters self.max_iter = max_iter self.tol = tol self.centroids = None self.verbose = verbose @staticmethod def euclidean_similarity(a, b): """ Compute euclidean similarity of 2 sets of vectors Parameters: a: torch.Tensor, shape: [m, n_features] b: torch.Tensor, shape: [n, n_features] """ return 2 * a @ b.transpose(-2,-1) - (a**2).sum(dim=1)[..., :, None] - (b**2).sum(dim=1)[...,None,:] def remaining_memory(self): """ Get the remaining memory in GPU """ torch.cuda.synchronize() torch.cuda.empty_cache() remaining = torch.cuda.memory_allocated() return remaining def maximum_similarity(self, a, b): """ Compute maximum similarity or minimum distance of each vector in 'a' with all vectors in 'b' Parameters: a: torch.Tensor, shape: [m, n_features] b: torch.Tensor, shape: [n, n_features] """ device = a.device.type batchsize = a.shape[0] similarity_function = self.euclidean_similarity if device == 'cpu': sim = similarity_function(a, b) max_sim_v, max_sim_i = sim.max(dim=-1) return max_sim_v, max_sim_i else: if a.dtype == torch.float: expected = a.shape[0] * a.shape[1] * b.shape[0] * 4 elif a.dtype == torch.half: expected = a.shape[0] * a.shape[1] * b.shape[0] * 2 ratio = math.ceil(expected / self.remaining_memory()) sub_batchsize = math.ceil(batchsize/ratio) msv, msi = [], [] for i in range(ratio): if i*sub_batchsize >= batchsize: continue sub_x = a[i*sub_batchsize: (i+1)*sub_batchsize] sub_sim = similarity_function(sub_x, b) sub_max_sim_v, sub_max_sim_i = sub_sim.max(dim=-1) del sub_sim msv.append(sub_max_sim_v) msi.append(sub_max_sim_i) if ratio == 1: max_sim_v, max_sim_i = msv[0], msi[0] else: max_sim_v = torch.cat(msv, dim=0) max_sim_i = torch.cat(msi, dim=0) return max_sim_v, max_sim_i def fit_predict(self, X, centroids=None): """ Fitting the data Parameters: X: torch.Tensor, shape: [n_samples, n_features] centroids: {torch.Tensor, None}, default: None if given, centroids will be initilized with given tensor if None, centroids will be randomly chosen from X Return: labels: torch.Tensor, shape: [n_samples] """ batchsize, emb_dim = X.shape device = X.device.type if centroids is None: self.centroids = X[torch.randint(low=0,high=99,size=(self.n_clusters,),device=device)] else: self.centroids = centroids num_points_in_clusters = torch.ones(self.n_clusters, device=device) closest = None for i in range(self.max_iter): x = X closest = self.maximum_similarity(a=x, b=self.centroids)[1] matched_clusters, counts = closest.unique(return_counts=True) c_grad = torch.zeros_like(self.centroids) expanded_closest = closest[None].expand(self.n_clusters, -1) mask = (expanded_closest==torch.arange(self.n_clusters, device=device)[:, None]).float() c_grad = mask @ x /mask.sum(-1)[..., :, None] c_grad [c_grad!=c_grad] = 0 error = (c_grad - self.centroids).pow(2).sum() lr = 1 num_points_in_clusters[matched_clusters] += counts self.centroids = self.centroids * (1-lr) + c_grad * lr if self.verbose >= 2: print('iter:', i, 'error:', error.item()) if error <= self.tol: break return closest def inertia_(self, X, labels): """ Calculating the mean squared distance of X from the centroids Parameters: X: torch.Tensor, shape: [n_samples, n_features] labels: torch.Tensor, shape: [n_samples] Return: inertia: the mean squared distance """ device = X.device.type inertia = torch.tensor(0.0).to(device) for i in range(len(X)): inertia += torch.sqrt(torch.sum(torch.pow((X[i] - self.centroids[labels[i]]),2))) return inertia/len(X)
import sys import os import datetime from argparse import ArgumentParser # Invoke this script using CMD e.g.: # # python art_sort.py --dry-run=false D:\pictures D:\OneDrive\new_sorted_art # ## parser = ArgumentParser( description="""Commandline tool for sorting files. Specify a source directory containing files with one or more space-delimited tags in the filename. The leading tag (first string of characters before the first space, which must be present to sort by tag, as opposed to extension) will be used to place the file into any (nested) folders in the specified destination folder. Each directory-name under the destination folder will be interpreted as a tag by which files can be sorted. Files can also be sorted into folders by extension (by creating a folder somewhere within the destination-directory ("dest", say) named like "dest/.jpg/", "dest/.png/", or similar). Extensions are used as a secondary, fallback way to sort files which don't match any tags; files with matching tags will be sorted according to the tag, even if there is an extension-based destination for them also. Files that have no tags (including any file without a space in the name) which also don't match any extension specified in the destination folders will simply be left in place. This utility can be used to RE-SORT files when the top-level source and dest folders are actually the same directory. """ ) def boolifier(arg): """ string arg representing a boolean from commandline -> boolean """ nolist = ["no","0","false","n","",False] yeslist = ["yes","true","1","y",True] if arg.lower() in nolist: return False elif arg.lower() in yeslist: return True else: parser.error(f"Valid choices for true/false flags: {nolist+yeslist}") def logpathifier(arg): """ string arg representeing a path to a log-file -> path or None """ if arg.lower() in ["None",""]: return None else: absolute_directory = os.path.join(*os.path.abspath(arg)[0:-1]) if len(os.path.split(arg))==2 and os.path.split(arg)[0]=="": return arg else: if os.path.isdir(absolute_directory): return arg else: print(os.path.split(arg)) parser.error( f"Log folder \"{os.path.split(arg)[0]}\" does not exist" ) parser.add_argument( "source_dir", type=str, help="The folder to search for files to move" ) parser.add_argument( "dest_dir", type=str, help="The folder into which matching files will be moved" ) parser.add_argument( "--no-op-log", "-n", type=logpathifier, help="Log-destination for files NOT moved. Pass 'NONE' to skip logging", default="no_ops.log", required=False ) parser.add_argument( "--move-log", "-l", "-m", type=logpathifier, help="Log-destination for files that were moved. Pass 'NONE' to skip logging", default="moves.log", required=False ) parser.add_argument( "--quiet","-q", help="Supress messages about where files are being moved." " Logs will still be written unless 'NONE' is specified for log files.", action='store_const', const=True, required=False ) parser.add_argument( "--dry-run", help="Only emit messages indicating that a moves would happen", action='store', type=boolifier, nargs='?', metavar="{true/false/yes/no}", default=True, required=False ) parser.add_argument( "--ignore_dirs", type=str, help="Folders to skip when looking for files to move", nargs='+', metavar="IGNORE_DIR", default=[], required=False ) args = parser.parse_args() ignore_dirs = [] if not os.path.isdir(args.source_dir): # if source_dir is invalid parser.error(f"source_dir {args.source_dir} is not a folder") elif not [ n for n in os.listdir(args.dest_dir) if os.path.isdir(os.path.join(args.dest_dir,n)) ]: # if dest_dir is empty (no subfolders, so therefore no tags) parser.error(f"dest_dir \"{args.dest_dir}\" has no tags") elif not os.path.isdir(args.dest_dir): parser.error(f"dest_dir \"{args.dest_dir}\" is not a folder") for d in args.ignore_dirs: if not os.path.isdir(d): parser.error(f"ignore_dir {d} is not a valid folder") ignore_dirs.append(os.path.abspath(d)) for log_path in [args.move_log, args.no_op_log]: if log_path: with open(log_path, "a") as wh: wh.write(datetime.datetime.now().strftime("Logs for %Y-%m-%d %H:%M:%S ")) wh.write(datetime.datetime.now().strftime(f"| WORKING DIRECTORY: \"{sys.path[0]}\":\n")) if not args.quiet: print(f"\nDRY RUN: {args.dry_run}", file=sys.stderr) # Step 1: Go scan for the tags in the dest folder, and compile a mapping from # tag to location tags = {} for n in os.walk(args.dest_dir): tag_name = os.path.split(n[0])[-1] # last component of path is tag if tag_name != "raw": if " " in tag_name: parser.error(f"Invalid tag \"{tag_name}\"; tags can't have spaces.") elif tag_name not in tags: tags[tag_name] = n[0] # each tag (key) maps to a specific location (value at key) else: raise Exception(f"{tag_name} appears more than once. Exiting.") # Step 2: Go scan the pictures/source folder for files that match the criteria # defined by what we picked up in step 1, moving files as we find them # DO NOT OVERWRITE FILES OF THE SAME NAME IN THE DEST FOLDER def move_file(f,dest,dry_run=None,if_conflict=None): """ file to move, destination directory, fake move -> None Source file and dest folder are always assumed to be valid. Be prepared to `catch` if you're not confident of this, caller! f -- file to move. either an absolute path or path to valid file relative to the current working directory dest -- destination directory (folder) dry_run -- whether to actually perform the move or just print what the action would have been. If the default value is received, `args` will be consulted for what to do if_conflict -- what to do if two files from the source directory (including subdirectories) have the same name in the same folder to which files are being copied. """ if dry_run is None: dry_run = args.dry_run move_message = f"MOVE{int(dry_run)*' (FAKE)'}: \"{f}\" -> {dest}{os.path.sep}" if if_conflict is not None: raise NotImplemented("Overwrite-handling? You're on your own, buddy.") elif not move_file.emitted_warning and not args.quiet: print( "\nWARNING: file-collision handling not selected. May exit on conflict.", "\n(No files will be overwritten if collisions are encountered.)\n", file=sys.stderr ) move_file.emitted_warning = True if not args.quiet: print(move_message,file=sys.stderr) if args.move_log: with open(args.move_log, "a") as wh: # UGLY wh.write(move_message+"\n") if not dry_run: os.rename(f, os.path.join(dest,os.path.basename(f))) # move_file.emitted_warning = False # traverse source dir: for n in os.walk(args.source_dir): # ^ n will be 3-ples (dirpath,dirnames[],filenames[]) if os.path.abspath(n[0]) not in ignore_dirs: # if current directory is not ignored for f in n[2]: if not os.path.abspath(f) == f: # if path is relative: f = os.path.join(n[0],f) filename_only = os.path.split(f)[-1] # for each file in current directory, perform DA MAGIX first_part = filename_only.split(" ")[0] if first_part in tags: # ^ if first part of filename before space is a tag, try to move # the file: move_file(f,tags[first_part]) else: moved_by_extension=False exts = [e for e in tags if "." in e] exts.sort(key=len, reverse=True) # <- longest extensions first for ext in exts: # for any extension-based sorting we're doing, check for matches: if filename_only.endswith(ext): moved_by_extension = True move_file(f,tags[ext]) break # ^ break to avoid trying to move an already-moved file if not moved_by_extension and not args.quiet: # if there was no reason to move the file, and we're supposed # to emit helful info, print a notice ff = os.path.join(args.source_dir,f) no_op_message = f"No tags or target extensions found for {ff}" if not args.quiet: print(no_op_message,file=sys.stderr) if args.no_op_log: with open(args.no_op_log,"a") as wh: wh.write(no_op_message + "\n") elif not args.quiet: print(f"Ignored dir {n[0]}", file=sys.stderr) if not args.quiet: print("\n\nDONE :3", file=sys.stderr)
# Program que implementa uma função que gera a contraparte invertida de um numero inteiro: def inverso(numero): # Como strings podem ser invertidas, convertemos o numero de entrada # para uma string, invertemos seus caracteres e depois o convertemos de # vota, para então, retorná-lo. numero_str = str(numero) inverso_str = numero_str[::-1] inverso = int(inverso_str) return inverso # Exemplo de uso da função: print(inverso(344)+1)
# Esse programa implementa uma função principal de contagem de palavras, que recebe um # texto e retorna um dicionário cujas chaves são as palavras do texto e os valores # são suas frequências de aparição, mas só para as palavras cuja frequência de apariç~ao # está acima de um determinado limiar. Para ta, define-se duas funções auxiliares: # uma para tokenizar o texto e uma para filtrar do dicionário as palavras com # frequencia abaixo do limiar. # FUNÇÕES AUXILIARES: # Função que tokeniza o texto, removendo sinais de pontuação: def tokenize(texto): indesejados = ['.', ',', ';', ':', '!', '?'] partes = texto.split() cont = 0 while cont < len(partes): if partes[cont][-1] in indesejados: partes[cont] = partes[cont][0:len(partes[cont])-1] cont += 1 return partes # Função que recebe um dicionario com contagens de frequencias e uma frequencia minima # e retorna uma nova versão do dicioário com todas as entradas com frequencia # menor ou igual à mínima removidas: def filtra_dicionario(freq, freq_min): freq_filtrado = {} # Temos que criar um novo dicionario for key in freq: if freq[key] > freq_min: freq_filtrado[key] = freq[key] return freq_filtrado # FUNÇÃO PRINCIPAL: def conta_palavras(texto, freq_min): tokens = tokenize(texto) freq = {} for token in tokens: if token not in freq: freq[token] = 1 else: freq[token] += 1 return filtra_dicionario(freq, freq_min) # EXEMPLO DE UTILIZAÇÃ DA FUNÇÃO PRINCIPAL: print(conta_palavras('Os pássaros, pássaros no céu, não se se lembram do chão.', 1))
# Programa que produz um córpus como o da atividade prática, a partir de arquivos # de texto separados que contenham as sentenças de cada classe, salvando # o córpus resultante num arquivo serializado, usando o módulo pickle. import pickle # importa-se a referência ao módulo # Define-se uma função auxiliarq que faz aasição da frase ao córpus com as devidas # correções: def add_corpus(frase, corpus, classe): if frase != '': if frase[0] == ' ': corpus.append((frase[1:], classe)) else: corpus.append((frase, classe)) return corpus # Abre-se e extrai o conteúdo bruto dos dois arquivos: with open('aves.txt', 'r') as leitor_aves: texto_aves = leitor_aves.read() with open('computadores.txt', 'r') as leitor_computadores: texto_computadores = leitor_computadores.read() # Separa-se o conteúdo em frases: frases_aves = texto_aves.split('.') frases_computadores = texto_computadores.split('.') corpus = [] # Usando a função auxiliar, adiciona-se as frases a córpus: for frase in frases_aves: corpus = add_corpus(frase, corpus, 0) for frase in frases_computadores: corpus = add_corpus(frase, corpus, 1) # Salva-se o córpus em disco, usando o módulo pickle: with open('corpus.pkl', 'wb') as f: pickle.dump(corpus, f)
from .cards import Card __all__ = ['Hand'] class Hand(object): """ Represents a playing card game hand containing instances of :class:`cardsource.cards.Card` A ``Hand`` is an iterable Python object that supports being added to other hands as well as other common iterable operations. Hands are not directly comparable but this is common in subclasses of ``Hand``. """ def __init__(self): self._cards = [] # Representation methods def __repr__(self): return '<{0}: {1}>'.format(self.__class__.__name__, self._cards) def __str__(self): return str(sorted(self._cards)) # Iteration methods def __len__(self): return len(self._cards) def __iter__(self): return iter(self._cards) def __getitem__(self, key): if type(key) is slice: return [self._cards[n] for n in range(*key.indices(len(self)))] else: return self._cards[key] def __getslice__(self, i, j): h = Hand() if j >= len(self): j = len(self) for k in range(i, j): if k >= len(self): break h.append(self[k]) return h # Arithmetic methods def __add__(self, otherhand): newhand = Hand() newhand.extend(self) newhand.extend(otherhand) return newhand def __iadd__(self, otherhand): return self + otherhand # Collection methods def append(self, card): """ Adds a Card to the hand This class can be overridden in subclasses to ensure that the correct type of cards are added to the hand. Hands should not contain both instances of ``Card`` and subclasses of ``Card``. :param card: the card to add :type card: :class:`cardsource.cards.Card` """ if not isinstance(card, Card): card = Card(card) self._cards.append(card) def remove(self, card): """ Removes a Card from the hand :param card: the card to remove :type card: :class`cardsource.cards.Card` """ if not isinstance(card, Card): card = Card(card) self._cards.remove(card) def clear(self): """ Removes all cards from the hand """ self._cards = [] def extend(self, otherhand): """ Extends hand by appending cards from another hand :param card: the hand to append to this hand :type card: :class:`cardsource.hand.Hand` """ for card in otherhand: self.append(card) def count(self, card): """ Returns the number of instances of the specified card :param card: the card to search for :type card: :class:`cardsource.cards.Card` :rtype: int :returns: the number of instances of the specified card """ num = 0 for c in self._cards: if c == card: num += 1 return num
# 荷兰国旗问题,将红白蓝分别记为0,1,2。解决方法是将0全部放前面,1全部放后面。 import random def Dutch_Flag(relist): length = len(relist) begin = 0 end = -1 current = 0 while True: # 如果为0,那么要放到前面,注意begin和current的值要互换,因为begin处的值可能为1。 # 然后begin、current都向右移 if str(relist[current]) == "0": relist[begin],relist[current] = relist[current],relist[begin] begin += 1 current += 1 # 如果为1,那么在中间,不影响begin和end,current右移即可 if str(relist[current]) == "1": current += 1 # 如果为2,那么放在最后,end和current的值互换,end左移, # 但是current不能右移,因为此刻换后relist[current]的值未知,需要重新判断。 if str(relist[current]) == "2": relist[end],relist[current] = relist[current],relist[end] end -= 1 if int(current)-int(end) == length: break return relist if __name__ == '__main__': relist = [random.randint(0,2) for i in range(20)] print(relist) print(Dutch_Flag(relist))
# 题目描述 # 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 # 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。 # -*- coding:utf-8 -*- class Solution: def minNumberInRotateArray(self, rotateArray): # write code here if len(rotateArray) == 0: return 0 for i in range(1,len(rotateArray)): if rotateArray[i] < rotateArray[i-1]: return rotateArray[i] def minNumberInRotateArray2(self, rotateArray): # 二分查找 if len(rotateArray) == 0: return 0 left = 0 right = len(rotateArray)-1 mid = int((right + left)/2) while left < right: if rotateArray[mid-1] <= rotateArray[mid] and rotateArray[mid] <= rotateArray[mid+1]: # 这里要加等号,不然遇到连续的数据,返回错误的结果 if rotateArray[mid] >= rotateArray[left]: left = mid else: right = mid mid = int((right + left)/2) elif rotateArray[mid] >= rotateArray[mid-1]: return rotateArray[mid+1] elif rotateArray[mid] < rotateArray[mid-1]: return rotateArray[mid] x = [1,1,1,1,1,1,1,1,0,1] s = Solution() print(s.minNumberInRotateArray2(x))
print('***********Welcome to Rock Paper Scissors Game***********') print('Rules: Rock beats scissors, Scissors beats paper, Paper beats rock \n') while True: player1 = input("What's your name?") player2 = input("And your name?") game_start={'rock': 1,'paper': 2,'scissors': 3} player_1 = input("%s, do yo want to choose rock, paper or scissors?" % player1) player_2 = input("%s, do you want to choose rock, paper or scissors?" % player2) a = game_start.get(player_1) b = game_start.get(player_2) difference = a - b if difference in [-2, 1]: print('player 1 wins.') if str(input('Do you want to play another game, yes or no?\n')) == 'yes': continue else: print('game over.') break elif difference in [-1, 2]: print('player 2 wins.') if str(input('Do you want to play another game, yes or no?\n')) == 'yes': continue else: print('game over.') break else: print('Draw.Please continue.') print('')
import datetime sum =0 while (True): user_input = input('enter the price of item: \n') user_input1 = input('enter the name of item:\n') print(f"{user_input}:{user_input1}") if user_input!='q': sum = sum + int(user_input) print(f"order total so far:{sum}") else: print(f"your tptal bill is {sum}. thank you for visiting us") break x = datetime.datetime.now() print(x)
# -*- coding: utf-8 -*- __author__ = 'Fábio Rodrigues Pereira' __email__ = '[email protected]' class LCGRand: """ It implements a linear congruential generator (LCG), which generates numbers according to the following equation r[n+1] = a * r[n] mod m where a = 7**5 = 16807 and m = 2**31-1. The constructor takes a single argument, the seed (in addition to self). """ a = 7 ** 5 m = 2 ** 31 - 1 def __init__(self, seed): self.seed_list = [seed] self.index = 0 def rand(self): """ Returns the next random number Should not take any arguments except self """ self.seed_list.append(LCGRand.a * self.seed_list[self.index] % LCGRand.m) self.index += 1 return self.seed_list[self.index] class ListRand: """ It shall be based on a list of numbers. The constructor takes a list of numbers, and rand() returns the first number from that list when it is called for the first time, the second number when called the second time... It shall raise a RuntimeError if rand() is called after the last number in the list has been delivered. """ def __init__(self, __list): self.__list = __list self.iter_list = iter(self.__list) self.__index = 0 def rand(self): """ Returns the next random number Should not take any arguments except self """ """ if list_num < 0: raise RuntimeError('Method called after the last number in ' 'the list has been delivered.') """ self.__index += 1 if self.__index > len(self.__list): raise RuntimeError('Method called after the last number in ' 'the list has been delivered.') return next(self.iter_list) if __name__ == '__main__': a, b = 346, [4, 5, 29, 11] # instantiate at least one generator of each class c1 = LCGRand(a) c2 = ListRand(b) # print a few numbers from each print(c1.rand(), c1.rand(), c1.rand(), c1.rand(), c1.rand()) print(c2.rand(), c2.rand(), c2.rand(), c2.rand())
# -*- coding: utf-8 -*- import pytest __author__ = 'FABIO RODRIGUES PEREIRA' __email__ = '[email protected]' def median(data): """ Returns median of data. :param data: An iterable of containing numbers :return: Median of data """ sdata = sorted(data) n = len(sdata) if not data: raise ValueError('Cannot empty list') return (sdata[n // 2] if n % 2 == 1 else 0.5 * (sdata[n // 2 - 1] + sdata[n // 2])) def test_median_one_element_list(): """A test that the median function returns the correct value for a one-element list """ one_element_list = [8] assert median(one_element_list) == 8 @pytest.mark.parametrize('odd_list, even_list, list_ordered, ' 'list_rev_ordered, list_unordered, result', [ [ (1, 3, 5), (1, 2, 4, 5), (1, 2, 3, 4, 5), (5, 4, 3, 2, 1), (2, 1, 5, 4, 3), 3 ] ] ) def test_several(odd_list, even_list, list_ordered, list_rev_ordered, list_unordered, result): """Several tests that check that the correct median is returned for - Lists with odd numbers of elements - Lists with even numbers of elements - Ordered list, - List with reverse-ordered - List with unordered elements """ assert median(odd_list) == median(even_list) == median( list_ordered) == median(list_rev_ordered) == median( list_unordered) == result def test_empty_list_exception(): """A test checking that requesting the median of an empty list raises a ValueError exception """ with pytest.raises(ValueError) as e: median([]) assert str(e.value) == 'Cannot empty list' def test_original_data_unchanged(): """A test that ensures that the median function leaves the original data unchanged. """ data = [5, 3, 4, 1, 2] assert median(data) == 3 != data == [5, 3, 4, 1, 2] def test_median_works_for_tuples_and_lists(): """A test that ensures that the median function works for tuples as well as lists """ data_list = [5, 3, 4, 1, 2] data_tuples = (5, 3, 4, 1, 2) assert median(data_list) == median(data_tuples) == 3
from typing import Tuple # class TrieNode(object): # """ # Our trie node implementation. Very basic. but does the job # """ # # def __init__(self, char: str): # self.char = char # self.children = [] # # Is it the last character of the word.` # self.word_finished = False # # How many times this character appeared in the addition process # self.counter = 1 # self.index = None from typing import Tuple # class TrieNode(object): # """ # Our trie node implementation. Very basic. but does the job # """ # # def __init__(self, char: str): # self.char = char # self.children = [] # # Is it the last character of the word.` # self.word_finished = False # # How many times this character appeared in the addition process # self.counter = 1 # # # class Trie(object): # def __init__(self): # self.root = TrieNode("*") # # def add(self, word: str, index): # """ # Adding a word in the trie structure # """ # node = self.root # word = word.lower() # for char in word: # found_in_child = False # # Search for the character in the children of the present node # for child in node.children: # if child.char == char: # # We found it, increase the counter by 1 to keep track that another # # word has it as well # child.counter += 1 # # And point the node to the child that contains this char # node = child # found_in_child = True # break # # We did not find it so add a new chlid # if not found_in_child: # new_node = TrieNode(char) # node.children.append(new_node) # # And then point node to the new child # node = new_node # # Everything finished. Mark it as the end of a word. # node.word_finished = True # node.index = index # # def find_prefix(self, prefix: str) -> Tuple[bool, int]: # """ # Check and return # 1. If the prefix exsists in any of the words we added so far # 2. If yes then how may words actually have the prefix # """ # node = self.root # # If the root node has no children, then return False. # # Because it means we are trying to search in an empty trie # if not self.root.children: # return False, 0 # for char in prefix: # char_not_found = True # # Search through all the children of the present node # for child in node.children: # if child.char == char: # # We found the char existing in the child. # char_not_found = False # # Assign node as the child containing the char and break # node = child # break # # Return False anyway when we did not find a char. # if char_not_found: # return False, 0 # # Well, we are here means we have found the prefix. Return true to indicate that # # And also the counter of the last node. This indicates how many words have this # # prefix # return True, node class TrieNode(): def __init__(self): self.children = {} self.terminating = False self.counter = 0 self.index = -1 self.first = 0 class Trie(): def __init__(self): self.root = self.get_node() def get_node(self): return TrieNode() def get_index(self, ch): return ord(ch) def insert(self, word, content_index): root = self.root len1 = len(word) for i in range(len1): index = self.get_index(word[i]) if index not in root.children: root.children[index] = self.get_node() root = root.children.get(index) root.terminating = True root.index = content_index root.counter += 1 def search(self, word): root = self.root len1 = len(word) first = 0 for i in range(len1): index = self.get_index(word[i]) if first == 0: first = index root.first = first if not root: return None root = root.children.get(index) if root and root.terminating: return root else: return None if __name__ == '__main__': strings = ["pqrs", "pprt", "psst", "qqrs", "pqrs"] t = Trie() index = 0 for word in strings: t.insert(word, index) index += 1 print(t.search("pqrs").index, t.search("pqrs").counter) # dict = {"w" : 2, "r" : 5} # dict["r"] += 3 # print(dict["r"])
# grow_river.py - # # A demonstration of a technique for generating random rivers in a gameworld. Specifically, # it demonstrates how one might build a world one region at a time, creating regions only # as the player explores them. This technique allows one to grow a river that terminates # at a body of water in one region, but has its spring in another. # # This is quick hack demo code and should be treated as such. No warranty is provided as to the quality # of code (probably poor). USE AT YOUR OWN RISK!! from random import randrange from copy import copy LENGTH = 20 WIDTH = 20 PLAINS = 0 WATER = 1 TREES = 2 HILLS = 3 class Terrain: def __init__(self,ch,type,elevation): self.__ch = ch self.__type = type self.__elevation = elevation def get_ch(self): return self.__ch def get_type(self): return self.__type def get_elevation(self): return self.__elevation class Region: def __init__(self,length,width): self.__borders = [] self.__length = length self.__width = width self.__area = length * width self.__border_features = [] # default the map squares to be plains self.__map = [Terrain('.',PLAINS,1)] * self.__area def set_sqr(self,r,c,sqr): self.__map[r*self.__width + c] = sqr def get_sqr(self,r,c): return self.__map[r*self.__width + c] def dump(self): for sqr in range(0,self.__area): if sqr % self.__width == 0: print print self.__map[sqr].get_ch(), print for j in self.__border_features: print 'There is a river bordering at ',j[1],j[2] def get_length(self): return self.__length def get_width(self): return self.__width def get_area(self): return self.__area def in_same_area(self,r0,c0,r1,c1): return self.get_sqr(r0,c0).get_type() == self.get_sqr(r1,c1) def add_border_feature(self,terrain,r,c,r_dir,c_dir): self.__border_features.append((terrain,r,c,r_dir,c_dir)) def get_border_features(self): return self.__border_features class RegionGenerator: def __init__(self): self.__count = 0 def get_new_region(self): # cook the first region so it is guaranteed to have a river flowing west. if self.__count == 0: self.__count += 1 self.r0 = self.__region0() self.__add_cooked_river(self.r0,3,15) return self.r0 elif self.__count == 1: self.__count += 1 r1 = self.__region1() self.__handle_border_features(r1,('',self.r0,'','')) return r1 def __region0(self): region0 = Region(LENGTH,WIDTH) # first, add a lake start = 8 for j in range(0,12): for k in range(start,WIDTH): region0.set_sqr(j,k,Terrain('~',WATER,0)) start += 1 # add some hills end = 1 for j in range(5,LENGTH): for k in range(0,end): region0.set_sqr(j,k,Terrain('^',HILLS,2)) end += 1 # add a few trees for variety for j in range(6,10): region0.set_sqr(11,j,Terrain('#',TREES,1)) for j in range(8,11): region0.set_sqr(12,j,Terrain('#',TREES,1)) region0.set_sqr(9,j,Terrain('#',TREES,1)) for j in (9,10): region0.set_sqr(13,j,Terrain('#',TREES,1)) for j in (7,8): region0.set_sqr(10,j,Terrain('#',TREES,1)) return region0 def __region1(self): region1 = Region(LENGTH,WIDTH) #add some hills for r in range(5,region1.get_length()): start = randrange(5,15) for c in range(start,region1.get_width()): region1.set_sqr(r,c,Terrain('^',HILLS,2)) # add some trees for r in range(3,region1.get_length()-2): end = randrange(1,9) for c in range(0,end): region1.set_sqr(r,c,Terrain('#',TREES,1)) return region1 def __add_cooked_river(self,region,r,c): move = +1 while 1: elevation = region.get_sqr(r,c).get_elevation() region.set_sqr(r,c,Terrain('~',WATER,elevation)) prev_r = r prev_c = c r += move c -= 1 if r == region.get_length() or r == -1: break if c == region.get_width() or c == -1: break move = self.__cooked_change_river_dir() elevation = region.get_sqr(prev_r,prev_c).get_elevation() region.add_border_feature(Terrain('~',WATER,elevation),prev_r,prev_c,move,-1) def __cooked_change_river_dir(self): x = randrange(0,100) if x < 60: return +1 elif x in range(61,80): return 0 else: return -1 def __handle_border_features(self,region,bordering_regions): # handle northern border if bordering_regions[0] != '': for br in bordering_regions[0].get_border_features(): if br[0].get_type() == WATER and br[1] == region.get_length()-1: self.__add_river(region,br[0],region.get_width()-1,br[3],br[4],br[0].get_elevation()) # handle eastern border if bordering_regions[1] != '': for br in bordering_regions[1].get_border_features(): if br[0].get_type() == WATER and br[2] == 0: self.__add_river(region,br[1],region.get_width()-1,br[3],br[4],br[0].get_elevation()) # handle southern border if bordering_regions[2] != '': for br in bordering_regions[2].get_border_features(): if br[0].get_type() == WATER and br[1] == 0: self.__add_river(region,br[1],region.get_width()-1,br[3],br[4],br[0].get_elevation()) # handle western border if bordering_regions[3] != '': for br in bordering_regions[3].get_border_features(): if br[0].get_type() == WATER and br[2] == region.get_width()-1: self.__add_river(region,br[1],region.get_width()-1,br[3],br[4],br[0].get_elevation()) def __add_river(self,region,r,c,r_dir,c_dir,elevation): region.set_sqr(r,c,Terrain('~',WATER,elevation)) stop_chance = 5 move = (r_dir,c_dir) while 1: stop = randrange(0,100) if stop < stop_chance: break else: stop_chance += 5 next_r = r + move[0] next_c = c + move[1] if next_r == region.get_length() or next_r == -1: region.add_border_feature(Terrain('~',WATER,elevation),r,c,move,-1) break elif next_c == region.get_width() or next_c == -1: region.add_border_feature(Terrain('~',WATER,elevation),r,c,move,-1) break next_sqr = region.get_sqr(next_r,next_c) if next_sqr.get_elevation() < elevation: break else: r = next_r c = next_c region.set_sqr(r,c,Terrain('*',WATER,next_sqr.get_elevation())) elevation = next_sqr.get_elevation() move = self.__change_river_dir(move) def __change_river_dir(self,move): j = randrange(0,100) # only change the dir about 1 in 4 if j > 25: return move j = randrange(0,50) if j < 50: # change x m = move[0] + 1 k = randrange(0,50) if k < 50: delta = 1 else: delta = -1 m += delta m = (m % 2) - 1 return (m,move[1]) else: m = move[1] + 1 k = randrange(0,50) if k < 50: delta = 1 else: delta = -1 m += delta m = (m % 2) - 1 return (move[0],m) rg = RegionGenerator() r0 = rg.get_new_region() r0.dump() r1 = rg.get_new_region() r1.dump()
a = list(range(1,15)) def double(el): return el*2 def is_even(el): return el%2 == 0; double_even_in_a= [ double(el) for el in a if is_even(el)] print(double_even_in_a) # [4, 8, 12, 16, 20, 24, 28]
str = "hello world" print("str:", str) # 大写首字母 print("str.title():", str.title()) # 大写所有字符 print("str.upper():", str.upper()) # 小写所有字符 print("str.lower():", str.lower()) # 拼接字符 print("'a''b':", 'a''b') print("'1' + str:", '1' + str) # 删除前后的空白 print("str.rstripe():", ('\t'+str+'\t').rstrip())
# 验证关键字实参的调用 def hi(time, name): print(time+" " + name) hi(time='morning', name="tom") # 直接指明形参名则无需考虑传入顺序 hi(name='tom', time="morning")
for num in [1,2,3,4]: if num % 2 == 0: print("even number: ", num) continue print("this code never execute") print("odd number: ", num)
def hi(self): print(f'hi {self.name}') class C1: def __init__(self, name): self.name = name hi = hi c1 = C1('tom') # 1. 实例调用 c1.hi() # hi tom # 2. 实例方法赋值给变量进行调用 g = c1.hi g() # hi tom # 3. 类调用 C1.hi(c1) # 4. 类方法赋值给变量调用 h = C1.hi h(c1) # hi tom # 5. 函数调用 hi(c1) # hi tom
''' String literals in python are surrounded by either single or double quotation marks ''' #The strings can be displayed using the print() function print('Hello') # output : Hello print("Hello") # output : Hello #Assigning a string to a variable a = "Hello there" print(a) # output : Hello there #Multiline Strings can be assigned to a variable using tripple quotations b = """ Hey there hows your day coming up My day is looking good so far,thanks """ print(b) #output : Hey there hows your day coming up # My day is looking good so far,thanks ''' >>>>>>>>>>>>>>>>>>>>>>>> Strings are arrays in python <<<<<<<<<<<<<<<<<<<<<<<< Like many other programming languages python strings are arrays of bytes representing unicode characters python doesn't have the type char , therefore they are represented as strings of length 1 ''' c = "Hey they Stratizen" print(c[1]) # output : e -> the first character has an index 0 #it increments from there therefore the second character which is e has an index of 1 ''' >>>>>>>>>>>>>>>>>>>>>>>> Slicing <<<<<<<<<<<<<<<<<<<<<<<< you can get a range of characters in a string through slicing by specifying the index of the start character and the end character separated by a semi colon ''' d = "Hello buddy" print(d[0:5]) # output : Hello - this gives you the range from 0 to 5 inclusive of index 0 and 5 ''' >>>>>>>>>>>>>>>>>>>>>>>> String length using the len() function <<<<<<<<<<<<<<<<<<<<<<<< you can get a range of characters in a string through slicing by specifying the index of the start character and the end character separated by a semi colon ''' print(len(d)) # output : 11 ''' >>>>>>>>>>>>>>>>>>>>>>>> String methods <<<<<<<<<<<<<<<<<<<<<<<< Python has a set of string methods that you can use to manipulate strings ''' '''The strip() function removes whitespaces at the beginning and at the end''' e = " where are we having lunch today " print(e.strip()) # output : where are we having lunch today '''The lower() function returns a string in lower case ''' f = "GOOD DAY MY FRIEND" print(f.lower()) # output : good day my friend '''The upper() function returns a string in upper case ''' g = "hoot at corners" print(g.upper()) # output : HOOT AT CORNERS '''The replace() function replaces a string with another string''' h = "hooting is bad" print(h.replace("h","l")) # output : looting is bad '''The split() function splits strings into substrings where it finds instances of the separator''' i = "John , Paul , Fred , Mary" print(i.split(",")) # output : ['John ', ' Paul ', ' Fred ', ' Mary'] """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Check String<<<<<<<<<<<<<<<<<<<<<<<<<<<<< To check a certain sring or phrase present in a string we use the phrase --'in'-- or --'not in'-- """ txt = "This is the first isle" j = "is" in txt print(j) # output : True l = "is" not in txt print(l) # output : False """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> String Concatenation <<<<<<<<<<<<<<<<<<<<<<<<<<<<< To concatenate two strings we use the + operator """ m = "Hello" n = "Tiri" o = m + n print(o) # output : HelloTiri print(m+" "+n) # output : Hello Tiri ''' We can combine string and numbers using the format() method The format method takes the argument formats them an places them where the placeholder calibraces are {} ''' p = "My name is Tiri, i am {} years old" age = 22 print(p.format(age)) # output : My name is Tiri, i am 22 years old ''' The format() method takes unlimited number of arguments and places them into their respective placeholders ''' quantity = 8 itemno = 234 price = 2000 statement = "The number of lether bags is {} , the item number is {} and each costs {}" print(statement.format(quantity,itemno,price)) # output : The number of lether bags is 8 , the item number is 234 and each costs 2000 ''' you can use index numbers to ensure the arguments are placed in the correct place ''' statement2 = "i want to pay {2} per bag and buy {0} pieces with the code {1}" print(statement2.format(quantity,itemno,price)) # i want to pay 2000 per bag and buy 8 pieces with the code 234 """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Escape character <<<<<<<<<<<<<<<<<<<<<<<<<<<<< To insert characters that are illegal in a string we use escape characters \ followed by the character you want to insert """ myillegalone = "My parents and i went to the so called \"five star\" hotels " print(myillegalone) # output :My parents and i went to the so called "five star" hotels """ below is the link to more python escape characters and string methods https://www.w3schools.com/python/python_strings.asp """
import numpy from random import randint ''' Algoritmo genético O problema proposto foi movimentar animais, mais especificamente formigas, dentro de um espaço delimitado. No qual o movimento seria gerado aleatoriamente, tendo como intervalo inicial um valor menor, de forma a limitar o espaço e aumentando gradativamente. O algoritmo considera que cada cromossomo tem como genes a posição, onde cada coordenada é um gene, e o fit, assim esses valores são calculados e armazenados na matriz pop. A seleção será feita usando o método da roleta, considerando como intervalo o menor valor de e a soma total dos fits, gerando valores aleatorios e associando cada cromossomo com um subintervalo correspondente. ''' class movAnimal(): ''' main: Função responsável por inicializar e preencher as matrizes da população(pop) Calcula-se a distância e fit de cada elemento. A matriz da população tem como parametros as posições x,y e fit de cada elemento(linha) ''' def main(elems,valorMax): #cromossomos iniciais - matriz 5xelems pop = numpy.zeros(shape=(elems,3)) aux = numpy.zeros(shape=(elems),2) novaPop = numpy.zeros(shape=(2,1)) somaFit = 0 qntdNovaPop=0 for i in range(elems): posX = randint(0,valorMax) posY = randint(0,valorMax) distElem = dist(posX,posY) fitElem = fit(distElem) pop[i] = [posX,posY,fitElem] aux= mutacao(posX,posY) #mutação do gene pop[i] = [aux[0],aux[1],fitElem] somaFit+= fitElem ind=0 #seleção dos elementos pelo método da roleta if(i == 0): aux[i] = pop[i][2] else: aux[i] = pop[i-1][2] + fitElem limInferior = aux[0] limSuperior = somaFit probabilidade = randint(limInferior,limSuperior) while(qntdNovaPop <= 2): for i in range(elems) if(probabilidade>aux[i-1] && probabilidade<=aux[i]) novaPop[ind] = aux[i] ind++ #modificação do gene def mutacao(posX,posY): #Gera-se uma nova posição, que será no máx. 49, já somando com a antiga posição novoX = posX + randint(0,(49-posX)) novoY = posY + randint(0,(49-posY)) return [novoX,novoY] #dist: Calcula a distância euclidiana de cada elemento com relação ao tamanho do espaço def dist(a,b): distTotal = ((49-a)**2 + (49-b)**2)**0.5 return distTotal # A função fit responsável por calcular a proximidade do elemento, considerando 1 como tendo chegado a posição final # e iniciando em (1+sqrt(2)50) def fit(distElem): fitElem = 1+distElem return fitElem #reprodução dos cromossomos def crossingOver(): class main: #gerações totais a serem geradas geracoes = 20
#!/usr/bin/python #-*- Coding: utf8 -*- var=raw_input() login=var.split("&")[0].split("=")[1] senha=var.split("&")[1].split("=")[1] if login=="lucas" and senha=="123" : print("content-type: text/html") print"" f = open("site/menu.html","r") arquivo=f.read() f.close print(arquivo) else: print("content-type: text/html") print"" print("<h1>Login falhou</h1>")
# sql1.py """Volume 3: SQL 1 (Introduction). <Name> Natalie Larsen <Class> 001 <Date> 11-14-2018 """ import sqlite3 as sql import csv import numpy as np from matplotlib import pyplot as plt # Problems 1, 2, and 4 def student_db(db_file="students.db", student_info="student_info.csv", student_grades="student_grades.csv"): """Connect to the database db_file (or create it if it doesn’t exist). Drop the tables MajorInfo, CourseInfo, StudentInfo, and StudentGrades from the database (if they exist). Recreate the following (empty) tables in the database with the specified columns. - MajorInfo: MajorID (integers) and MajorName (strings). - CourseInfo: CourseID (integers) and CourseName (strings). - StudentInfo: StudentID (integers), StudentName (strings), and MajorID (integers). - StudentGrades: StudentID (integers), CourseID (integers), and Grade (strings). Next, populate the new tables with the following data and the data in the specified 'student_info' 'student_grades' files. MajorInfo CourseInfo MajorID | MajorName CourseID | CourseName ------------------- --------------------- 1 | Math 1 | Calculus 2 | Science 2 | English 3 | Writing 3 | Pottery 4 | Art 4 | History Finally, in the StudentInfo table, replace values of −1 in the MajorID column with NULL values. Parameters: db_file (str): The name of the database file. student_info (str): The name of a csv file containing data for the StudentInfo table. student_grades (str): The name of a csv file containing data for the StudentGrades table. """ conn = sql.connect(db_file) try: with sql.connect(db_file) as conn: cur = conn.cursor() #Drop MajorInfo, CourseInfo, StudentInfo and StudentGrades if they exist cur.execute("DROP TABLE IF EXISTS MajorInfo") cur.execute("DROP TABLE IF EXISTS CourseInfo") cur.execute("DROP TABLE IF EXISTS StudentInfo") cur.execute("DROP TABLE IF EXISTS StudentGrades") #Create MajorInfo, CourseInfo, StudentInfo and StudentGrades tables cur.execute("CREATE TABLE MajorInfo (MajorID INTEGER, MajorName TEXT)") cur.execute("CREATE TABLE CourseInfo (CourseID INTEGER, CourseName TEXT)") cur.execute("CREATE TABLE StudentInfo (StudentID INTEGER, StudentName TEXT, MajorID INTEGER)") cur.execute("CREATE TABLE StudentGrades (StudentID INTEGER, CourseID INTEGER, Grade TEXT)") #Insert info for MajorInfo and CourseInfo major_rows = [(1,"Math"),(2,"Science"),(3,"Writing"),(4,"Art")] course_rows = [(1,"Calculus"),(2,"English"),(3,"Pottery"),(4,"History")] cur.executemany("INSERT INTO MajorInfo VALUES(?,?);", major_rows) cur.executemany("INSERT INTO CourseInfo VALUES(?,?);", course_rows) #Retrieve and insert info for StudentInfo and StudentGrades with open("student_info.csv") as infile: info_rows = list(csv.reader(infile)) with open("student_grades.csv") as infile: grades_rows = list(csv.reader(infile)) cur.executemany("INSERT INTO StudentInfo VALUES(?,?,?);", info_rows) cur.executemany("INSERT INTO StudentGrades VALUES(?,?,?);", grades_rows) #Change MajorID from -1 to NULL cur.execute("UPDATE StudentInfo SET MajorID=NULL WHERE MajorID==-1") finally: conn.close() # Problems 3 and 4 def earthquakes_db(db_file="earthquakes.db", data_file="us_earthquakes.csv"): """Connect to the database db_file (or create it if it doesn’t exist). Drop the USEarthquakes table if it already exists, then create a new USEarthquakes table with schema (Year, Month, Day, Hour, Minute, Second, Latitude, Longitude, Magnitude). Populate the table with the data from 'data_file'. For the Minute, Hour, Second, and Day columns in the USEarthquakes table, change all zero values to NULL. These are values where the data originally was not provided. Parameters: db_file (str): The name of the database file. data_file (str): The name of a csv file containing data for the USEarthquakes table. """ try: with sql.connect(db_file) as conn: cur = conn.cursor() #Clear out USEarthquakes cur.execute("DROP TABLE IF EXISTS USEarthquakes") #Create new USEarthquakes table with Year, Month, Day, Hour, Minute, Second, Latitude, Longitude and Magnitude columns cur.execute("CREATE TABLE USEarthquakes" "(Year INTEGER, Month INTEGER, Day INTEGER, Hour INTEGER, Minute INTEGER, " "Second INTEGER, Latitude REAL, Longitude REAL, Magnitude REAL)") #Read and insert info from file with open(data_file) as infile: rows = list(csv.reader(infile)) cur.executemany("INSERT INTO USEarthquakes VALUES(?,?,?,?,?,?,?,?,?);", rows) #Delete magnitude 0 entries and set 0 to NULL in Day, Hour, Minute and Second column cur.execute("DELETE FROM USEarthquakes WHERE Magnitude==0") cur.execute("UPDATE USEarthquakes SET Day=NULL WHERE Day==0") cur.execute("UPDATE USEarthquakes SET Hour=NULL WHERE Hour==0") cur.execute("UPDATE USEarthquakes SET Minute=NULL WHERE Minute==0") cur.execute("UPDATE USEarthquakes SET Second=NULL WHERE Second==0") finally: conn.close() # Problem 5 def prob5(db_file="students.db"): """Query the database for all tuples of the form (StudentName, CourseName) where that student has an 'A' or 'A+'' grade in that course. Return the list of tuples. Parameters: db_file (str): the name of the database to connect to. Returns: (list): the complete result set for the query. """ good_grades = [] try: with sql.connect(db_file) as conn: cur = conn.cursor() #Find all names and classes where the grade is A or A+ good_grades = list(cur.execute("SELECT SI.StudentName, CI.CourseName " "FROM StudentInfo AS SI, CourseInfo AS CI, StudentGrades AS SG " "WHERE SI.StudentID == SG.StudentID AND CI.CourseID == SG.CourseID AND SG.Grade IN ('A','A+')")) cur.fetchall() finally: conn.close() #return results of search return good_grades # Problem 6 def prob6(db_file="earthquakes.db"): """Create a single figure with two subplots: a histogram of the magnitudes of the earthquakes from 1800-1900, and a histogram of the magnitudes of the earthquakes from 1900-2000. Also calculate and return the average magnitude of all of the earthquakes in the database. Parameters: db_file (str): the name of the database to connect to. Returns: (float): The average magnitude of all earthquakes in the database. """ mag_19 = [] mag_20 = [] average = 0 try: with sql.connect(db_file) as conn: cur = conn.cursor() #find list of magitudes from years 1800-1899 abd 1900-1999 mag_19 = list(cur.execute("SELECT Magnitude FROM USEarthquakes " "WHERE Year IN (1800,1899);")) mag_20 = list(cur.execute("SELECT Magnitude FROM USEarthquakes " "WHERE Year IN (1900,1999);")) #find average of all the magnitudes average = list(mag_20+mag_19) average = sum(np.ravel(average))/len(average) #plot the magitudes hist19 = plt.subplot(121) hist20 = plt.subplot(122) hist19.hist(mag_19) hist20.hist(mag_20) plt.show() finally: conn.close() return average
'''Contains Hand class''' class Hand: """ Creates a player or dealer hand, the hand can contain cards and has a score count and aces count. Upon construction 2 cards are immediately added. """ def __init__(self,name,deck): self.is_dealer = name == 'dealer' self.cards = [] self.score = 0 self.aces = 0 self.name = name self.hit(deck) self.hit(deck) def __str__(self): '''Returns a different string depending on if it is a player or dealer hand''' card_list = [str(card) for card in self.cards] if self.is_dealer: return 'The dealer\'s cards are \n'\ +',\n'.join(card_list)\ +f'\nTheir score is {self.score}' return f'{self.name}\'s cards are \n'\ +',\n'.join(card_list)\ +f'\n{self.name}\'s score is {self.score}' def hit(self,deck): ''' Takes a deck, Hand recieves a card from the deck, updates the aces count and the hands score ''' rank_value_pairs = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11} card = deck.pop() self.cards.append(card) if card.is_ace: self.aces += 1 self.score += rank_value_pairs[card.rank] if self.score > 21 and self.aces > 0: self.score -= 10 self.aces -= 1
import cx_Oracle username = 'MYONLINEEDU' password = 'RV-81-19-14f' database = 'localhost/xe' connection = cx_Oracle.connect(username, password, database) cursor = connection.cursor() print("Castle - gold") query1 = """ SELECT CASTLE.CASTLE, SUM(UNITS.GOLD) AS TOTAL_GOLD FROM CASTLE JOIN UNITS ON CASTLE.UNIT_NAME = UNITS.UNIT_NAME GROUP BY CASTLE.CASTLE ORDER BY TOTAL_GOLD ASC """ cursor.execute(query1) for row in cursor: print(row) print("\nCastle - percent") query2 = """ SELECT CASTLE.CASTLE, round ((SUM(UNITS.GOLD) + 0.0) / tg.TOTAL * 100, 2) AS PERCENT_ FROM ( SELECT SUM(UNITS.GOLD) AS TOTAL FROM UNITS )tg, CASTLE JOIN UNITS ON CASTLE.UNIT_NAME = UNITS.UNIT_NAME GROUP BY CASTLE.CASTLE, tg.TOTAL ORDER BY PERCENT_ ASC """ cursor.execute(query2) for row in cursor: print(row) print("\nLevel - max attack") query3 = """ SELECT UNIT_LEVELS.UNIT_LEVEL, MAX(UNITS.ATTACK) AS MAX_ATTACK FROM UNIT_LEVELS JOIN UNITS ON UNIT_LEVELS.UNIT_NAME = UNITS.UNIT_NAME GROUP BY UNIT_LEVELS.UNIT_LEVEL ORDER BY UNIT_LEVELS.UNIT_LEVEL """ cursor.execute(query3) for row in cursor: print(row) cursor.close() connection.close()
#!/usr/bin/python # The sum of the squares of the first ten natural numbers is, 12 + 22 + ... + 102 = 385 # The square of the sum of the first ten natural numbers is (1 + 2 + ... + 10)2 = 552 = 3025 # Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. n = int(input("input n = ")) #user able to input value def square_of_sum(n): a = (n*(n + 1))/2 # Formula for sum of a series up to n a = a**2 return a def sum_of_squares(n): #Finds the sum of square numbers a = range(1,101) b = 0 for x in a: b += x**2 # Increments b with each n**2 return b print(square_of_sum(n) - sum_of_squares(n))
import os import platform import sys import time from datetime import datetime from pytz import timezone """ Simple proof of concept python application """ def looper(): """ Simple proof of concept function. Loops indefinitely, prints to stdout and writes to file. :return: """ while True: string = (f"Hello var1:{os.getenv('VAR1')} var2:{os.getenv('VAR2')} var3:{os.getenv('VAR3')}! " f"the time now is {datetime.now(tz=timezone('Europe/Athens'))} " f"and I am going to sleep for 1 second.") print(string) with open("/data/out.txt", "a") as f: f.write(string + '\n') f.flush() time.sleep(1) if __name__ == "__main__": print(f"python: {platform.python_version()} " f"now: {datetime.now(tz=timezone('Europe/Athens')).strftime('%Y-%m-%dT%H:%M:%S')}") sys.exit(looper())
''' Study Drills 1. Go online an find out what Python'a input does. it asks for data from the user and stores it as a varaible 2. Can you find other ways to use it? Try some samples you find. ask the prompt in the input. line 16 3. Write another "form" like this to ask some questions. line 16 ''' print("How old are you?", end=' ') age = input() print("How tall are you?", end=' ') height = input() print("How much do you weigh?", end=' ') weight = input() color = input("What is your favorite color? ") # prompt 2 and three print(f"So, you're {age} old, {height} tall, {weight} heavy and your favorite color is {color}.")
while True: display = input('Press enter to continue ----- pre entret fo kontino') print('-------------------- Welcome to the main menu Aliens and Humans -------------------- \n\ Enter an option of your choice ---- echer nu topion fo rou kois\n\ 1. English to Aliench ---- English tre Aliench \n\ 2. Aliench to English ---- Aliench to English') try: choice = int(input('Choice ---- Kois : ')) if choice == 1: with open('englishdict.txt','r') as eng: eng_dict = eval(eng.read()) print('English to Aliench') find_word = input('Enter an english word : ') for key in eng_dict.keys(): if find_word == key: print(key,' :',eng_dict[key]) elif choice == 2: with open('englishdict.txt','r') as aln: aln_dict = eval(aln.read()) print('Aliench tre English') find_word = input('Enor ne english wur : ') for key, value in aln_dict.items(): if find_word == value: print(value,' :',key) else: print('Invalid entry ---- iroi entrio') except ValueError: print('Invalid entry ---- iroi entrio') except: print('An error has occured')
count = 1 while count < 11 : print(count) count = count + 1 if count == 11 : print('Counting complete.') myvar = 3 myvar += 2 mystring = "Hello" mystring += " world" print(myvar) print(mystring) myvar, mystring = mystring, myvar print(myvar) print(mystring) rangelist = range(10) print(rangelist) for number in rangelist: # Check if number is one of # the numbers in the tuple. if number in (3, 4, 7, 9): # "Break" terminates a for without # executing the "else" clause. break else: # "Continue" starts the next iteration # of the loop. It's rather useless here, # as it's the last statement of the loop. continue else: # The "else" clause is optional and is # executed only if the loop didn't "break". pass # Do nothing if rangelist[1] == 2: print("The second item (lists are 0-based) is 2") elif rangelist[1] == 3: print("The second item (lists are 0-based) is 3") else: print("Dunno") while rangelist[1] == 1: pass
import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import numpy as np from matplotlib.colors import LinearSegmentedColormap def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. :param y_true: list of true labels :param y_pred: list of predicted labels :param classes: list of strings containing names of the classes :param normalize: boolen to normalize percentages :param title: string :param cmap: colormap :return: """ # Compute confusion matrix cm = confusion_matrix(y_true, y_pred) cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] fig, ax = plt.subplots() im = ax.imshow(cm, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) # We want to show all ticks... ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), # ... and label them with the respective list entries xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, format(cm[i, j], fmt), ha="center", va="center", color="white" if cm[i, j] > thresh else "black") fig.tight_layout() return def plot_metrics(metrics, acc, classes, full_acq=False): """ This function prints and displays the metrics as a table :param metrics: array of metrics recall and precision :param acc: accuracy :param classes: names of the classes :param full_acq: boolean to change the title of the figure :return: """ colors = [(1, 1, 1), (1, 1, 1), (1, 1, 1)] cm = LinearSegmentedColormap.from_list("white", colors, N=1) fig, ax = plt.subplots(figsize=(4, 4)) im = ax.imshow(metrics, interpolation=None, cmap=cm) # We want to show all ticks... if full_acq: title = "Accuracy over acquisitions = " + str(int(10000 * acc) / 100) + "%" else: title = "Accuracy over slices = " + str(int(10000 * acc) / 100) + "%" ax.set(xticks=np.arange(metrics.shape[1]), yticks=np.arange(metrics.shape[0]), # ... and label them with the respective list entries xticklabels=classes, yticklabels=["Recall", "Precision"], title=title ) # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. fmt = '.2f' for i in range(metrics.shape[0]): for j in range(metrics.shape[1]): ax.text(j, i, format(metrics[i, j], fmt), ha="center", va="center", color="black") fig.tight_layout() return ax
#------------------------------------------------------------------------------- # Name: agentframework_final_180204 # Purpose: # # Author: Michael Iseli # # Created: 23/01/2018 # Copyright: (c) iseli 2018 #------------------------------------------------------------------------------- ''' Coding for GEOG5991M Assessment1 Geographical Information Analysis module for MSc GIS at University of Leeds Tutor: Dr. Andy Evans All code derived from practical handouts by Dr. Evans ''' # Import radom module for creation of agents import random # Creating Agent class and the relevant environment class Agent(): def __init__(self, environment, agents, neighbourhood): self.x = random.randint(0,99) self.y = random.randint(0,99) self.environment = environment self.agents = agents self.store = 0 self.neighbourhood = neighbourhood # Movment of agents withing the defined environment # Limiting movement to the "environment" perimeter # If an agents "leaves" environment it will reappear on the oposite side def move(self): if random.random() < 0.5: self.y = (self.y +1) % len(self.environment) else: self.y = (self.y -1) % len(self.environment) if random.random() < 0.5: self.x = (self.x +1) % len(self.environment) else: self.x = (self.x -1) % len(self.environment) # Nibbling away the current location def eat(self): if self.environment[self.y][self.x] > 10: self.environment[self.y][self.x] -= 10 self.store += 10 # Defining the distance between the agent and its sibblings # a2+b2=c2... Pythagoras - Ellada kai pali Ellada! def distance_between(self, agent): return(((self.x - agent.x)**2)+((self.y - agent.y)**2))**0.5 # if within neigbourhood eat only an "average" portion def share_with_neighbours(self, neighbourhood): for agent in self.agents: dist = self.distance_between(agent) if dist <= neighbourhood: sum = self.store + agent.store avg = sum/2 self.store = avg agent.store = avg #print("sharing" + str(dist) + " " + str(avg))
text = """Lattice paths Problem 15 Starting in the top left corner of a 2x2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20x20 grid? """ print(text) import time # create the permutations leaving out the unallowed ones def permutations(right_and_down,elements_left,used_list,perms): #print('elements_left: ' + str(elements_left) + ' used_list: ' + str(used_list) + ' perms: ' + str(perms)) for element in elements_left: # if elements before element in right or down are not in used_list, continue if element in right_and_down[0]: # determine if element in right or down right_and_down_ix = 0 else: right_and_down_ix = 1 location = right_and_down[right_and_down_ix].index(element) # find index of element in right or down skip = False for prior in right_and_down[right_and_down_ix][0:location]: # look at prior elements in right or down if prior not in used_list: # if prior elements not already used, there will be an illegal reversal #print('prior: ' + str(prior) + ' used_list: ' + str(used_list) + ' skip element: ' + str(element)) skip = True break if skip: continue new_used_list = list(used_list) new_used_list.append(element) #print('new_used_list: ' + str(new_used_list)) new_elements_left = list(elements_left) new_elements_left.remove(element) #print('new_elements_left: ' + str(new_elements_left)) if len(new_elements_left) == 0: new_perm = list(new_used_list) perms.append(new_perm) #print('new_perm: ' + str(new_perm)) continue permutations(right_and_down,new_elements_left, new_used_list,perms) return def factorial(n): factors = list(range(2,n+1)) prod = 1 for factor in factors: prod *= factor return prod ''' start_time = time.clock() for i in range(2,10): start_time = time.clock() n = i elements = [str(x) for x in range(2*n)] right = list(elements[0:len(elements)/2]) down = list(elements[(len(elements)/2):]) right_and_down = [right,down] perms = [] permutations(right_and_down,elements, [], perms) answer = len(perms) end_time = time.clock() print('n: ' + str(n) + ' answer: ' + str(answer) + ' time: ' + str(end_time-start_time)) #for perm in perms: # s="" # for letter in perm: # s+=letter # print(s) ''' start_time = time.clock() n=20 # do 40 choose 20 or 40!/(20!*20!) answer = factorial(2*n)/(factorial(n)**2) end_time = time.clock() runtime = end_time - start_time print('=======') print('ANSWER:') print('=======') print('found in ' + str(runtime) + ' seconds') print('number of paths: ' + str(answer))