blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
e0fc1d62963d1aa138c71380f71d844872d1e0bb
KingAshiru/Leetcode-weekly-Medium
/3Sum.py
1,206
3.71875
4
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() triplets = [] for i in range(len(nums)): if i > 0 and nums[i] == nums[i-1]: # skip same element to avoid duplicate triplets continue self.search_pair(nums, -nums[i], i+1, triplets) return triplets def search_pair(self, nums, target_sum, left, triplets): right = len(nums) - 1 while(left < right): current_sum = nums[left] + nums[right] if current_sum == target_sum: # found the triplet triplets.append([-target_sum, nums[left], nums[right]]) left += 1 right -= 1 while left < right and nums[left] == nums[left - 1]: left += 1 # skip same element to avoid duplicate triplets while left < right and nums[right] == nums[right + 1]: right -= 1 # skip same element to avoid duplicate triplets elif target_sum > current_sum: left += 1 # we need a pair with a bigger sum else: right -= 1 # we need a pair with a smaller sum
e6d3eef9d9a2699c50e6b286e2850d2ad1fd6bc0
jpars26/Python_Training
/JetBrains/Conditions & nested lists.py
162
3.828125
4
students = [["Will", "B"], ["Kate", "B"], ["Max", "A"], ["Elsa", "C"], ["Alex", "B"], ["Chris", "A"]] print([name for name, grade in students if grade == 'A'])
477295c4221b6c83bbf1229150dcfd3930ceed0b
mission-learning/Algorithms
/Graph algorithms/Eulerian graph.py
2,113
3.5
4
#IS EULERIAN class Graph: def __init__(self,vertices): self.V = vertices self.graph = [[] for i in range(verticles)] def addEdge(self,u,v): self.graph[u].append(v) self.graph[v].append(u) def DFS(self,v,visited): visited[v] = True for i in self.graph[v]: if visited[i] == False: self.DFS(i,visited) def isConnected(self): #Spojny visited =[False for i in range(self.V)] for i in range(self.V): if len(self.graph[i]) > 1: break if i == self.V-1: return True self.DFS(i,visited) for i in range(self.V): if visited[i] == False and len(self.graph[i]) > 0: return False return True def isEulerian(self): if self.isConnected() == False: return 0 else: odd = 0 for i in range(self.V): if len(self.graph[i]) % 2 !=0: odd +=1 if odd == 0: return 2 elif odd == 2: return 1 elif odd > 2: return 0 #Let us create and test graphs shown in above figures g1 = Graph(5); g1.addEdge(1, 0) g1.addEdge(0, 2) g1.addEdge(2, 1) g1.addEdge(0, 3) g1.addEdge(3, 4) g1.test() g2 = Graph(5) g2.addEdge(1, 0) g2.addEdge(0, 2) g2.addEdge(2, 1) g2.addEdge(0, 3) g2.addEdge(3, 4) g2.addEdge(4, 0) g2.test(); g3 = Graph(5) g3.addEdge(1, 0) g3.addEdge(0, 2) g3.addEdge(2, 1) g3.addEdge(0, 3) g3.addEdge(3, 4) g3.addEdge(1, 3) g3.test() #Let us create a graph with 3 vertices # connected in the form of cycle g4 = Graph(3) g4.addEdge(0, 1) g4.addEdge(1, 2) g4.addEdge(2, 0) g4.test() # Let us create a graph with all veritces # with zero degree g5 = Graph(3) g5.test() #This code is contributed by Neelam Yadav
9c0071d2f764fc0db1631c1b8fea65c094227ee3
rekbun/project-euler
/src/python/problem41.py
625
3.875
4
from itertools import * def getPandigitalList(length): num='' for i in range(1,length+1): num+=str(i) return (''.join(each) for each in list(permutations(num,length))) def isPrime(n): if n==2 or n==3 or n==5 or n==7: return True if n%2==0 or n%3==0 or n%5==0: return False k=5 while k*k<=n: if n%k==0 or n%(k+2)==0: return False; k+=6 return True lastPrime=123 def checkAll(): lastPrime=123 for i in range(9,1,-1): for (n,p) in enumerate(getPandigitalList(i)): if isPrime(int(p)) and int(p)>lastPrime: lastPrime=int(p) if lastPrime!=123: return lastPrime print checkAll()
a28c7a16f077e5b86188fc90bd4562c3be4c2ab3
1040979575/baseDataStructureAndAlgorithm
/algorithm/dynamicProgramming.py
546
3.515625
4
''' 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6 ''' # 一维变换dp def dp(arr): temp = [] for i in range(arr.__len__()): if i == 0: temp.append(arr[i]) else: temp.append(max(temp[i - 1] + arr[i], arr[i])) return max(temp) if __name__ == '__main__': print(dp([-2,1,-3,4,-1,2,1,-5,4]))
494fee0ae500bc6a26bcb2752d7aa7f95b7b3f39
tyler7771/learning_python
/num_repeats.py
753
4.1875
4
# Write a method that takes in a string and returns the number of # letters that appear more than once in the string. You may assume # the string contains only lowercase letters. Count the number of # letters that repeat, not the number of times they repeat in the # string. # # Difficulty: hard. def num_repeats(string): repeated = [] for idx1, letter1 in enumerate(string): for idx2, letter2 in enumerate(string): if letter1 == letter2 and idx1 != idx2: if letter1 not in repeated: repeated.append(letter1) return len(repeated) print num_repeats("abdbc") #1 print num_repeats("aaa") #1 print num_repeats("abab") #2 print num_repeats("cadac") #2 print num_repeats("abcde") #0
fc30a90635d2fe46b03ba33ae0111dbf7275bb89
VovaPicha/VovaPicha
/task1.py
880
3.65625
4
def main(): s = input() nums = [] words = [] for word in s.split(): try: nums.append(int(word)) except ValueError: words.append(word) print(' '.join(words)) # виводим числа print(nums) words = list(map(lambda x: x.upper() if len(x) == 1 else x[0].upper() + x[1:-1] + x[-1].upper(), words)) print(' '.join(words)) if len(nums) == 0: print('No nums in string') else: idx = 0 for i in range(len(nums)): if nums[idx] < nums[i]: idx = i print('Idx: {}, Num: {}'.format(idx, nums[idx])) numsPow=[] for i in range(len(nums)): if i == idx: continue numsPow.append(pow(nums[i], i)) print(numsPow) if __name__ == '__main__': main()
8bb7dc7a74c7e30363d83a82d92e06992b5fb261
brenomacedodm/pca
/k_nn.py
1,093
3.5625
4
#função para cálculo da distância euclidiana import math def distancia_eucl(item_1, item_2): somatorio = 0 for i in range(len(item_1)-1): somatorio += pow((float(item_1[i]) - float(item_2[i])),2) return math.sqrt(somatorio) #Função do K-NN para comparar com o desempenho do método proposto def knn (conjunto, item, k): distancias = [] resultado = [] nn = [] for i in range(len(conjunto)): distancias.append(distancia_eucl(conjunto[i], item)) resultado = sorted(distancias)[:k] qtdClasse0, qtdClasse1 = 0, 0 for a in range(len(resultado)): if conjunto[distancias.index(resultado[a])][-1] == "0\n": #print(conjunto[distancias.index(resultado[a])][4]) qtdClasse0 += 1 elif conjunto[distancias.index(resultado[a])][-1] == "1\n": #print(conjunto[distancias.index(resultado[a])][4]) qtdClasse1 += 1 #print(qtdSet) #print(qtdVer) #print(qtdVir) if (qtdClasse0 > qtdClasse1): return "0\n" else: return "1\n"
48bb8ca03de943b1d0892886124f7860005b58ef
surinder1/new-file
/assignment_no_13.py
2,014
4.28125
4
#Q.1- Name and handle the exception occured in the following program: #a=3 #if a<4: # a=a/(a-3) # print(a) # try: # a=3 # if a<4: # a=a/(a-3) # print(a) # except Exception: # print("Hello") # Q.2- Name and handle the exception occurred in the following program: # l=[1,2,3] # print(l[3]) # try: # l=[1,2,3] # print(l[3]) # except Exception: # print("element is not present") #Q.4- What will be the output of the following code: # Function which returns a/b # def AbyB(a,b): # try: # c = ((a+b) / (a-b)) # except ZeroDivisionError: # print("a/b result in 0") # else: # print(c) # Driver program to test above function # AbyB(2.0, 3.0) # AbyB(3.0, 3.0) #Q.3- What will be the output of the following code: # Program to depict Raising Exception # try: # raise NameError("Hi there") # Raise Error # except NameError: # print "An exception" # raise # To determine whether the exception was raised or not # Q.4- What will be the output of the following code: # Function which returns a/b # def AbyB(a , b): # try: # c = ((a+b) / (a-b)) # except ZeroDivisionError: # print("a/b result in 0") # else: # print(c) # Driver program to test above function # AbyB(2.0, 3.0) # AbyB(3.0, 3.0) #Q.5- Write a program to show and handle following exceptions: #1. Import Error #2. Value Error #3. Index Error # import error # try: # import surinder # except Exception as e: # print(e) # value error # try: # a=int("ab") # except Exception as a: # print(a) #index error # a=[1,2,3] # print(a(5)) #Q.6- Create a user-defined exception AgeTooSmallError() that warns the user when they have entered age less than 18. The code must keep taking input till the user enters the appropriate age number(less than 18). class AgeTooSmallError(Exception): pass try: while True: age=int(input("enter the age")) if age<18: print("age is less than 18",age) else: raise AgeTooSmallError("age is above 18") except AgeTooSmallError as e: print(e)
af5f83a9fb74aa1f0a30c879267ca7dc46994712
naedavis/BMI_Calc
/main.py
4,914
4.1875
4
#Naeemah Davis #BMI Calculator import tkinter as tk from tkinter import * from tkinter import INSERT from tkinter import messagebox top = tk.Tk() stvar = StringVar(top) top.title("Naeemah Davis") #size of the window on which everything will be displayed top.geometry("700x700") #made it non-resizable so the user cannot change the size of the window top.resizable(width=False, height=True) top.config(bg= "light blue") #making a Frame variable called frame frame = tk.Frame(top) #setting the width, height and position of frame frame.place(x=70, y=210, height=250, width=550) #making a label with the title thats being displaye ont hte window called top lbl_title = Label(top, text= "Ideal Body Mass Index", font="Arial 23") #position of title label on window called top lbl_title.place(x=300, y=50) lbl = Label(top, text="Calculator", font= "Arial 23") lbl.place(x=380, y=89) lbl_sub = Label(top, text="Enter the following", font="Arial 18") lbl_sub.place(x=100, y=180) lbl_height = Label(frame, text="Height(cm) :", font="Arial 16") lbl_height.place(x=50, y=30) #height of user will be entered and value will be displayed in blue ent_height = Entry(frame, fg="blue") ent_height.place(x=300, y=30, height= 25) ent_height.focus_set() lbl_weight = Label(frame, text="Weight(kg) :", font="Arial 16") lbl_weight.place(x=50, y=80) ent_weight = Entry(frame, fg="blue") ent_weight.place(x=300, y=80) lbl_gender = Label(frame, text="Gender :", font="Arial 16") lbl_gender.place(x=50, y=130) # Section that if the user is female the AGE entry becomes active and will be taken into consideration lbl_age = Label(frame, text="Age :", font="Arial 16") lbl_age.place(x=50, y=180) ent_age = Entry(frame, fg="blue", state="readonly") ent_age.place(x=300, y=180, width=50) def females(item): stvar.set(item) if item != "Female": ent_age.config(state="readonly") else: ent_age.config(state="normal") dict_genders= { "Male", "Female"} stvar.set(["Male"]) # set the default option gender_menu = tk.OptionMenu(frame, stvar, *dict_genders, command= females) gender_menu.place(x=300, y=130) #Section that calculates the BMI of User def bmi(): if ent_age['state'] == "normal": try: weight = float(ent_weight.get()) height = float(ent_height.get()) age = int(ent_age.get()) bmi = weight/(height/float(100))**float(2) txt_bmi.configure(state= "normal") txt_bmi.insert(INSERT, str(round(bmi,1))) ideal_bmi = 0.5*weight/(height/100)**2+0.03*age+11 txt_ibmi.config(state="normal") txt_ibmi.insert(INSERT, str(round(ideal_bmi,1))) except ValueError: messagebox.showinfo("Error", "Incorrect value entered") ent_height.delete(0, END) ent_weight.delete(0, END) ent_age.delete(0, END) txt_bmi.delete(0, END) txt_ibmi.delete(0, END) else: try: weight = float(ent_weight.get()) height = float(ent_height.get()) bmi = weight/(height/float(100))**float(2) txt_bmi.configure(state="normal") txt_bmi.insert(INSERT, str(round(bmi, 1))) ideal_bmi = 0.5*weight/(height/100)**2+11.5 txt_ibmi.config(state="normal") txt_ibmi.insert(INSERT, str(round(ideal_bmi,1))) except ValueError: messagebox.showinfo("Error", "Incorrect value entered") ent_height.delete(0, END) ent_weight.delete(0, END) txt_bmi.delete(0, END) txt_ibmi.delete(0, END) btncalculate = Button(top, text="Calculate Your Ideal Body Mass Index", font= "Arial 20", command=bmi) btncalculate.place(x=100, y=480, width=500) lbl_bmi = Label(top, text="BMI :", font="Arial 16") lbl_bmi.place(x=100, y=530) txt_bmi = Text(top, fg= "blue", state="disabled") txt_bmi.place(x=200, y=530, height=30, width=100) lbl_ibmi = Label(top, text= "Ideal BMI", font="Arial 16") lbl_ibmi.place(x=350, y=530) txt_ibmi = Text(top, fg= "blue", state= "disabled") txt_ibmi.place(x=500, y=530, height=30, width=100) def clear(): ent_height.delete(0, END) ent_weight.delete(0, END) ent_age.delete(0, END) txt_bmi.delete(1.0, END) txt_ibmi.delete(1.0, END) txt_bmi.config(state = "disabled") txt_ibmi.config(state ="disabled") ent_height.focus_set() btn_clear =Button(top, font="Arial 20", text="Clear", fg="Red", command=clear) btn_clear.place(x=70, y=600, width=150) def exit(): msg =messagebox.askquestion("Exit Application", "Are you sure you want to exit the BMI Calculator?") if msg == "yes": top.destroy() else: messagebox.showinfo("Return", "You will now return to the BMI Calculator") btn_exit =Button(top, font="Arial 20", text="Exit", bg="Red") btn_exit.place(x=500, y=600, width=150) # pic = tk.PhotoImage(file="treadmill.jpg") top.mainloop()
d6104a2860598ea81698c9f527063fdefc7579c3
carloshssouza/UniversityStudies
/COM220/T8/com220_trab08.py
3,993
3.921875
4
from abc import ABC, abstractmethod #Definição de exceptions class TitulacaoNaoPermitida(Exception): pass class IdadeInvalida(Exception): pass class CursoNaoPermitido(Exception): pass class CpfDuplicado(Exception): pass #Classes class Pessoa(ABC): def __init__(self, nome, endereco, idade, cpf): self.__nome = nome self.__endereco = endereco self.__idade = idade self.__cpf = cpf def getNome(self): return self.__nome def getEndereco(self): return self.__endereco def getIdade(self): return self.__idade def getCpf(self): return self.__cpf @abstractmethod def printDescricao(self): pass class Professor(Pessoa): def __init__(self, nome, endereco, idade, cpf, titulacao): super().__init__(nome, endereco, idade, cpf) self.__titulacao = titulacao def getTitulacao(self): return self.__titulacao def printDescricao(self): print() print('----------PROFESSOR CADASTRADO---------') print(f'Nome: {self.getNome()}') print(f'Endereco: {self.getEndereco()}') print(f'Idade: {self.getIdade()}') print(f'CPF: {self.getCpf()}') print(f'Titulação: {self.getTitulacao()}') print('------------------------------------') print() class Aluno(Pessoa): def __init__(self, nome, endereco, idade, cpf, curso): super().__init__(nome, endereco, idade, cpf) self.__curso = curso def getCurso(self): return self.__curso def printDescricao(self): print() print('----------ALUNO CADASTRADO---------') print(f'Nome: {self.getNome()}') print(f'Endereco: {self.getEndereco()}') print(f'Idade: {self.getIdade()}') print(f'CPF: {self.getCpf()}') print(f'Titulação: {self.getCurso()}') print('------------------------------------') print() #Criando a lista de professores listaDeProfessores = [ ('Elisa', 'Rua 1', 33, '10101010', 'Doutor'), ('Baldochi', 'Rua 2', 34, '12121212', 'Doutor'), ('Alysson', 'Rua 3', 30, '13131313', 'Mestre'), ('Flávio', 'Rua 4', 28, '14141414', 'Doutor'), ('Adriana', 'Rua 5', 35, '10101010', 'Doutor') ] #Criando a lista de alunos listaDeAlunos = [ ('Carlos', 'Rua 10', 25, '91919191', 'SIN'), ('Henrique', 'Rua 11', 20, '92929292', 'CCO'), ('João', 'Rua 12', 20, '93939393', 'SIN'), ('José', 'Rua 13', 18, '94949494', 'ADM'), ('Maria', 'Rua 14', 28, '93939393', 'SIN'), ('Letícia', 'Rua 15', 17, '98989898', 'SIN') ] cadastro = {} # for nome, endereco, idade, cpf, titulacao in listaDeProfessores: try: if cpf in cadastro: raise CpfDuplicado if idade < 30: raise IdadeInvalida if titulacao != 'Doutor': raise TitulacaoNaoPermitida except CpfDuplicado: print(f'CPF {cpf} do professor {nome} já existe um igual cadastrado') except IdadeInvalida: print(f'Idade do professor {nome} não permitida') except TitulacaoNaoPermitida: print(f'Titulação do professor {nome} não permitido') else: cadastro[cpf] = Professor(nome, endereco, idade, cpf, titulacao) cadastro[cpf].printDescricao() for nome, endereco, idade, cpf, curso in listaDeAlunos: try: if cpf in cadastro: raise CpfDuplicado if idade < 18: raise IdadeInvalida if curso != 'SIN' and curso != 'CCO': raise CursoNaoPermitido except CpfDuplicado: print(f'CPF {cpf} do aluno {nome} já existe um igual cadastrado') except IdadeInvalida: print(f'Idade do aluno {nome} não permitida') except CursoNaoPermitido: print(f'Curso do aluno {nome} não permitido') else: cadastro[cpf] = Aluno(nome, endereco, idade, cpf, curso) cadastro[cpf].printDescricao()
473994573de4b5aa397f5ae4c644f648cc685227
dharness/ctci
/Chapter 1 - Arrays and Strings/question_4.py
568
4.34375
4
# Write a method to replace all spaces in a string with'%20'. You may assume that # the string has sufficient space at the end of the string to hold the additional # characters, and that you are given the "true" length of the string. (Note: if implementing # in Java, please use a character array so that you can perform this operation # in place.) # # EXAMPLE # Input: "Mr John Smith # Output: "Mr%20Dohn%20Smith" def encode_string(s): return s.rstrip().replace(' ', '%20') r1 = encode_string("tigers lemmons pie") r2 = encode_string("dylan harness ") print(r1, r2)
833e1994cb43dc28266dce0e573162cb7fd892d3
BrendanStringer/CS021
/Assignment 03.0/BMICalc.py
819
4.5625
5
#Brendan Stringer #CS 021 #Assignment 3.1 #This program will calculate a person's BMI and determine if it is within the correct range. #Get input from the user WEIGHT = int(input('What is your weight in pounds? ')) HEIGHT = int(input('What is your height in inches? ')) #Is weight < 50 lbs if WEIGHT < 50: print('You cannot weigh < 50 lbs') #Is height < 48 inches elif HEIGHT < 48: print('You cannot be less than 48 inches tall') #Variables are valid else: #Perform BMI Calculation BMI = WEIGHT * 703.0 / (HEIGHT * HEIGHT) #Print BMI print('Your BMI is ', format(BMI, '.2f')) #Print information regarding the users BMI if BMI < 18.5: print('You are underweight') elif BMI > 25: print('You are overweight') else: print('You are the optimal weight')
5fcd3c0e284a6ef85783f640154cfe2222270733
thariqkhalid/TwitterHateSpeech
/notebooks/spell check.py
1,255
3.59375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: def edit_distance(s1, s2): m=len(s1)+1 n=len(s2)+1 tbl = {} for i in range(m): tbl[i,0]=i for j in range(n): tbl[0,j]=j for i in range(1, m): for j in range(1, n): cost = 0 if s1[i-1] == s2[j-1] else 1 tbl[i,j] = min(tbl[i, j-1]+1, tbl[i-1, j]+1, tbl[i-1, j-1]+cost) return tbl[i,j] print(edit_distance("Helloworld", "HalloWorld")) # In[14]: import sys get_ipython().system(u'{sys.executable} -m pip install textblob ') # In[16]: from textblob import TextBlob a = "cmputr" # incorrect spelling print("original text: "+str(a)) b = TextBlob(a) # prints the corrected spelling print("corrected text: "+str(b.correct())) # In[18]: import sys get_ipython().system(u'{sys.executable} -m pip install pyspellchecker ') # In[19]: from spellchecker import SpellChecker spell = SpellChecker() # find those words that may be misspelled misspelled = spell.unknown(["cmputr", "watr", "study", "wrte"]) for word in misspelled: # Get the one `most likely` answer print(spell.correction(word)) # Get a list of `likely` options print(spell.candidates(word)) # In[ ]:
e66c0a6095395928a19c56f86828db476a3ff891
chan-alex/python-explorations
/pythonic_practice/properties.py
1,856
4.0625
4
# In python, it is possible to make class method appears as if they are class attributes # this is one way: using the "property" declaration. # With this method it is important to name the actual data attribute and the getters/setters # correctly or risk infinite recurision. class Complex1: def __init__(self, real=0, img=0): self._real = real self._img = img def __str__(self): if self.img < 0: return "{} - {}j".format(self.real, abs(self.img)) else: return "{} + {}j".format(self.real, self.img) def _get_real(self): print("_get_real called") return self._real def _set_real(self, real): print("_set_real called with {}".format(real)) # By intercepting setter, we can implment checks on the argument. if not (isinstance(real, int) or isinstance(real,float)): raise Exception("Argument not numeric") self._real = real def _del_real(self): pass def _get_img(self): print("_get_img called") return self._img def _set_img(self, img): print("_set_img called with {}".format(img)) # checking argument is of right type before setting it. if not (isinstance(img, int) or isinstance(img,float)): raise Exception("Argument not numeric") self._img = img def _del_img(self): pass # to see docstring, use help(Complex1) real = property(_get_real, _set_real, _del_real, "Sets the real part") img = property(_get_img, _set_img, _del_real, "Sets the imaginary") def main(): print("Testing Complex1") i1 = Complex1(1,2) print(i1) print(i1.real) print(i1.img) i1.real = 10 i1.img = -10 print(i1)
4b661d0e0d118e01226b602987aaf7bf7988a983
Kodermatic/SN-web1
/06_HW - Python (Conditions and loops)/06_Converter.py
880
4.3125
4
# Plan: # The program greets user and describes what's the purpose of the program. # The program asks user to enter number of kilometers. # User enters the amount of kilometers. # The program converts these kilometers into miles and prints them. # The program asks user if s/he'd want to do another conversion. # If yes, repeat the above process (except the greeting). # If not, the program says goodbye and stops. print("Hi, with this program you can convert kilometers into miles.") another_conversion = "y" while another_conversion in ["y", "yes"]: number_of_km = float(input("Please input number of kilometers: ").replace(",",".")) number_of_mi = number_of_km * 0.6213712 print (f"{number_of_km} km is {number_of_mi} miles! \n \n") another_conversion = input("Do you want another conversion (y/n): ").lower() else: print("Thank you for using our program. Googbye!")
105958c2547ccba9bea40558cd6fff0314a4f753
MiguelAtencio/Tableaux
/tableaux.py
5,341
3.546875
4
#-*-coding: utf-8-*- from random import choice ############################################################################## # Variables globales ############################################################################## # Crea las letras minúsculas a-z letrasProposicionales = [chr(x) for x in range(97, 123)] # inicializa la lista de interpretaciones listaInterpsVerdaderas = [] # inicializa la lista de hojas listaHojas = [] ############################################################################## # Definición de objeto tree y funciones de árboles ############################################################################## class Tree(object): def __init__(self, label, left, right): self.left = left self.right = right self.label = label def Inorder(f): # Imprime una formula como cadena dada una formula como arbol # Input: tree, que es una formula de logica proposicional # Output: string de la formula if f.right == None: return f.label elif f.label == '-': return f.label + Inorder(f.right) else: return "(" + Inorder(f.left) + f.label + Inorder(f.right) + ")" ############################################################################## # Definición de funciones de tableaux ############################################################################## def StringtoTree(A): conect = ['O', 'Y', '>', '<'] trees = [] for x in A: if x in letrasProposicionales: trees.append(Tree(x, None, None)) elif x == '-': Aux = Tree(x, None, trees[-1]) trees.clear() trees.append(Aux) elif x in conect: Aux = Tree (x, trees[-1], trees[-2]) trees.clear() trees.append(Aux) return trees[-1] def imprime_hoja(H): cadena = "{" primero = True for f in H: if primero == True: primero = False else: cadena += ", " cadena += Inorder(f) return cadena + "}" def par_complementario(l): for i in range(0,len(l)-1): for j in range(i+1,len(l)): if l[i].label=='-': if l[j].label!='-': if l[i].right.label==l[j].label: return True else: if l[j].label=='-': if l[i].label==l[j].right.label: return True return False def es_literal(f): sim=['O','Y','>','<->'] if f.label in sim: return False else: if f.label=='-': if f.right.label in sim or f.right.label=='-': return False else: return True else: return True def no_literales(l): for i in l: if es_literal(i)==0: return i return None def classif(f): if f.label=='-': if f.right.label=='-': return '1Alpha' elif f.right.label=='O': return '3Alpha' elif f.right.label=='>': return '4Alpha' elif f.right.label=='Y': return '1Beta' elif f.label=='Y': return '2Alpha' elif f.label=='O': return '2Beta' else: return '3Beta' def clasifica_y_extiende(f): if es_literal(f)==False: for i in listaHojas: if f in i: if classif(f)=='1Alpha': i.remove(f) i.append(f.right.right) elif classif(f)=='2Alpha': i.remove(f) i.append(f.left) i.append(f.right) elif classif(f)=='3Alpha': i.remove(f) i.append(Tree('-',None,f.right.left)) i.append(Tree('-',None,f.right.right)) elif classif(f)=='4Alpha': i.remove(f) i.append(f.right.left) i.append(Tree('-',None,f.right.right)) elif classif(f)=='1Beta': i.remove(f) k=i[:] i.append(Tree('-',None,f.right.left)) k.append(Tree('-',None,f.right.right)) listaHojas.append(k) elif classif(f)=='2Beta': i.remove(f) k=i[:] i.append(f.left) k.append(f.right) listaHojas.append(k) elif classif(f)=='3Beta': i.remove(f) k=i[:] i.append(Tree('-',None,f.left)) k.append(f.right) listaHojas.append(k) def Tableaux(f): global listaHojas global listaInterpsVerdaderas A = StringtoTree(f) listaHojas = [[A]] while len(listaHojas)>0: hoja=choice(listaHojas) res=no_literales(hoja) if res==None: if par_complementario(hoja): listaHojas.remove(hoja) else: listaInterpsVerdaderas.append(hoja) listaHojas.remove(hoja) else: clasifica_y_extiende(res) return listaInterpsVerdaderas
639e410593253471dcafc79f2c012efe4fc7a0f7
BenjaminKamena/pythonadvanced
/Computation+with+NumPy/main.py
2,971
3.953125
4
import numpy as np import matplotlib.pyplot as plt from scipy import misc from PIL import Image #create new ndarray from scatch my_array = np.array([1.1, 9.2, 8.1, 4.7]) #show rows and columns my_array.shape #accessing elements by index print(my_array[2]) #show dimensions of an array my_array.ndim my_array1 = np.array([[1, 2, 3, 9], [5, 6, 7, 8]]) print(f'array_2d has {my_array1.ndim} dimensions') print(f'Its shape is {my_array1.shape}') print(f'It has {my_array1.shape[0]} rows and {my_array1.shape[1]} columns') print(my_array1) print(my_array1[1, 2]) print(my_array1[0, :]) print('Benjamin') #the aswers below mystery_array = np.array([[[0, 1, 2, 3], [4, 5, 6, 7]], [[7, 86, 6, 98], [5, 1, 0, 4]], [[5, 36, 32, 48], [97, 0, 27, 18]]]) #How many dimensions does the array below have? print(mystery_array.ndim) print(f'We have {mystery_array.ndim} dimensions') #What is its shape (i.e., how many elements are along each axis)? print(mystery_array.shape) print(f'The shape is {mystery_array.shape}') #Try to access the value 18 in the last line of code. print(mystery_array[2, 1][-1:]) #or print(mystery_array[2, 1, 3]) #Try to retrieve a 1-dimensional vector with the values [97, 0, 27, 18] print(mystery_array[2, 1]) #or print(mystery_array[2, 1, :]) #Try to retrieve a (3,2) matrix with the values [[ 0, 4], [ 7, 5], [ 5, 97]] print(mystery_array[:, :, 0]) #Use .arange()to createa a vector a with values ranging from 10 to 29 a = np.arange(10, 30) print(a) #Create an array containing only the last 3 values of a print(a[-3:]) #Reverse the order of the values in a, so that the first element comes last print(np.flip(a)) #Print out all the indices of the non-zero elements in this array: [6,0,9,0,0,5,0] b = np.array([6,0,9,0,0,5,0]) nz_indices = np.nonzero(b) print(nz_indices) #Use NumPy to generate a 3x3x3 array with random numbers x = np.random.random((3, 3, 3)) print(x) #Use .linspace() to create a vector x of size 9 with values spaced out evenly between 0 to 100 (both included y = np.linspace(start=-3, stop=3, num=9) plt.plot(x, y) plt.show() #Use NumPy to generate an array called noise with shape 128x128x3 that has random values. # Then use Matplotlib's .imshow() to display the array as an image. # The random values will be interpreted as the RGB colours for each pixel. noise = np.random.random((128, 128, 3)) print(noise.shape) plt.imshow(noise) #Let's multiply a1 with b1. Looking at the Wikipedia example above, # work out the values for c12 and c33 on paper. # Then use the .matmul() function or the @ operator to check your work a1 = np.array([[1, 3], [0, 1], [6, 2], [9, 7]]) b1 = np.array([[4, 1, 3], [5, 8, 5]]) a1_b1 = np.matmul(a1, b1) print(a1_b1) #image img = misc.face() plt.imshow(img) type(img) img.shape img.ndim
423e63dc94967c21e3b8e6f53d65557a4911ac79
kinjal2110/PythonTutorial
/37_introspection.py
749
3.71875
4
# python in everything is object # object introspection means everything know about object that which class those object is derived # and anything info. which type object. class Employee: def __init__(self, fname, lname): self.fname = fname self.lname = lname self.email = f"{fname}.{lname}@99.com" skill = Employee("skill", "F") print(skill.email) print(type(skill)) #skill object is main function of employee class. print(type("this is string")) #it tis type of string class. print(id("this is id")) #it will return id of object. print(id("hi")) o = "this is dir" print(dir(o)) #it will return all method, which can be used by us. import inspect print(inspect.getmembers(skill))
156289934213a7230f1c68a2bd37d4e6a41698f1
mtreviso/university
/Machine Learning/K-Nearest-Neighbors/knn.py
1,853
3.625
4
import numpy as np import scipy.io, math, sys, time from matplotlib import pyplot from utils import Utils from statistics import Statistics from features import Features from reader import Reader from plots import Plots from keras.datasets import cifar10 # http://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/ class KNN: """ Simple K-Nearest Neighbors """ def __init__(self, nb_cluster): self.nb_cluster = nb_cluster def find_neighbors(self, X, Z): distances = Utils.euclidian_distance(X, Z) neighbors = np.argsort(distances, axis=0) return neighbors[:self.nb_cluster] # return X[neighbors][:self.nb_cluster].flatten() def compute_response(self, X): votes = np.zeros(np.max(X)+1) for x in X: votes[x] += 1 return np.argmax(votes) def get_class(self, major, Y): return Y[major] def train(self, X, Y1, Z, Y2, verbose=True): m, n = Z.shape predictions = np.zeros(m) for i in range(m): sys.stdout.write("Iter: %6d of %d\r" % (i+1, m)) sys.stdout.flush() neighbors = self.find_neighbors(X, Z[i]) major = self.compute_response(neighbors) predictions[i] = self.get_class(major, Y1) # calculate accuracy with predictions and Y2 print("\n") if __name__ == '__main__': # x,y = Reader.read_data('dados/data.dat', False) # X = np.hstack((x,y)) # mat = {'X':X} # Reader.save_mat('dados/data.mat', mat) # mat = Reader.load_mat('dados/data.mat') # X = np.matrix(mat['X']) K = 10 knn = KNN(K) X = np.random.rand(200, 2) Z = np.random.rand(1, 2) # query neighbors = knn.find_neighbors(X, Z) pyplot.plot(X[:,0], X[:,1], 'bo') pyplot.plot(Z[:,0], Z[:,1], 'ro') N = X[neighbors] pyplot.plot(N[:,0], N[:,1], 'o', markeredgecolor='r', markerfacecolor='None', markersize=15, markeredgewidth=1) pyplot.show() # km.train(X)
af15139e7fe599db8a6360337e42f241832fea5d
sidneycadot/nexstar
/Coordinates.py
821
3.703125
4
#! /usr/bin/env python3 import math def to_dms(x): sign = (x > 0) - (x < 0) # Python lacks a sign() function. x *= sign # make sure that x is non-negative d = math.floor(x) x = (x - d) * 60.0 m = math.floor(x) x = (x - m) * 60.0 s = x d *= sign # correct sign of the result return (d, m, s) def show_coordinates(label, lat, lon): (lat_d, lat_m, lat_s) = to_dms(lat) (lon_d, lon_m, lon_s) = to_dms(lon) print("[{}] latitude: {:.9f} (dms: {:+4d}°{:02d}′{:06.3f}″) longitude: {:.9f} (dms: {:+4d}°{:02d}′{:06.3f}″)".format( label, lat, lat_d, lat_m, lat_s, lon, lon_d, lon_m, lon_s )) if __name__ == "__main__": show_coordinates("WS13", 52.010285, 4.350061) show_coordinates("BW47", 52.011310, 4.361599)
36f67efc7b52f48d2ec173d775a3fcdc93b8d500
vvspearlvvs/CodingTest
/2.프로그래머스lv1/문자열_내림차순/solution.py
153
3.671875
4
def solution(s): answer = '' tmp=sorted(list(s),reverse=True) answer = "".join(tmp) return answer print(solution("Zbcdefg")) #"gfedcbZ"
cda9333b4408b96baa766d1203afe2ec8feb9ce0
pooja13196/102
/findingWord.py
452
4.25
4
import os import shutil file_name = input('Enter you file name: ') f = open(file_name) file_lines = f.readlines() found = False search_string = input('Enter the word you want to search: ') for lines in file_lines: print(lines) words = lines.split() for word in words: if(word == search_string): found = True if(found == True): print('Word is present') else: print('Word is not present')
533b2b48101e62c5bf8f6d66f6f5b90afba1de6f
AnthonyFloyd/2015-AdventOfCode-Python
/day08.py
12,034
3.84375
4
# Day 8 # 2015-12-07 # # Matchsticks # def countCharacters(totalString, debug=False): ''' Counts characters in given string, counting the number of characters in the literal string, in memory, and if the string were to be encoded. ''' # convert the string to a list totalString = [c for c in totalString] nCharactersLiteral = len(totalString) nCharactersMemory = 0 nCharactersEncoded = 0 # loop over all the characters, popping them off as needed while len(totalString) > 0: # get first character in group c = totalString.pop(0) if c == '\\': # if it's a slash, escape it for encoding, but don't count it in memory nCharactersEncoded += 2 if debug: print("{0}: {1:d}".format(c, nCharactersEncoded)) # get the escaped character c = totalString.pop(0) if c == 'x': # If it's an 'x', then there are two more characters to follow # we need to encode the x and the text two characters # but only one real character goes into memory nCharactersEncoded += 1 if debug: print("{0}: {1:d}".format(c, nCharactersEncoded)) c = totalString.pop(0) if debug: print("{0}: {1:d}".format(c, nCharactersEncoded)) c = totalString.pop(0) if debug: print("{0}: {1:d}".format(c, nCharactersEncoded)) # add the two more for encoding and one for memory nCharactersEncoded += 2 nCharactersMemory += 1 else: # If it's not an 'x', there are two more special cases # It might be another '\' or a '"', both of which need # to be escaped again, so add 2 to encoded # If it's not, just add 1 to encoded # In both cases, memory increases by 1 if c == '\\' or c == '"': # another slash or quote, need to encode nCharactersEncoded += 2 else: # normal popped character nCharactersEncoded += 1 if debug: print("{0}: {1:d}".format(c, nCharactersEncoded)) nCharactersMemory += 1 else: # Not a leading slash # If the character isn't a '"' then it's normal and encodes as 1, # goes into memory as 1 # # But, if it is a '"' then it needs to be escaped. # Encodes as 3 (have to escape the slash and the quote), but doesn't go into # memory because it begins or ends a quoted string # if c != '"': nCharactersEncoded += 1 nCharactersMemory += 1 else: # if it is a quote, we escape it and add quote, but don't count it as in memory nCharactersEncoded += 3 if debug: print("{0}: {1:d}".format(c, nCharactersEncoded)) print("Number of characters in string literal: {0:d}".format(nCharactersLiteral)) print("Number of characters in memory: {0:d}".format(nCharactersMemory)) print("Number of characters in encoded string: {0:d}".format(nCharactersEncoded)) print("Difference between literal and memory: {0:d}".format(nCharactersLiteral - nCharactersMemory)) print("Difference between encoded and literal: {0:d}\n".format(nCharactersEncoded - nCharactersLiteral)) if __name__ == '__main__': testStrings = [r'""', r'"abc"', r'"aaa\"aaa"', r'"\x27"'] day8Strings = r""" "sjdivfriyaaqa\xd2v\"k\"mpcu\"yyu\"en" "vcqc" "zbcwgmbpijcxu\"yins\"sfxn" "yumngprx" "bbdj" "czbggabkzo\"wsnw\"voklp\"s" "acwt" "aqttwnsohbzian\"evtllfxwkog\"cunzw" "ugvsgfv" "xlnillibxg" "kexh\"pmi" "syvugow" "m\"ktqnw" "yrbajyndte\\rm" "f\"kak\x70sn\xc4kjri" "yxthr" "alvumfsjni\"kohg" "trajs\x5brom\xf1yoijaumkem\"\"tahlzs" "\"oedr\"pwdbnnrc" "qsmzhnx\"" "\"msoytqimx\\tbklqz" "mjdfcgwdshrehgs" "\"rivyxahf\"" "ciagc\x04bp" "xkfc" "xrgcripdu\x4c\xc4gszjhrvumvz\"mngbirb" "gvmae\"yiiujoqvr\"mkxmgbbut\"u" "ih" "ncrqlejehs" "mkno\x43pcfdukmemycp" "uanzoqxkpsksbvdnkji\"feamp" "axoufpnbx\\ao\x61pfj\"b" "dz\\ztawzdjy" "ihne\"enumvswypgf" "\"dgazthrphbshdo\\vuqoiy\"" "dlnmptzt\\zahwpylc\\b\"gmslrqysk" "mhxznyzcp" "rebr\"amvxw\x5fmbnfpkkeghlntavj" "lades\x47ncgdof\"\"jmbbk" "dwxuis\xa5wdkx\\z\"admgnoddpgkt\\zs" "g\\k\x27qsl\x34hwfglcdxqbeclt\xca\\" "lhyjky\\m\"pvnm\\xmynpxnlhndmahjl" "c\"uxabbgorrpprw\"xas\\vefkxioqpt" "rfrvjxpevcmma\x71gtfipo" "fgh\"kcwoqwfnjgdlzfclprg\"q" "onxnwykrba" "hkkg\x60f\"tjzsanpvarzgkfipl" "\"aintes\"ofq\"juiaqlqxmvpe\\a" "wiyczzs\"ciwk" "mfqeu" "v\xe1z\x7ftzalmvdmncfivrax\\rjwq" "k\"vtg" "exhrtdugeml\xf0" "behnchkpld" "mhgxy\"mfcrg\xc5gnp\"\"osqhj" "rlvjy" "awe" "ctwy" "vt" "\x54t" "zugfmmfomz" "cv\"cvcvfaada\x04fsuqjinbfh\xa9cq\xd2c\"d" "oj" "xazanf\"wbmcrn" "\\\\zkisyjpbzandqikqjqvee" "dpsnbzdwnxk\\v" "sj\"tuupr\\oyoh" "myvkgnw\x81q\xaaokt\\emgejbsyvxcl\\\xee" "ejeuqvunjcirdkkpt\"nlns" "twmlvwxyvfyqqzu" "\"xwtzdp\x98qkcis\"dm\\\"ep\"xyykq" "vvcq\\expok" "wgukjfanjgpdjb" "\"mjcjajnxy\\dcpc" "wdvgnecw\\ab\x44klceduzgsvu" "dqtqkukr\"iacngufbqkdpxlwjjt" "\"xj\"\x66qofsqzkoah" "nptiwwsqdep" "gsnlxql\x30mjl" "yeezwokjwrhelny\"" "bjauamn\\izpmzqqasid" "tvjdbkn\"tiziw\x82r" "w" "xwoakbbnjnypnaa\xa9wft\"slrmoqkl" "vwxtnlvaaasyruykgygrvpiopzygf\"vq" "qdancvnvmhlmpj\\isdxs" "xzc\\elw" "b\"wxeqvy\"qf\"g\xcaoklsucwicyw\"dovr" "yomlvvjdbngz\"rly\"afr" "bfb\"x\"aweuwbwmoa\x13\"t\"zhr" "\"dmfoxb\"qvpjzzhykt\xd2\"\"ryhxi" "psqef\"yu\\qiflie\"\x79w" "arzewkej\"lqmh\\sayyusxxo\\" "vuvvp" "hc\"lg\x6bcpupsewzklai\"l" "cjdfygc\"auorqybnuqghsh\x10" "j" "wqjexk\"eyq\\lbroqhk\\dqzsqk" "dws\"ru\"dvxfiwapif\"oqwzmle" "agcykg\\jt\\vzklqjvknoe" "kksd\"jmslja\\z\"y\\b\xaagpyojct" "nnpipxufvbfpoz\"jno" "dtw" "xlolvtahvgqkx\\dgnhj\\spsclpcxv\\" "mxea\\mbjpi" "lgbotkk\"zmxh\\\\qji\"jszulnjsxkqf" "lwckmhwhx\"gmftlb\x91am" "xxdxqyxth" "\"lmqhwkjxmvayxy" "tf" "qy" "wdqmwxdztax\"m\"\x09\x11xdxmfwxmtqgwvf" "\xcbnazlf\"ghziknszmsrahaf" "e\x6aupmzhxlvwympgjjpdvo\"kylfa" "\x81vhtlillb\xactgoatva" "dvnlgr" "f" "xg\xfacwizsadgeclm" "vnnrzbtw\"\\prod\\djbyppngwayy\"" "lrt\xf4jahwvfz" "aqpnjtom\"ymkak\\dadfybqrso\\fwv" "gz\"aac\"mrbk\"ktommrojraqh" "wycamwoecsftepfnlcdkm" "nrhddblbuzlqsl\x9cben" "vckxhyqkmqmdseazcykrbysm" "sil\xbbtevmt\"gvrvybui\"faw\"j" "cjex\\tp\x45pzf" "asjobvtxszfodgf\"ibftg" "gkyjyjdrxdcllnh\"sjcibenrdnxv" "oswsdpjyxpbwnqbcpl\"yrdvs\\zq" "\"\"tyowzc\\fycbp\"jbwrbvgui" "cbpcabqkdgzmpgcwjtrchxp" "iyrzfh\x45gw\"fdlfpiaap\x31xqq" "evgksznidz" "b\\w\\" "loufizbiy\x57aim\"bgk" "qjfyk" "g\"anmloghvgr\x07zwqougqhdz" "usbbmwcxd\\bdgg" "htitqcpczml" "eke\\cqvpexqqk\"to\"tqmljrpn\xe6lji\"" "g\xd2ifdsej" "h\"sk\"haajajpagtcqnzrfqn\xe6btzo" "wfkuffdxlvm\\cvlyzlbyunclhmpp" "myaavh\"spue" "hqvez\x68d\"eo\"eaioh" "s\"qd\"oyxxcglcdnuhk" "ilqvar" "srh" "puuifxrfmpc\"bvalwi\x2blu\\" "yywlbutufzysbncw\\nqsfbhpz\"mngjq" "zbl\\jfcuop" "hjdouiragzvxsqkreup\\" "qi" "ckx\\funlj\xa7ahi" "k" "ufrcnh\"ajteit" "cqv\"bgjozjj\x60x\xa8yhvmdvutchjotyuz" "hkuiet\"oku\x8cfhumfpasl" "\"\\sbe\x4d" "vhknazqt" "eyyizvzcahgflvmoowvs\\jhvygci" "kki\x3ewcefkgtjap\"xtpxh\"lzepoqj" "wvtk" "\"ynet" "zh\\obk\"otagx\x59txfzf" "ocowhxlx\xe6zqg\x63wx\\tclkhq\\vmaze" "w\"cf" "qpniprnrzrnvykghqnalr" "jctcqra\"\x05dhlydpqamorqjsijt\\xjdgt" "sig" "qhlbidbflwxe\"xljbwls\x20vht" "irmrebfla\xefsg\"j" "nep" "hjuvsqlizeqobepf" "guzbcdp\"obyh" "\"mjagins\xf9tqykaxy\"" "knvsdnmtr\"zervsb" "hzuy" "zza\"k\"buapb\\elm\xfeya" "lrqar\"dfqwkaaqifig\"uixjsz" "\"azuo\x40rmnlhhluwsbbdb\x32pk\\yu\"pbcf" "dplkdyty" "rfoyciebwlwphcycmguc" "ivnmmiemhgytmlprq\\eh" "lhkyzaaothfdhmbpsqd\\yyw" "tnlzifupcjcaj" "\\qiyirsdrfpmu\\\x15xusifaag" "\\lcomf\\s" "uramjivcirjhqcqcg" "kkbaklbxfxikffnuhtu\xc6t\"d" "n\xefai" "\"toy\"bnbpevuzoc\"muywq\"gz\"grbm" "\"muu\\wt" "\\srby\"ee" "erf\"gvw\"swfppf" "pbqcgtn\"iuianhcdazfvmidn\\nslhxdf" "uxbp" "up\\mgrcyaegiwmjufn" "nulscgcewj\\dvoyvhetdegzhs\"" "masv\"k\\rzrb" "qtx\x79d\"xdxmbxrvhj" "fid\\otpkgjlh\"qgsvexrckqtn\xf4" "tagzu" "bvl\\\"noseec" "\\xgicuuh" "w\"a\"npemf" "sxp" "nsmpktic\x8awxftscdcvijjobnq\"gjd" "uks\"\"jxvyvfezz\"aynxoev\"cuoav" "m" "lkvokj" "vkfam\"yllr\"q\x92o\x4ebecnvhshhqe\\" "efdxcjkjverw" "lmqzadwhfdgmep\x02tzfcbgrbfekhat" "cpbk\x9azqegbpluczssouop\x36ztpuoxsw" "cqwoczxdd\"erdjka" "cwvqnjgbw\\fxdlby" "mvtm" "lt\"bbqzpumplkg" "ntd\xeeuwweucnuuslqfzfq" "y\xabl\"dbebxjrlbmuoo\\\x1au" "qjoqx\\a" "pu\"ekdnfpmly\xbago\"" "fjhhdy" "arl" "xcywisim\"bwuwf\"\"raepeawwjub" "pbe" "dbnqfpzyaumxtqnd\xc5dcqrkwyop" "ojv\x40vtkwgkqepm\x8bzft\\vedrry" "wggqkfbwqumsgajqwphjec\"mstxpwz" "zjkbem" "icpfqxbelxazlls" "pvpqs\\abcmtyielugfgcv\"tjxapxqxnx" "oqddwlvmtv\"\x39lyybylfb\"jmngnpjrdw" "gisgbve" "\"aglg" "y\"\"ss\xafvhxlrjv" "qbgqjsra" "ihshbjgqpdcljpmdwdprwloy" "djja\\wcdn\"svkrgpqn\"uz\"hc\x43hj" "cbjm" "pnn" "pqvh\"noh" "\"\\fdktlp" "ncea" "pqgzphiyy" "\xbedovhxuipaohlcvkwtxwmpz\"ckaif\"r" "arjuzbjowqciunfwgxtph\"vlhy\"n" "c" "nrpdxunulgudqzlhtae" "iefheu\"uru\"" "aqijysxuijud\"np\\opbichhudil\xbesum" "pfpevmtstl\"lde\"bzr\"vspdxs" "vparfbdjwvzsocpnzhp" "g\x4ffxaarafrsjthq\\\xc1rw" "ng\\rqx\\gwpzucbh\xafl" "rw\"nf\\dna" "jkkeahxurxla\\g\xb3czrlsyimmwcwthr" "twaailoypu\"oas\"kpuuyedlaw\\\xb0vzt" "hznex\\gdiqvtugi" "imdibsunjeswhk" "ta\\icileuzpxro\"cfmv\"mzp" "coykr\x57luiysucfaflmilhlehmvzeiepo" "u\x3dfh\xd4yt" "piw\x1bz\"eowy\"vfk\"wqiekw" "gan\"y" "p\"bevidoazcznr\"hddxuuq\"" "bwzucczznutbxe" "z\"viqgyqjisior\\iecosmjbknol" "dmlpcglcfkfsctxydjvayhymv\x3c\\gp" "bfvkqrintbbvgfv" "xlzntrgdck\"cprc\xadczyarbznqmuhxyuh" "uqdxnuwioc\"kdytxq\\ig" "xrafmucpmfi" "vr\"hltmfrge" "eonf\"nt\\wtcnsocs" "j\xb7xoslyjeyjksplkqixncgkylkw" "njw\"pefgfbez\x9axshdmplxzquqe" "di\x58bvptfsafirpc" "l\x1fkco" "x" "mprndo\"n" "psegit" "svbdnkkuuqs\"sqxu\"oqcyz\"aizashk" "cwkljukxer\\\"\\nff\"esjwiyaoy" "ilxrkgbjjxpvhdtq\"cpiuoofdnkpp" "hlngi\"ulxep\\qohtmqnqjb\"rkgerho" "gxws\"bcgm\"p" "bv\"mds\\zhfusiepgrz\\b\x32fscdzz" "l\xfampwtme\x69qvxnx\"\"\xc4jruuymjxrpsv" "qqmxhrn" "xziq\\\x18ybyv\x9am\"neacoqjzytertisysza" "aqcbvlvcrzceeyx\\j\"\"x" "yjuhhb" "\x5em\"squulpy" "dpbntplgmwb" "utsgfkm\\vbftjknlktpthoeo" "ccxjgiocmuhf\"ycnh" "lltj\"kbbxi" """ # # Using test strings # totalTestString = "" for testString in testStrings: testString = "".join(testString.split()) totalTestString += testString countCharacters(totalTestString) # # Using day 8 inputs # totalString = "".join(day8Strings.split()) countCharacters(totalString)
c1d5f5e5998d51d9b7806dda45ac3c59692dd9dd
patterson-dtaylor/python_work
/Chapter_6/favorite_number.py
444
4.34375
4
# 10/6/19 Exercise 6-2: Using a dictionary to poll people's fav number. favorite_numbers = { 'carrie': ['12', '4'], 'scout': ['11', '21'], 'emaline': ['3', '12'], 'taylor': ['33', '11'], 'nikki': ['69', '99'], } # 10/7/19 Exercise 6-10: Using a list in a dictionary. for name, numbers in favorite_numbers.items(): print(f"\n{name.title()}'s favorite numbers are:") for number in numbers: print(f"{number}")
90d91ed5fa7c45c509f5635ba7d85a2f066dcfe1
daniel-reich/ubiquitous-fiesta
/KcnQtNoX5uC6PzpEF_6.py
335
3.640625
4
import itertools from itertools import combinations ​ def check_sum(lst, n): ​ Duets = list(combinations(lst,2)) Counter = 0 Length = len(Duets) while (Counter < Length): Pair = Duets[Counter] Total = sum(Pair) if (Total == n): return True else: Counter += 1 return False
941c9f44f14d8db9ca0ecc334b9a516eb5544c29
SanjithMohanan/Game
/Puzzle.py
10,150
4.28125
4
#I ran this code using Python 3.6 in PyCharm #How to run the code # Compile the code # Run the code # Give initial state and goal state respectively as input # examaple: """ Enter the initial state :: 1,0,3,8,2,4,7,6,5 Enter the goal state :: 1,2,3,8,0,4,7,6,5 <built-in function input> Input state :: 1 0 3 8 2 4 7 6 5 Goal state :: 1 2 3 8 0 4 7 6 5 The solution can be found in 1 move(s) Step 1 :: Move 2 from ( 2 , 2 ) to ( 1 , 2 ) 1 2 3 8 0 4 7 6 5 """ #About assign1.py # It contains two classes, Strips and Utility and a main method. The execution starts from the main method. from builtins import print #Utility class that holds methods for doing many functions required for this assignment. class Utility: #This function reads input from the user def read_input_from_user(self): initial_state = input("Enter the initial state :: ") goal_state = input("Enter the goal state :: ") return initial_state,goal_state #The input read is in string format. So this method will convert it in to numbers def split_and_convert_to_integer(self, user_input): converted_input = [int(x) for x in user_input.split(",")] return converted_input #This function will create all possible moves possible in a 3*3 puzzle def getAllPossibleMoves(self): all_moves = [] for value in range(1, 9): for i in range(1, 4): for j in range(1, 4): if (i == 1 or i == 2): all_moves.append((value, i, j, i+1, j)) #all_moves.append((value, i+1, j, i , j)) if (i == 2 or i == 3): all_moves.append((value, i, j, i-1 , j)) # all_moves.append((value, i-1, j, i, j)) if (j == 2 or j == 3): all_moves.append((value, i, j, i, j-1 )) # all_moves.append((value, i, j-1, i , j)) if (j == 1 or j == 2): all_moves.append((value, i, j, i, j+1)) # all_moves.append((value, i, j+1, i, j)) # print(all_moves) return all_moves #Creates precondition required to move a tile def createMoveOperator(self, all_moves): precondition_action_remove = {} for entry in all_moves: precondition_action_remove[entry] = { "precondition": set([(entry[0], entry[1], entry[2]), (0, entry[3], entry[4])]) } #print(precondition_action_remove) return precondition_action_remove #Test method- for testing purpose def getGoalState(self): return set( [(1, 1, 1), (2, 1, 2), (3, 1, 3), (4, 2, 1), (5, 2, 2), (6, 2, 3), (7, 3, 1), (8, 3, 2), (0, 3, 3) ]) #Defines position for all values from the input def define_position_for_input(self, input): index = 0 input_positions = set() for i in range(1, 4): for j in range(1, 4): input_positions.add((input[index], i, j)) index += 1 # incrementing the position from the inout list return input_positions #Returns position of 0 from the puzzle def get_position_of_0(self, anystate): for entry in anystate: if entry[0] == 0: return (entry[1], entry[2]) #Returns the value at the position i,j def get_valueat_indexes(self, anystate, i, j): for entry in anystate: if (entry[1] == i and entry[2] == j): return entry[0] #Returns all possible moves in the puzzle realtive to the position of tile with value 0. def get_possible_moves(self, anystate): actions = set() utility = Utility() i, j = utility.get_position_of_0(anystate) if (i == 1 or i == 2): #checking whether tile can be moved towards right value = utility.get_valueat_indexes(anystate, i + 1, j) actions.add((value, i, j, i+1 , j)) #? if (i == 2 or i == 3): #checking whether tile can be moved towards left value = utility.get_valueat_indexes(anystate, i - 1, j) actions.add((value, i, j, i-1, j)) if (j == 2 or j == 3): value = utility.get_valueat_indexes(anystate, i, j - 1) actions.add((value, i, j, i, j-1))#checking whether tile can be moved towards down if (j == 1 or j == 2): value = utility.get_valueat_indexes(anystate, i, j + 1)#checking whether tile can be moved towards up actions.add((value, i, j, i, j+1 )) return actions #Displays the output def display_output(self, output_steps,output_states): utility = Utility() print("The solution can be found in ", len(output_steps), "move(s)") step = 1 for eachEntry in output_steps: print("Step ", step, " :: Move ", eachEntry[0], " from (", eachEntry[1], ",", eachEntry[2], ") to (", eachEntry[3], ",", eachEntry[4], ")") utility.display(output_states[step - 1]) step += 1 #Displays the given state def display(self,state): for i in range(1, 4): nextLine = 0 for j in range(1, 4): for eachState in state: if eachState[1] == i and eachState[2] == j: nextLine += 1 print(eachState[0], " ", end='') if (nextLine == 3): print(" ") #Class that executes STRIPS algorithm class Strips: utility = Utility() #constructor of Strips class def __init__(self, input_state,goal_state): self.all_moves = utility.getAllPossibleMoves() # computing all possible moves self.predicate_action_removes = utility.createMoveOperator( self.all_moves) # defining predicate,action and remove self.goal_state = goal_state self.initial_state = input_state #Identifying the best moves given all the possible moves def get_best_move(self, possible_moves_from_goal_state): max = 0 indexes = [] position_of_move = 0 for eachMove in possible_moves_from_goal_state: predicate = self.predicate_action_removes[eachMove]["precondition"] #getting the precondition for the move number_of_equal_predicate = len(predicate.intersection(self.initial_state)) #number of common predicates if (number_of_equal_predicate >= max): if (number_of_equal_predicate > max): indexes = [] max = number_of_equal_predicate indexes.append(position_of_move) #storing the index of the move from the possible_moves_from_goal_state position_of_move += 1 # if more than one move, fetch the first value.Heuristic to choose the best possible move towards initial stae can be given here return list(possible_moves_from_goal_state)[indexes[0]] # casting set to list and fetching the first entry #Returns the precondition def get_predicate_for_move(self, move): return self.predicate_action_removes[move]["precondition"] #Updates the goal state based on the given move def get_updated_state(self, required_move): utility = Utility() new_state = self.goal_state.copy() for eachValue in self.goal_state: if ((eachValue[1] == required_move[1] and eachValue[2] == required_move[2]) or ( eachValue[1] == required_move[3] and eachValue[2] == required_move[4])): new_state.remove(eachValue) predicates = self.get_predicate_for_move(required_move) for predicate in predicates: new_state.add(predicate) # new_state.add((required_move[0],required_move[1],required_move[2])) #new_state.add((0, required_move[3], required_move[4])) return new_state #This is the main strips implementation def execute_strips(self): required_move_list = [] self.output_state = [] while (len(self.goal_state.intersection(self.initial_state)) < 9): possible_moves_from_goal_state = utility.get_possible_moves(self.goal_state) #Fetching all possible moves required_move = self.get_best_move(possible_moves_from_goal_state) #Selecting the best possible move # print("best moves ", required_move) required_move_list.append(required_move) # predicate = self.get_predicate_for_move(required_move) self.output_state.append(self.goal_state.copy()) self.goal_state = self.get_updated_state(required_move) if (len(required_move_list) > 10): print("Sorry, the number of steps needed to reach the solution is more than 10 !!!") print("Terminating program....") exit(0) required_move_list.reverse() self.output_state.reverse() return required_move_list,self.output_state if __name__ == "__main__": utility = Utility() initial_state,goal_state = utility.read_input_from_user() # reading input from user through console as string initial = utility.split_and_convert_to_integer(initial_state) # extracting only the numbers and creating the list of input goal = utility.split_and_convert_to_integer(goal_state) print(input) # Printing the input state input_state = utility.define_position_for_input(initial) # defining the position fo each input value goal_state = utility.define_position_for_input(goal) # defining the position fo each goal state value print("Input state :: ") utility.display(input_state) #displaying input state print("Goal state :: ") utility.display(goal_state) #displaying goal state strips_instance = Strips(input_state,goal_state) # instantiating Strips instance output_steps,output_states = strips_instance.execute_strips() #executing STRIPS algorithm utility.display_output(output_steps,output_states) #displaying output
d153a3d97cbe94a091a73ced8ac641390a1339d9
Anshuman-Chiranjib/heads-or-tails
/BM .PY
457
4.125
4
from random import randint num = input('Number of times to flip coin: ') num = int(num) flips = [randint(0,1) for r in range(num)] results = [] for object in flips: if object == 0: results.append('Heads') elif object == 1: results.append('Tails') print (results) # IT WILL GIVE THE RESULT ACCORDING TO YOUR NUMBER GIVEN # SO IF I WRITE 2 AND PRESS ENTER IT WILL FLIP THE COIN TWO TIMES AND IVE TWO RESULTS
bf4b4ea77822c54bece715de3f1ad3974d0fba97
mattheww22/COOP2018
/Chapter07/U07_Ex11_LeapYr.py
1,358
4.28125
4
""" U07_Ex11_LeapYr.py Author: Matthew Wiggans Course: Coding for OOP Section: A2 Date: 2019-02-21 IDE: PyCharm Assignment Info Exercise: 11 Source: Python Programming Chapter: 07 Program Description This problem computes whether the year entered was a leap year. Algorithm Print intro Ask user for year they want to check Send to function Check if year is leap return leap Check if year is leap century return leap Anything else is not leap print results """ def main(): print("This program computes if a given year is a leap year of not.") year = int(input("What year do you want to check? ")) value = checkYr(year) if value == 1: print("{0} was a leap year.".format(year)) if value == 2: print("{0} was not a leap year".format(year)) def checkYr(year): if year % 4 == 0: if year % 400 == 0: value = 2 else: value = 1 else: value = 2 return value if __name__ == '__main__': main() """ RESULTS: ======== checkYr(1600) --> 2 | 2 | [ Pass ] checkYr(1800) --> 1 | 1 | [ Pass ] checkYr(2000) --> 2 | 2 | [ Pass ] checkYr(2300) --> 1 | 1 | [ Pass ] checkYr(1959) --> 2 | 2 | [ Pass ] checkYr(1928) --> 1 | 1 | [ Pass ] ======== """
e7fe8ffa16f0c95d77d5949aa4b352a1646dfb3b
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/trappingRainWater.py
1,647
4.03125
4
""" Trapping Rain Water Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! Example: Input: [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 """ """ DP Time and Space: O(N) Find maximum height of bar from the left end upto an index i in the array left_max. Find maximum height of bar from the right end upto an index i in the array right_max. Iterate over the \text{height}height array and update ans: Add min(max_left[i],max_right[i])−height[i] to ans """ class Solution: def trap(self, height: List[int]) -> int: arr = [] left, right = 0, 0 water = 0 for h in height: left = max(left, h) arr.append(left) for idx, h in enumerate(reversed(height)): right = max(right, h) water += min(arr[len(height)-1-idx], right) - h return water class Solution: def trap(self, height: List[int]) -> int: res = 0 arrLeft = [] currLeft = 0 for i in range(1, len(height)): currLeft = max(currLeft, height[i-1]) arrLeft.append(currLeft) currRight = 0 for i in range(len(height)-2, -1, -1): currRight = max(currRight, height[i+1]) res += max(min(arrLeft[i], currRight) - height[i], 0) return res
67c16be359e48c150b89f3bcb315b9af69794996
levinyi/scripts
/python_tricks/pytricks_dict_if.py
812
4.21875
4
# Because python has first-class functions they can # be used to emulate switch/case statement. def dispatch_if(operator, x, y): """docstring for dispatch_if""" if operator == 'add': return x + y elif operator == 'sub': return x - y elif operator == 'mul': return x * y elif operator == 'div': return x / y else: return None def dispatch_dict(operator, x, y): """docstring for dispatch_dict""" return { 'add' : lambda: x + y, 'sub' : lambda: x - y, 'mul' : lambda: x * y, 'div' : lambda: x / y, }.get(operator, lambda:None)() print(dispatch_if('mul', 2, 8)) print(dispatch_dict('mul',2, 8)) print(dispatch_if('unknow', 2, 8)) print(dispatch_dict('unknow', 2, 8))
807d1766069218f99b86e2555db266df3c5fcde9
marcosfsoares/INTRO-COMPUTER-SCIENCE-WITH-PYTHON
/63_maiusculas_frase.py
320
4
4
def maiusculas(frase): ''' Recebe uma frase como parâmetro e devolve uma string com letras maiúsculas que existem na frase, na ordem em que elas aparecem''' retorno = "" for caracter in frase: if ord("A")<= ord(caracter)<= ord("Z"): retorno += caracter return retorno
88fd9b3255161daccb913dc25f44d07e3d811e99
lucasgarciabertaina/hackerrank-python3
/set/mutations.py
737
3.640625
4
# https://www.hackerrank.com/challenges/py-set-mutations/problem?h_r=next-challenge&h_v=zen def setOperation(a_list, n_list, operation): if operation == 'update': a_list.update(n_list) elif operation == 'intersection_update': a_list.intersection_update(n_list) elif operation == 'difference_update': a_list.difference_update(n_list) elif operation == 'symmetric_difference_update': a_list.symmetric_difference_update(n_list) return a a_elmts = int(input()) a = set(input().split()) for _ in range(int(input())): setMutation, lengh = input().split() n = set(input().split()) a = setOperation(a, n, setMutation) total = 0 for i in [*a, ]: total += int(i) print(total)
86f1a4590815515cbe2f2ffdf4d43e6072c2dab2
SlavXX/w3Python
/04.numbers.py
1,915
4.5625
5
#Python Numbers """ There are three numeric types in Python: """ int float complex """ Variables of numeric types are created when you assign a value to them: """ #Example x = 1 # int y = 2.8 # float z = 1j # complex """ To verify the type of any object in Python, use the type() function: """ #Example print(type(x)) print(type(y)) print(type(z)) """ Int Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. """ #Example #Integers: x = 1 y = 35656222554887711 z = -3255522 print(type(x)) print(type(y)) print(type(z)) """ Float Float, or "floating point number" is a number, positive or negative, containing one or more decimals. """ #Example #Floats: x = 1.10 y = 1.0 z = -35.59 print(type(x)) print(type(y)) print(type(z)) """ Float can also be scientific numbers with an "e" to indicate the power of 10. """ #Example #Floats: x = 35e3 y = 12E4 z = -87.7e100 print(type(x)) print(type(y)) print(type(z)) """ Complex Complex numbers are written with a "j" as the imaginary part: """ #Example #Complex: x = 3+5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z)) """ Type Conversion You can convert from one type to another with the int(), float(), and complex() methods: """ #Example #Convert from one type to another: x = 1 # int y = 2.8 # float z = 1j # complex #convert from int to float: a = float(x) #convert from float to int: b = int(y) #convert from int to complex: c = complex(x) print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c)) #Note: You cannot convert complex numbers into another number type. """ Random Number Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers: """ #Example #Import the random module, and display a random number between 1 and 9: import random print(random.randrange(1, 10))
8278fc8d96206bc8bb48545d1c1045a230868fb0
ZeeshanSameed/1stWeek
/python/word_search.py
271
3.90625
4
from PyDictionary import PyDictionary search = input("Enter a word:") try: myDict = PyDictionary(search) print("Meanng") meaning = myDict.getMeanings() print("Synonym") print(myDict.getSynonyms()) except: print("Not a legal word")
1b47d1690294b5a96f60b4a2540ff898c7e7932f
tiaotiao/leetcode
/218-the-skyline-problem.py
4,294
3.640625
4
import heapq class PriorityQueue: def __init__(self): self._queue = [] self._index class Solution: def getSkyline(self, buildings): pass lines = [] #List[(pos, height, id, isStart)] for i in range(len(buildings)): left, right, height = buildings[i] lines.append((left, height, i, True)) lines.append((right, height, i, False)) lines.sort(key=lambda l:l[0]) skylines = [] platform = 0 platform_id = None heap = [] deleted = set() for line in lines: pos, height, line_id, start = line if not start: if platform_id == line_id: # TODO remove # remove marked buildings pass else: deleted.add(line_id) # mark as deleted pass continue # TODO heap.insert(height) if height <= platform: continue platform = height platform_id = line_id skylines.append((pos, platform)) # ----------------------------------------------- def _wrong_answer(self, buildings): """ :type buildings: List[List[int]] :rtype: List[List[int]] """ lines = [] # List[(pos, low, high)] buildings.sort(key=lambda b: b[1]) for b in buildings: left, right, height = b self.insert(lines, left, right, height) return self.to_answer(lines) def to_answer(self, lines): platform = 0 results = [] for line in lines: x, l, h = line if l < 0 or h < 0: continue platform = self.next_platform(platform, l, h) results.append((x, platform)) return results def insert(self, lines, left, right, height): idx = 0 low = 0 high = height visible = True current_platform = 0 overlap_left = False overlap_right = False delete_idx = [] if len(lines) > 0 and lines[-1][0] == right: overlap_right = True if lines[-1][2] >= height: visible = False # modify for i in range(len(lines) - 1, -1, -1): x, l, h = lines[i] if x < left: # print("insert idx: ", i + 1, x, left) idx = i + 1 break if l < 0 or h < 0: continue current_platform = self.next_platform(current_platform, l, h) if h <= height: # above a building lines[i] = (x, -1, -1) # mark the building to be deleted delete_idx.append(i) low = current_platform visible = True # go visible continue if height <= l: # below a building low = -1 visible = False # go invisible continue # l < height < h # cross a building if visible or x > left: lines[i] = (x, height, h) # cut off the line visible = not visible # change inviaible if visible: low = current_platform if x == left: overlap_left = True # delete lines for i in delete_idx: del lines[i] # insert if not visible: return lines.insert(idx, (left, low, high)) # print("insert -------------------", idx, ":", left, ",", low, high) # print(lines) def next_platform(self, curr, low, high): if curr == low: return high if curr == high: return low return None # exception def main(): s = Solution() buildings = [ [2, 9, 10], [3, 7, 15], [5, 12, 12], [15, 20, 10], [19, 24, 8] ] # buildings = [ [2, 12, 10], [3, 7, 15], [3, 12, 12], [15, 20, 10], [15, 24, 8] ] # buildings = [[2,4,7],[2,4,5],[2,4,6]] print(s.getSkyline(buildings)) if __name__ == '__main__': main()
9d3981bd48dfed8402146c156b65c526b37e8284
olamug/kurs_python
/06_lesson(28_10)/06_credit_cards/06_cards.py
1,889
3.84375
4
def is_visa(is_card, number): if not is_card: # wcześniej if is_card == False: return False if len(number) == 16 or len(number) == 13: if number[0] == '4': return True def is_mastercard(is_card, number): if not is_card: return False if is_card and len(number) == 16: if int(number[0:2]) in range(51, 56) or int(number[0:4]) in range(2221, 2721): return True def is_american_express(is_card, number): if not is_card: return False if is_card and len(number) == 15: if int(number[0:2]) in (34, 37): # nie trzeba int bo porównujemy 2 stringi, 34 i 37 są w krotce czyli jest to niezmienne co jest w anwiazise return True filename = 'all_cards.txt' with open(filename, 'r') as f: cards = f.readlines() card_numbers = [] for card_number in cards: card_number = card_numbers.append(card_number.strip()) # card_number = (input("Podaj numer karty: ")) can_be_card_number = False for card_number in card_numbers: if len(card_number) < 13 or len(card_number) > 16: print("Wrong number") else: if card_number.isdecimal(): print("Can be card number") can_be_card_number = True else: print("Not a number") for card_number in card_numbers: if is_visa(can_be_card_number, card_number): print("I'm Visa") with open('visa.txt', 'a') as v: v.write(card_number+'\n') elif is_mastercard(can_be_card_number, card_number): print("I'm MasterCard") with open('mastercard.txt', 'a') as m: m.write(card_number+'\n') elif is_american_express(can_be_card_number, card_number): print("I'm American Express") with open('americanexpress.txt', 'a') as a: a.write(card_number+'\n') else: print("Not known card type.")
f085dd0f0b9a3fad3f58c11f642306b5f20af8fa
Frendy222/Assignment-vero-
/Assignment 1 driving simulator.py
611
3.734375
4
t = int(input('Time spend on road :'))+1 a = int(input('Acceleration :')) d = int(input('Distance :')) speedlimit = 60 iv = 0 v = 0 s = 0 for i in range (t) : v = iv*a s = a/2*iv*iv star=s/10 print('Duration:',i,'Distance:','*'*int(star)) iv+=1 if (v>speedlimit): print('\nThis person went over the speed limit( Max speed :',v,' )') else : print('\nThis person does not went over the speed limit( Max speed :',v,' )') if (s>d): print('This person reach the destination( Max distance :',s,' )') else: print('This peron does not reach the destination( Max distance :',s,' )')
d611898493757cbd4bf0028414fc77e64e681ecc
Ryrden/Projetos-em-Python
/Algoritmo-RSA/Bloco-Decodificado-Em-Texto.py
867
3.546875
4
import os bloco = [] texto = [] frase = [] bloco.append(int(input("Digite o primeiro bloco codificado: "))) while bloco[-1] != 0: os.system("cls") print("Caso não queira Digitar mais nenhum bloco, digite 0\n") print("Blocos Digitados até o momento: -> ", end="") for x in range(len(bloco)): print(bloco[x], end=" ") bloco.append( int(input("\n\nDigite o próximo bloco codificado: "))) del bloco[-1] for x in range(len(bloco)): texto.append(str(bloco[x])) texto = str(''.join(texto)) for x in range(0, len(texto), 2): temp = [] temp.append(texto[x]) try: temp.append(texto[x+1]) except: None temp = int(''.join(temp)) if (temp+55) == '99': frase.append(" ") else: frase.append(chr(temp+55)) for x in range(len(frase)): print(frase[x], end=' ')
5ef1a0c929c931daa68a94b2b5b6c88b2a19f63e
viz06/python_codes
/rearrange_set2.py
675
3.53125
4
def rearrange(arr,n): min_index=0 max_index=n-1 max_elm=arr[n-1]+1 for i in range(0,n): if(i%2==0): arr[i]+=(arr[max_index]%max_elm)*max_elm max_index-=1 else: arr[i]+=(arr[min_index]%max_elm)*max_elm min_index+=1 for i in range(0,n): a[i]=a[i]/max_elm def print_array(arr,n): for i in range(n): print(arr[i],end=" ") print() t=int(input("Enter no of test cases: ")) while(t>0): n=int(input("Enter no of elements in array: ")) arr=[int(x) for x in input("Enter array: ").strip().split()] rearrange(arr,n) print_array(arr,n)
dd40c1e1f65d3f32fc092f43632052074b96806c
tyler-patton44/CodingDojo-Sept-Dec-2018
/Python/python_fundamentals/intermediate1.py
166
3.515625
4
import random def radInt(min=50, max=100): x = random.random()*max while x < min: x = random.random()*max x = int(x) print(x) radInt(50,500)
572960476db9cb5ef790c0db6b57eaa43e731c08
cyrsis/TensorflowPY36CPU
/_1_PythonBasic/_5_FunctionalApproach/Calculator.py
615
4.28125
4
OPERATORS = "+", "-", "*", "/" def f_calculate(number1, operator, number2): return number1 + number2 if operator == "+" \ else number1 - number2 if operator == "-" \ else number1 * number2 if operator == "*" \ else number1 / number2 if operator == "/" \ else None def f_get_number(): return int(input("Enter an integer : ")) def f_get_operator(): return input("Enter an Operator :") def f_main(): return f_calculate( f_get_number(), f_get_operator(), f_get_number(), ) if __name__ == '__main__': print("The result is %s " % f_main())
bf43167f2a4c3b759d0c4e801f8c7ae7875fa6b4
bobmayuze/RPI_Education_Material
/CSCI_1100/Week_7/HW_4/hw4Files/hw4Part1.py
1,352
3.96875
4
# Author: Yuze Bob Ma # Date: Oct, 7th, 2016 # This code is written for RPI_CSCI_1100 HW4 Part 1 # Import modules import sys # define functions def is_alternating(word): word_test = word.lower() length = len(word) word_l = list(word_test) vowels = ['a', 'e', 'i', 'o', 'u'] # test the length if length < 8: print('The word \'{}\' is not alternating'.format(word)) sys.exit() # test if the word starts with an vowel if word_l[0] not in vowels: print('The word \'{}\' is not alternating'.format(word)) sys.exit() # test if has alternating consonants and vowels i = 0 for charater in range(length-1): if word_l[i] not in vowels: print('The word \'{}\' is not alternating'.format(word)) sys.exit() i += 1 if word_l[i] in vowels: print('The word \'{}\' is not alternating'.format(word)) sys.exit() i += 1 if length % 2 == 0: if i > length-1: break else: if i > length-2: break # test if the consonants are increasing i = 1 for charater in range(length-1): if not word_l[i] < word_l[i+2]: print('The word \'{}\' is not alternating'.format(word)) sys.exit() i += 2 if length % 2 == 0: if i > length-2: break else: if i > length-4: break print('The word \'{}\' is alternating'.format(word)) # main code word = input('Enter a word => ') print(word) is_alternating(word)
4c6d30440bbab9d597de4045aa9ea52425f1ebd0
akankaku1998/Turtle-Random-Walk
/main.py
578
3.609375
4
import turtle as t import random tim = t.Turtle() # colours = ["CornflowerBlue", "DarkOrchid", "IndianRed", "DeepSkyBlue", "LightSeaGreen", "wheat", "SlateGray", "SeaGreen"] t.colormode(255) def random_color(): r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) return tim.pencolor(r, g, b) direction = [0, 90, 180, 270] tim.pensize(15) tim.speed("fastest") for x in range(200): # tim.color(random.choice(colours)) random_color() tim.forward(30) tim.setheading(random.choice(direction)) screen = t.Screen() screen.exitonclick()
b71416d8a6e0362822fa33a7b9c9ac40e4a9e27a
liushuangfromwh/python
/py5/chapter4/py5.4.6_operator.py
523
3.8125
4
# 运算符 # == # is 比较地址值(比较同一性) x = y = [1, 2, 3] z = [1, 2, 3] print(x == y) # True print(x == z) # True print(x is z) # False # in # 字符串和序列比较 : 字符串可以按照字母顺序排列进行比较 print('alpha' < 'beta') # True # and 类似于 java&& 已结包含了短路. number = 11 # if number > 10 and number < 20: if 10 < number < 20: print(number) # 断言 assert age = 10 assert 0 < age < 100 age = -1 # assert 0 < age < 100 # assert 0 < age < 100 AssertionError
6784ebdad8e3275931b7b1c62601e90eea0a2a69
Valery-Bolshakov/learning
/theory/lesson_26.py
3,852
3.578125
4
print('Пользовательские функции. Часть 1\n') ''' Последовательность инструкций, возвращающая некое значение. В функцию могут быть переданы ноль и более аргументов, которые могут использоваться в теле функции. Для возврата значения из функции используется инструкция return. Допускается использование нескольких return, в том числе для раннего выхода из функции. Внутри функций можно определять еще функции. Функции можно передавать в качества аргумента в другой функции Внимание Функции без инструкции return (равно как и с нею, но без указания аргумента) всё равно возвращают результат — None. ''' def hello(name, word): print(f'Hello, {name}! Say {word}') hello('Yiou', 'Hi') # Hello, Yiou! Say Hi hello('Xian', 'hello\n') # Hello, Xian! Say hello def get_sum(a, b): print(a + b) get_sum(1, 4) # 5 # То что мы указываем в качестве аргументов(a, b) НИКАК не связано с тем KAK мы вызываем функцию (x, y) x, y, = 5, 8 get_sum(x, y) # 13 ''' return: Хорошей практикой является не печатать результат в функции(print), а взвращать его(return) return нужен для того что бы получить и сохранить какой-то результат для дальнейшего использования. Например сумму всех товаров в корзине, функция его считает и сохраняет в переменную. И потом выводит, если надо. ''' def get_sum(a, b): return a + b get_sum(4, 5) # в консоли ничего не выведет, надо выводить принтом либо присвоить переменной и её принтовать print(get_sum(5, 7)) # 12 c = get_sum(3, 8) print(c, '\n') # 11 def hi(): print('Hi\n') # Если функция уже что то печатает - то вызываем функцию без принта, иначе кроме результата она еще вернет None # print(hi()) # Hi None hi() # Hi print('Домашнее задание\n') ''' 1. Дан список. Получите новый список, в котором каждое значение будет удвоено: [1, 2, 3] --> [2, 4, 6] ''' my_list = [1, 2, 3] def def_list(arg): new_list = [i * 2 for i in arg] return new_list # def_list(my_list) # эта запись не обязательна, передаем её сразу в принте print(f'Task 1: new_list = {def_list(my_list)}\n') ''' 2. Дан список. Возведите в квадрат каждый из его элементов и получит сумму всех полученных квадратов: [1, 2, 3] --> 14 --> 1^2 + 2^2 + 3^2 = 14 ''' def pow_num(arg): my_sum = sum(i ** 2 for i in arg) return my_sum print(f'Task 2: my_sum = {pow_num(my_list)}\n') def str_def(arg): if ' ' in arg: s = arg.upper() else: s = arg.lower() return s print(str_def('Hello world')) # HELLO WORLD print(str_def('Hello,world')) # hello,world # def str_def(s): # Второй вариант написание функции # if ' ' in s: # return s.upper() # else: # return s.lower()
996ca72cb7c2ad8481d096a1ad2de4c73e00a323
JakubCzerny/02443-stochastic-simulation
/sim_event_handler.py
7,723
3.671875
4
import matplotlib.pyplot as plt import pandas as pd import numpy as np class SimEventHandler: """ A simulation handler allows you to add additional behavior to the base simulation, e.g. to collect statistics or modify car behavior. It contains a bunch of methods that are called by the simulation at specific moments in the simulation. These methods should be overwritten by sub-classes. """ enabled = True def before_time_step(self, dt, sim_time): pass def after_time_step(self, dt, sim_time): pass def before_vehicle_update(self, dt, vehicle): pass def after_vehicle_update(self, dt, vehicle): pass def after_vehicle_spawn(self, vehicle, sim_time): pass def before_vehicle_despawn(self, vehicle, sim_time): pass def __str__(self): return self.__class__.__name__ class SlowZoneEvHandler(SimEventHandler): """ Simulation handler that forces cars to go slow down in a certain section of the road. """ def __init__(self, start, stop, max_velocity=10): """ Section of road defined by [start, stop], in meters. """ self._start = start self._stop = stop self._max_velocity = max_velocity self._acc = -3 self.simTimeList = [] self.enableList = [] def after_vehicle_update(self, dt, vehicle): if self.enabled and vehicle.position > self._start and vehicle.position < self._stop: if vehicle.velocity > self._max_velocity and vehicle.acceleration > self._acc: vehicle.acceleration = self._acc def after_time_step(self, dt, sim_time): self.simTimeList.append(sim_time) if self.enabled: self.enableList.append(1) else: self.enableList.append(0) def plot(self, subplot = False): plt.plot(self.simTimeList, self.enableList) plt.grid() plt.ylabel("On/off [1/0]", fontsize = 20) plt.title("On/Off status of slow zone from {}m to {}m with max_velocity {:.2f}".format(self._start, self._stop, self._max_velocity), fontsize = 20) if not subplot: plt.xlabel("Time [s]") def __str__(self): return "{}: max_velocity={}".format(self.__class__.__name__, self._max_velocity) class StatsEvHandler(SimEventHandler): """ Simulation handler that collects statistics. """ def __init__(self): self.unspawned_count = 0 def before_vehicle_despawn(self, vehicle, sim_time): self.unspawned_count += 1 def __str__(self): return """ Statistics summary: - unspawned_count: {} """.format(self.unspawned_count) class AverageSpeedHandler(SimEventHandler): """ Tracks the average speed of the vehicles. """ def __init__(self): self.averageSpeed = 0 self.numberOfVehicles = 0 self.averageSpeedList = [] self.simTimeList = [] self.updatecount = 0 def after_vehicle_update(self, dt, vehicle): self.averageSpeed += vehicle.velocity self.numberOfVehicles += 1 def after_time_step(self, dt, sim_time): self.updatecount += 1 if self.updatecount > 1: #Only update ever 3. timestep if self.numberOfVehicles > 0: self.averageSpeedList.append(self.averageSpeed / self.numberOfVehicles) self.averageSpeed = 0 self.numberOfVehicles = 0 self.simTimeList.append(sim_time) self.updatecount = 0 def plot(self, subplot = False): windowSize = 5 speed = pd.DataFrame(self.averageSpeedList) r = speed.rolling(window = windowSize) # Average last 10 values r = r.mean() if not subplot: plt.figure() #plt.plot(self.simTimeList,speed, linewidth = 2) plt.plot(self.simTimeList[3:],r[3:], linewidth = 3) plt.grid() plt.ylabel("Average speed of cars [m/s]", fontsize = 20) #plt.title("Average speed of cars as function of time, rolling window = {}".format(windowSize), fontsize = 20) #plt.rcParams.update({'font.size': 45}) if not subplot: plt.show() plt.xlabel("Time [s]", fontsize = 23) #print(len(self.simTimeList)) class ThroughPutHandler(SimEventHandler): def __init__(self): self.nb_vehicles = 0 self.nb_vehicles_list = [] self.interval = 15 # seconds self.max_time = 0 def before_vehicle_despawn(self, vehicle, sim_time): self.nb_vehicles += 1 def after_time_step(self, dt, sim_time): if len(self.nb_vehicles_list) < sim_time // self.interval: self.nb_vehicles_list.append(self.nb_vehicles) self.nb_vehicles = 0 self.max_time = sim_time def plot(self, subplot = False): if len(self.nb_vehicles_list) == 0: return print("Average/min/max throughput", np.mean(self.nb_vehicles_list), np.min(self.nb_vehicles_list), np.max(self.nb_vehicles_list)) if not subplot: plt.figure() plt.xlabel("Time [s]", fontsize = 23) plt.ylabel("Throughput [vehicles/{}s]".format(self.interval), fontsize = 20) plt.plot(np.linspace(0, self.max_time, len(self.nb_vehicles_list)), self.nb_vehicles_list, '-b*',linewidth = 3) plt.grid() if not subplot: plt.show() class TravelTimeHandler(SimEventHandler): def __init__(self): self.dict = {} def after_vehicle_spawn(self, vehicle, sim_time): self.dict[vehicle] = (sim_time, 0) def before_vehicle_despawn(self, vehicle, sim_time): p = self.dict[vehicle] self.dict[vehicle] = (p[0], sim_time - p[0]) def plot(self, subplot = False): times = [] travel_times = [] for k in self.dict: p = self.dict[k] if p[1] != 0: times.append(p[0]) travel_times.append(p[1]) if len(times) == 0: return print("Average/min/max travel times", np.mean(travel_times), np.min(travel_times), np.max(travel_times)) if not subplot: plt.figure() windowSize = 8 times = np.array(times) travel_times = np.array(travel_times) indicies = np.argsort(times) times = times[indicies] travel_times = travel_times[indicies] travel_times = pd.DataFrame(travel_times) r = travel_times.rolling(window = windowSize) r = r.mean() plt.ylabel("Travel time [s]", fontsize = 20) plt.plot(times, r, linewidth = 3) plt.grid() if not subplot: plt.xlabel("Time [s]", fontsize = 23) plt.show() class VehicleCountHandler(SimEventHandler): def __init__(self): self.count = 0 self.counts = [] self.max_time = 0 def before_vehicle_update(self, dt, vehicle): self.count += 1 def after_time_step(self, dt, sim_time): self.max_time = sim_time self.counts.append(self.count) self.count = 0 def plot(self, subplot = False): if len(self.counts) == 0: return x = np.linspace(0, self.max_time, len(self.counts)) if not subplot: plt.figure() plt.plot(x, self.counts, linewidth = 3) plt.ylabel("Number of vehicles \n on the road", fontsize = 20) plt.grid() plt.xlabel("Time [s]", fontsize = 23) if not subplot: plt.show()
e412602003ad88e2608b666ef86266bd1708e085
chichutschang/6.00.1x-1T2014
/Week 4/ProblemSet4/ProblemSet4/Problem Set 4 Computer Chooses a Word.py
4,549
3.75
4
# 6.00x Problem Set 4A Template # # The 6.00 Word Game # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens> # Modified by: Sarina Canelake <sarina> # import random import string VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } # # Problem #1: Scoring a word # def getWordScore(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, multiplied by the length of the word, PLUS 50 points if all n letters are used on the first turn. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES) word: string (lowercase letters) n: integer (HAND_SIZE; i.e., hand size required for additional points) returns: int >= 0 """ # TO DO ... <-- Remove this comment when you code this function score = 0 if int(n) == int(len(word)): bonus = 50 else: bonus = 0 for c in word: score += SCRABBLE_LETTER_VALUES[c] return int(score) * int(len(word)) + int(bonus) # # Problem #2: Update a hand by removing letters # def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ # TO DO ... <-- Remove this comment when you code this function letters = "" test = hand.copy() for x in word: if x in test: test[x] = test.get(x, 0) - 1 return test # # Problem #3: Test word validity # def isValidWord(word, hand, wordList): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList. word: string hand: dictionary (string -> int) wordList: list of lowercase strings """ # TO DO ... <-- Remove this comment when you code this function test = hand.copy() for x in word: if test.get(x): test[x] = test[x] - 1 else: return False if word not in wordList: return False else: return True def compChooseWord(hand, wordList, n): """ Given a hand and a wordList, find the word that gives the maximum value score, and return it. This word should be calculated by considering all the words in the wordList. If no words in the wordList can be made from the hand, return None. hand: dictionary (string -> int) wordList: list (string) returns: string or None """ # BEGIN PSEUDOCODE (available within ps4b.py) # Create a new variable to store the maximum score seen so far (initially 0) maxScore = 0 # Create a new variable to store the best word seen so far (initially None) bestWord = None # For each word in the wordList for word in wordList: # If you can construct the word from your hand if isValidWord(word, hand, wordList) == True: # (hint: you can use isValidWord, or - since you don't really need to test if the word is in the wordList - you can make a similar function that omits that test) score = getWordScore(word, n) # Find out how much making that word is worth # If the score for that word is higher than your best score if score > maxScore: # Update your best score, and best word accordingly maxScore = score bestWord = word # return the best word you found. return bestWord
82bf64e651d21cfb1c373aefa95f02a86b646345
whatsreal/CIS-120-Assignments
/Guttag Finger Exercises/FE9.py
266
3.8125
4
#Finger Exercise 6 #Chapter 4 Secition 1.1 """Implement a function that meets the specification below. Use a try-except block. """ def sumDigits(s): """Assumes s is a string Returns the sum of the decimal digits in s For example, if s is 'a2b3c' it returns 5"""
cbfd0427d255ac0d03457ce96225de831e2c905d
camilabraatzz/Trabalho1.2
/07.py
640
4.15625
4
# Faça um programa que mostre todos os primos entre 1 e N sendo N um número inteiro fornecido pelo usuário. # O programa deverá mostrar também o número de divisões que ele executou para encontrar os números primos. # Serão avaliados o funcionamento, o estilo e o número de testes (divisões) executados. num = int(input("Digite um número: ")) contador = 0 for i in range(1, num + 1): if num % i == 0: print(f'O número {num} é divisível por {i}') contador += 1 print(f'O número {num} foi divisível {contador} vezes!') print('O número é primo') if contador == 2 else print('O número não é primo')
51c5798fab967e98a510bd02042fd6b123d546df
1i0n0/Python-Learning
/practices/lcm.py
825
4.3125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Determine the least common multiple of two positive integer numbers. import sys def lcm(num1, num2): _lcm = max(num1, num2) while True: if _lcm % num1 == 0 and _lcm % num2 == 0: break _lcm += 1 return _lcm if __name__ == "__main__": try: number1 = int(input("Enter a number: ")) number2 = int(input("Enter another number: ")) assert number1 > 0 assert number2 > 0 except ValueError: print("Please enter two non-zero positive integers.") sys.exit(1) except AssertionError: print("Please enter two non-zero positive integers.") sys.exit(1) print("The least common multiple of {} and {} is {}" .format(number1, number2, lcm(number1, number2)))
501ffc427f99c4ddacfdcc867ef90ac9051c274a
gschen/sctu-ds-2020
/1906101019-贾佳/Day0303课后作业/test3.py
1,260
4
4
#第一种方法 class Person(): def __init__(self): self.name = "贾佳" self.age = 19 self.gender = "male" self.class_ = "信管01" self.college = "信息与工程学院" def personInfo(self): return self.name,self.age,self.gender,self.class_,self.college class Student(Person): def __init__(self): Person.__init__(self) def another(self): Person.personInfo(self) a = Student() print(super(Student,a).personInfo()) #第二种方法 class Person(): def __init__(self): self.name = "贾佳" self.age = 19 self.gender = "male" self.class_ = "信管01" self.college = "信息与工程学院" def personInfo(self): return self.name,self.age,self.gender,self.class_,self.college class Student(Person): def another(self): return Person.personInfo(self) b = Student() print(b.another()) class Teacher(): def __init__(self): self.today = "今天讲了:‘面向对象编程’" def teacherObj(self): return self.today class study(Teacher): def work(self): return "老师{},我终于学会了".format(Teacher.teacherObj(self)) c = study() print(c.work())
4b05235328ff2e14dfe47ede5c9547cbc3cce746
zhengjiani/pyAlgorithm
/leetcodeDay/May/prac221.py
2,745
3.5625
4
# -*- encoding: utf-8 -*- """ @File : prac221.py @Time : 2020/5/8 8:13 上午 @Author : zhengjiani @Email : [email protected] @Software: PyCharm """ from typing import List class Solution: """动态规划""" def maximalSquare(self, matrix: List[List[str]]) -> int: if not matrix: return 0 n,m = len(matrix),len(matrix[0]) ans = 0 pre = [] for val in matrix[0]: pre.append(int(val)) if int(val) > ans: ans = int(val) for i in range(1,n): cur = [0]*m for j in range(m): if matrix[i][j] == '0': continue if j == 0: cur[j] = 1 else: cur[j] =min(cur[j-1],pre[j-1],pre[j]) + 1 if cur[j] > ans: ans = cur[j] pre = cur return ans*ans class Solution1: """暴力法""" def maximalSquare(self, matrix: List[List[str]]) -> int: """ - 遍历矩阵中的每个元素,每次遇到1,就把它作为矩阵的左上角 - 根据左上角所在的行和列,计算可能的最大正方形边长 - 每次在下方新增一行或者在右方新增一列,判断所增的行和列是否满足所有元素都是1 :param matrix: :return: """ if len(matrix) == 0 or len(matrix[0]) == 0: return 0 maxSide = 0 rows, columns = len(matrix), len(matrix[0]) for i in range(rows): for j in range(columns): if matrix[i][j] == '1': # 遇到一个 1 作为正方形的左上角 maxSide = max(maxSide, 1) # 计算可能的最大正方形边长 currentMaxSide = min(rows - i, columns - j) for k in range(1, currentMaxSide): # 判断新增的一行一列是否均为 1 flag = True if matrix[i + k][j + k] == '0': break for m in range(k): if matrix[i + k][j + m] == '0' or matrix[i + m][j + k] == '0': flag = False break if flag: maxSide = max(maxSide, k + 1) else: break maxSquare = maxSide * maxSide return maxSquare if __name__ == '__main__': matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] s = Solution1() print(s.maximalSquare(matrix))
f8c47d41b6ccab3b1c8297e53a9d22bdcb082e20
Bernatovych/DZ_11
/phone_book.py
3,567
3.625
4
from datetime import datetime from collections import UserDict class AddressBook(UserDict): def add_record(self, record): self.data[record.name] = record def iterator(self, n): data_list = list(self.data.values()) while data_list: for i in data_list[:n]: yield i data_list = data_list[n:] class Record: def __init__(self, name, birthday=None): self.name = name self.phones = [] self.birthday = birthday def add_field(self, phone): self.phones.append(phone) def change_field(self, phone, new_phone): try: self.phones[self.phones.index(phone)] = new_phone except ValueError as e: print(e) def delete_field(self, phone): try: self.phones.remove(phone) except ValueError: print(f'{phone} is not in list') def days_to_birthday(self): now = datetime.today() try: if datetime(self.birthday.value.year, self.birthday.value.month, self.birthday.value.day) < now: birthday_date = datetime(now.year, self.birthday.value.month, self.birthday.value.day) if birthday_date > now: return (birthday_date - now).days + 1 else: birthday_date = datetime(now.year + 1, self.birthday.value.month, self.birthday.value.day) return (birthday_date - now).days + 1 else: print('The date cannot be in the future!') except AttributeError: print('Wrong date format!') def __repr__(self): return f"{self.name} {self.birthday} {self.phones}" class Field: def __init__(self, value): self.__value = value @property def value(self): return self.__value @value.setter def value(self, new_value): self.__value = new_value def __repr__(self): return str(self.value) class Name(Field): def __init__(self, value): super().__init__(value) class Phone(Field): def __init__(self, value): super().__init__(value) self.__value = value self.value = value @property def value(self): return self.__value @value.setter def value(self, value): self.__value = value if value.isdigit(): if len(value) == 10: self.__value = value else: print('There should be 10 numbers!') else: print('There should be only numbers!') class Birthday(Field): def __init__(self, value): super().__init__(value) self.__value = value self.value = value @property def value(self): return self.__value @value.setter def value(self, value): self.__value = value try: s = datetime.strptime(value, '%Y-%m-%d').date() self.__value = s except ValueError as e: print(e) if __name__ == '__main__': pass name = Name('Sasha') phone = Phone('0236537890') birthday = Birthday('2020-11-30') name1 = Name('Masha') phone1 = Phone('0948763456') phone2 = Phone('0000000000') birthday1 = Birthday('2020-10-30') r = Record(name, birthday) r.change_field(phone, phone2) r.add_field(phone1) r1 = Record(name1) r.add_field(phone) r1.add_field(phone1) print(r.days_to_birthday()) print(r1.days_to_birthday()) ab = AddressBook() ab.add_record(r) ab.add_record(r1) it = ab.iterator(3) for i in it: print(i)
8e75fa1548e6ef6fc059d53689727a3bbc8a0f2a
pranaymate/PythonExercises
/ex042.py
611
4.09375
4
a = float(input('Type a number to form a Triangle: ')) b = float(input('Type a number to form a Triangle: ')) c = float(input('Type a number to form a Triangle: ')) if (b - c) < a and a < (b + c) and (a - c) < b and b < a + c and (a - b) < c and c < (a + b): if a == b and a == c: print('These three numbers cam form a Equilateral Triangle!') elif a == b or a == c or b == c: print('These three numbers cam form a Isosceles Triangle!') else: print('These three numbers cam form a Scalene Triangle!') else: print('{}, {} and {} can not form a Triangle!'.format(a, b, c))
dd9eee804fc24593bb24eb65c33088e31f3781f0
dalehuangzihan/vidBarcodeReader
/OpenCV_Tutorials/geometric_shapes_tutorial.py
1,448
3.53125
4
import numpy as np import cv2 #img = cv2.imread('lena.jpg',1) ## Draw image using numpy array (mtx of 0s gives a black image) img = np.zeros([512,512,3], np.uint8) # z-coord = 3 to indicate 3-channel image ''' Top-left-hand corner of image has coordinate (0,0). Bottom-right-hand corner of iamge has coordinates (imagHeight, imageWidth) ''' ## Drawing line and arrowed line: linePt1 = (0,0) linePt2 = (255,255) lineColour = (0,255,0) # is in BGR channel format (reverse of RGB!) lineThickness = 3 img = cv2.line(img, linePt1, linePt2, lineColour, lineThickness) img = cv2.arrowedLine(img, (0,255), linePt2, (255,0,0), lineThickness) ## Drawing rectangle: topLeftCoord = (300,50) bottomRightCoord = (510, 128) rectThickness = 5 rectLineType = cv2.LINE_4 img = cv2.rectangle(img, topLeftCoord, bottomRightCoord, lineColour, rectThickness, rectLineType) ## Drawing circle: circleCenter = (300,400) circleRadius = 70 circleColour = (0,0,255) circleThickness = -1 # this will cause the circle to be shaded-in! img = cv2.circle(img, circleCenter, circleRadius, circleColour, -1) ## Placing text: font = cv2.FONT_HERSHEY_SIMPLEX fontSize = 4 textColour = (255,255,255) textThickness = 5 textLineType = cv2.LINE_AA img = cv2.putText(img,'OpenCV!', (10,500), font, fontSize, textColour, textThickness, textLineType) cv2.imshow('image',img) k = cv2.waitKey(0) & 0xFF if k == 27: cv2.destroyAllWindows() print("quit")
ff7623fe38966e4b3d0c91a6340cf583d06376ef
dakshitgm/Specialization-Data-structure-and-Algorithm-Coursera
/algorithmic toolbox/week4_divide_and_conquer/closest2.py
1,084
3.953125
4
#Uses python3 import sys import math from collections import namedtuple point=namedtuple('point', 'x y') def minimum_distance(points): #write your code here n=len(points) if n==1: return float('inf') if n==2: return distance(points[0], points[1]) mid=n//2 d1=minimum_distance(points[0:mid]) d2=minimum_distance(points[mid:n]) d=min(d1, d2) sline=(points[mid].x+points[mid-1].x)/2 low=sline-d high=sline+d st_points=[] for i in points: if low<=i.x<=high: st_points.append(i) st_points.sort(key=lambda point:point.y) diff=d size=len(st_points) for i in range(size): j=i+1 while j<size and st_points[j].y-st_points[i].y<diff: diff=distance(st_points[i+1], st_points[i]) j+=1 return min(d, diff) def distance(p1, p2): x_dif=abs(p1.x-p2.x)**2 y_dif=abs(p1.y-p2.y)**2 return (x_dif+y_dif)**0.5 if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) n = data[0] x = data[1::2] y = data[2::2] points=[point(x[i], y[i]) for i in range(n)] points.sort() print("{0:.9f}".format(minimum_distance(points)))
6cc35c51e504d53853e2ab6e5c0f44bb858959a8
muhammaduamirkhalid/Assignment-1
/Area calculator.py
203
4.125
4
import math b = float(math.pi) a = int(input("Enter the radius of the circle here in meters:")) area = b * a * a print("The area of the circle of radius" + str(a) + " " + "is" + " " + str(area) + "m")
3817250afcb67ab9f46731bb90cd63fb3ef2b70f
quqixun/Hackerrank_Python
/Algorithm/Implementation/grading_students.py
554
3.578125
4
#!/bin/python3 import sys def solve(grades): # Complete this function for i in range(len(grades)): if grades[i] < 38: continue else: mod = grades[i] % 5 multi5 = int(((grades[i] - mod) / 5 + 1) * 5) if multi5 - grades[i] < 3: grades[i] = multi5 return grades n = int(input().strip()) grades = [] grades_i = 0 for grades_i in range(n): grades_t = int(input().strip()) grades.append(grades_t) result = solve(grades) print("\n".join(map(str, result)))
e5169e586cab560dd18ca38147523b06ecc46c51
Vuntsova/first-repo-feb-2020-ev
/prework.py
466
3.765625
4
def display_name(user_name): print(user_name) display_name("Emiliya") def print_odd(): for num in range(1, 100): if num % 2 == 0: print(num) print_odd() def max_num_in_list(a_list): print(max(a_list)) alist = [ 1,2,3,4,888] max_num_in_list(alist) def is_leap_year(a_year): if a_year % 4 == 0 and (a_year % 100 != 0 or a_year % 400 == 0): print("leap") else: print("no leap") is_leap_year(3000)
aa7764079381361088cae881afbc7634ce07f204
johnehunt/computationalthinking
/week5/books.py
245
4.15625
4
books = set() user_input = input('please enter name of book: ') while user_input != 'x': books.add(user_input) user_input = input('please enter name of book: ') print('Print books entered:') for book in books: print('Book: ', book)
37c0cd3097bf56c976f141fb34e06efeb9e7de25
victord96/advanced_level_python
/iterators/iterators.py
974
4.09375
4
import time class FiboIter: """Iterator that prints the fibonacci sequence up to a specified number """ def __init__(self, limit): self.limit = limit def __iter__(self): self.n1 = 0 self.n2 = 1 self.counter = 0 self.aux = 0 return self def __next__(self): if self.counter == 0: self.counter += 1 return self.n1 elif self.counter == 1: self.counter += 1 return self.n2 else: self.aux = self.n1 + self.n2 # self.n1 = self.n2 # self.n2 = self.aux if self.aux < self.limit: self.n1, self.n2 = self.n2, self.aux self.counter += 1 return self.aux else: raise StopIteration if __name__ == '__main__': fibonacci = FiboIter(100) for i in fibonacci: print(i) #time.sleep(1)
d925b5c5557ebc641c4c3d1b342a23edaf83b036
reshavcodes/python
/Prime_Game.py
2,520
3.921875
4
''' Prime Game Rax, a school student, was bored at home in the pandemic. He wanted to play but there was no one to play with. He was doing some mathematics questions including prime numbers and thought of creating a game using the same. After a few days of work, he was ready with his game. He wants to play the game with you. GAME: Rax will randomly provide you a range [ L , R ] (both inclusive) and you have to tell him the maximum difference between the prime numbers in the given range. There are three answers possible for the given range. There are two distinct prime numbers in the given range so the maximum difference can be found. There is only one distinct prime number in the given range. The maximum difference in this case would be 0. There are no prime numbers in the given range. The output for this case would be -1. To win the game, the participant should answer the prime difference correctly for the given range. Example: Range: [ 1, 10 ] The maximum difference between the prime numbers in the given range is 5. Difference = 7 - 2 = 5 Range: [ 5, 5 ] There is only one distinct prime number so the maximum difference would be 0. Range: [ 8 , 10 ] There is no prime number in the given range so the output for the given range would be -1. Can you win the game? Input Format The first line of input consists of the number of test cases, T Next T lines each consists of two space-separated integers, L and R Constraints 1<= T <=10 2<= L<= R<=10^6 Output Format For each test case, print the maximum difference in the given range in a separate line. Sample TestCase 1 Input 5 5 5 2 7 8 10 10 20 4 5 Output 0 5 -1 8 0 ''' def main(): testCase = int(input()) def isprime(n): if n <= 1: return False for i in range(2, n): if n % i == 0: return False return True while testCase > 0: LR = list(map(int, input().strip().split())) first = LR[0] last = LR[1] f = 0 l = 0 for i in range(first, last+1): if f == 0: if isprime(i): f = i else: i = i+1 if l == 0: if isprime(last): l = last else: last -= 1 if f != 0 and l != 0: break if f != 0 and l != 0: print(l-f) else: print(-1) testCase -= 1 main()
28848e87a7e2f1152bf260c19bd065ab35838ba8
rrebase/algorithms
/d13_coin_change.py
2,178
4
4
# Dynamic programming coin change problem def coin_change(coins, n): """ Returns the minimum amount of coins to get the sum of n. Recursive solution. coins is a tuple or list n is the sum to get """ values = {} # cached results def solve(x): if x < 0: return float("inf") elif x == 0: return 0 elif x in values: return values[x] best = float("inf") for c in coins: best = min(best, solve(x - c) + 1) values[x] = best return best return solve(n) def coin_change2(coins, n): """ Returns the minimum amount of coins to get the sum of n. Iterative solution. coins is a tuple or list n is the sum to get """ v = [0] * (n + 1) def iterative(): for x in range(1, len(v)): v[x] = float("inf") for c in coins: if x - c >= 0: v[x] = min(v[x], v[x - c] + 1) return v return iterative()[n] def coin_change3(coins, n): """ Returns the minimum amount of coins and the solution to get the sum of n as a tuple -> (minimum amount (int), solution (list of ints)) Iterative solution. coins is a tuple or list n is the sum to get """ v = [0] * (n + 1) first = [0] * (n + 1) for x in range(1, len(v)): v[x] = float("inf") for c in coins: if x - c >= 0 and v[x - c] + 1 < v[x]: v[x] = v[x - c] + 1 first[x] = c result = v[n] solution = [] while n > 0: solution.append(first[n]) n -= first[n] return result, solution def count_ways(coins, n): """ Return the count of possible ways to get a sum of n with coins. coins is a tuple or list n is the sum to get """ ways = [1] + [0] * n for c in coins: for i in range(c, n + 1): ways[i] += ways[i - c] return ways[n] N = 11 COINS = (1, 3, 4) print(coin_change(COINS, N)) # -> 3 print(coin_change2(COINS, N)) # -> 3 print(coin_change3(COINS, N)) # -> (3, [3, 4, 4]) print(count_ways(COINS, N)) # -> 9
8ac8dd8ce68d1015c4b1b7ae71a86f8dc9bddf50
saviovincent/DSA
/basic_ds/LinkedList.py
1,990
4.21875
4
# LinkedList Implementation class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.current = None def addLast(self, node): if self.head is None: self.head = node self.current = node # else: # self.current.next = node # self.current = self.current.next # through single pointer else: tmp = self.head while tmp.next is not None: tmp = tmp.next tmp.next = node # if node.data == 3: # node.next = self.head def contents(self): temp = self.head while temp is not None: print(temp.data) temp = temp.next def addFirst(self, node): if self.head is None: self.head = node self.current = node else: node.next = self.head self.head = node def removeFirst(self): if self.head is None: print("Nothing to remove") else: self.head = self.head.next def removeLast(self): if self.head is None: print("Nothing to remove") elif self.head.next is None: self.head = None else: prev = None current = self.head while current.next is not None: prev = current current = current.next prev.next = None def peekFirst(self): return self.head.data def peekLast(self): # return self.current.data # if only 1 pointer tmp = self.head while tmp.next is not None: tmp = tmp.next return tmp.data if __name__ == '__main__': ll = LinkedList() ll.addLast(Node(1)) ll.addLast(Node(2)) ll.addLast(Node(3)) ll.contents() ll.removeLast() ll.contents()
1021c28fe92598f2c4799aa873af5ca77eaadb86
MathieuCNC/AdventOfCode2019
/Condition.py
312
4.0625
4
#!/usr/bin/python2.7 # -*-coding:Utf-8 -* print("Hello!") year = input("Saisissez une année pour vérifier si elle est bisextile: ") print(type(year)) if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0): print("L'année ", year, " est bisextile") else: print("L'année ", year, " n'est pas bisextile")
01dbb0092405a78aecf180008520a6a9643797ad
Riotam/competitive-pg-py
/utils.py
1,915
4.03125
4
def get_lines(count: int) -> list: """ get_lines は引数に与えられた値の行数だけ、標準入力を取得する :param count: 取得したい行数 :return input_list: 取得した行数strのlist """ lines = [] for _ in range(count): line = input() lines.append(line) return lines def get_lines_by_first_line() -> list: """ get_lines_by_first_line は1行目に与えられた標準入力の値を行数として、2行目以降の標準入力を文字列のリストにして取得する :param: None :return lines: """ count = int(input()) return get_lines(count) def cast_int_for_two_dimensional_list(str_list_in_list: list) -> list: """ cast_int_for_two_dimensional_list は、文字列の入った二次元リストを数値の二次元リストにキャストする :param str_list_in_list: [[str, str, ...], [str, str, ...], ...] :return int_list_in_list: [[int, int, ...], [int, int, ...], ...] """ int_list_in_list = [] for row in str_list_in_list: row[:] = map(int, row) int_list_in_list.append(row) return int_list_in_list def print_list(result_list: list) -> None: """ print_list は任意の型のリストを、str型にキャストして、下記のように出力する ``` 1 2 3 4 5 ``` :param result_list: [any, any, ...] :return: None (print) """ str_list = [str(i) for i in result_list] print(*str_list) def print_two_dimensional_list(result_list_in_list): """ print_two_dimensional_list は二次元配列をstr型にキャストして、下記のように出力する ``` 1 2 3 4 5 6 7 8 9 ``` :param result_list_in_list: [[any, any, ...], [any, any, ...], ...] :return: None (print) """ for result_list in result_list_in_list: print_list(result_list)
5adc13e1c9ce5526a57e8aa18f3ed16e80e6af5d
Andrew-Zarenberg/Scheduler
/utils.py
1,797
4.09375
4
# Utility functions to handle parsing dates and times # Converts a time string (from data) to an integer. def time_to_int(n): spl = n.split(':') return int(spl[0])*60+int(spl[1]) # Converts a day (from data) to an integer. def days_to_ints(data): days = "MTWRFS" r = [] for x in data: r.append(days.index(x)*1440) return r # Given a specific section's information, return the times as ints. # Each time will be the amount of minutes from Monday 12:00am. def section_time_to_ints(start_time, end_time, days): r = [] start_int = time_to_int(start_time) end_int = time_to_int(end_time) for x in days_to_ints(days): r.append((x+start_int, x+end_int)) return r # Converts an integer to the day def time_to_day(n): #days = "MTWRFS" days = ["Mon","Tue","Wed","Thu","Fri","Sat"] return days[int(n/1440)] # Converts an integer time to human readable string def time_to_str(n): n %= 1440 hour = int(n/60) minute = str(n%60) if(len(minute) == 1): minute = '0'+minute ampm = "am" if(hour == 12): ampm = "pm" elif(hour > 12): hour -= 12 ampm = "pm" return str(hour)+':'+minute+ampm # For testing purposes if __name__ == "__main__": # Sample info for Databases Fall 2016 start_time = "11:00:00" end_time = "12:20:00" days = "TR" times = section_time_to_ints(start_time, end_time, days) print("Ints: "+str(times)) print("\nBack to human readable:") for x in times: print(time_to_day(x[0])+' '+time_to_str(x[0])+'-'+time_to_str(x[1])) # OUTPUT of the above code: # # Ints: [(2100, 2180), (4980, 5060)] # # Back to human readable: # Tue 11:00am-12:20pm # Thu 11:00am-12:20pm
c4aa7e5cedc073199a1ea4139eb586f07ee7e448
dkothari777/pacmanAI
/multiagent/multiAgents.py
12,755
3.5625
4
# multiAgents.py # -------------- # Licensing Information: Please do not distribute or publish solutions to this # project. You are free to use and extend these projects for educational # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by # John DeNero ([email protected]) and Dan Klein ([email protected]). # For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html from util import manhattanDistance from game import Directions import random, util import math from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (oldFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() oldFood = currentGameState.getFood() newGhostStates = successorGameState.getGhostPositions() # newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" distances_to_foods = [] for food in oldFood: distances_to_foods.append(manhattanDistance(newPos, food)) # print newPos, food closest_food = max(distances_to_foods) distances_to_ghosts=[] for i in newGhostStates: distances_to_ghosts.append(manhattanDistance(newPos, i)) closest_ghost = min(distances_to_ghosts) state_score = min(closest_ghost,closest_food) if closest_ghost-closest_food >= 0: state_score += min(closest_food, closest_ghost) return currentGameState.getScore() + state_score def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def miniMax(self, gameState, depth, score): legalActions = gameState.getLegalPacmanActions() maxAction ="" maxScore = -99999999999999999999 depthScore = {} for action in legalActions: z = self.evaluationFunction(gameState.generatePacmanSuccessor(action)) depthScore[action] = self.mini(gameState.generatePacmanSuccessor(action), depth, z) for x, y in depthScore.iteritems(): if(y > maxScore): maxScore = y maxAction = x print maxScore, maxAction return maxAction def maxi(self, gameState, depth, score): if(depth == 0): return score legalActions = gameState.getLegalPacmanActions() depthScore = [] maxScore = -99999999999999999 for action in legalActions: z = self.evaluationFunction(gameState.generatePacmanSuccessor(action)) depthScore.append(self.mini(gameState.generatePacmanSuccessor(action), depth-1, z)) for x in depthScore: if x > maxScore: maxScore = x return maxScore def mini(self, gameState, depth, score): if(depth == 0): return score depthScore=[] miniScore = -9999999999999999999 for i in range(0, gameState.getNumAgents()): for action in gameState.getLegalActions(i): z = self.evaluationFunction(gameState.generateSuccessor(i, action)) depthScore.append(self.maxi(gameState.generateSuccessor(i, action), depth-1, z)) for x in depthScore: if x > miniScore: miniScore = x return miniScore def minimax2(self, gameState, depth, maximizingPlayer): if depth == 0: return self.evaluationFunction(gameState) if(maximizingPlayer): maxValue = -999 for action in gameState.getLegalPacmanActions(): score = self.minimax2(gameState.generatePacmanSuccessor(action), depth - 1, False) # print score maxValue = max(maxValue, score) return maxValue else: minValue = -999 for i in range(1, gameState.getNumAgents()): for action in gameState.getLegalActions(i): score = self.minimax2(gameState.generateSuccessor(i, action), depth - 1, True) minValue = max(minValue, score) return minValue def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 Directions.STOP: The stop direction, which is always legal gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" legalActions = gameState.getLegalPacmanActions() scoresForAction = {} maxAction = "" maxScore = -99999999999999 for action in legalActions: scoresForAction[action] = self.minimax2(gameState.generatePacmanSuccessor(action), self.depth, False) for x,y in scoresForAction.iteritems(): if(maxScore < y): maxScore = y maxAction = x return maxAction # return self.miniMax(gameState, self.depth, 0) class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def alphaBeta(self, gameState, depth, a, b, maximizingPlayer): if depth == 0: return betterEvaluationFunction(gameState) if maximizingPlayer: v = -(float("inf")) for i in range(1, gameState.getNumAgents()): for action in gameState.getLegalActions(i): v = max(v, self.alphaBeta(gameState.generateSuccessor(i, action), depth - 1, a, b, False)) a = max(a, v) if b <= a: break # beta cut-off return v else: v = float("inf") legalActions = gameState.getLegalPacmanActions() for action in legalActions: v = min(v, self.alphaBeta(gameState.generatePacmanSuccessor(action), depth - 1, a, b, True)) b = min(b, v) if b <= a: break # alpha cut-off return v def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" legalActions = gameState.getLegalPacmanActions() scoresForAction = {} maxAction = "" maxScore = -99999999999999 for action in legalActions: scoresForAction[action] = self.alphaBeta(gameState.generatePacmanSuccessor(action), self.depth, -(float("inf")), float("inf"), True) for x,y in scoresForAction.iteritems(): if(maxScore < y): maxScore = y maxAction = x return maxAction class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def expectiminimax(self, gameState, depth): scareTimes = [ghosts.scaredTimer for ghosts in gameState.getGhostStates()] if(depth == 0): return betterEvaluationFunction(gameState) if(depth%2 !=0): a = -float("inf") for i in range(1,gameState.getNumAgents()): for action in gameState.getLegalActions(i): a = max(a, self.expectiminimax(gameState.generateSuccessor(i, action), depth - 1)) elif(depth%2 == 0 and scareTimes[0] == 0 ): a = -(float("inf")) for action in gameState.getLegalPacmanActions(): a = max(a, self.expectiminimax(gameState.generatePacmanSuccessor(action), depth - 1)) else: a = 0 for action in gameState.getLegalPacmanActions(): a = a + (betterEvaluationFunction(gameState.generatePacmanSuccessor(action)) + self.expectiminimax(gameState.generatePacmanSuccessor(action), depth -1)) return a def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" maxScore = {} bestVal = -(float("inf")) maxAction = "" for action in gameState.getLegalPacmanActions(): maxScore[action] = self.expectiminimax(gameState.generatePacmanSuccessor(action), self.depth) for x,y in maxScore.iteritems(): if(bestVal< y): bestVal = y maxAction = x return maxAction def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: This heuristic prioritizes winning regardless where the ghosts are. It will avoid all actions from getting a loss unless if it is trapped. """ "*** YOUR CODE HERE ***" ghostScaredTimes = [ghosts.scaredTimer for ghosts in currentGameState.getGhostStates()] if(ghostScaredTimes[0] > 0): return ghostScaredTimes + currentGameState.getScore() if(currentGameState.isLose()): return -(float("inf")) elif(currentGameState.isWin()): return float("inf") else: return currentGameState.getScore() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined()
ad5db63a06a6274c13120b7a6b36c343b33002f8
bermec/challenges
/re.test.py
507
3.546875
4
import re ''' words = '*-5=3-8*-5' # pick out a neg number preceded by an operator ans = re.findall('([^\d](-\d)[^\d](\d)[^\d](\d))|(^\d](-\d))', words) ans2 = re.findall('[^\d](-\d)|(\d)', words) print(ans) print(ans2) ''' words = '*-5+4-3' ans3 = re.findall('\W(-\d)|(\d)', words) print('ans3: ', ans3) strng = '' for x in range(0, len(ans3)): for y in range(0, 2): temp = ans3[x][y] if temp != '': strng += temp + ',' s = strng.split() print(s) print(s[0], s[1], s[2])
104294d02998d058cff093f3accdf43d3b8dc0ea
zhawj159753/PythonEveryday
/0006/frequency.py
597
3.6875
4
# coding = utf-8 import re def read_file(path): f = open(path) return f.read() def get_all_words(string): words = re.findall(r'[a-zA-Z]+\b', string) return words def get_frequent_word(words): word_dic = {} for word in words: if word in word_dic: word_dic[word] += 1 else: word_dic[word] = 1 reverse = {} for key in word_dic: reverse[word_dic[key]] = key times = max(reverse) word = reverse[times] return times, word if __name__ == '__main__': txt = read_file(raw_input('input the txt: ')) times, word = get_frequent_word(get_all_words(txt)) print word , ':', times
058b0855068574fab8994ad483dc4fbf9486e2fc
tengr/Algorithms
/LeetCode/303.Range-Sum-Query-Immutable.py
1,069
3.625
4
class NumArray(object): def __init__(self, nums): """ initialize your data structure here. :type nums: List[int] """ self.nums = nums self.sums = [None for x in xrange(len(nums) + 1)] def sumRange(self, i, j): """ sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int """ if j < i: return 0 if j == i: return self.nums[j] if self.sums[j + 1] is not None: return self.sums[j + 1] - self.sums[i] self.sums[0] = 0 #sum[i] := sums from nums[0] to nums[i-1] for ii in xrange(1, len(self.sums)): self.sums[ii] = self.nums[ii-1] + self.sums[ii-1] print self.sums return self.sums[j + 1] - self.sums[i] # Your NumArray object will be instantiated and called as such: numArray = NumArray([-2,0,3,-5,2,-1]) print numArray.sumRange(0, 2) print numArray.sumRange(2, 5) print numArray.sumRange(0, 5)
539cbacc92c44078b6b6852e25807ffc47454c11
iampaavan/Pure_Python
/Exercise-72.py
712
3.640625
4
"""Write a Python program to get a directory listing, sorted by creation date.""" from stat import S_ISREG, ST_CTIME, ST_MODE import os, sys, time # Relative or absolute path to the directory dir_path = sys.argv[1] if len( sys.argv ) == 2 else r'.' # all entries in the directory w/ stats os.chdir('C:\\Users\\Paavan Gopala\\Desktop\\OS-Demo\\New Folder') data = (os.path.join( dir_path, fn ) for fn in os.listdir( dir_path )) data = ((os.stat( path ), path) for path in data) # regular files, insert creation date data = ((stat[ST_CTIME], path) for stat, path in data if S_ISREG( stat[ST_MODE] )) for cdate, path in sorted( data ): print( time.ctime( cdate ), os.path.basename( path ) )
65c159f0162be7118153d0386c472f799fd134d6
leopoldmiao/PythonDemo
/src/subclassTest.py
2,564
3.546875
4
#coding=utf-8 class InventoryItem(object): def __init__(self, title, description, price, store_id): self.title = title self.description = description self.price = price self.store_id = store_id def __str__(self): return self.title def __eq__(self, other): if self.store_id == other.store_id: return True else: return False def change_description(self, description = ""): if not description: description = raw_input("Please give me a description: ") self.description = description def change_price(self, price = -1): while price<0: price = raw_input("Please give me the new price [x.xx]: ") try: price = float(price) break except: print "I'm sorry. but {} is not valid.".format(price) self.price = price def change_title(self, title = ""): if not title: title = raw_input("Please give me a new title:") self.title = title class Software(InventoryItem): def __init__(self, title, description, price, store_id, os, ESRB): super(Software,self).__init__(title = title, description = description, price = price, store_id = store_id) self.os = os self.ESRB = ESRB def __str__(self): software_info = "{} for {} with {}".format(self.title, self.os, self.ESRB) return software_info def __eq__(self, other): if self.title == other.title and self.os == other.os and self.ESRB == other.ESRB: return True else: return False def change_os(self,os = ""): if not os: os = raw_input("Please give me the osinfo:") self.os = os def change_ESRB(self,ESRB = ""): if not ESRB: ESRB = raw_input("Please give the ESRB:") self.ESRB = ESRB def main(): pycharm = Software(title = "pycharm", description="a python IDE", price=5, store_id= "55555555", os="windows", ESRB="A") pycharm2 = Software(title="pycharm", description="a python IDE", price=20, store_id="1111111", os="windows",ESRB="A") pyIDE = Software(title = "pycharm", description="a python IDE", price=20, store_id= "6666666", os="linux", ESRB="B") print pycharm print pycharm2 print pyIDE print pycharm == pycharm2 print pycharm == pyIDE pycharm2.change_os() print pycharm2 pyIDE.change_ESRB() print pyIDE if __name__ == "__main__": main()
369b988a796a48aef91baebab6762e8619eacd1f
xettrisomeman/pythonsurvival
/listcompre/conditional_inclu.py
659
4.1875
4
#include positive number only #HARD WAY num_list = [1,-1,2,-2,5,-7] pos_list = [] for i in num_list: if i>0: #include positive numbers only pos_list.append(i) #append each positive number print(pos_list) #print [1,2,5] #EASY WAY #if, else in list comprehension #syntax: [value+1 if value>0 else value+2 for value in range] #it means add each value to 1 if the range value is greater than 0 else add each value to 2 #print all i which is greather than 0 hos_list = [i for i in num_list if i>0] print(hos_list) #advanced #add 1 to i if i is greater than 0 #else add 2 to i hos_list = [i+1 if i>0 else i+2 for i in num_list ] print(hos_list)
8223230f67ae686185f0f011441c83f2b8aed713
SylvainGuieu/path
/api.py
5,009
3.546875
4
import os from .dfpath import fpath,dpath def exists(path): """Test whether a path exists. Returns False for broken symbolic links""" if isinstance(path, (fpath, dpath)): return path.exists() return os.path.exists(path) def splitext(path): """Split the extension from a pathname. Extension is everything from the last dot to the end, ignoring leading dots. Returns "(root, ext)"; ext may be empty. """ if isinstance(path, (fpath, dpath)): return path.splitext() return os.path.splitext(path) def basename(p): """Returns the final component of a pathname""" if isinstance(path, fpath): fpath(path.directory, *os.path.split()) def walk(top, func, arg): """Directory tree walk with callback function. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), call func(arg, dirname, fnames). dirname is the name of the directory, and fnames a list of the names of the files and subdirectories in dirname (excluding '.' and '..'). func may modify the fnames list in-place (e.g. via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common. """ if isinstance(top, dpath): return dpath.walk(func, arg) os.path.walk(top, func, arg) def expanduser(p): """Expand ~ and ~user constructions. If user or $HOME is unknown, do nothing. """ if isinstance(p, (fpath,dpath)): return p.expanduser() return os.path.expanduser(p) def getmtime(p): """Return the last modification time of a file, reported by os.stat().""" if isinstance(p, (fpath,dpath)): return p.getmtime() return os.path.getmtime(p) def getatime(): """Return the last access time of a file, reported by os.stat().""" if isinstance(p, (fpath,dpath)): return p.getatime() return os.path.getatime(p) def getctime(): """Return the metadata change time of a file, reported by os.stat().""" if isinstance(p, (fpath,dpath)): return p.getctime() return os.path.getctime(p) def dirname(p): """Returns the directory component of a pathname""" if isinstance(p,(fpath,dpath)): return p.dirname() return os.path.dirname(p) def isfile(p): """Test whether a path is a regular file""" if isinstance(p, fpath): return p.check() if isinstance(p, dpath): return False return os.path.isfile(p) def isdir(p): """Return true if the pathname refers to an existing directory.""" if isinstance(p, dpath): return p.check() if isinstance(p, fpath): return False return os.path.isfile(p) def getsize(p): """Return the size of a file, reported by os.stat().""" if isinstance(p, (fpath,dpath)): return p.getsize() return os.path.getsize(p) def abspath(p): """Return an absolute path.""" if isinstance(p, (fpath,dpath)): return p.path return os.path.abspath(p) def islink(p): """Test whether a path is a symbolic link""" return os.path.islink(p) def split(p): """Split a pathname. Returns tuple "(head, tail)" where "tail" is everything after the final slash. Either part may be empty. """ if isinstance(p, (fpath,dpath)): return p.psplit() return os.path.split(p) def samefile(p1,p2): """Test whether two pathnames reference the same actual file""" if isinstance(p, (fpath,dpath)): return p1.directory == p2.directory and\ p1 == p2 return os.path.samefile def expandvars(p): """Expand shell variables of form $var and ${var}. Unknown variables are left unchanged.""" if isinstance(p, (fpath,dpath)): return p.expandvars() return os.path.expandvars(p) def join(a, *p): """Join two or more pathname components, inserting '/' as needed. If any component is an absolute path, all previous path components will be discarded. An empty last part will result in a path that ends with a separator. """ if isinstance(a, dpath): return a.cd(*p) return os.path.join(a,*p) def normpath(p): """Normalize path, eliminating double slashes, etc.""" if isinstance(p, (fpath,dpath)): return p.normpath() return os.path.normpath(p) isabs = os.path.isabs commonprefix = os.path.commonprefix lexists = os.path.lexists samestat = os.path.samestat ismount = os.path.ismount sameopenfile = os.path.sameopenfile splitdrive = os.path.splitdrive relpath = os.path.relpath realpath = os.path.realpath
93cb5a731b8f5636b42a384e39544db29ca85881
xsl521/Assignment
/Prj01-1.py
357
3.65625
4
import numpy as np def is_prime(a): r=a%np.arange(2,a) return np.all(r!=0) def search(): counter=1;record=(None,None) for i in range(1000,1000000): if is_prime(i): if is_prime(i+2): record=(i,i+2) counter+=1 print('{}:\t{}'.format(counter,record)) search()
8b81d2945fb078808234c72a851d3f777462c476
Huijiny/TIL
/algorithm/kakao/4.py
1,412
3.6875
4
import heapq def change_adj(trap_num, adj): for i in range(len(adj)): if adj[trap_num][i]: adj[trap_num][i], adj[i][trap_num] = adj[i][trap_num], adj[trap_num][i] for i in range(len(adj)): if adj[i][trap_num]: adj[trap_num][i], adj[i][trap_num] = adj[i][trap_num], adj[trap_num][i] return adj def dijstra(start, distance, adj, traps): q = [] distance[start] = 0 heapq.heappush(q, (0, start)) while q: w, node = heapq.heappop(q) print(node) if node in traps: adj = change_adj(node, adj) for end_node in range(len(adj[node])): weight = adj[node][end_node] if weight == 0: continue next_weight = weight + distance[node] if distance[end_node] > next_weight: distance[end_node] = next_weight heapq.heappush(q, (next_weight, end_node)) print(q) return distance def solution(n, start, end, roads, traps): INF = float('inf') distance = [INF for _ in range(n+1)] adj = [[0] * (n+1) for _ in range(n+1)] for road in roads: adj[road[0]][road[1]] = road[2] print(adj) distance = dijstra(start, distance, adj, traps) answer = distance[end] print(answer) print(distance) return answer solution(4, 1, 4,[[1, 2, 1], [3, 2, 1], [2, 4, 1]], [2, 3])
512196dcfc9fe61ab8be2ce2e982e7f70231a0dd
Abarthra/Protothon01
/permutations.py
205
3.78125
4
from itertools import permutations def Permutations(string): permList=permutations(string) for perm in permList: print(''.join(perm)) string='Protosem' Permutations(string)
ee27305ea4a56f2e282de366e26592766e239b7b
anuragpatil94/coursera-python
/Lists/lists1.py
290
3.71875
4
#fname = raw_input("Enter file name: ") fh = open("romeo.txt") lst = list() i=0 for line in fh: line.rstrip() x=line.split() for i in range(len(x)): print x[i] if x[i] not in lst: lst.append(x[i]) #lst.append(x[0]) lst.sort() print lst
877415dd41813f7419546597316d485822a58b3c
Ved005/project-euler-solutions
/code/sum_of_a_square_and_a_cube/sol_348.py
831
3.671875
4
# -*- coding: utf-8 -*- ''' File name: code\sum_of_a_square_and_a_cube\sol_348.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #348 :: Sum of a square and a cube # # For more information see: # https://projecteuler.net/problem=348 # Problem Statement ''' Many numbers can be expressed as the sum of a square and a cube. Some of them in more than one way. Consider the palindromic numbers that can be expressed as the sum of a square and a cube, both greater than 1, in exactly 4 different ways. For example, 5229225 is a palindromic number and it can be expressed in exactly 4 different ways: 22852 + 203 22232 + 663 18102 + 1253 11972 + 1563 Find the sum of the five smallest such palindromic numbers. ''' # Solution # Solution Approach ''' '''
8a5b8d91457b75159eb3df09f02db3aab7d0ceb1
aishwaryabhalla/mapquest_api
/outputs.py
2,531
3.734375
4
"""implements various outputs as a separate class""" import api_interactions class steps: ''' information about steps taken from api_interactions ''' def output(self, json): ''' prints out steps info ''' print() print("DIRECTIONS:") for line in api_interactions.steps_parse(json): print(line) class totaldistance: ''' information about total distance taken from api_interactions ''' def output(self, json): ''' prints out total distance info ''' print() distance = round(api_interactions.distance_parse(json)) print("TOTAL DISTANCE:", distance, "miles") class totaltime: ''' information about total time taken from api_interactions ''' def output(self, json): ''' prints out total time info ''' print() time = round((api_interactions.time_parse(json))/60) print("TOTAL TIME:", time, "minutes") class latlong: ''' information about latitude/longitude taken from api_interactions ''' def output(self, json): ''' prints out latitude/longitude info ''' print() print("LATLONGS") tup_list = api_interactions.latlongs_parse(json) for tup in tup_list: if tup[0] < 0 and tup[1] < 0: print(round(tup[0], 2), "S", round(tup[1], 2), "W") elif tup[0] < 0 and tup[1] > 0: print(round(tup[0], 2), "S", round(tup[1], 2), "E") elif tup[0] > 0 and tup[1] < 0: print(round(tup[0], 2), "N", round(tup[1], 2), "W") elif tup[0] > 0 and tup[1] > 0: print(round(tup[0], 2), "N", round(tup[1], 2), "E") class elevation: ''' information about elevation taken from api_interactions ''' def output(self, json): ''' prints out elevation info ''' print() print("ELEVATIONS") url_list = api_interactions.elevation_url(api_interactions.latlongs_parse(json)) for every_url in url_list: elev_json = api_interactions.url_to_json(every_url) elevation = api_interactions.elevations_parse(elev_json) for height in elevation: print(round(int(height)*3.28084), "feet") def read_outputs(output_list: list, json: 'json') -> None: '''duck-typing for classes so that all classes go through output''' for output_str in output_list: output_str.output(json) return None
44b866b67043ed6894734f4cf5d0f44ac669a5c8
MrVeshij/Michael-Dawson
/_Chapter_9_ACTIVE_USE_CLASSES/simple_game.py
520
3.859375
4
import games, random print("Welcome to simple game!\n") again = None while again != 'n': players = [] num = games.ask_number(question = 'How much player play? (2-5): ', low = 2, high = 6) for i in range(num): name = input('Name player: ') score = random.randrange(100) + 1 player = games.Player(name, score) players.append(player) print('\nIt results games:') for player in players: print(player) again = games.ask_yes_no('\nWould you play agin? (y/n): ')
1d18d32c9a102cf04d770a817b5186c97a9ab33d
s-kyum/Python
/ch05/lambda_exp/lambda_ex4(map).py
306
3.921875
4
#map() - 값을 매핑(맞춰서 계산) li = [1,2,3,4,5] li2 = map(lambda x : x*3, li) #map(함수,자료형) print(list(li2)) print((list(map(lambda x : x*3,li)))) #filter() - 어떤 조건으로 값을 필터링 li3 = filter(lambda x : x <4,li) print(list(li3)) print(list(filter(lambda x : x<4,li)))
0fdade07c2cd2f7202cafbf6a1e17b60c3766bfb
EduardoSantos7/Algorithms4fun
/Cracking_the_coding_interview/Linked list/2.6 Palindrome/solution2.py
607
3.609375
4
# Iterative approach def iterate_and_compare(items): if len(items) == 1: return True mid = len(items) // 2 stack = [] for i in range(mid): stack.append(items[i]) start = mid if not len(items) % 2 else mid + 1 for i in range(start, len(items)): if items[i] != stack.pop(): return False return True print(iterate_and_compare([1, 2, 3, 3, 2, 1])) # True print(iterate_and_compare([1, 2, 3, 2, 4])) # False print(iterate_and_compare([1, 2, 3, 2, 1])) # True print(iterate_and_compare([1])) # True print(iterate_and_compare([])) # True
e5a2f4f647647d8f44293cfbab8eed1f37dfa139
jassler/dailycodingproblems
/problem_002/jassler.py
518
3.53125
4
def with_division(input: list): result = [] product = 1 zeros = 0 for x in input: if x is 0: zeros += 1 else: product *= x if zeros == 0: for x in input: result.append(product / x) elif zeros == 1: for n in input: if n == 0: result.append(product) else: result.append(0) else: result = [0] * len(input) return result # TODO single pass
21117c34ce099935032224aa80560e86a3e4beb0
kotternaj/py-exercises
/dist_slope.py
621
3.9375
4
class Line: def __init__(self, coor1, coor2): self.coor1 = coor1 self.coor2 = coor2 # d is sqrt of (x2-x1)^2 + (y2-y1)^2 def distance(self): return ((self.coor2[0] - self.coor1[0])**2 + (self.coor2[1] - self.coor1[1])**2) **.5 # slope is y2 - y1 / x2 - x1 def slope(self): x1,y1 = self.coor1 x2,y2 = self.coor2 return 1.0 * (y2 - y1) / (x2 - x1) # return (self.coor2[1] - self.coor1[1]) / (self.coor2[0] - self.coor1[0]) c1 = (3,2) c2 = (8,10) li = Line(c1, c2) # li.distance is 9.43398... # li.slope is 1.6 print(li.distance()) print (li.slope())
dcb36d80190c57a56cf9b9617b4950ec0ba39745
ndenefe/python
/MATH_3315/Lecture/examples/feb_3.py
1,824
3.8125
4
#Feb 3, lecture #example: find the smallest integer n such that #1**3 + 2**3 + 3**3 + ... + n**3 < 10**6 #solution 1: use for loop s = 0 for i in range(1, 100): s += i**3 if (s >= 10**6): print('largest n=', i-1) s -= i**3 break #this is an important command to break out of loop #print ('i=', i) print('s=',s) #solution 2: use while loop s=0; i=1 while s < 10**6 - i**3: s += i**3 i += 1 print(s) #a bug of extra n=45 which violate s <10**6 s=0; i=1 while s < 10**6: s += i**3 i += 1 if (s> 10**6): s -= (i-1)**3 print(s) #a bug of extra n=45 which violate s <10**6 s=0; i=1 while i < 100: if (s + i**3 < 10**6): s += i**3 else: break i += 1 print(s) s=0; i=1 while i < 100: s += i**3 if s > 10**6: s -= i**3 break i += 1 print(s) #this fixed the bug of extra n=45 above #use while loop to print out all integers n such that # 100 < n**3/n**(1/2) <10**4 n = 1 while n < 10**4: if 100 < n**3/n**(0.5) < 10**4: print ('n=', n) if n**3/n**(0.5) >= 10**4: break n += 1 ##find all the integers n such that # 10**6 <= 2**2 + 4**4 + 6**6 + ... (2*n)**n <= 10**90 s = 0; nlist = [] for i in range(2, 100, 2): #use step length==2 s += i**i if (s >= 10**6) and (s <= 10**90): nlist.append(i/2) if (s > 10**90): break nlist s = 0; nlist2 = [] for i in range(1, 100): #use step length==1 s += (2*i)**(2*i) if (s >= 10**6) and (s <= 10**90): nlist2.append(i) if (s > 10**90): break nlist2
26bdb07e3fd53d10c5b0fff8b73b55a940549f8d
renzowesterbeek/phonebook
/phonebook.py
1,151
3.90625
4
# Define lists, dicts, functions etc. f = open('phonedata.txt', 'r') book = eval(f.readline()) menu = ['A - Add a person/number', 'D - Delete a person/number', 'P - Print out phonebook'] # Print functions def printNames(dic): print "Names in book: " for i in sorted(book): print i def printContent(dic): print "Phonebook content: " for name, phone in sorted(dic.iteritems()): print name + " : " + phone def printMenu(list): print "What do you want to do?" for i in menu: print i # Menu functions def computeMenu(userInput): if userInput == "a" or userInput == "d" or userInput == "p": if userInput == "a": addItem() elif userInput == "d": delItem() else: printContent(book) else: print "You didn't make a choise..." # Functions of menu actions def addItem(): name = raw_input("Name: ") number = raw_input("Number: ") book[name] = number print "" printContent(book) def delItem(): name = raw_input("Name: ") if name in book: del book[name] printContent(book) else: print "This name isn't in the book" # Start of main program printMenu(menu) menuInput = raw_input("").lower() computeMenu(menuInput)
f729053d9cd8d2bdcd1d64322d3fdbcc0e4e2ec6
hmc-koala-f17/CTCI-Edition-6-Solutions-in-Python
/Array_Strings/string_permutation.py
471
3.734375
4
# Cracking the Coding interview Problems # find all permutation of the string def permutation(remaining,prefix=""): remaining = list(remaining) if(len(remaining)==1): return list(remaining) else: permutations = [] for i,_ in enumerate(remaining): tmp_set = [] prefix = remaining[i] rem = remaining[0:i]+remaining[i+1:] tmp_per = permutation(rem,prefix) for e in tmp_per: tmp_set.append(prefix+e) permutations+=tmp_set return permutations
bd1bde36921395521fa4be79bb89e56859f598dc
Raghu1505/guvi-task
/uber billing.py
1,528
4.28125
4
print("Welcome to uber services!!!") sp= int(input("Enter starting point in km")) #user input for starting point in integer dp= int(input("Enter destination point in km")) #user input for destination point in integer dist=dp-sp #computing total distance print("1.Two wheeler") print("2.Car") print("3.Auto") ch = (input("Enter your choice of travel")) #getting user choice if(ch=="1" or ch=="Two wheeler"): amount=5*dist #two wheeler cost per km is 5 print("-------Billing Info-------") print("starting point is ",sp) print("destination point is ",dp) print("Total distance is ",dist) print("Total amount to be paid",amount) print("Enjoy your Ride") elif(ch=="2" or ch=="Car"): amount=9*dist #cab per km is 5 print("------Billing Info-------") print("starting point is ",sp) print("destination point is ",dp) print("Total distance is ",dist) print("Total amount to be paid",amount) print("Enjoy your Ride") elif(ch=="3" or ch=="Auto"): amount=12*dist #Auto km is 5 print("------Billing Info-------") print("starting point is ",sp) print("destination point is ",dp) print("Total distance is ",dist) print("Total amount to be paid",amount) print("Enjoy your Ride") else: print("Enter a valid input")
08af8e9f93505bf0e1123119d3694cef1f693f7c
lulalulala/leetcode
/1--50/49. Group Anagrams.py
842
3.9375
4
""" Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] """ class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ rlist = [] for i in strs: n = list(i) n.sort() rlist.append(n) rlist_1 = enumerate(rlist) list_1 = [] list_2 = [] for key in rlist_1: if key[1] not in list_1: list_1.append(key[1]) list_2.append([strs[key[0]]]) else: for m in range(len(list_1)): if list_1[m] == key[1]: list_2[m].append(strs[key[0]]) return list_2
3f68c25a3a368433bdb393c0b516842dfc09d467
MathieuPinger/PythonSpielwiese
/pycourse_chap8_functions.py
1,968
4
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 15 15:13:07 2020 @author: mathieu.pinger """ # Function with optional arguments # '' and none create optional arguments # None acts as a logical False def name_infos(first_name, last_name, middle_name='', age=None): info = {'first': first_name, 'last': last_name, 'middle': middle_name} if age: info['age'] = age return(info) PI = name_infos('Peter', 'Kirsch', age=50) print(PI) # local vs global variables # in Python, variables passed to functions can be globally changed # if not desired, use [:] for slice copy def create_stuff(letters, numbers): stuff = {'letters': letters, 'numbers': numbers} return(stuff) # local variable: without return, nothing happens # slicing when variables are changed by the function # This function removes elements from the first list: not_preprocessed = ['VP_1', 'VP_2', 'VP_3'] preprocessed = [] def preprocessing(to_process, processed_list): while to_process: current_VP = to_process.pop() processed_list.append(current_VP) print(f"Preprocessing: {current_VP}.") preprocessing(not_preprocessed, preprocessed) # Using slicing, the first list stays untouched: not_preprocessed = ['VP_1', 'VP_2', 'VP_3'] preprocessed = [] preprocessing(not_preprocessed[:], preprocessed) # arbitrary number arguments creates tuples def make_pizza(dough, cheese, *toppings): print("You ordered the following pizza:") print(f"\n{dough.title()} dough, {cheese} cheese,") for topping in toppings: print(f"- {topping}") make_pizza('italian', 'cheddar', 'tuna', 'bulgur', 'toenails') # arbitrary keyword arguments create dictionaries def make_pizza_dict(dough, cheese, **pizza_info): pizza_info['dough'] = dough pizza_info['cheese'] = cheese return(pizza_info) pizza_orders = make_pizza_dict('Italian', 'Cheddar', fish='tuna', fruit='olives') print(pizza_orders)
e3bd13a1f2265a4736130e0d35a7c7a4bfed29d6
WangXiaoyugg/python-journey
/demo/decorator.py
825
3.765625
4
# 装饰器 import time def decorator(func): def wrapper(*args,**kw): print(time.time()) func(*args,**kw) return wrapper # 装饰器没有改变函数原来的调用方式 # 装饰器利用可变参数,解决参数不一致的问题 # 不知道参数是什么,抽象用 *args,**kw @decorator def f1(func_name): print('this is a function ' + func_name) # f = decorator(f1) # f() @decorator def f2(func_name1,func_name2): print('this is a function ' + func_name1) print('this is a function ' + func_name2) @decorator def f3(func_name1,func_name2,**kw): print('this is a function ' + func_name1) print('this is a function ' + func_name2) print(kw) f1('func1') f2('func1','func2') f3('test func1','test func2',a=1,b=2,c='123') # flask @api.route 验证身份
ee0f7ff820065c43058b9d2f3ebe0818ae84528a
Letris/Encoding2
/Ceasar Cypher.py
2,251
3.875
4
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m', 'n','o','p','q','r','s','t','u','v','w','x','y','z'] text = 'move your troops to the designated location' encryption_letter_move = 13 decryption_letter_move = 13 def encrypt(message): encrypted_text = '' for letter in message: if letter == ' ': encrypted_text += ' ' else: for index in range(len(alphabet)): current_index = index current_letter = alphabet[index] if letter == current_letter and current_letter != 'z': new_index = current_index + encryption_letter_move if new_index >= len(alphabet) - 1: difference = new_index - len(alphabet) newer_index = 0 + difference new_letter = alphabet[newer_index] encrypted_text += new_letter else: new_letter = alphabet[new_index] encrypted_text += new_letter elif letter == current_letter and letter == 'z': new_index = encryption_letter_move -1 newer_letter = alphabet[new_index] final_letter = newer_letter encrypted_text += final_letter print encrypted_text return encrypted_text def decrypt(message): decrypted_text = '' for letter in message: if letter == ' ': decrypted_text += ' ' else: for index in range(len(alphabet)): current_index = index current_letter = alphabet[index] if letter == current_letter and letter != 'a': new_index = current_index - decryption_letter_move new_letter = alphabet[new_index] decrypted_text += new_letter elif letter == current_letter and letter == 'a': new_index = len(alphabet) - decryption_letter_move decrypted_text += alphabet[new_index] print decrypted_text encrypted_text = encrypt(text) decrypt(encrypted_text)
5d9338af5b916b7f27bb56cdc6c87db80c1b7fff
Wafflya/python_pract
/brain_games/service.py
1,271
3.703125
4
import random import prompt def ask_question(question): print(f"Question: {question}") answer = prompt.string('Your answer: ') return answer def check_answer(answer, right_answer, name): if answer == right_answer: print("Correct!") return True else: print(f"'{answer}' is wrong answer ;(. Correct answer was " f"'{right_answer}'.\nLet's try again, {name}!") return False def find_gcd(x, y): """ Простая рекурсивная функция нахождения НОД двух чисел. Да, с циклом быстрее. Да, есть math.gcd. """ if y == 0: return x else: return find_gcd(y, x % y) def create_progression(): start = random.randint(1, 100) step = random.randint(-10, 10) result_progression = [str(start + step * i) for i in range(10)] deleted_index = random.randint(0, 9) deleted_element = result_progression[deleted_index] result_progression[deleted_index] = ".." return " ".join(result_progression), deleted_element def isprime(num): if num > 1: for n in range(2, num // 2 + 1): if num % n == 0: return "no" return "yes" else: return "no"
6d380a1df7357839519d29e23a6cf5397246b135
bksahu/dsa
/dsa/patterns/k_way_merge/k_pairs_with_largest_sum.py
2,098
4.15625
4
""" Given two sorted arrays in descending order, find ‘K’ pairs with the largest sum where each pair consists of numbers from both the arrays. Example 1: Input: L1=[9, 8, 2], L2=[6, 3, 1], K=3 Output: [9, 3], [9, 6], [8, 6] Explanation: These 3 pairs have the largest sum. No other pair has a sum larger than any of these. Example 2: Input: L1=[5, 2, 1], L2=[2, -1], K=3 Output: [5, 2], [5, -1], [2, 2] """ from heapq import heappush, heappop # # TC: O(M*NlogK) SP: O(K) # def find_k_largest_pairs(num1, num2, k): # ret = [] # minHeap = [] # for i in range(len(num1)): # for j in range(len(num2)): # if len(minHeap) < k: # heappush(minHeap, (num1[i] + num2[j], num1[i], num2[j])) # else: # if num1[i] + num2[j] < minHeap[0][0]: # break # else: # heappop(minHeap) # heappush(minHeap, (num1[i] + num2[j], num1[i], num2[j])) # for _, i, j in minHeap: # ret.append([i, j]) # return ret def find_k_largest_pairs(num1, num2, k): """ TC: O(K) SP: O(K) Convert the arrays into a matrix and use BFS L1=[9, 8, 2], L2=[6, 3, 1], K=3 | 6 3 1 ------------------- 9 | 15 12 10 8 | 14 11 9 2 | 8 5 3 """ ret = [] if len(num1) * len(num2) > 0: maxHeap = [(-num1[0] - num2[0], (0, 0))] visited = {} while len(ret) < k and maxHeap: _, (i, j) = heappop(maxHeap) ret.append([num1[i], num2[j]]) if i+1 < len(num1) and (i+1, j) not in visited: heappush(maxHeap, (-num1[i+1] - num2[j], (i+1, j))) visited[(i+1, j)] = 1 if j + 1 < len(num2) and (i, j + 1) not in visited: heappush(maxHeap, (-num1[i] - num2[j + 1], (i, j + 1))) visited[(i, j + 1)] = 1 return ret if __name__ == "__main__": print(find_k_largest_pairs([9, 8, 2], [6, 3, 1], 3)) print(find_k_largest_pairs([5, 2, 1], [2, -1], 3))
ba1ad681208acacd47a6c40fe06f748542687572
trangnth/hoc_python
/Code/Lab/300718/bai2.py
398
4.375
4
# Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself. Go to the editor # Sample String : 'restart' # Expected Result : 'resta$t' def convert_str(stri): ch = stri[0] stri = stri.replace(ch, '$') stri = ch + stri[1:] return stri stri = input("Enter your string:") print(convert_str(stri))
bbbcbcd4c6b6ae894163fdc9b39c96c9297c5ef8
kenji132/AtCoder
/2022/11-05/ABC276/A.py
99
3.5
4
S = list(input()) cnt = 0 ans = -1 for s in S: cnt += 1 if s == "a": ans = cnt print(ans)
fb4b284b16e81054e751fadee879dadd4439c6f4
marcusorefice/-studying-python3
/Exe027.py
320
3.921875
4
'''Desafio 027 Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o último nome separadamente. Ex.: Ana Maria de Souza Primeiro = Ana Último = Souza''' n = input('Digite seu nome completo: ').strip() m = n.split() print(f'O primeiro nome é: {m[0]} \nO ultimo nome é: {m[-1]}')