blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
6d6f43a664218851da589bd35209e32221085cd2
ntkaggarwal/Two-Pointers-2
/Search_2D_matrixII.py
1,068
3.828125
4
#Time Complexity : O(m+n) #Space Complexity : O(1) #Did this code successfully run on Leetcode : Yes #Any problem you faced while coding this :None # ============================================================================= # Solution: Start from a corner which is increasing in one direction and decreasing in other direction, so that if target is less #than that number, then move in decreasing direction, else move in increasing direction. If you out of bounds, meaning target doesn't exist else return True. # ============================================================================= class Solution: def searchMatrix(self, matrix, target): if matrix is None or len(matrix) == 0: return False ht = len(matrix) width = len(matrix[0]) row = ht -1 col = 0 while col < width and row >=0: if target < matrix[row][col]: row -= 1 elif target > matrix[row][col]: col += 1 else: return True return False
c3634a25b84548821150df641d54187a2e8d41c2
eber-kachi/scripts_servidores
/agregarUnaPc.py
617
3.640625
4
######## ejemplo para dar ip a una maquina # host windows7-pc { # hardware ethernet 00:0c:29:e6:75:b9; # fixed-address 192.168.50.20; # } print("para saber cual es mi mac addres en otra PC (ifconfig | grep ether)") print("dijite la mac de la PC que desea agregar") mac=input() print("nombre de la pc (pc1)") nombre=input() print("ip para esa maquina ") ip=input() dhcpd = open("/etc/dhcp/dhcpd.conf","a") dhcpd.write('host {0} {1}\n'.format(nombre,chr(123))) dhcpd.write('hardware ethernet {0} ;\n'.format(mac)) dhcpd.write('fixed-address {0} ;\n'.format(ip)) dhcpd.write('}\') dhcpd.close()
5c45f5892ea0ff74668914a3371e7f175a097b0d
CStrue/python-ai
/neuralNetwork.py
5,152
3.609375
4
#!/bin/usr/python # -*- coding: utf-8 -*- import numpy import scipy.special import matplotlib.pyplot #neural network class definition class neuralNetwork: #initialise the neural network def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate): #set number of nodes in each inout, hidden, output layer self.inodes=inputnodes self.hnodes=hiddennodes self.onodes=outputnodes #learning rate self.lr=learningrate #gewichtsmatrizen wih and who #weigths im array w_i_j, wo der link von node i zu node j im nächsten layer geht #w11 w21 w31 etc #w12 w22 w32 etc #w13 w23 w33 etc #initialisierung mit 1/Wurzel(Anzahl der eingehenden Verknüfpungen), -0.5 um sicher zu stellen #das alle zahlen zwischen -1 und 1 sind, 0 darf nicht vorkommen. self.wih=numpy.random.normal(0.0, pow(self.hnodes, -0.5), (self.hnodes, self.inodes)) self.who=numpy.random.normal(0.0, pow(self.onodes, -0.5), (self.onodes, self.hnodes)) #activation funtion is the sigmoid function self.activation_function=lambda x: scipy.special.expit(x) pass #train neural netork def train(self, inputs_list, targets_list): #convert inputs into 2D array inputs = numpy.array(inputs_list, ndmin=2).T targets = numpy.array(targets_list, ndmin=2).T #calculate signals into hidden layer hidden_inputs = numpy.dot(self.wih, inputs) #calculate the signals emerging from hidden layer hidden_outputs = self.activation_function(hidden_inputs) #calculate signals into final output layer final_inputs = numpy.dot(self.who, hidden_outputs) #calcualte the signals emerging from final output layer final_outputs = self.activation_function(final_inputs) #error is the (target - actual) output_errors = targets - final_outputs #hidden layer errors is the output_errors, split by weights, recombined at hidden nodes hidden_errors = numpy.dot(self.who.T, output_errors) #update the weights for the links between the hidden and output layers self.who += self.lr * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)), numpy.transpose(hidden_outputs)) #update the weights for the links between the input and hidden layers self.wih += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)), numpy.transpose(inputs)) pass #query neural network def query(self, inputs_list): #convert inputs list to 2d array inputs = numpy.array(inputs_list, ndmin=2).T #calculate signals into hidden layer hidden_inputs = numpy.dot(self.wih, inputs) #calculate the signasl emerging from hidden layout hidden_outputs=self.activation_function(hidden_inputs) #calculate signals into final output layer final_inputs=numpy.dot(self.who, hidden_outputs) #calculate the signals emerging from final output layer final_outputs = self.activation_function(final_inputs) return final_outputs def main(): inputNodes=784 hiddenNodes=200 outputNodes=10 learningRate=0.2 n=neuralNetwork(inputNodes, hiddenNodes, outputNodes, learningRate) epochs = 2 #load the mnist training data #training_data_file = open("/data/mnist_train_100.csv",'r') training_data_file = open("/data/mnist_train.csv",'r') training_data_list = training_data_file.readlines() training_data_file.close() #train the neural network for e in range(epochs): #go tgrough all records in the training data set for record in training_data_list: #split record by ',' commas all_values = record.split(",") #scale and shift the inputs inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01 #create the target output values (all 0.01, except the desired label which i 0.99) targets = numpy.zeros(outputNodes) + 0.01 #all_values[0] us the target label for this record targets[int(all_values[0])] = 0.99 n.train(inputs, targets) pass pass #load the mnist test data csv file into a list #test_data_file = open("/data/mnist_test_10.csv",'r') test_data_file = open("/data/mnist_test.csv",'r') test_data_list = test_data_file.readlines() test_data_file.close() #test the neural_network #scorecard for how well the network performs, initially empty scorecard = [] #go through all the records in the test data set for record in test_data_list: #split the record by the ',' all_values=record.split(",") #correct answer is first values correct_label=int(all_values[0]) print(correct_label, "correct label") #scale and shift the inputs inputs=(numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01 #query the network outputs = n.query(inputs) label=numpy.argmax(outputs) print(label, "network's label") #append correct or incorrect to list if (label == correct_label): #networks answer matches correct answer, add 0 to scrorecard scorecard.append(1) else: #networks answer doesn't match correct answer, add 0 to scorcard scorecard.append(0) pass pass #calculate the performance score, the fraction of correct answers scorecard_array = numpy.asarray(scorecard) print("performance = ", scorecard_array.sum() / scorecard_array.size) if __name__ == '__main__': main()
8551a9e749940d669b7c15ad0f930a2064425c1a
topheadliner/Stepik
/A few tasks.py
3,493
3.859375
4
Напишите программу, которая считывает список чисел lst из первой строки и число xx из второй строки, которая выводит все позиции, на которых встречается число x в переданном списке lst. Позиции нумеруются с нуля, если число xx не встречается в списке, вывести строку "Отсутствует" (без кавычек, с большой буквы). Позиции должны быть выведены в одну строку, по возрастанию абсолютного значения. #РЕШЕНИЕ a=[int(i) for i in input().split()] #генератор списков b=int(input()) #число X e=[] d=-1 for i in a: d+=1 if i==b: e.append(d) if len(e)==0: print('Отсутствует') else: print(' '.join(map(str,e))) Напишите программу, которая выводит часть последовательности 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ... (число повторяется столько раз, чему равно). На вход программе передаётся неотрицательное целое число n — столько элементов последовательности должна отобразить программа. На выходе ожидается последовательность чисел, записанных через пробел в одну строку. Например, если n = 7, то программа должна вывести 1 2 2 3 3 3 4. #ПЕРВОЕ РЕШЕНИЕ: n=int(input()) a=[] if n>2: for i in range(n): a+=[i]*i if len(a)==n: break while True: if len(a)==n: break a.pop(len(a)-1) print(" ".join(map(str, a))) if n==1: print(1) if n==2: print(1,2) if n==0: print() #КАК ПИСАЛ С САМОГО НАЧАЛА И НЕ РАБОТАЛО WHILE TRUE #МАЛО СТРОК, МНОГО ИТЕРАЦИЙ a = int(input()) c = 0 for i in range(a+1): for j in range(i): c += 1 if c<a+1: print(i, end=' ') Загуглил последовательность, у нее оказалась готовая форма для любого элемента и соответственно печатаем его: a(n)=floor(1/2+sqrt(2n))a(n)=floor(1/2+sqrt(2n)) #код: import math x = int(input()) print(*[int( 1/2 + math.sqrt(2 * n) ) for n in range(1, x + 1)]) выводит сумму двух соседних для каждого числа из списка a=[int(i) for i in input().split()] if len(a)==1: print(a[0]) else: for i in range(len(a)-1): print(a[i-1]+a[i+1],end=' ') print(a[len(a)-2]+a[0]) выводит только те числа, что повторяются a=[int(i) for i in input().split()] a.sort() if len(a)!=1: for i in range(len(a)-2): if a[i]==a[i+1] and a[i]!=a[i+2]: print(a[i],end=' ') if a[len(a)-1]==a[len(a)-2]: print(a[len(a)-1]) else: print() принимаем числа по 1 в строке пока сумма введенных не обнулится, после выводим сумму квадратов a=0 b=int(input()) c=b*b while b!=0: a=int(input()) b+=a c+=a*a print(c)
bb04a986834327a073002898027990390b7e66e6
aghotikar/ComputationalBiology
/dummy.py
211
3.625
4
def overlaps1(a, b): for i in range(1, min(len(a), len(b))): if a[-i:] == b[:i]: print(a + b[i:]) def overlaps2(a, b): overlaps1(a, b) overlaps1(b, a) overlaps2('bbb', 'bbab')
9596e52eae1915dda99761693b24efc58d4c0891
destinysam/Python
/concatenation of strings.py
345
3.5625
4
# CODED BY SAM@SMAEER # EMAIL:[email protected] # DATE:11/08/2019 # PROGRAM: CONCATENATION OF STRINGS first_name = "sameer " last_name = "ahmad" address = " from tarigam" college = " studying in cluster university\n " full_name = first_name + last_name + address + college print(full_name) # PRINTING SINGLE TYMZ print(full_name * 3) # PRINTING 3 TYMZZ
d41a8a5147296836010b435c0d3fbc43f012123c
sagnitude/leetcode
/Python/2/AddTwoNumbers.py
1,160
3.703125
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param {ListNode} l1 # @param {ListNode} l2 # @return {ListNode} def addTwoNumbers(self, l1, l2): overflow = 0 val = ListNode(None) handler = val while l1 is not None or l2 is not None: if l1 is None or l1.val is None: v1 = 0 else: v1 = l1.val if l2 is None or l2.val is None: v2 = 0 else: v2 = l2.val r = v1 + v2 + overflow overflow = r / 10 handler.val = r % 10 if l1 is not None: l1 = l1.next if l2 is not None: l2 = l2.next if l1 is not None or l2 is not None: handler.next = ListNode(None) handler = handler.next if overflow != 0: handler.next = ListNode(overflow) handler.next.next = None return val s = Solution() n1 = ListNode(0) n2 = ListNode(0) s.addTwoNumbers(n1, n2)
0dbe7bdd21f1ad72734583356c82368c82110144
darshitpandya18/algorithm-implementations
/RockPaperScissor.py
797
4
4
import random def RNG(): # Function defines, selects and returns the output # of one of those return random.randint(1,3) def check_winner(input_1, input_2): #Checks the winner as per the input 1 an input 2 if input_1 == 1 and input_2 == 2: print("Computer Wins") elif input_1 == 1 and input_2 == 3: print("User Wins") elif input_1 == 2 and input_2 == 1: print("User Wins") elif input_1 == 2 and input_2 == 3: print("Computer Wins") elif input_1 == 3 and input_1 == 1: print("Computer Wins") elif input_1 == 3 and input_1 == 2: print("User Wins") elif input_1 == input_2: print("Draw! Try again") input_1 = int(input("Enter the user input: ")) input_2 = RNG() print("Computer Selected: ", input_2) #1: Rock #2: Paper #3: Scissor check_winner(input_1, input_2)
f1b55a0f351d21af467b93c89e846f487300daa7
SEDarrow/PythonCode
/ScheduleOptions.py
7,426
3.65625
4
class Node(): def __init__(self, data=None, nextNode=None, prevNode=None): self.data = data self.nextNode = nextNode self.prevNode = prevNode def getData(self): return self.data def setData(self, data): self.data = self def getNext(self): return self.nextNode def setNext(self, nextNode): self.nextNode = nextNode def getPrev(self): return self.nextPrev def setPrev(self, nextPrev): self.nextPrev = nextPrev class LinkedList(): def __init__(self): self.first = Node(None) self.last = Node(None, None, self.first) self.first.setNext(self.last) def add(self, data): newNode = Node(data, self.first.getNext(), self.first) self.first.getNext().setPrev(newNode) self.first.setNext(newNode) def append(self, data): newNode = Node(data, self.last, self.last.getPrev()) self.last.getPrev().setNext(newNode) self.last.setPrev(newNode) def insert(self, data, aNode): newNode = Node(data, aNode.getNext(), aNode) aNode.getNext().setPrev(newNode) aNode.setNext(newNode) def getNode(self,index): currNode = self.first for each in range(0, index): currNode = currNode.getNext() return currNode def getLen(self): try: length = len(self.getList()) return length except: return 0 def getList(self): currNode = self.first listForm = [currNode.getData()] while(currNode.getNext().getData() != None): currNode = currNode.getNext() listForm.append(currNode.getData()) return listForm[1:] def __add__(self, other): currNode = other.first while(currNode.getNext().getData() != None): currNode = currNode.getNext() self.append(currNode.getData()) return self class Time(): def __init__(self, string): self.original = string self.hour = int(string[0:2])%12 self.minute = int(string[3:5]) self.name = string[5:7] #am or pm def __str__(self): return self.original class TimePeriod(): def __init__(self, string): self.original = string self.start = Time(string[0:7]) self.end = Time(string[10:17]) def __str__(self): return self.original class Class(): def __init__(self, classType, section): self.number = classType[0] self.name = classType[1] self.days = section[0] self.time = TimePeriod(section[1]) self.room = section[2] self.prof = section[3] def __str__(self): output = str(self.number)+" "+str(self.name)+"\n\t" output+= str(self.days)+'\t'+str(self.time)+'\t'+str(self.room)+'\t'+str(self.prof) return output def getTime(self): return self.time.start.hour def ampm(self): return self.time.start.name def compare(self, other): if(self.getTime()%12 > other.getTime()%12): return 1 if(self.getTime()%12 < other.getTime()%12): return -1 return 0 def sortDays(days): am = LinkedList() pm = LinkedList() added = False for day in days: if(day.ampm() == "am"): if(am.getLen()<=0): am.add(day) else: for i in range(1, am.getLen()+1): if(am.getNode(i).getData().compare(day)>=0): am.insert(day, am.getNode(i-1)) added = True break if not added: am.append(day) added = False else: if(pm.getLen()<=0): pm.add(day) else: for i in range(1, pm.getLen()+1): if(pm.getNode(i).getData().compare(day)>=0): pm.insert(day, pm.getNode(i-1)) added = True break if not added: pm.append(day) added = False #return am.getList()+pm.getList() return (am+pm).getList() def printClasses(classes): Monday = [["Monday:"]] Tuesday = [["Tuesday:"]] Wednesday = [["Wednesday:"]] Thursday = [["Thursday:"]] Friday = [["Friday:"]] for each in classes: for section in classes[each]: if 'M' in section[0]: Monday.append(Class(each, section)) if 'T' in section[0]: Tuesday.append(Class(each, section)) if 'W' in section[0]: Wednesday.append(Class(each, section)) if 'R' in section[0]: Thursday.append(Class(each, section)) if 'F' in section[0]: Friday.append(Class(each, section)) days = [Monday, Tuesday, Wednesday, Thursday, Friday] ScheduleOptions = [] for day in days: #print(day[0]) ScheduleOptions.append(sortDays(day[1:])) #for each in sortDays(day[1:]): #print(each) #print('') return ScheduleOptions #Asks user for classes to search for def getPossibilities(): posibilities = [] entered = ' ' #print("Return when done.") entered = input("Enter a class: ") while entered != '': posibilities.append(entered) entered = input("Enter a class: ") print("") return posibilities def main(): #masterSchedule = input("Enter master schedule file name or return for last entered:") #clear the data of blank lines schedule = open("MasterClassSchedule.txt", 'r') formattedSchedule = open("formatted.txt", 'w') for each in schedule.readlines(): if each != '\n' and each != ' \n': formattedSchedule.write(each) schedule.close() formattedSchedule.close() #save data to a list formattedSchedule = open("formatted.txt", 'r') classList = formattedSchedule.readlines() formattedSchedule.close() possibilities = getPossibilities() #Remove extra formatting for each in range(0, len(classList)): classList[each] = classList[each].strip("\n") classList[each] = classList[each].strip("\t") try: classes = {} index = -1 while(True): index +=1 if classList[index] == "View Textbooks": #find anchor in list if classList[index-1] in possibilities or classList[index-3] in possibilities: #found name of class name = classList[index-1] number = classList[index-3] try: while('-' not in classList[index]): index+=1 while('-' in classList[index]): index+=1 classes[(number, name)].append(classList[index:index+4]) except KeyError: classes[(number, name)] = [classList[index:index+4]] except Exception as ex: #done going through list Options = printClasses(classes) return Options #main()
bbe88f09f50e37049841e8d23bcbee2d7f3b5e78
NathanNNguyen/challenges
/leetcode/shuffle_string.py
1,012
3.890625
4
# Given a string s and an integer array indices of the same length. # The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. # Return the shuffled string. # Example 1: # Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3] # Output: "leetcode" # Explanation: As shown, "codeleet" becomes "leetcode" after shuffling. # Example 2: # Input: s = "abc", indices = [0,1,2] # Output: "abc" # Explanation: After shuffling, each character remains in its position. class Solution: def restoreString(self, s, indices): # make a dict to store k, v as values from indices and s cache = {} for i in range(len(indices)): cache[indices[i]] = s[i] r = '' # use the sorted method on the dict keys to figure out the value for it for k in sorted(cache.keys()): r += cache[k] return r s = 'codeleet' indices = [4, 5, 6, 7, 0, 2, 1, 3] print(Solution().restoreString(s, indices))
2c074079e92d8fb56a935e8c530d9a0fee595b80
patrick-du/python-dsa
/algorithms/recursion.py
1,105
4.03125
4
# Converting an Integer to a String in Any Base def toStr(n, base): convertString = "0123456789ABCDEF" if n < base: return convertString[n] else: return toStr(n//base, base) + convertString[n%base] print(toStr(769,10)) # Write a function that takes a string as a parameter and returns a new string that is the reverse of the old string def reverse(s): if len(s) > 1: s = reverse(s[1:]) + s[:1] return s print(reverse("hellllo dalgjad flg")) # Write a function that takes a string as a parameter and returns True if the string is a palindrome, False otherwise. # A string is a palindrome if it is spelled the same both forward and backward. # For example: radar is a palindrome. Palindromes can also be phrases, but you need to remove the spaces and punctuation before checking. # For example: madam i’m adam is a palindrome. def removeWhite(s): s = s.replace(' ', '') return s def palindrome(s): if len(s) < 2: return True if s[0] != s[-1]: return False return palindrome(s[1:-1]) print(palindrome(removeWhite("racecasdar"))) #
b0851fcee1bf15ec57febe20a8c2581c4e7bea3d
rachel6854/Python-Projects
/python_functions/exercise2.py
246
4.03125
4
def longest_string(string1, string2): if len(string1) > len(string2): return string1 elif len(string2) > len(string1): return string2 else: return "same length" #print(longest_string("helloo","world"))
7205f5faeb43a19f7027b92d6326a0bf534c1af3
anderson-s/Python
/Secao9/atividade5.py
348
3.78125
4
#variaveis vetor = [] aux = False for n in range(0, 10): num = int(input("Digite um valor para o vetor")) vetor.append(num) for n in vetor: if n > 50: print("O número {0} maior que 50 na posição: {1}".format(n, vetor.index(n))) aux = True if aux == False: print("não existem valores maiores que 50")
a67dc63b645232730a78291bde47db4370415a46
rostykusvasyl/StartDragon-m5_lesson5
/task_max/password_check.py
754
4.3125
4
#! /usr/bin/python3 ''' Password Verification Program ''' import re def password_verification(): ''' Check the password entered by the user. ''' print('The password must contain at least one character from' 'the following groups: (a-z), (A-Z), (0-9).') print("Must contain at least one character from the set: (* # @ +).") print("Length: 4 to 6 characters (no spaces).") while True: password = input('Input a strong password: \n') if re.match(r'^(?=.*[0-9].*)(?=.*[a-z].*)(?=.*[A-Z].*)(?=.*[@*#+].*)' r'[0-9a-zA-Z@*#+]{4,6}$', password): print('Very nice password.') break else: print('Not a valid password.') password_verification()
22f7624e2cd54c3c539c1a00d8b343401fd8af46
yanmarcossn97/Python-Basico
/Exercicios/exercicio084.py
1,172
3.640625
4
grupo = [] dados = [] pessmenpeso = [] pessmaipeso = [] cond = '' menpeso = maipeso = 0 while cond != 'N': dados.append(str(input('Nome: '))) dados.append(float(input('Peso(Kg): '))) grupo.append(dados[:]) dados.clear() cond = str(input('\nCadastrar outra pessoas[S/N]? ')).strip().upper()[0] for contd, pessoa in enumerate(grupo): if contd == 0: pessmenpeso.append(pessoa[0]) pessmaipeso.append(pessoa[0]) menpeso = maipeso = pessoa[1] elif pessoa[1] < menpeso: pessmenpeso.clear() pessmenpeso.append(pessoa[0]) menpeso = pessoa[1] elif pessoa[1] == menpeso: pessmenpeso.append(pessoa[0]) elif pessoa[1] > maipeso: pessmaipeso.clear() pessmaipeso.append(pessoa[0]) maipeso = pessoa[1] elif pessoa[1] == maipeso: pessmaipeso.append(pessoa[0]) print(f'Total de pessoas cadastradas: {len(grupo)}') print(f'Menor peso cadastrado: {menpeso} Kg ', end='') for p in pessmenpeso: print(f'{p}', end=', ') print(f'\nMaior peso cadastrado: {maipeso} Kg ', end='') for p in pessmaipeso: print(f'{p}', end=', ')
daee7e883daa846cb144581ec5742fee0364532b
jsutch/Python-Algos
/number_to_string.py
1,868
4.375
4
#!/usr/local/bin/python #Write a program that takes an array of numbers and replaces any number that's negative to a string. For example if array = [-1, -3, 2] after your program is done array should be ['somestring', 'somestring', 2]. my_array = [-3, 3, -50, 10, 14, -2, 21, -4] loop = 0 while loop < len(my_array): num = my_array[loop] if num < 0: my_array[loop] = 'somestring' loop += 1 print(my_array) # slightly more interesting. we'll replace the negative numbers with the "negative <string of num>" output In [212]: numdict = {1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten'} In [213]: my_array = [-3, 3, -4, 10, 6, -2, 9, -4] In [216]: for x in my_array: ...: if x < 0: ...: print('negative',numdict[abs(x)]) ...: negative three negative four negative two negative four In [226]: for x in range(0,len(my_array)): ...: if my_array[x] < 0: ...: my_array[x] = 'negative' + numdict[abs(my_array[x])] ...: In [227]: my_array Out[227]: ['negativethree', 3, 'negativefour', 10, 6, 'negativetwo', 9, 'negativefour'] # and as a function: In [228]: def replace_negatives(arr): ...: numdict = {1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten'} ...: for x in range(0,len(arr)): ...: if arr[x] < 0: ...: arr[x] = 'negative' + numdict[abs(arr[x])] ...: return arr ...: In [229]: myarr Out[229]: [4444, 2222, 53, 32, 26, 90, 57, 44, 61, 81, 38, 15, 69] In [230]: myarr = [random.randint(-10,11) for x in range(20)] In [231]: replace_negatives(myarr) Out[231]: [2, 8, 11, 'negativeeight', 'negativefive', 'negativeeight', 'negativeone', 6, 'negativesix', 9, 10, 5, 'negativefour', 'negativefour', 4, 5, 'negativeeight', 9, 6, 6]
00a5e20233fcf29f7cafaf9acdc18cf97b0ed834
ZhengLiangliang1996/LeetcodePyVersion
/16_WordSearch.py
1,448
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 6 22:58:48 2019 @author: liangliang """ import numpy as np class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ # get 1, then dfs, all the connected 1, mark them as 0 n = len(board) m = len(board[0]) if n == 0: return 0 for i in range(n): for j in range(m): if self.dfs(board, i, j, n, m, word): return True return False def dfs(self, board, x, y, n, m, word): if len(word) == 0: return True if x < 0 or y < 0 or x >= n or y >= m or word[0] != board[x][y]: return False temp = board[x][y] board[x][y] = "#" # avoid visit agian res = self.dfs(board, x + 1, y, n, m, word[1:]) or self.dfs(board, x - 1, y, n, m, word[1:]) or self.dfs(board, x, y + 1, n, m, word[1:]) or self.dfs(board, x, y - 1, n, m, word[1:]) board[x][y] = temp return res def main(): S = Solution() board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] a = S.exist(board, 'ABCED') print(a) if __name__ == '__main__': main()
08dc88202fcc42c598b3946e5717e1840c822b9f
amitshipra/PyExercism
/simple-cipher/cipher.py
1,678
3.546875
4
__author__ = 'agupt15' import string class Caesar: def __init__(self): self.all_letters = string.ascii_lowercase def get_cipher(self, ch): ch = ch.lower() if ch == ' ' or ch not in self.all_letters: return '' idx = self.all_letters.index(ch) + 3 if idx > len(self.all_letters): idx = - 25 return self.all_letters[idx] def get_plain(self, ch): ch = ch.lower() idx = self.all_letters.index(ch) - 3 return self.all_letters[idx] def encode(self, plain_text): return ''.join([self.get_cipher(x) for x in plain_text]) def decode(self, cryptic): return ''.join([self.get_plain(x) for x in cryptic]) class Cipher: def __init__(self, key=''): self.all_letters = string.ascii_lowercase self._key_map = key def encode(self, plain_text): return ''.join(self.encode_decode(plain_text, encode=True)) def decode(self, cryptic): return ''.join(self.encode_decode(cryptic, encode=False)) def encode_decode(self, text, encode=True): result = [] for i, ch in enumerate(text): _original_idx = self.all_letters.index(ch) if i < len(self._key_map) - 1: _code = self._key_map[i] else: _code = 'a' _code_idx = self.all_letters.index(_code) if encode is False: _idx = _original_idx - _code_idx else: _idx = _original_idx + _code_idx if _idx > 25: _idx -= 26 result.append(self.all_letters[_idx]) return result
554442bd9fe8129b3e7ad7f1418070093cad7950
smueksch/pdf2txt
/src/postprocessors/unknown_char_fixer.py
659
3.609375
4
import re class UnknownCharFixer: """ Replace unknown character with best interpretation. """ name = 'UnknownCharFixer' desc = 'Replace unknown character with best interpretation' def __call__(self, raw_text: str): text = re.sub(u'', r'0', raw_text) text = re.sub(u'', r'1', text) text = re.sub(u'', r'2', text) text = re.sub(u'', r'3', text) text = re.sub(u'', r'4', text) text = re.sub(u'', r'5', text) text = re.sub(u'', r'6', text) text = re.sub(u'', r'7', text) text = re.sub(u'', r'8', text) return re.sub(u'', r'9', text)
13d545fa660c77dffe6de472180e184206ed68ea
bfialkoff/pytorch-thesis-stuff
/utils/losses/numpy_losses.py
1,891
3.6875
4
import numpy as np def compute_stable_bce_cost(Y, Z): """ This function computes the "Stable" Binary Cross-Entropy(stable_bce) Cost and returns the Cost and its derivative w.r.t Z_last(the last linear node) . The Stable Binary Cross-Entropy Cost is defined as: => (1/m) * np.sum(max(Z,0) - ZY + log(1+exp(-|Z|))) Args: Y: labels of data Z: Values from the last linear node Returns: cost: The "Stable" Binary Cross-Entropy Cost result dZ_last: gradient of Cost w.r.t Z_last """ m = len(Y) cost = (1/m) * np.sum(np.maximum(Z, 0) - Z*Y + np.log(1+ np.exp(- np.abs(Z)))) return cost def numpy_bce(y_true, y_pred, from_logits=False): """ This function computes the Binary Cross-Entropy(stable_bce) Cost function the way Keras implements it. Accepting either probabilities(P_hat) from the sigmoid neuron or values direct from the linear node(Z) Args: y_true: labels of data y_pred: Probabilities from sigmoid function from_logits: flag to check if logits are being provided or not(Default: False) Returns: cost: The "Stable" Binary Cross-Entropy Cost result dZ_last: gradient of Cost w.r.t Z_last """ if from_logits: # assume that P_hat contains logits and not probabilities return compute_stable_bce_cost(y_true, Z=y_pred) else: # Assume P_hat contains probabilities. So make logits out of them # First clip probabilities to stable range EPSILON = 1e-07 P_MAX = 1- EPSILON # 0.9999999 y_pred = np.clip(y_pred, a_min=EPSILON, a_max=P_MAX) # Second, Convert stable probabilities to logits(Z) Z = np.log(y_pred / (1 - y_pred)) # now call compute_stable_bce_cost return compute_stable_bce_cost(y_true, Z) numpy_mse = lambda y, p: ((y - p) ** 2).mean()
983dbbba3483c14d50e4cf9761ad477693065b83
Epilena/Python-Challenge
/PyPoll/main.py
2,181
3.609375
4
#import the os module to create file paths across operating system import os #import module for reading CSV files import csv # os.chdir(os.path.dirname("election_data.csv")) elect_data = os.path.join("PyPoll","Resources", "election_data.csv") #read the CSV file with open (elect_data) as csvfile: #create a csv reader object csvreader = csv.reader(csvfile) csvheader = next(csvreader) # initializing the titles and rows list Voters_ID = [] County = [] Candidate = [] Votes = 0 CandidateVotes={} #read through each data row: for row in csvreader: #total vote count Votes = Votes+1 #candidate voted for candidate_name= row[2] #create loop to tally candidate voted for if candidate_name not in CandidateVotes: CandidateVotes[candidate_name] = 1 Candidate.append(candidate_name) else: win_vote= max(CandidateVotes, key=CandidateVotes.get) #add votes to candidate's total count CandidateVotes[candidate_name]+=1 #CandidateVotes[candidate_name]+=1 cand_res_list = [] for name, vote in CandidateVotes.items(): result= name vote_perc = float(vote)/float(Votes) *100 cand_res_list.append(f"{name}: {vote_perc:.2f}% ({vote:,})") #print results print("Election Results") print(f"--------------------------") print(f"Total Votes: {Votes}") print("--------------------------") for name2 in cand_res_list: print(name2) print("---------------------------") print(f"Winner: {win_vote}") print("---------------------------") # print output to a text file output = os.path.join ("PyPoll", 'output.txt') with open(output, "w") as new: new.write("Election Results") new.write("\n") new.write("----------------------------------") new.write("\n") new.write(f"Total Votes: {Votes}") new.write("\n") for name3 in cand_res_list: new.write(name3) new.write("-----------------------------------") new.write("\n") new.write(f"Winner: {win_vote}") new.write("\n") new.write("-----------------------------------")
0aa0273049b58bdfb7ec0d5b56b6a8b297b1a8d2
sangyuan6122/kaikeba-wangwentao
/exercise11/utils.py
338
3.78125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- def print_line(text): total=90; lenTxt = len(text) lenTxt_utf8 = len(text.encode('utf-8')) size = int((lenTxt_utf8 - lenTxt) / 2 + lenTxt) remainder=(total - size)%2 left= (total - size)//2 right=left if remainder==0 else left+1 print("*" * left+text+"*" * right)
af399acca911c72c397f3c5dfe7289da92b69c16
Comyn-Echo/leeCode
/常见的数据结构.py
2,716
3.5625
4
# # #初始化数组 # dp = [0 for i in range(5)] # [0, 0, 0, 0, 0] # #定义二维数组 # dp = [[0 for i in range(5)] for i in range(3)] # [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] # # 排序数据结构 # my_dict = {"a":"2", "c":"5", "b":"1"} # # result = sorted(my_dict) # #默认对dict排序,不指定key参数,会默认对dict的key值进行比较排序 # #result输出: ['a', 'b', 'c'] # # result2 = sorted(my_dict, key=lambda x:my_dict[x]) # #指定key参数,根据dict的value排序 # #result2输出:['b', 'a', 'c'] # sorted()的reverse参数接受False 或者True 表示是否逆序 # 使用比较函数 # import functools # def cmp(a, b): # if a > b: # return -1 # elif a < b: # return 1 # else: # return 0 # # # nums = [1, 2, 3, 4, 5, 6] # sorted_nums = sorted(nums, key=functools.cmp_to_key(cmp)) # # #[6, 5, 4, 3, 2, 1] # # 有序数据结构 # from sortedcontainers import SortedList # sl = SortedList(['e', 'a', 'c', 'd', 'b']) # print(sl) # from sortedcontainers import SortedDict # sd = SortedDict({'c': 3, 'a': 1, 'b': 2}) # sd['a'] =10 # 更新 # sd['d'] =0 # 新增 # sd.pop('a') # 删除 # print(sd) # # # 正常先进先出队列 leecode不支持 # import queue # # q=queue.Queue() #如果不设置长度,默认为无限长 # q.put(123) # q.put(456) # q.put(789) # q.put(100) # q.put(111) # q.put(233) # 后进先出队列 # q = queue.LifoQueue() # q.put(12) # q.put(34) # print(q.get()) # # # 数组 # q = [] # q.append(1) # q.append(2) # q.append(3) # a = q.pop() # a =q.remove(1) # # print(a) # print(q) # # # 优先级队列 # # import heapq as hq # #向堆中插入元素,heapq会维护列表heap中的元素保持堆的性质 # h = [] # hq.heappush(h, [5, 'write code']) # hq.heappush(h, [7, 'release product']) # hq.heappush(h, [1, 'write spec']) # hq.heappush(h, [3, 'create tests']) # laptops = [ # {'name': 'ThinkPad', 'amount': 100, 'price': 91.1}, # {'name': 'Mac', 'amount': 50, 'price': 543.22}, # {'name': 'Surface', 'amount': 200, 'price': 21.09}, # {'name': 'Alienware', 'amount': 35, 'price': 31.75}, # {'name': 'Lenovo', 'amount': 45, 'price': 16.35}, # {'name': 'Huawei', 'amount': 75, 'price': 115.65} # ] # # cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price']) # expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price']) # print(h) # # a = hq.heappop(h) # print(a) # # b = hq.nlargest(2, h,lambda s:s[1]) # print(b) # 哈希表 #判断是否在表里面 # A = {1,2,3,4} # a =1 # flag = a in A # print(flag) # # 栈 # # a =[] # a.append(1) # a.append(2) # a.append(3) # b= a.pop() # print(a) #
65951cf0009b7a71adf343a66e73d84eb3d73ff4
pennywong/mooc
/Rice-Algorithmic Thinking/module1-Graphs and brute-force algorithms/project1.py
1,207
3.828125
4
""" Degree distributions for graphs """ EX_GRAPH0 = {0:set([1,2]), 1:set(), 2:set()} EX_GRAPH1 = {0:set([1,4,5]), 1:set([2,6]), 2:set([3]), 3:set([0]), 4:set([1]), 5:set([2]),6:set()} EX_GRAPH2 = {0:set([1,4,5]), 1:set([2,6]), 2:set([3,7]), 3:set([7]), 4:set([1]), 5:set([2]),6:set(),7:set([3]),8:set([1,2]),9:set([0,3,4,5,6,7])} def make_complete_graph(num_nodes): """ Complete directed graph with the specified number of nodes """ graph = {} for row in range(num_nodes): edges = set() for col in range(num_nodes): if row!=col: edges.add(col) graph[row] = edges return graph def compute_in_degrees(digraph): """ Computes the in-degrees for the nodes in the graph """ result = {} for key in digraph: result[key] = 0 for key in digraph: edges = digraph[key] for edge in edges: result[edge] += 1 return result def in_degree_distribution(digraph): """ Computes the unnormalized distribution of the in-degrees of the graph """ in_degrees = compute_in_degrees(digraph) distribution = {} for key in in_degrees: value = in_degrees[key] if distribution.has_key(value): distribution[value] += 1 else: distribution[value] = 1 return distribution
115b864e68805e0937bcd6fb1841951cb60260fd
Mozes721/PythonCrashCourse
/chapter_8/City_name.py
250
3.8125
4
def city_country(city,country): return(city.title() + ", " + country.title()) city1 = city_country('Riga', 'Latvia') print(city1) city2 = city_country('Tallin', 'Estonia') print(city2) city3 = city_country('Copenhagen', 'Denmark') print(city3)
f40defd2208ece1a088ec0e7489b55d3ac07741b
AKHILESH1705/programing_questions
/func2.py
443
4.125
4
#cheack which number is greater def number(num1,num2): if num1>num2: return a else: return b a=int(input("enter num1 = ")) b=int(input("enter num2 = ")) bigger=number(a,b) print(f"{bigger} is greater") # diffrent way def number(num1,num2): if num1>num2: return "num1 is greater" else: return "num2 is greater" a=int(input("enter num1 = ")) b=int(input("enter num2 = ")) print(number(a,b))
498bdf0186335a845c4d342eae60ff8e7cf6c024
sidgan/Who-Said-it-
/gaura.py
756
3.625
4
#!/usr/bin/env python #import regex import re #start process_tweet def processTweet(tweet): # process the tweets #Convert to lower case tweet = tweet.lower() #Convert www.* or https?://* to URL tweet = re.sub('((www\.[\s]+)|(https?://[^\s]+))','URL',tweet) #Convert @username to AT_USER tweet = re.sub('@[^\s]+','AT_USER',tweet) #Remove additional white spaces tweet = re.sub('[\s]+', ' ', tweet) #Replace #word with word tweet = re.sub(r'#([^\s]+)', r'\1', tweet) #trim tweet = tweet.strip('\'"') return tweet #end #Read the tweets one by one and process it fp = open('Desktop/aip.txt', 'r') line = fp.readline() while line: processedTweet = processTweet(line) print processedTweet line = fp.readline() #end loop fp.close()
7b9d3877238a7e7c984087ee20383ad7e8c017b2
jonathanpan777/hashcode
/car.py
254
3.546875
4
class Car: def __init__(self, length, path): self.length = length self.path = path self.current = path[0] self.path_length = 0 def car_sum(self,street_dict): s = 0 for p in self.path: s += street_dict[p].length self.path_length = s
00d1173f8e8c319e19cae4203c5010f91870cbe9
Ayush10/CSC-3530-Advance-Programming
/ayush_ojha_swap_without_temp.py
250
3.984375
4
# Taking input from the user a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) print("Variables before swapping") print(a, b) # Swapping Algorithm a = a + b b = a - b a = a - b print("Variable after swapping") print(a, b)
52d828c4720c9bbf09217572c419e3ac6d94f30f
arthurDz/algorithm-studies
/leetcode/minimum_difference_between_largest_and_smallest_value_in_three_moves.py
1,050
3.921875
4
# Given an array nums, you are allowed to choose one element of nums and change it by any value in one move. # Return the minimum difference between the largest and smallest value of nums after perfoming at most 3 moves. # Example 1: # Input: nums = [5,3,2,4] # Output: 0 # Explanation: Change the array [5,3,2,4] to [2,2,2,2]. # The difference between the maximum and minimum is 2-2 = 0. # Example 2: # Input: nums = [1,5,0,10,14] # Output: 1 # Explanation: Change the array [1,5,0,10,14] to [1,1,0,1,1]. # The difference between the maximum and minimum is 1-0 = 1. # Example 3: # Input: nums = [6,6,0,1,1,4,6] # Output: 2 # Example 4: # Input: nums = [1,5,6,14,15] # Output: 1 # Constraints: # 1 <= nums.length <= 10^5 # -10^9 <= nums[i] <= 10^9 def minDifference(self, nums: List[int]) -> int: nums.sort() min_val = float('inf') for i in range(4): if len(nums) + i - 4 > i: min_val = min(nums[len(nums) + i - 4] - nums[i], min_val) else: return 0 return min_val
794071c39fabacf515ea33f3549ba76a9df5535a
Sahil12S/DataCompass
/Python/userv2.py
1,060
3.84375
4
class User: def __init__(self, name): self.username = name self.balance = 0 def make_deposit(self, amount): self.balance += amount return self def make_withdrawl(self, amount): self.balance -= amount return self def display_user_balance(self): print(f"Balance for user {self.username} is {self.balance}.") return self def transfer_money(self, other_user, amount): print(f"Transferring {amount} to {other_user.username}.") other_user.make_deposit(amount) self.balance -= amount return self smith = User("Smith") smith.make_deposit(100).make_deposit( 50).make_withdrawl(120).display_user_balance() ana = User("Ana") ana.make_deposit(50).make_deposit(175).make_withdrawl( 25).make_withdrawl(100).display_user_balance() john = User("John") john.make_deposit(250).make_withdrawl(150).make_withdrawl( 20).make_withdrawl(15).display_user_balance() ana.transfer_money(smith, 20).display_user_balance() smith.display_user_balance()
a3213f10753b87a4030453dfe7f3ba1109c672c9
jinsuupark/chapter0601
/ex01.py
355
3.71875
4
student =1 while student <=5: print(student, "번 학생의 성적을 처리합니다.") student += 1 #복합대입연산자 print() num = 1 even_total =0 odd_total =0 while num<=100: if num%2 ==0: even_total +=num else: odd_total += num num +=1 print("짝수의 합:", even_total) print("홀수의 합:", odd_total)
85a0c9f580327c276fb9ed8a5a6fca7ceeb8403a
Smelly-calf/python-calf
/calf/basic/lambda_func.py
645
3.984375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 简约而不简单的匿名函数:lambda 匿名函数是函数, 不是变量 lambda函数用在 常规函数不能用的地方:列表内 map(func, iterable): 返回新的可遍历的集合 filter(func, iterable) reduce(func, iterable) 1、对字典d值由高到低排序:d={'mike':10,'lucy':2,'ben':30} 2、使用匿名函数的场景 """ if __name__ == '__main__': print("请开始你的程序") square = lambda x: x ** 2 # 定义lambda函数 square square(3) # 调用匿名函数 d = {'mike': 10, 'lucy': 2, 'ben': 30} sorted_d = sorted(d, key=lambda x: -x[1])
403b7068c5e178983c0273a204a382ef970721f4
Leeoku/anagram
/backend/anagram.py
740
3.828125
4
from collections import Counter class AnagramCheck: def __init__(self): self.anagram_counter = Counter() # Take in two words and determine if they are anagram def is_anagram(self, first_word, second_word): first_word = first_word.lower() second_word = second_word.lower() first_counter = Counter(first_word) second_counter = Counter(second_word) self.anagram_counter[first_word, second_word] += 1 return first_counter == second_counter #Take the counter object of all words and return top searches def get_anagram_count_top(self, n): return self.anagram_counter.most_common(n) def reset_anagram(self): self.anagram_counter.clear()
11d4b3f27e6a65d5a1365a9b5bd865dda79a899b
Sammion/PythonStudy
/source/Notebook/test1_15.py
912
3.640625
4
# -*- coding: utf-8 -*- """ Created on 11/26/2018 @author: Samuel @Desc: @dependence: Noting """ rows = [ {'addr': "shanghai", "name": "Amy", "date": "1/12/2018"}, {'addr': "sichuan", "name": "Bmy", "date": "1/12/2018"}, {'addr': "shanghai", "name": "Cmy", "date": "1/12/2018"}, {'addr': "sichuan", "name": "Dmy", "date": "1/12/2017"}, {'addr': "shanghai", "name": "Emy", "date": "1/12/2017"}, {'addr': "henan", "name": "Fmy", "date": "1/12/2017"}, {'addr': "henan", "name": "Gmy", "date": "1/12/2017"}, {'addr': "shanghai", "name": "Hmy", "date": "1/12/2017"} ] from operator import itemgetter from itertools import groupby # 首先需要排序,因为groupBy只能比较相邻项 rows.sort(key=itemgetter('addr')) # 分组 for date, items in groupby(rows, key=itemgetter('addr')): print(date) for i in items: print(" ", i)
a6e6822a1a121aac2d8489725a80117e91c63130
npradheep/home-automation-system
/gateway/utilities/ConfigUtil.py
1,035
3.515625
4
''' Created on 28-Jan-2020 @author: Pradheep This class parses the configuration file and makes the data usable in python ''' import configparser import os.path import sys parser = configparser.ConfigParser() path = '../../ConnectedDevicesConfig.props' class ConfigUtil(): # Checks if the file has any valid configuration data def hasConfig(self): return True if parser.sections() else False # Loads the configuration file def loadConfig(self, path): if os.path.exists(path) is True: # Checks if path exists parser.read(path) return True else: return False # Parses the config file def getValue(self, section): conf.loadConfig(path) if (conf.hasConfig()) == True else sys.exit('Not a valid Configuration file') return dict(parser.items(section)) # Formats the parsed values as a dictionary and returns it def __init__(self): self.loadConfig(path) conf = ConfigUtil()
94dbb9870a35ed7a5033f184a7d7f279e88fe7f2
athirarajan23/luminarpython
/inheritence in advanced python/multilevel or heirarical inheritence.py
530
3.8125
4
class Person: def details(self,name,age): self.name=name self.age=age print(self.name) print(self.age) class Employee(Person): def print(self,emp_company): self.emp_company=emp_company print(self.emp_company) class Staff(Employee): def info(self,salary): self.salary=salary print(self.salary) per=Person() per.details("SITHA",26) emp=Employee() emp.details("arun",28) emp.print("abc") st=Staff() st.details("akshay",24) st.print("luminar") st.info(30000)
552cf7122307e51188a3e223cef916ab28f533b4
re4lfl0w/codewars
/kata/length_of_the_line_segment.py
696
3.96875
4
from math import sqrt def length_of_line_my1(array): a, b = array tmp = sum(abs(a[i] - b[i]) ** 2 for i in range(len(array))) tmp = '{:1.2f}'.format(sqrt(tmp)) return tmp def length_of_line_my2(array): a, b = array tmp = sum(abs(a[i] - b[i]) ** 2 for i in range(len(array))) result = '{:1.2f}'.format(sqrt(tmp)) return result def length_of_line_my3(array): a, b = array tmp = sum((a[i] - b[i]) ** 2 for i in range(len(array))) result = '{:.2f}'.format(sqrt(tmp)) return result def length_of_line_best(array): x1, y1, x2, y2 = array[0][0], array[0][1], array[1][0], array[1][1] return '{:.2f}'.format((sqrt((x2-x1)**2 + (y2-y1)**2)))
9881cf3d8ff828b9728916db69dc1c768cbfa5ef
Nayyx/energy_quest
/equest_namur_gr_50.py
30,258
3.8125
4
# imports import copy import math import colored def display_board(dict_board, height, width, players, dict_army): """display the board at the beginning of the game parameters ---------- dict_board: dictionnary with all the characteristic of the board (dict) height:height of the board(int) width:width of the board(int) players:names of the players(tuple) Version −−−−−−− specification: Dominik Everaert (v.3 24/02/20) implementation: François Bechet (v.1 01/03/20) """ # define colored colors default_color = colored.attr('reset') green = colored.fg('#00ff00') red = colored.fg('#ff0000') blue = colored.fg('#0000ff') # display the board print(' ', end='') for i in range(1, height + 1): if i < 10: print(i, end=' ') else: print(i, end=' ') print('') for x in range(width): n = 1 for y in range(height): if players[0] in dict_board['@%d-%d' % (x + 1, y + 1)]: tempDict = dict_board['@%d-%d' % (x + 1, y + 1)][players[0]] if 'hub' in tempDict: print(green + ' ⌂ ' + default_color, end='') else: for key in tempDict: unit = tempDict[key] if 'cruiser' in unit['ship_type']: print(green + ' ☿ ' + default_color, end='') if 'tanker' in unit['ship_type']: print(green + ' * ' + default_color, end='') elif players[1] in dict_board['@%d-%d' % (x + 1, y + 1)]: tempDict = dict_board['@%d-%d' % (x + 1, y + 1)][players[1]] if 'hub' in tempDict: print(red + ' ⌂ ' + default_color, end='') else: for key in tempDict: unit = tempDict[key] if 'cruiser' in unit['ship_type']: print(red + ' ☿ ' + default_color, end='') if 'tanker' in unit['ship_type']: print(red + ' * ' + default_color, end='') elif 'peak' in dict_board['@%d-%d' % (x + 1, y + 1)]: print(blue + ' ⚐ ' + default_color, end='') else: print(" . ", end='') n = n + x print(' ' + str(n)) for player in players: print(player + ' : ') for unit, value in dict_army[player].items(): print(unit.upper()) for property, value in dict_army[player][unit].items(): print(property, ':', value, end=' ▍') print('') print('\n' * 2) print(dict_board) def game(play_game): """start the game and play it Version −−−−−−− specification: François Bechet (v.1 24/02/20) implementation: François Bechet (v.1 01/03/20) """ # create the players players = (input("who is player1 : "), input("who is player2 : ")) # create dict_recruit dict_recruit = {players[0]: {'cruiser': {'ship_type': 'cruiser', 'hp': 100, 'current_energy': 200, 'energy_capacity': 400, 'shooting_range': 1, 'move_cost': 10, 'shooting_cost': 10, 'cost': 750, 'turn_attack': False}, 'tanker': {'ship_type': 'tanker', 'hp': 50, 'current_energy': 400, 'energy_capacity': 600, 'move_cost': 0, 'cost': 1000}, 'research': {'regeneration': 0, 'storage': 0, 'range': 0, 'move': 0}}, players[1]: {'cruiser': {'ship_type': 'cruiser', 'hp': 100, 'current_energy': 200, 'energy_capacity': 400, 'shooting_range': 1, 'move_cost': 10, 'shooting_cost': 10, 'cost': 750, 'turn_attack': False}, 'tanker': {'ship_type': 'tanker', 'hp': 50, 'current_energy': 400, 'energy_capacity': 600, 'move_cost': 0, 'cost': 1000}, 'research': {'regeneration': 0, 'storage': 0, 'range': 0, 'move': 0}}} # call the create_board function and store its return values board_values = create_board("board.txt", players) dict_board, height, width = board_values[0], board_values[1], board_values[2] # create dictionnary of the army dict_army = board_values[3] # call the display_board function display_board(dict_board, height, width, players, dict_army) # start the main game loop while play_game is not False: play_turn(dict_board, dict_army, dict_recruit, width, height, players) def get_order(players): """ask the player for orders Orders must respect this syntax : RECRUIT ORDER : 'alpha:tanker bravo:cruiser' UPGRADE ORDER : 'upgrade:regeneration; upgrade:storage; upgrade:shooting_range; upgrade:move_cost' MOVE ORDER(name:@r-c where r is row and c is column) : 'alpha:@30-31' ATTACK ORDER(nom:*r-c=q where r,c is position of target and q are damages) : 'charlie:*10-15=23' TRANSFER ORDER(nom:<r-c where the tanker take energy in the targeted hub; name1:>name2 where name1(tanker) gives energy to name2(cruiser or hub)) : alpha:<30-31 bravo:>charlie delta:>hub parameters ---------- players: names of the players(tuple) return ------ dict_order: dictionnary with all the order Version −−−−−−− specification: Dominik Everaert (v.3 24/02/20) implementation: François Bechet (v.1 01/03/20) """ # convert list_oder to dict_order dict_order = {players[0]: {'move': [], 'attack': [], 'upgrade': [], 'recruit': [], 'transfer': []}, players[1]: {'move': [], 'attack': [], 'upgrade': [], 'recruit': [], 'transfer': []}} # ask orders to players and add them to dict_order for player in players: list_order_player = (input("%s, please enter your orders : " % player)).split() for i in range(len(list_order_player)): if '@' in list_order_player[i]: dict_order[player]['move'].append(list_order_player[i]) elif '*' in list_order_player[i]: dict_order[player]['attack'].append(list_order_player[i]) elif 'upgrade' in list_order_player[i]: dict_order[player]['upgrade'].append(list_order_player[i]) elif '>' in list_order_player[i] or '<' in list_order_player[i]: dict_order[player]['transfer'].append(list_order_player[i]) else: dict_order[player]['recruit'].append(list_order_player[i]) # return dictionnary of orders return dict_order def create_board(board_file, players): """take a file and change it into a board parameters ---------- board_file: file in which all the element needed for the board are(path) players: names of the players(tuple) return ------ dict_board: dictionnary with all the characteristic of the board (dict) Version −−−−−−− specification: Dominik Everaert (v.3 24/02/20) implementation: François Bechet (v.1 01/03/20) """ # open the board file and save its content with open(board_file, "r") as f: data = f.readlines() # create a dict and store all board file infos into it dictFile = {} for i in data: if ':' in i: for j in range(len(i)): if i[j] == ':': index = j key = i[:index] dictFile[key] = [] else: dictFile[key].append(i.split()) # get map width and height width, height = int(dictFile['map'][0][0]), int(dictFile['map'][0][1]) # create a dictionnary of the board with keys as cases dict_board = {} for x in range(width): for y in range(height): dict_board['@%d-%d' % (x + 1, y + 1)] = {} # add hubs to the board's dictionnary dict_board['@%d-%d' % (int(dictFile['hubs'][0][0]), int(dictFile['hubs'][0][1]))] = {players[0]: {'hub': ''}} dict_board['@%d-%d' % (int(dictFile['hubs'][1][0]), int(dictFile['hubs'][1][1]))] = {players[1]: {'hub': ''}} # create dict_army hub_1 = {'hp': int(dictFile['hubs'][0][2]), 'current_energy': int(dictFile['hubs'][0][3]), 'energy_capacity': int(dictFile['hubs'][0][3]), 'regeneration': int(dictFile['hubs'][0][4]), 'ship_type': 'hub'} hub_2 = {'hp': int(dictFile['hubs'][1][2]), 'current_energy': int(dictFile['hubs'][1][3]), 'energy_capacity': int(dictFile['hubs'][1][3]), 'regeneration': int(dictFile['hubs'][1][4]), 'ship_type': 'hub'} dict_army = {players[0]: {'hub': hub_1}, players[1]: {'hub': hub_2}} # add peaks to the board's dictionnary for i in range(len(dictFile['peaks'])): dict_board['@%d-%d' % (int(dictFile['peaks'][i][0]), int(dictFile['peaks'][i][1]))] = {'peak': {'energy': int(dictFile['peaks'][i][2])}} # returns return dict_board, height, width, dict_army def attack(dict_order, dict_army, dict_board, players): """execute attack order of each player and modify stats of each effected unit parameters ---------- dict_order[attack]: dictionnary of attack order(dict) dict_army: dictionnary with the unit of the two player(dict) players: names of the players(tuple) return ------ dict_army: dictionnary of the 2 army modified in result of the attack(dict) Version −−−−−−− specification: Dominik Everaert (v.3 24/02/20) implementation : Dominik Everaert (v.1 11/03/20) """ # extract the attack order from dict_order and change unit stat attackList = '' x_shooter, y_shooter, x_target, y_target = '', '', '', '' for player in players: if player == players[0]: attacker = players[0] target = players[1] else: attacker = players[1] target = players[0] # extract the attack order for i in range(len(dict_order[attacker]['attack'])): attack = dict_order[attacker]['attack'][i] print(attack) # change order into list [shooter_name,attack_stats] attackList = attack.split(':*') # separate attack_stats into position and damage spliting = attackList[1].split('=') shooter_name = attackList[0] damage = int(spliting[1]) target_position = spliting[0] # separate position_target into target x et target y targetxy = target_position.split('-') # separate target position x_target = int(targetxy[0]) y_target = int(targetxy[1]) target_units = [] for unit in dict_board['@%s-%s' % (x_target, y_target)][target]: target_units.append(unit) # search shooter position for key, value in dict_board.items(): if attacker in value: unit = value[attacker] if attackList[0] in unit: case = key.split('-') case_0 = case[0].strip('@') x_shooter, y_shooter = int(case_0), int(case[1]) # execute the attack # check manhattan distance and check that that the unit has enough energy to attack if compute_manhattan_distance(x_shooter, y_shooter, x_target, y_target) and dict_army[attacker][shooter_name]['current_energy'] >= 10 * damage: dict_army[attacker][shooter_name]['current_energy'] -= 10 * damage for i in target_units: # delete the unit if damage is >= unit hp if damage >= dict_army[target][i]['hp']: # if the unit is the hub the attacker win if i == 'hub': return('win') del dict_army[target][i] # if there is only one unit delete the player key if len(dict_board['@%s-%s' % (x_target, y_target)][target]) == 1: del dict_board['@%s-%s' % (x_target, y_target)][target] # else delete only the unit key else: del dict_board['@%s-%s' % (x_target, y_target)][target][i] # change the unit hp : hp = hp - damage else: dict_army[target][i]['hp'] -= damage # if it's a cruiser disable his move ability for the turn if dict_army[attacker][attackList[0]]['ship_type'] == 'cruiser': dict_army[attacker][attackList[0]]['turn_attack'] = True return dict_board, dict_army def move(dict_order, dict_board, dict_army, players): """execute move order of each player and modify board and stats of moving units prameters --------- dict_order[move]: dictionnary of move order(dict) dict_board: dictionnary with all the characteristic of the board (dict) dict_army: dictionnary with the unit of the two player(dict) players: names of the players(tuple) return ------ dict_board: dictionnary with all the characteristic of the board (dict) Version −−−−−−− specification: François Bechet (v.3 24/02/20) implementation: François Bechet (v.1 25/02/20) """ # extract the move order from dict_order and change the position unit in dict_board for player in players: moveList = [] # extract the move order for i in range(len(dict_order[player]['move'])): move = dict_order[player]['move'][i] moveList = move.split(':') if moveList != []: # check manhattan distance x_shooter, y_shooter, x_target, y_target = 0, 0, 0, 0 xy_shooter = '' moveLegality = True # destination correspond to target case = moveList[1].split('-') case_0 = case[0].strip('@') x_target, y_target = int(case_0), int(case[1]) # unit to move correspond to shooter for key, value in dict_board.items(): if player in value: unit = value[player] if moveList[0] in unit: xy_shooter = key # store unit position to delete it after the move case = key.split('-') case_0 = case[0].strip('@') x_shooter, y_shooter = int(case_0), int(case[1]) # verify that the cruiser didn't already attack this turn if dict_army[player][moveList[0]]['ship_type'] == 'cruiser': if dict_army[player][moveList[0]]['turn_attack']: moveLegality = False # check manhattan distance and moveLegality if compute_manhattan_distance(x_shooter, y_shooter, x_target, y_target) and moveLegality: # move the unit position in dict_board # store the case position case = moveList[1] for i in dict_board: # change the position of the unit in dict_board if player in dict_board[i]: tempBoard = dict_board[i][player] if moveList[0] in tempBoard: unit = (dict_board[i][player][moveList[0]]) tempDict = {player: {moveList[0]: {}}} tempDict[player][moveList[0]].update(unit) dict_board[case].update(tempDict) print(xy_shooter) # delete the old unit position # if there is only one unit delete the player key if len(dict_board[xy_shooter][player]) == 1: del dict_board[xy_shooter][player] # else delete only the unit key else: del dict_board[xy_shooter][player][moveList[0]] # make the cruiser pay the move if dict_army[player][moveList[0]]['ship_type'] == 'cruiser': move_cost = dict_army[player][moveList[0]]['move_cost'] dict_army[player][moveList[0]]['current_energy'] -= move_cost # restore cruiser move legality for unit, value in dict_army[player].items(): for property in dict_army[player][unit]: if property == 'turn_attack': dict_army[player][unit][property] = False return dict_board def upgrade(dict_order, dict_army, dict_recruit, players): """execute the upgrage order of each player and modify the stats of each affected unit parameters ---------- dict_order[upgrade]: dictionnary of upgrade order(dict) dict_army: dictionnary with the unit of the two player(dict) dict_recruit: dictionnary with research and stat of new ship(dict) players: names of the players(tuple) return ------ dict_army: dictionnary with the unit of the two player(dict) dict_recruit: dictionnary with research and stat of new ship(dict) Version −−−−−−− specification: François Bechet (v.2 24/02/20) implementation: Dominik Everaert (v.1 05/03/20) """ # extract the upgrade order from dict_order and change the stat of unit upgradeList = '' for player in players: # extract the upgrade order for i in range(len(dict_order[player]['upgrade'])): upgrade = dict_order[player]['upgrade'][i] upgradeList = upgrade.split(':') upgradeList.append(player) # choose which upgrade must be done if upgradeList != '': if upgradeList[1] == 'regeneration': if (dict_army[player]['hub']['current_energy']) >= 750 and (dict_recruit[player]['research']['regeneration']) < 10: dict_army[player]['hub']['regeneration'] += 5 dict_recruit[player]['research']['regeneration'] += 1 else: print("you can't upgrade energy regeneration") elif upgradeList[1] == 'storage': if (dict_army[player]['hub']['current_energy']) >= 600 and (dict_recruit[player]['research']['storage']) < 12: dict_recruit[player]['research']['storage'] += 1 dict_recruit[player]['tanker']['energy_capacity'] += 100 temp_dict = list(dict_army[player]) for i in range(len(temp_dict)): if dict_army[player][temp_dict[i]]['ship_type'] == 'tanker': dict_army[player][temp_dict[i]]['energy_capacity'] += 100 print('1 time') else: print("you can't upgrade energy capacity") elif upgradeList[1] == 'range': if (dict_army[player]['hub']['current_energy']) >= 400 and (dict_recruit[player]['research']['range']) < 5: dict_recruit[player]['research']['range'] += 1 dict_recruit[player]['cruiser']['shooting_range'] += 1 temp_dict = list(dict_army[player]) for i in range(len(temp_dict)): if dict_army[player][temp_dict[i]]['ship_type'] == 'cruiser': dict_army[player][temp_dict[i]]['shooting_range'] += 1 else: print("you can't upgrade shooting range") elif upgradeList[1] == 'move': if (dict_army[player]['hub']['current_energy']) >= 500 and (dict_recruit[player]['research']['move']) < 5: dict_recruit[player]['research']['move'] += 1 dict_recruit[player]['cruiser']['move_cost'] -= 1 temp_dict = list(dict_army[player]) for i in range(len(temp_dict)): if dict_army[player][temp_dict[i]]['ship_type'] == 'cruiser': dict_army[player][temp_dict[i]]['move_cost'] -= 1 else: print("you can't upgrade movement") # reset upgradeList upgradeList = '' return dict_army, dict_recruit def energy_transfert(dict_army, dict_order, dict_board, players): """execute transfert order and modify affected unit's stat parameters ---------- dict_army: dictionnary with the unit of the two player(dict) dict_order[energy_transfert]:dictionnary of energy transfert order(dict) dict_board: dictionnary with all the characteristic of the board (dict) players: names of the players(tuple) return ------ dict_army: dictionnary with the unit of the two player(dict) dict_board: dictionnary with all the characteristic of the board (dict) Version −−−−−−− specification: Dominik Everaert (v.3 24/02/20) """ for player in players: order_peak = [] order_unit = [] order_hub = [] tempList = [] # extract order from dict_order and place each kind of transfert order in a specific list tempList = dict_order[player]['transfer'] for i in range(len(tempList)): temp_order = tempList[i] if ':<' in temp_order: order_peak = temp_order.split(':<') elif ':>' in temp_order: order_unit = temp_order.split(':>') elif '>:' in temp_order: order_hub = temp_order.split('>:') # execute peak to unit transfert if order_peak != []: energy_unit = dict_army[player][order_peak[0]]['energy_capacity'] - dict_army[player][order_peak[0]]['current_energy'] if energy_unit >= dict_board['@' + order_peak[1]]['peak']['energy']: energy = dict_board['@' + order_peak[1]]['peak']['energy'] else: energy = energy_unit dict_board['@' + order_peak[1]]['peak']['energy'] -= energy dict_army[player][order_peak[0]]['current_energy'] += energy # if peak's energy reach 0, remove the peak if dict_board['@' + order_peak[1]]['peak']['energy'] == 0: del dict_board['@' + order_peak[1]]['peak'] # execute unit to unit transfert if order_unit != []: energy_unit = dict_army[player][order_unit[1]]['energy_capacity'] - dict_army[player][order_unit[1]]['current_energy'] if energy_unit >= dict_army[player][order_unit[0]]['current_energy']: energy = dict_army[player][order_unit[0]]['current_energy'] else: energy = energy_unit dict_army[player][order_unit[0]]['current_energy'] -= energy dict_army[player][order_unit[1]]['current_energy'] += energy # execute unit to hub transfert if order_hub != []: # the hub must not be full energy_hub = dict_army[player][order_hub[1]]['energy_capacity'] - dict_army[player][order_hub[1]]['current_energy'] if energy_hub >= dict_army[player][order_hub[0]]['current_energy']: energy = dict_army[player][order_hub[0]]['current_energy'] else: energy = energy_hub # do the energy transfert dict_army[player][order_hub[0]]['current_energy'] -= energy dict_army[player][order_hub[1]]['current_energy'] += energy return dict_army, dict_board def regenerate(dict_army, players): """makes hub regenerate energy(at the end of the turn) parameters ---------- dict_army: dictionnary with the unit of the two player(dict) players: names of the players(tuple) return ------ dict_army: dictionnary with the unit of the two player(dict) Version −−−−−−− specification: Dominik Everaert (v.2 24/02/20) implementation : Dominik Everaert (v.1 13/03/20) """ for player in players: regen = dict_army[player]['hub']['regeneration'] empty = dict_army[player]['hub']['energy_capacity'] - dict_army[player]['hub']['current_energy'] if empty < regen: regen = empty dict_army[player]['hub']['current_energy'] += regen return dict_army def recruit_units(dict_order, dict_army, players, dict_board, dict_recruit): """execute recruit order and add unit to the army parameters ---------- dict_army: dictionnary with the unit of the two player(dict) dict_recruit: dictionnary with research and stat of new ship(dict) dict_order[recruit]: dictionnary of upgrade order(dict) players: names of the players(tuple) return ------ dict_army: dictionnary with the unit of the two player(dict) Version −−−−−−− specification: Dominik Everaert (v.3 24/02/20) implementation: François Bechet (v.1 01/03/20) """ # create a deepcopy of dict_recruit because otherwise it would point to the same object and cause issues later dict_recruit_copy = copy.deepcopy(dict_recruit) # extract the units from dict_order and place them into dict_board and dict_army for player in players: # extract the order from dict_order for i in range(len(dict_order[player]['recruit'])): unit = dict_order[player]['recruit'][i] unitList = unit.split(':') buy = False # check that the player hub has enough energy to buy the unit if unitList[1] == 'cruiser': if dict_army[player]['hub']['current_energy'] > dict_recruit_copy[player]['cruiser']['cost']: buy = True elif unitList[1] == 'tanker': if dict_army[player]['hub']['current_energy'] > dict_recruit_copy[player]['tanker']['cost']: buy = True if buy: # add the unit to dict_board for case, value in dict_board.items(): current_string = value unitDict = {unitList[0]: {'ship_type': unitList[1]}} if player in current_string: dict_board[case][player].update(unitDict) # add the unit to dict_army and pay the unit price if unitList[0] not in dict_army[player]: # verify that the unit is not already in dict_army if 'cruiser' in unitList: dict_army[player][unitList[0]] = dict_recruit_copy[player]['cruiser'] dict_army[player]['hub']['current_energy'] -= dict_recruit_copy[player]['cruiser']['cost'] elif 'tanker' in unitList: dict_army[player][unitList[0]] = dict_recruit_copy[player]['tanker'] dict_army[player]['hub']['current_energy'] -= dict_recruit_copy[player]['tanker']['cost'] return dict_army, dict_board def compute_manhattan_distance(x_shooter, y_shooter, x_target, y_target): """compute the distance between a cruiser and its target Parameters ---------- x_shooter: coordinate x of the shooter(int) y_shooter: coordinate y of the shooter(int) x_target: coordinate x of the target(int) y_target: coordinate y of the target(int) Return ------ distance: distance between the cruiser and the target(int) Version ------- specification: François Bechet (v.1 24/02/20) """ # formula : max( |r2−r1| , |c2−c1| ) x = abs(x_shooter - x_target) y = abs(y_shooter - y_target) if max(x, y) <= 1: return True def play_turn(dict_board, dict_army, dict_recruit, width, height, players): """ manage each turn of the game by receiving the commands of each player Parameters ---------- dict_army: dictionnary with the unit of the two player(dict) dict_order:dictionnary of players orders(dict) dict_board: dictionnary with all the characteristic of the board (dict) dict_recruit: dictionnary with research and stat of new ship(dict) players: names of the players(tuple) Version ------- specification: François Bechet (v.2 24/02/20) """ # get players orders dict_order = get_order(players) # call all functions to execute the player's orders recruit_units(dict_order, dict_army, players, dict_board, dict_recruit) upgrade(dict_order, dict_army, dict_recruit, players) # check if the hub is destroyed # if the hub is destroyed stop the game if attack(dict_order, dict_army, dict_board, players) == 'win': game(False) # else continue the game else: move(dict_order, dict_board, dict_army, players) energy_transfert(dict_army, dict_order, dict_board, players) regenerate(dict_army, players) display_board(dict_board, height, width, players, dict_army) game(True)
779c72597383aca077c634ce4b24a9f30854a18c
annaxarkhipova/geekbrains
/Lesson_1/task_1.py
632
4.21875
4
# 1. Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь. # https://drive.google.com/file/d/1ydDhgRFY0F_4WXiqLSupQQdnR_XbU7Fo/view?usp=sharing print("Введи трехзначное число") # целые числа a = int(input("Первая цифра - ")) b = int(input("Вторая цифра - ")) c = int(input("Третья цифра - ")) if a < 0 or b < 0 or c < 0: print("Решений нет") else: d = a + b + c f = a * b * c print(f"Сумма цифр {d=}, произведение - {f=}")
69b25938b1d5b4f42058e1b3823afb4e3a8d06b5
ashutoshdumiyan/CSES-Solutions
/string/requiredsubstring.py
353
3.53125
4
mod = 10 ** 9 + 7 def power(a, b): res = 1 while b: if b & 1: res = (res % mod * a % mod) % mod b -= 1 else: a = (a % mod * a % mod) % mod b = b // 2 return res % mod n = int(input()) s = input() k = len(s) t = n - k + 1 print(t * (power(26, (t - 1))))
bfe0a562736ffc80081730035e912e73a9353eae
today4king/leetcode
/1-20/11-container-with-most-water.py
1,430
3.671875
4
# Copyright 2021 jinzhao.me All rights reserved # # # Authors: Carry Jin <[email protected]> from typing import List class Solution: def maxArea(self, height: List[int]) -> int: i = 0 j = len(height) - 1 area = 0 last_min_h = 0 while j > i: d = j - i if min(height[i], height[j])>last_min_h: last_min_h=min(height[i], height[j]) this_area = d * min(height[i], height[j]) area = max(area, this_area) if height[i] > height[j]: j -= 1 else: i += 1 return area if __name__ == "__main__": solution = Solution() height = [1, 8, 6, 2, 5, 4, 8, 3, 7] print(height) print(solution.maxArea(height)) print(solution.maxArea(height) == 49) print('-------------------------------------') height = [1, 1] print(height) print(solution.maxArea(height)) print(solution.maxArea(height) == 1) print('-------------------------------------') height = [4, 3, 2, 1, 4] print(height) print(solution.maxArea(height)) print(solution.maxArea(height) == 16) print('-------------------------------------') height = [1, 2, 1] print(height) print(solution.maxArea(height)) print(solution.maxArea(height) == 2) print('-------------------------------------')
829dfc3ddf9d8e2caf5cefba3affa3de5d467b3b
nithyaraman/pythontraining
/chapter1/src/data_type_conversion.py
622
4.53125
5
""" Get the input from user and convert it into different data types and print it """ float_num = float(raw_input("enter any float=")) print"this float can convert as int %d" % (int(float_num)) int_num = int(raw_input("enter any integer=")) print"this int convert as float %f" % (float(int_num)) name = raw_input("enter your name=") print"name is a string ,it can convert as list" name_as_list = list(name) print name_as_list print"list can convert as tuple" list_as_tuple = tuple(name_as_list) print list_as_tuple print"again this tuple can convert as string" name_str = ''.join(list_as_tuple) print name_str
b199c98ea9d46d88bd9518241055ddc7759c3c4c
vladvesa/PEP20G06
/modul5/homework5.py
5,122
4.46875
4
# We want to create class for an object that behaves like a triangle, that has flexible sides and angles. # Because of approximations in python the triangle will get distorted after some of the changes so this is not a # perfect model # 30P # - class constructor can receives 3 arguments for angles (with default value of 60) and 3 arguments for sides (with # default value of 1) # class variables for sides will be called A, B, C # class variables for angles will be called AB, BC, CA (indicating sides) # 30P # - class implements method to modify_angle: # - modify_angle method takes two argument: # - "angle" and can be one of 3 string values 'AB', 'BC', 'CA' # - "degrees" that can be a positive or negative and represents the amount by which the angle will be modified # If as a result of the change any of the angles will be outside interval (0, 180) then method should raise an exception # When an angle is modified you will need to recalculate the opposing side which can be done using the following # example: angle AB is changed then C = (A**2 + B**2 - 2*A*B*cos(AB))**(1/2) # Because angles in a triangle must sum up to 180 degrees unmodified angles need to be recalculated after we have # recalculated the opposite side using the following example: # angle AB is changed then BC = arccos((B**2+ C**2 - A**2) / (2*B*C)), CA = arccos((C**2+ A**2 - B**2) / (2*C*A)), # 30P # - class implements method to modify_side: # - modify_side method takes two argument: # - "side" and can be one of 3 string values 'A', 'B', 'C' # - "meters" that can be a positive or negative and represents the amount by which the side will be modified # If as a result of the change sum of the unmodified sides is less then or equal to the changed side then method should # throw an exception # If as a result of the change side will be less then or equal to 0 then method should raise a different exception # When a side is modified by some value all other sides need to be modified by the fraction of the change to maintain # the same triangle angles. For example if A increase by +1 then B = ((A+1)/A)*B and C = ((A+1)/A)*C from math import cos, acos, degrees class Triangle: A = B = C = 1 AB = BC = CA = 60 def __init__(self, a=1, b=1, c=1, ab=60, bc=60, ca=60): self.A = a self.B = b self.C = c self.AB = ab self.BC = bc self.CA = ca def modify_angle(self, angle, degrees_to_add): if angle == "AB": self.AB += degrees_to_add self.C = (self.A ** 2 + self.B ** 2 - 2 * self.A * self.B * cos(self.AB)) ** (1 / 2) self.BC = degrees(acos((self.B ** 2 + self.C ** 2 - self.A ** 2) / (2 * self.B * self.C))) self.CA = degrees(acos((self.C ** 2 + self.A ** 2 - self.B ** 2) / (2 * self.C * self.A))) elif angle == "BC": self.BC += degrees_to_add self.A = (self.B ** 2 + self.C ** 2 - 2 * self.B * self.C * cos(self.BC)) ** (1 / 2) self.AB = degrees(acos((self.A ** 2 + self.B ** 2 - self.C ** 2) / (2 * self.A * self.B))) self.CA = degrees(acos((self.C ** 2 + self.A ** 2 - self.B ** 2) / (2 * self.C * self.A))) elif angle == "CA": self.CA += degrees_to_add self.B = (self.C ** 2 + self.A ** 2 - 2 * self.C * self.A * cos(self.CA)) ** (1 / 2) self.AB = degrees(acos((self.A ** 2 + self.B ** 2 - self.C ** 2) / (2 * self.A * self.B))) self.BC = degrees(acos((self.B ** 2 + self.C ** 2 - self.A ** 2) / (2 * self.B * self.C))) if not (0 <= self.AB <= 180 or 0 <= self.BC <= 180 or 0 <= self.CA <= 180): raise ValueError("Angle out of range") def modify_side(self, side, meters): if side == "A": self.A += meters self.B = ((self.A + meters) / self.A) * self.B self.C = ((self.A + meters) / self.A) * self.C if self.B + self.C <= self.A: raise AttributeError("Modified side A too small") elif side == "B": self.B += meters self.A = ((self.B + meters) / self.B) * self.A self.C = ((self.B + meters) / self.B) * self.C if self.A + self.C <= self.B: raise AttributeError("Modified side B too small") elif side == "C": self.C += meters self.A = ((self.C + meters) / self.C) * self.A self.B = ((self.C + meters) / self.C) * self.B if self.A + self.B <= self.C: raise AttributeError("Modified side C too small") if self.A <= 0 or self.B <= 0 or self.C <= 0: raise ValueError("Side equal to 0") # 10P # Create an object from your class with default constructor values and modify angle AB by +30 degrees and side A by +1.5 triangle = Triangle() triangle.modify_angle("AB", 30) print("Angles: \n", "AB =", triangle.AB, "\n", "BC =", triangle.BC, "\n", "CA =", triangle.CA) triangle2 = Triangle() triangle2.modify_side("A", 1.5) print("Sides:\n", "A =", triangle2.A, "\n", "B =", triangle2.B, "\n", "C =", triangle2.C)
3905188b18eee497e3e7fd039fcf867026643345
dinnguyen1495/daily-coding
/DC29.py
1,324
4.34375
4
# Daily Coding 29 # Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent # repeated successive characters as a single count and character. For example, the string "AAAABBBCCDAA" # would be encoded as "4A3B2C1D2A". # Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and # consists solely of alphabetic characters. You can assume the string to be decoded is valid. def encode(string): stack = [] for c in string: if len(stack) == 0 or c != stack[-1][1]: stack.append([str(1), c]) continue old_number = stack.pop(-1)[0] stack.append([str(int(old_number) + 1), c]) return "".join("".join(elem) for elem in stack) def decode(string): decode_result = "" j = 0 for i in range(len(string)): try: val = int(string[i]) except ValueError: decode_result += int(string[j:i]) * string[i] j = i + 1 return decode_result def main(): encode_string = "AAAAAAAAAABBBCCDAA" print("Encode result for \"" + encode_string + "\": " + encode(encode_string)) decode_string = "4A10B2C1D2A" print("Decode result for \"" + decode_string + "\": " + decode(decode_string)) if __name__ == "__main__": main()
7ec2d675b00c391393f28eba0a2d1c8bfc074b3a
hari007/First-Program
/methods/variable local scope.py
469
3.671875
4
_Author_ = " HS " a = 10 def test(a): print("The value of local 'a' is "+ str(a)) a = 2 print("The value of local 'a' is "+ str(a)) print("Value of Global 'a' is " + str(a)) test(a) print("Value of Global 'a' is " + str(a)) a = 10 def test(): global a print("The value of local 'a' is "+ str(a)) a = 2 print("The value of local 'a' is "+ str(a)) print("Value of Global 'a' is " + str(a)) test() print("Value of Global 'a' is " + str(a))
d6cf9cee6c5fa297dc0faa77f18eaf32bb1e56ba
hienpham15/Codeforces_competitions
/Codeforces_round739/A.py
996
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 18 16:34:12 2021 @author: hienpham """ import os import math import sys parse_input = lambda: sys.stdin.readline().rstrip("\r\n") def check(val): str_val = str(val) if val%3 != 0 and str_val[-1] != '3': return True else: False def function(k, d): if k in d.keys(): return d[k] else: val = list(d.keys())[-1] for i in range(val+1, k+1): flag = True c_val = d[i-1] + 1 while flag: if check(c_val): d[i] = c_val flag = False else: c_val += 1 return d[k] #k = 10 #d = {} #d[1] = 1 #ans = function(k, d) def main(): n_cases = int(parse_input()) d = {} d[1] = 1 for i in range(n_cases): k = int(parse_input()) print(function(k, d)) if __name__ == "__main__": main()
688c841517d66e9f0c2f503748779e7d5dbffd3e
GemmaLou/iteration
/class ex rev 4.py
328
4.21875
4
#Gemma Buckle #17/10/2014 #rev ex 4 user_num=int(input("Please enter a number between 10 and 20, 10 and 20 included: ")) while user_num<10 or user_num>20: user_num=int(input("Invalid! Please try again. Enter a number between 10 and 20, 10 and 20 included. ")) print("Thank you! {0} is within range! :)".format(user_num))
173dbd81f2f2c3ddbf59970d83366e12248795f0
yasarkocyigit/MYSQL-PYHTON-DATA-SCIENCE-
/CREATING DATABASE copy.py
949
4.21875
4
""" i will upload everything about mysql as part once you learn previous part you will be ok for next one! i uploaded how to connect mysql to python as previous project. """ import mysql.connector mydb = mysql.connector.connect( host = "localhost", user ="root", passwd = "gs163264" ) # on this lesson we will learn how create a database mycursor = mydb.cursor() #CREATE A TABLE #my_cursor.execute(CREATE TABLE table_name) #SHOW TABLE #my_cursor.execute("SHOW TABLES") #SHOW DATABASE #my_cursor.execute("SHOW DATABASES") mycursor.execute("CREATE DATABASE IF NOT EXISTS test1") # when you check mysql application you will see there is a "matrixdb" databes # IF YOU DONT USE " IF NOT EXISTS " once you run code you will get syntax error next time # its because once you execute code you will have that named database and you cant have 2 same named database # and also you wont get syntax error if you use " IF NOT EXISTS "
de801ddeeb1be30e13afc1897a8da6875baa6eaf
cicerohr/Practice_Python
/exercicio001.py
883
3.953125
4
"""exercicio001.py em 2018-09-29. Projeto Practice Python. tipos de strings de entrada int Crie um programa que peça ao usuário para inserir seu nome e sua idade. Imprima uma mensagem endereçada a eles, informando o ano em que completará 100 anos. """ from datetime import datetime from cicero import cabecalho def idade_100(nome: str, idade: int) -> object: """Obtem nome e idade e retorna o ano em que fará 100 anos :param nome: nome do usuário :type nome: str :param idade: idade do usuário :type idade: int :return: ano em que completará 100 anos :rtype: object """ return print(f'Olá {nome}! Você completará 100 anos em {(datetime.now().year - idade) + 100}.') if __name__ == '__main__': cabecalho('Entrada de dados') n = str(input('Digite seu nome: ')) i = int(input('Digite sua idade: ')) idade_100(n, i)
dfda2e2a2477771b3220876536d25bea34c26ab7
ph0ph0/Python--Stepping-Motor
/L16_StepMotor.py
2,187
3.515625
4
import RPi.GPIO as GPIO import time motorPins = (12, 16, 18, 22) #define pins connected to four phase ABCD of stepper motor CCWStep = (0x01, 0x02, 0x04, 0x08) #define power supply order for coil rotating anticlockwise CWStep = (0x08, 0x04, 0x02, 0x01) #define power supply order for coil rotating clockwise def setup(): print('Program is starting...') GPIO.setmode(GPIO.BOARD) for pin in motorPins: GPIO.setup(pin, GPIO.OUT) # For a four phase stepping motor, four steps are a cycle. This function is used to drive the stepping motor clockwise or # anticlockwise to take four steps def moveOnePeriod(direction, ms): print('Moving one period') for j in range(0, 4, 1): #cycle for power supply order print('period ', j) for i in range(0, 4, 1): #assign to each pin, total of 4 if (direction == 1): #power supply order anticlockwise print('direction was clockwise') GPIO.output(motorPins[i], ((CCWStep[j] == 1 << i) and GPIO.HIGH or GPIO.LOW)) else: print('direction was anticlockwise') GPIO.output(motorPins[i], ((CWStep[j] == 1 << i) and GPIO.HIGH or GPIO.LOW)) if (ms < 3): #The delay can not be less than 3 ms, otherwise it will exceed speed limit of motor print('ms was less than 3', ms) ms = 3 time.sleep(ms * 0.001) # Continuous rotation function, the parameter steps specify the rotation cycles, every four steps is a cycle. def moveSteps(direction, ms, steps): print('Moving steps') for i in range(steps): moveOnePeriod(direction, ms) # function used to stop rotating def motorStop(): print('Stopping motor') for i in range(0, 4, 1): GPIO.output(motorPins[i], GPIO.LOW) def loop(): while True: moveSteps(1, 3, 512) #rotating 360 degrees clockwise, total of 2048 steps in a circle (512 cycles) time.sleep(0.5) moveSteps(0, 3, 512) #rotating 360 degrees anticlockwise time.sleep(0.5) def destroy(): GPIO.cleanup() if __name__ == '__main__': setup() try: loop() except KeyboardInterrupt: destroy()
5e4cf687d3f1108f851e0454a9e4f60a76962d5b
DaryaFilimonova7/cp8
/1.py
2,366
3.875
4
def bin1(a,answer): while True: if a // 1 != 0: if a % 2 == 0: answer.append(0) a = a // 2 elif a % 2 != 0: answer.append(1) a = a // 2 else: answer.reverse() print ("Двоичное представление числа равно " + "".join(map(str, answer))) break def oct1(a,answer): while True: if a // 1 != 0: if a % 8 == 0: answer.append(0) a = a // 8 #print(a) elif a % 8 == 1: answer.append(1) a = a // 8 elif a % 8 == 2: answer.append(2) a = a // 8 elif a % 8 == 3: answer.append(3) a = a // 8 elif a % 8 == 4: answer.append(4) a = a // 8 elif a % 8 == 5: answer.append(5) a = a // 8 elif a % 8 == 6: answer.append(6) a = a // 8 elif a % 8 == 7: answer.append(7) a = a // 8 else: answer.reverse() print ("Восьмеричное представление числа равно " + "".join(map(str, answer))) break while True: try: a = int(input("Введите десятичное число: ")) if a > 0: break else: print("Ошибка. Введите положительное число.") continue except: print("Ошибка.") continue answer = [] while True: try: syst = int(input("Введите основание системы счисления для перевода десятичного числа: ")) if syst == 2 or syst == 8: break else: print("Ошибка. Введите основание равное 2 или 8.") continue except: print("Ошибка.") continue if syst == 2: bin1(a,answer) else: oct1(a,answer)
43f8184842e82139aad1e08ca2ff2b4246a4755d
samuelhwolfe/pythonPractice
/programs/lists/chapterFourProblems.py
506
3.6875
4
spam = ['apples', 'bananas', 'tofu', 'cats'] myFavoriteThings = ['Beer', 'Pizza', 'Family', 'Snowboarding', 'Murphy', 'Kona', 'Movies', 'Cheese'] def listString(myList): myList.insert(-1, 'and ') firstPortion = myList[0:-2] for x in firstPortion: print((x) + ', ', end='') lastPortion = myList[-2:] for x in lastPortion: print((x), end='') myList = myFavoriteThings listString(myFavoriteThings)
e6cc2cc7eef22b44a794e50796773312c5c998fb
EwertonWeb/UriOnlineJudge
/1021_urionlinejudge.py
441
3.9375
4
values = float(input()) cash = [100,50,20,10,5,2] coins = [1,0.50,0.25,0.10,0.05,0.01] print('NOTAS:') for cash in cash: volume_cash = int(values / cash) print('{} nota(s) de R$ {:.2f}'.format(volume_cash,cash)) values -= volume_cash * cash print('MOEDAS:') for coins in coins: volume_coins = int(round(values,2) / coins) print('{} moeda(s) de R$ {:.2f}'.format(volume_coins,coins)) values -= volume_coins * coins
aa6af6724f5e3b9d89b604ddf5471bce8243cbb5
musram/python_progs
/real_python_tutorails/print_topic/printsa.py
3,588
4.03125
4
if __name__ == "__main__": #Three ways to declare string var = 'I am god' var = "I am god" var = """ I am god """ # supporting two types of string allows to putting quote in a string easier var = ' hellow "sai" bye' print(var) print(70*'=') print( " my name \n is \n sai") print(" hi i am " + str(1)) print('i', 6, 'memeners of') print('i', 6, 'memeners of', sep=' ') print('i', 6, 'memeners of', sep='\n') print('i', 6, 'memeners of', sep=None) # print() adds a \n at the end of what is being printed. This can be changed with the end parameter. Output from print() goes into a buffer. When you change the end parameter, the buffer no longer gets flushed. To ensure that you get output as soon as print() is called, you also need to use the flush=True parameter: import time def count_items(items): print('Counting ', end='', flush=True) num = 0 for item in items: num += 1 time.sleep(1) print('.', end='', flush=True) print('\nThere were {} items'.format(num)) data = [ ['year', 'last', 'first'], [1943, 'Idle', 'Eric'], [1939, 'Cleese', 'John'] ] for row in data: print(*row, sep = ' ') #print() normally prints to the <stdout> file stream. You can change this behavior using the file parameter. You can access the <stdout> stream directly from the sys library: import sys result = sys.stdout.write('hello\n') print(result) #to write to file with open('file.txt', mode='w') as f: print('hello world', file=f) #When you pass an object to print(), it converts it to a string using the str() function. You can create a __str__() method on your custom objects to change what is output: class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return 'Person({})'.format(self.name) def __repr__(self): return 'Person(name={}, age={}'.format( self.name, self.age) john = Person('john Cllese', 80) print(john) #The __str__() method is meant to output a human-readable version of your object. There is also a __repr__() method, which is meant for a Python representation of the object. There is a repr() function that corresponds to the str() function. If you define your __repr__() properly, then eval() can be called on its result to create a new object. print(repr(john)) #john2 = eval(repr(john)) #print(type(john2)) #print(id(john)) #print(id(john2)) #Some terminals support the ability to pass in special escape sequences to alter the color, weight, and appearance of the text being printed. #print('this is ', esc('31'), 'really', esc(0), ' important', sep='') #print('this is ', esc('31;1'), 'really', esc(0), ' important', sep='') #print('this is ', esc('31;1;4'), 'really', esc(0), ' important', sep='') #for real project print is not useful import logging, sys logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) logger = logging.getLogger(__name__) def count_lower_case(item): logger.info('count_lower_case(%s)', item) num = 0 for letter in item: if 97 <= ord(letter) <= 122: logger.debug(' letter *%s* is lowercase', letter) num += 1 logger.info(' returning %s', num) return num count_lower_case('AbCdE')
85a756985a57c9de154a1a0bcaeacc3d749f970d
abbykahler/Python
/bank_account/BankAccount.py
936
3.796875
4
class BankAccount: def __init__(self, name,int_rate, balance): self.int_rate = .1 self.balance = 0 def make_deposit(self, amount): self.balance += amount return self def make_withdrawal(self,amount): self.balance -= amount return self def display_balance(self): print(f'${self.balance}') return self def yield_interest(self): money = 0 if self.balance > 0: money = self.balance * self.int_rate self.balance += money return self account1 = BankAccount("Jason",.05,0) account2 = BankAccount("Mary",.05,0) account1.make_deposit(100).make_deposit(100).make_deposit(100).make_withdrawal(100).yield_interest().display_balance() account2.make_deposit(100).make_deposit(50).make_withdrawal(5).make_withdrawal(10).make_withdrawal(10).make_withdrawal(10).yield_interest().display_balance()
96bb453aaa5d8dd68d1027605286eff0bfe37fed
wballard/mailscanner
/mailscanner/layers/reverse.py
670
3.734375
4
''' Layers for the reversing of input tensors. ''' import keras class TimeStepReverse(keras.layers.Layer): """ A custom keras layer to reverse a tensor along the first non batch dimension, assumed to be the time step. # Input shape nD tensor with shape: `(batch_size, time_step, ...)`. # Output shape nD tensor with shape: `(batch_size, time_step, ...)`. """ def call(self, tensor): """ Use the backed to reverse. """ return keras.backend.reverse(tensor, 1) def compute_output_shape(self, input_shape): """ No change in shape. """ return input_shape
85500269ddf322186da7058d9bc924f5cc733fbb
daniel-reich/ubiquitous-fiesta
/6pEGXsuCAxbWTRkgc_21.py
227
3.671875
4
def loves_me(n): new = "" for i in range(n - 1): if i % 2 == 0: new += "Loves me, " else: new += "Loves me not, " if n % 2 == 0: new += "LOVES ME NOT" else: new += "LOVES ME" return(new)
e3dc46220ad0317677ad848b648c2eef15ba7eef
AShoom85/MyPythonCode
/L1/numberL1_3.py
452
4.1875
4
#Напишите программу, которая считывает целое число и выводит текст #The next number for the number число is число+1. The previous #number for the number число is число-1. С начала num = int(input("Input number = ")) print("The next number for the number " + str(num)+" is " + str(num + 1)) print("The previous number for the number " + str(num)+" is " + str(num - 1))
533e1904b02e6e8af91609c22228daf9f39aa907
yareddada/CSC101
/CH-06/check-points.py
3,656
4.125
4
check_point = { '6.1 What are the benefits of using a function?' : '\n\tcode reusability and simplification \n', '6.2 How do you define a function? How do you invoke a function?' : '\n\tdef name(params):body, m = main() \n', '6.3 Can you simplify the max function in Listing 6.1 by using a conditional expression?' : '\n\t \n', '6.4 True or false? A call to a None function is always a statement itself, but a call to a value-returning function is always a component of an expression.' : '\n\tTrue \n', '''\ 6.5 Can you have a return statement in a None function? Does the return statement in the following function cause syntax errors? def xFunction(x,y): print(X+y) return ''' : '\n\tYes. No \n', '6.6 Define the terms function header, parameter, and argument' : '\n\tHeader starts with def ends with :. params are vars, args are vals to params \n', '6.7' : '\n\t \n', '6.8' : '\n\t \n', '6.9' : '\n\t \n', '6.10' : '\n\t \n', '6.11 Compare positional arguments and keyword arguments' : '\n\tPositional args: specific order, kywd args: name=val \n', '''\ 6.12 Suppose a function header is as follows: def f(p1, p2, p3, p4): Which of the following calls are correct? a. f(1, p2 = 3, p3 = 4, p4 = 4) b. f(1, p2 = 3, 4, p4 = 4) c. f(p1 = 1, p2 = 3, 4, p4 = 4) d. f(p1 = 1, p2 = 3, p3 = 4, p4 = 4) e. f(p4 = 1, p2 = 3, p3 = 4, p1 = 4) ''' : 'a, d, e', '6.13 What is pass-by-value?' : '\n\tpassing the reference of a var to a functions param \n', '6.14 Can the argument have the same name as its parameter?' : '\n\tYes \n', '''\ 6.15 Show the result of the following programs: ''' : '''\ a. 2 b. 2 2 4 2 4 8 2 4 8 16 2 4 8 16 32 c. Before the call, variable times is 3 n = 3 Welcome to CS! n = 2 Welcome to CS! n = 1 Welcome to CS! After the call, variable times is 3 d. i is 1 1 i is 2 2 i is 3 nothing ''', '''\ 6.17 What is the printout of the following code? def function(x): print(x) x = 4.5 y = 3.4 print(y) x = 2 y = 4 function(x) print(x) print(y) ''': '''\ function(x) = 2, 3.4 print(x) = 2 print(y) = 4 ''', '''\ def f(x, y = 1, z = 2): return x + y + z print(f(1, 1, 1)) print(f(y = 1, x = 2, z = 3)) print(f(1, z = 3)) ''' : "3, 6, 5", '''\ 6.18 What is wrong with the following code? 1 def function(): 2 x = 4.5 3 y = 3.4 4 print(x) 5 print(y) 6 7 function() 8 print(x) 9 print(y) ''': "lines 8 and 9 will raise NameError as not being defined", '''\ 6.19 Can the following code run? If so, what is the printout? x = 10 if x < 0: y = -1 else: y = 1 print("y is", y) ''': "It runs, 1", '''\ 6.20 Show the printout of the following code: def f(w = 1, h = 2): print(w, h) f() f(w = 5) f(h = 24) f(4, 5) ''' : '''\ 1, 2 5, 2 1, 24 4, 5 ''', '''\ 6.21 ID and correct the errors in the following code 1 def main(): 2 nPrintln(5) 3 4 def nPrintln(message = "Welcome to Python!", n): 5 for i in range(n): 6 print(message) 7 8 main() # Call the main function ''' : "Line 4 should read: def nPrintln(n, message = 'Welcome to Python!')", '''\ 6.22 What happens if you define two functions in a module that have the same name? ''' : "The most recent will get loaded", '''\ 6.23 Can a function return several values? Show the printout of the following code: 1 def f(x, y): 2 return x + y, x - y, x * y, x / y 3 4 t1, t2, t3, t4 = f(9, 5) 5 print(t1, t2, t3, t4) ''' : "Yes, 14, 4, 45, 1.8" } for k, v in sorted(check_point.items()): print(k, v)
0935d43e0e117a48a2487a6a533ad4944eec4e29
SHJoon/Algorithms
/arrays/3_insert_at.py
434
4.15625
4
# InsertAt # Given an array, index, and additional value, insert # the value into the array at the given index. Do this # without using built-in array methods. You can # think of PushFront(arr,val) as equivalent to # InsertAt(arr,0,val). def insert_at(lst, idx, val): lst.append(0) for i in reversed(range(idx, len(lst))): lst[i] = lst[i - 1] lst[idx] = val my_lst = [0,1,3] insert_at(my_lst, 2, 2) print(my_lst)
1bc3db01b3f33d50978332c4c80ea8ce150f4214
yuquanle/JZOffer
/Num16_MergeListNode.py
1,320
3.78125
4
# -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 返回合并后列表 def Merge(self, pHead1, pHead2): if pHead1 == None and pHead2 == None: return None if pHead1 == None and pHead2 != None: return pHead2 if pHead1 != None and pHead2 == None: return pHead1 pMerge = ListNode(None) pTail = pMerge while pHead1 and pHead2: p1 = pHead1 p2 = pHead2 # 尾插法 if p1.val <= p2.val: pHead1 = pHead1.next p1.next = None pTail.next = p1 pTail = p1 if p2.val < p1.val: pHead2 = pHead2.next p2.next = None pTail.next = p2 pTail = p2 if pHead1 != None: pTail.next = pHead1 if pHead2 != None: pTail.next = pHead2 return pMerge.next a1 = ListNode(1) b1 = ListNode(4) c1 = ListNode(9) a1.next = b1 b1.next = c1 a2 = ListNode(2) b2 = ListNode(5) c2 = ListNode(8) a2.next = b2 b2.next = c2 solution = Solution() pmerge = solution.Merge(a1, a2) while pmerge: print(pmerge.val) pmerge = pmerge.next
b84e6857963d0c28fcbb89a0925556a3b0f25324
Creedes/HarvardCourse
/python/loops.py
268
4
4
for i in range(5): # one Statement print("Durchgang:", i) print("\n") for i in range(0, 10, 2): # start, stop, iteration (auch negative Werte erlaubt) print("Durchgang:", i) print("\n") name = "Harry" for character in name: print(character) print("\n")
70769f84a37c8544e1ac7db39e7e7c886f61154a
SindiCullhaj/pcs2
/lecture 5 - sorting/quick.py
353
4.1875
4
def quickSort(list): pivot = list[0] left = [] right = [] for i in range(1, len(list)): if (list[i] > pivot): right.append(list[i]) quickSort(right) else: left.append(list[i]) quickSort(left) a = [5, 1, 4, 2, 6, 3] print("Initial: ", a) quickSort(a) print("Final: ", a)
b2433b131ace21324eeb17e6c47ab02258cbc5ef
eskuye11/python
/myPy/studentGrades.py
3,187
4.28125
4
def student_rank(students): """ This function takes ('dictionary' or 'list of (name, grade) tuples') of students 'name' and 'numeric' grades and Returns the names and 'letter' grade's as (student_name, letter_grade) if a student had a single grade or (student_name, [letter_grades]) if a student had multiple grades Dict returns Dict and List returns List example_dict = {'Mary': 89, 'Mark': [85, 92], 'John': 100, 'Tina': 95, 'Sara': (89, 95, 99), 'Kelly': 95} one grade or more or mix """ ranks = {range(90, 101): 'A', range(80, 90): 'B', range(70, 80): 'C', range(60, 70): 'D', range(0, 60): 'F'} if isinstance(students, dict): letter_grades = dict() for student, grades in students.items(): all_grades = [] # if the student have more than one grade . . . if type(grades) == list or type(grades) == tuple: for grade in grades: if type(grade) != str: for rank in ranks: if grade in rank: all_grade = ranks.get(rank) all_grades.append(all_grade) else: all_grades.append('Type-Err! ') letter_grades[student] = all_grades else: # if the student has only a single grade . . . if type(grades) != str: for rank in ranks: if grades in rank: results = ranks.get(rank) letter_grades[student] = results else: letter_grades[student] = 'Type-Err! ' return letter_grades elif isinstance(students, list): # Check if it is a list if all(isinstance(item, tuple) for item in students): # to check it is a list of tuples try: letter_gradeL = [] for student, grades in students: if type(grades) != str: for rank in ranks: if grades in rank: results = ranks.get(rank) letter_gradeL.append((student, results)) else: letter_gradeL.append((student, 'Type-Err! ')) return letter_gradeL except ValueError as e: print("list of 'two pair tuples' only ") else: print(" All items in the list need to be 'tuples'") else: print("This func only take a 'Dict' or a 'List of tuple' ") # test class1 = {'Mary': 89, 'Mark': [85, 92], 'John': 100, 'Tina': 95, 'Sara': (89, 95, 99), 'Kelly': 95} mm = [('mom', 55), ('dad', 70), ('eyo', 89), ('esk', 94), ('Can', 98)] if __name__ == '__main__': # mylist = student_rank(mm) # for key in mylist: # print(key) print() mydict = student_rank(class1) for key in mydict.items(): print(key)
4218346877ba8848669e657408fdfdad55bcc215
Jamesical/Python
/Python Batch/Project 1/Exam_Student.py
807
3.9375
4
#Travis Saulat Python Programming Assignment: Exam Student 1/22/2021 DUE:1/29/2021 held = float(input('How many classes have been held?: ')) #series of inputs for the questions atte = float(input('How many classes have you attended?: ')) temp = float(input('What is your current temperature in Farenheit: ')) total = (atte/held)*100 #print(total) used to test what the total is for the if statement if total < 75: print("\nYou are NOT allowed to attend the exam because your attendence is", round(total,2),'% and your temperature is', temp, end=' degress Farenheit') else: print("\nYou are allowed to attend the exam because your attendence is", round(total,2),'% and your temperature is', temp, end=' degress Farenheit')
528fd137efc4263e3f54b7509b682426b9d9803f
A-Mitch/apythonaday
/week8/setsntuples.py
1,166
4.21875
4
# Lists (review), tuples, and sets # Lists - mutable # Exclusive list names = ['Alex','Samantha','Jun','Ravi','Eric'] morenames = ['Jeff','Michael'] # exlcusive range print/slicing print(names[0:3]) names.insert(1,'Jay') print(names) print("adding multiple values with extend") names.extend(morenames) print(names) names.remove("Ravi") print(names) # reverse a list names.reverse() print(names) # names.sort() sortednames = sorted(names) print(sortednames) numlist = [7,1,3,6,5,4] print(sum(numlist)) # Find the index of a value print(names.index('Samantha')) # enumerating for index,name in enumerate(names): print(index,name) print("I know "+' and '.join(names)) # Tuples - inmutable ~ Like lists nametupe = ('Alex', 'Samantha', 'Jun', 'Ravi', 'Eric') nametupe2 = nametupe print(nametupe) # Sets - returns only unique values nameset = {'Alex', 'Samantha', 'Jun', 'Ravi', 'Eric'} nameset2 = {'Michael', 'Jin', 'Sarah', 'Ib', 'Eric'} print(nameset) print("Alex" in nameset) print(nameset.intersection(nameset2)) # like a left join print(nameset.difference(nameset2)) print(nameset.union(nameset2)) # How to create empty versions emptyset = set()
fde35cc2c7496ebef4303743a3169e343454e482
houyizhong/ATM-of-python
/core/demo_shoplist.py
1,406
3.640625
4
import pickle,os from demo_login import login import demo_credit filename=os.path.abspath(__file__) dirname=os.path.dirname(filename) product_path=dirname+os.sep+'product.txt' def shopping(): shopping_list=[] price=0 '''read product''' f=open(product_path,'rb') product_list=pickle.load(f) f.close() @login def credit_payment(username,shoplist,price): result=demo_credit.payment(username,shoplist,price) if result == 'success': print ('You shopping done!') elif result == 'failure': print ('Sorry,your credit card balance is not enought!\n') else: print('Sorry,there have some unknown error!\n') while True: for index,item in enumerate(product_list): print(index+1,item) user_choice=input("Choice a product code('q' is exit.'pay' is settlement):") if user_choice.isdigit(): user_choice = int(user_choice) if user_choice <= len(product_list) and user_choice > 0: user_choice -= 1 price += int(product_list[user_choice][1]) shopping_list.append(product_list[user_choice][0]) print ('Add {} to your shopplist!\n'.format(product_list[user_choice][0])) else: print("Sorry,product code isn's exist!\n") elif user_choice == "q": break elif user_choice == 'pay': print('Your check is {}'.format(price)) if price != 0: credit_payment(shopping_list,price) break else: print("Your enter invalid!\n")
d9a35952d09592a48da868243b7d09e5941f28e3
AlSavva/Algorytms_and_data_structure
/task6_les1.py
1,414
4.21875
4
# По длинам трех отрезков, введенных пользователем, определить возможность # существования треугольника, составленного из этих отрезков. Если такой # треугольник существует, то определить, является ли он разносторонним, # равнобедренным или равносторонним. a = float(input('Введите длинну отрезка АВ: ')) b = float(input('Введите длинну отрезка BC: ')) c = float(input('Введите длинну отрезка AC: ')) if (a + b > c) and (b + c > a) and (a + c > b) and a > 0 and b > 0 and c > 0: if a != b and b != c and c != a: print(f'Треугольник со сторонами АВ = {a}, BC = {b} и AC = {c} - ' f'разносторонний.') elif a == b == c: print(f'Треугольник со сторонами АВ = {a}, BC = {b} и AC = {c} - ' f'равносторонний.') else: print(f'Треугольник со сторонами АВ = {a}, BC = {b} и AC = {c} - ' f'равнобедренный.') else: print(f'Треугольника со сторонами АВ = {a}, BC = {b} и AC = {c} - ' f'не существует.')
5cd14bb498d4ccd1e2edc726149cf196428be70b
naye0ng/Algorithm
/SWExpertAcademy/D4/1238.py
1,016
3.5
4
""" 1238.Contact """ def contact(start): queue = [] queue.append([0, start]) depth = 0 maxitem = 0 while queue: node = queue.pop(0) # 깊이가 깊어질때 if depth < node[0]: depth = node[0] maxitem = node[1] # 깊이가 같은데 현재 노드의 값이 더 클때 if depth == node[0] and maxitem < node[1]: maxitem = node[1] for g in G[node[1]]: if visitied[g] == 1: continue queue.append([node[0] + 1, g]) # 삽입 시에 visitied 체크해줘야 중복으로 가리키는 같은 depth를 피할 수 있음 visitied[g] = 1 return maxitem for test_case in range(1, 11): n, start = map(int, input().split()) path = list(map(int, input().split())) visitied = [0 for _ in range(101)] G = [[] for _ in range(101)] for i in range(0, n, 2): G[path[i]] += [path[i + 1]] print(f'#{test_case} {contact(start)}')
0f512c04af480cc001ad8324770cb98309139a64
NMBURobotics/IMRT100
/python/basics/04_if_statements_and_while_loops.py
687
4.21875
4
program_is_running=True while program_is_running: # Get user name and age user_name = input("Please enter your name: ") user_age = int(input("Please enter your age: ")) # Evaluate input, and output answer to user if user_age < 18: print("You are too young to drive a car, " + user_name) elif user_age > 99: print("You are too old to drive a car, " + user_name) else: print("You are old enough to drive a car, " + user_name) # Ask user if it's time to exit the program user_command = input("Type exit to terminate program: ") if user_command == "exit": program_is_running = False print("Goodbye")
13526b556b43f6ab8d26ce0cd1267db867cd9621
ongaaron96/kattis-solutions
/python3/2_4-lindenmayorsystem.py
332
3.53125
4
num_rules, iterations = map(int, input().split()) rules = dict() for _ in range(num_rules): x, _, y = input().split() rules[x] = y word = input() for _ in range(iterations): new_word = "" for char in word: if char in rules: new_word += rules[char] else: new_word += char word = new_word print(word)
38d903f220b44c57f00820a12d76108a99520245
berkayalatas/data-structures-and-algorithms
/hastTable.py
5,089
3.875
4
class Hashtable: # Assumption: table_length is a prime number (for example, 5, 701, or 30011) def __init__(self, table_length): self.table = [None] * table_length ## An internal search function. # If it finds the given key in the table, it will return (True, index) # If not, it will return (False, the index where it would be inserted) # If the table is full, it will return (False, -1) # If test_mode is true, it will also add a third return value that shows # the number of elements that have been checked (in the case where # the key is not found and the table is not full). # Assumption: key is a string. def _search(self, key, test_mode = False): hash1 = hash(key) m = len(self.table) initial_i = hash1 % m # initial_i's range: [0, m - 1] (inclusive) count = 1 # the number of elements that have been checked - only used when test_mode = True. if not self.table[initial_i]: if test_mode: return (False, initial_i, count) return (False, initial_i) elif self.table[initial_i][0] == key: return (True, initial_i) ## We have a collision! # We're going to deal with it with double-hashing. # First, create a new hashed value by slightly modifying the input key. hash2 = hash(key + 'd') # hash2 = hash1 # I tried this method and it worked as well as the above method. # hash2 = 0 # This would be linear probing. It did NOT perform as well as the above method. # Our constraint here: 1 <= c < m # Note that hash2 % (m - 1) produces a number in the range [0, m - 2] inclusive c = hash2 % (m - 1) + 1 i = (initial_i + c) % m while i != initial_i: count += 1 if not self.table[i]: if test_mode: return (False, i, count) return (False, i) elif self.table[i][0] == key: return (True, i) else: i = (i + c) % m return (False, -1) # The table is full. ## Inserts a key value pair. If the key exists, it updates the value. # If it doesn't exit, it inserts it. # If the table is full, it returns without doing anything. # Assumption: key is a string. # Returns: nothing. def insert(self, key, value): result = self._search(key) if result[1] == -1: return # The table is full. # If the key already exists, update the value. if result[0]: i = result[1] self.table[i][1] = value return # At this point, we'll know that the given key doesn't exist # in the table yet, and that result[1] is the index # where the new key-value pair should be inserted. i = result[1] self.table[i] = [key, value] ## Returns the value if the key is found. # If not, it will return False. # Assumption: key is a string. def search(self, key): result = self._search(key) if result[1] == -1: return False # The table is full. if not result[0]: return False i = result[1] return self.table[i][1] ## I haven't implemented this yet. # To implement this one with open-addressing (double-hashing), # you should replace the deleted entry with a dummy value instead of deleting it. def delete(key): pass ## The following is for testing the Hashtable class. if __name__ == "__main__": ht = Hashtable(5) ht.insert('key1', 9) ht.insert('key2', 2) ht.insert('key3', 10) ht.insert('key4', 100) assert not ht.search('key5') # Since this key doesn't exist yet, it should return False. ht.insert('key5', 10) assert ht.search('key1') == 9 assert ht.search('key2') == 2 assert ht.search('key3') == 10 assert ht.search('key4') == 100 assert ht.search('key5') == 10 assert not ht.search('key6') # Since this key doesn't exist, it should return False. # You should be able to update existing values, too. ht.insert('key3', -1) ht.insert('key5', 42) assert ht.search('key3') == -1 assert ht.search('key5') == 42 ## The following part is for checking the number of # elements being checked for un unsuccessful search. ht2 = Hashtable(30011) for i in range(1, 20004): # We're going to fill in about two thirds of the table. ht2.insert('key' + str(i), 1) # Try searching for a bunch of new keys. # Then, find the average number of elements that were checked. total = 0 num_trials = 10**5 max_num = 0 for i in range(0, num_trials): num_checked = ht2._search('new_key_' + str(i), test_mode=True)[2] total += num_checked if num_checked > max_num: max_num = num_checked average = total / num_trials print('Average number of elements checked:', average) print('Max number of elements checked:', max_num)
c3a9135833a2ec2da1a3cabab427ef83d9216b12
HaseebGitWitIt/MachineLearningGroceryListMobileApp
/Python/GrocListObj.py
1,454
3.59375
4
import os import sys import ItemObj file_dir = os.path.dirname(__file__) sys.path.append(file_dir) class GrocList(object): def __init__(self, name, items=[]): if type(items) != list: raise ValueError("Error in GrocListObj: items parameter must be a list") self.setName(name) self.items = [] for item in items: self.addItem(item) """ str Returns a string describing the Store object @input None @return A string describing the Store object """ def __str__(self): retStr = "%s:\n" % (self.name) for item in self.items: retStr += "\t%s\n" % (item.getName()) return(retStr) """ setName Sets the name of the object to given name @input newName The new name of the object @return None """ def setName(self, newName): if type(newName) != str: raise ValueError("Error in GrocListObj: name parameter must be a string") self.name = newName """ getName Returns the name of the object @input None @return The name of the object """ def getName(self): return(self.name) """ addItem Adds the given item to the list of items @input newItem The item to add to the list @return None """ def addItem(self, newItem): if type(newItem) != ItemObj.Item: raise ValueError("Error in GrocListObj: items must be Item objects") self.items.append(newItem) """ getItems Returns the current list of items @input None @return The current list of items """ def getItems(self): return(self.items)
75ce897730a8fa73c53d0324e86be8137adf2204
khayatioualid/LangageDeScrips2021
/ListeCreation Analyse Probleme.py
715
3.90625
4
def createList1D(d1): return [0]*d1 def createList2D(d1,d2): L=createList1D(d1) for i in range(len(L)): L[i]=createList1D(d2) return L def createList3D(d1, d2, d3): L=createList1D(d1) for i in range(len(L)): L[i]=createList2D(d2, d3) return L def createList4D(d1,d2, d3, d4): L=createList1D(d1) for i in range(len(L)): L[i]=createList3D(d2, d3, d4) return L print(createList4D(2, 3, 2, 4)) """ L1 = createList(4) print(L1) # ==> [0, 0, 0, 0] L2 = createList(2, 4) print(L2) # ==> [[0, 0, 0, 0], [0, 0, 0, 0]] L3 = createList(3, 2, 4) print(L2) # ==> [[[0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0]]] """
2dccb8cb72f6f83ff04f8f24a4030f37e4522c9a
arinablake/python-selenium-automation
/hw_algorithms_3/fibonacci_element.py
402
4.15625
4
#Домашнее задание: Написать программу для вывода только указаного элемента последовательности Fibonacci num = int(input("Enter the Number: ")) first = 0 second = 1 for i in range(1, num+1): if i <= 1: fib = i else: fib = first + second first = second second = fib print(fib)
7f5b279c95835a9f795044c0473b9344148cd8ef
emrectn/Python_Tutorial
/db_sqlite.py
2,510
3.625
4
import sqlite3 """ Python ile Sqlite Veritabanı nasıl kullanılır öğrenmeye çalışacağız. Bu bölümde basit anlamda Sqlite veritabanı kodları bulunmaktadır. """ # Sqlite'yı dahil ediyoruz import sqlite3 # Tabloya bağlanıyoruz. con = sqlite3.connect("kütüphane.db") # cursor isimli değişken veritabanı üzerinde işlem yapmak için kullanacağımız imleç olacak. cursor = con.cursor() def tablo_oluştur(): cursor.execute("CREATE TABLE IF NOT EXISTS kitaplık (İsim TEXT, Yazar TEXT, Yayınevi TEXT, Sayfa_Sayısı INT)") # Sorguyu çalıştırıyoruz. # Sorgunun veritabanı üzerinde geçerli olması için commit işlemi gerekli. con.commit() # INSERT INTO kitaplık VALUES('İstanbul Hatırası','Ahmet Ümit','Everest',561) def deger_ekle(): cursor.execute("INSERT INTO kitaplık VALUES('İstanbul Hatırası','Ahmet Ümit','Everest',261)") con.commit() # Peki kullanıcıdan aldığımız değerleri tabloya nasıl ekliyoruz ? Onun için de sorgumuzu ve kodumuzu biraz değiştireceğiz. def kullanıcı_deger_ekle(isim,yazar,yayınevi,sayfa_sayısı): cursor.execute("INSERT INTO kitaplık VALUES(?,?,?,?)",(isim,yazar,yayınevi,sayfa_sayısı)) con.commit() def verileri_al(): cursor.execute("Select * From kitaplık") # Bütün bilgileri alıyoruz. data = cursor.fetchall() # Veritabanından bilgileri çekmek için fetchall() kullanıyoruz. print("Kitaplık Tablosunun bilgileri.....") for i in data: print(i) # con.commit() işlemine gerek yok. Çünkü tabloda herhangi bir güncelleme yapmıyoruz. def verileri_al3(yayınevi): cursor.execute("Select * From kitaplık where Yayınevi = ?",(yayınevi,)) # Sadece yayınevi ,Everest olan kitapları alıyoruz. data = cursor.fetchall() print("Kitaplık Tablosunun bilgileri.....") for i in data: print(i) def verigüncelle(yayınevi): cursor.execute("Update kitaplık set Yayınevi = ? where Yayınevi = ?", ("Everest", yayınevi)) con.commit() def verilerisil(yazar): cursor.execute("Delete From kitaplık where Yazar = ?", (yazar,)) con.commit() # isim = input("İsim:") # yazar = input("Yazar:") # yayınevi = input("Yayınevi:") # sayfa_sayısı = int(input("Sayfa Sayısı:")) tablo_oluştur() # deger_ekle() # kullanıcı_deger_ekle(isim,yazar,yayınevi,sayfa_sayısı) verileri_al() verileri_al3("Everest") verigüncelle("Doğan Kitap") verilerisil("Besen Ümit") # Bağlantıyı koparıyoruz. con.close()
a723b86e700204e88cb7c6021cbd20367d819ebe
hc973591409/python
/13.py
632
3.828125
4
# str遍历 str_1 = '1234abcd' for ch in str_1: print(ch,end=',') print("") # 列表遍历 list_1 = [1,2,3,4,5,6,7,8,9] i = 0 for li in list_1: print('%d %d' %(i,li),end=',') i += 1 print("") # 元组遍历 tuple_1 = (9,8,7,6,5,4) i = 0 for item in tuple_1: print("%d %d" %(i,item),end=',') i += 1 print("") # 字典遍历 info = {'name':'班长', 'id':100, 'sex':'f', 'address':"地球亚洲北京"} for key in info.keys(): print(key,end=',') print("") for value in info.values(): print(value,end=',') print("") for item in info.items(): print(item, end=',') print("")
6277d44114bd1a6ababda0ec482fdc8b6b1dcbe6
smothly/algorithm-solving
/boj-11003.py
766
3.515625
4
''' 백준 11003번 최솟값 찾기 링크: https://www.acmicpc.net/problem/11003 풀이방법 - 슬라이딩 윈도우 - deque ''' from sys import stdin from collections import deque stdin = open("input.txt", "r") # N: 숫자의 개수 # L: 임의의 수 N, L = map(int, stdin.readline().split()) numbers = list(map(int, stdin.readline().split())) queue = deque() for i in range(N): # i-L+1 인덱스 이전인 것들을 pop해준다. while queue and queue[0][0] <= i-L: queue.popleft() # 들어갈 숫자보다 큰 것들은 전부 pop해준다. while queue and queue[-1][1] >= numbers[i]: queue.pop() queue.append((i, numbers[i])) print(queue[0][1], end=' ') # 큐에 최소값 출력
c2ec4d21e129253f2afd8b0230a2721a34a41104
fimanishi/DigitalCrafts-Week1
/list_multiply_items.py
146
4.125
4
#!/usr/env/bin python3 def multiply_list(l,f): for i in range(len(l)): l[i] = l[i]*f a = [1,2,3,4,5] multiply_list(a,3) print(a)
e4155922478979ee193220d2d72b2cedb45e4d64
botelhomn/4linux
/4linux-master/aula03/ex03.py
1,085
4.09375
4
#!/usr/bin/python3 """ Script para realizar funções de uma calculadora Autor: Data: Alterações.... """ def escolhe_op(): opcao = int(input("Digite a opcao desejada:")) while opcao < 1 or opcao > 4 : print("Opcao Invalida") opcao = int(input("Digite a opcao desejada:")) return opcao def soma(a,b): print(a+b) def sub(a,b): print(a-b) def mult(a,b): print(a*b) def div(a,b): if b == 0: print("Não existe div por zero") else: print(a/b) dic = {1:soma, 2:sub, 3:div, 4:mult} def main(): print("Calculadora:") num1 = int(input("Digite o primeiro n:")) num2 = int(input("Digite o segundo n:")) print("Escolha a opcao:") print("1 - SOMA\n2 - SUB\n3 - DIV\n 4 - MULT") opcao = escolhe_op() dic[opcao](num1,num2) if __name__ == "__main__": main() exit() if opcao == 1: soma(num1,num2) elif opcao == 2: sub(num1, num2) elif opcao == 3: div(num1,num2) elif opcao == 4: mult(num1,num2) else: print("Opcao Invalida.") #funções
acf919ca7c07f8cbc7d89b31aca2e748b938b729
Cocoolanu/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python
/Chapter3_DataStructures/disQ1.py
363
3.78125
4
from stack import Stack def binaryConvert(num): myStack = Stack() binaryString = '' while num > 0: temp = num % 2 myStack.push(temp) num = num // 2 while not myStack.isEmpty(): binaryString += str(myStack.pop()) return binaryString print(binaryConvert(17)) print(binaryConvert(45)) print(binaryConvert(96))
368a7793a6123ca4d5fe08014311a27c46792958
Mauzzz0/study-projects
/python/lab2_python/15.5.py
410
3.515625
4
lst = list() for _ in range(int(input())): """ Ivanov came Kyznetsov came Polivanov came Zorina over Kyznetsov Ivanova gone """ g = input().split(" ") if len(g) == 2: if g[1] == "came": lst.append(g[0]) elif g[1] == 'gone': lst.remove(g[0]) elif len(g) == 3: lst.insert(lst.index(g[2])+1, g[0]) for j in lst: print(j)
5cd3c407bc16e8294ce7ba1a9e0443ccd2bf6e54
threedworld-mit/tdw
/Python/tdw/object_data/transform.py
1,253
3.828125
4
import numpy as np class Transform: """ Positional data for an object, robot body part, etc. """ def __init__(self, position: np.ndarray, rotation: np.ndarray, forward: np.ndarray): """ :param position: The position vector of the object as a numpy array. :param rotation: The rotation quaternion of the object as a numpy array. :param forward: The forward directional vector of the object as a numpy array. """ """:field The position vector of the object as a numpy array: `[x, y, z]` The position of each object is the bottom-center point of the object. The position of each Magnebot body part is in the exact center of the body part. `y` is the up direction. """ self.position: np.ndarray = position """:field The rotation quaternion of the object as a numpy array: `[x, y, z, w]` See: [`tdw.quaternion_utils.QuaternionUtils`](https://github.com/threedworld-mit/tdw/blob/master/Documentation/python/tdw_utils.md#quaternionutils). """ self.rotation: np.ndarray = rotation """:field The forward directional vector of the object as a numpy array: `[x, y, z]` """ self.forward: np.ndarray = forward
92262f345e002d6e6b8674be374852ed98774f92
syurskyi/Python_Topics
/010_strings/examples/Python 3 Most Nessesary/6.11.Listing 6.4. Summing an indefinite number of numbers.py
1,046
3.859375
4
# -*- coding: utf-8 -*- print("Введите слово 'stop' для получения результата") summa = 0 while True: x = input("Введите число: ") if x == "stop": break # Выход из цикла if x == "": print("Вы не ввели значение!") continue if x[0] == "-": # Если первым символом является минус if not x[1:].isdigit(): # Если фрагмент не состоит из цифр print("Необходимо ввести число, а не строку!") continue else: # Если минуса нет, то проверяем всю строку if not x.isdigit(): # Если строка не состоит из цифр print("Необходимо ввести число, а не строку!") continue x = int(x) # Преобразуем строку в число summa += x print("Сумма чисел равна:", summa) input()
0756adeb749b37c885b4a761960aa492ded3597c
tosha96/euler-solutions
/p23.py
749
3.875
4
def sumofpd(number): sum = 0 for divisor in range(1, number + 1): if number % divisor == 0 and number != divisor: sum = sum + divisor return sum abundants = [] cantbesummedsum = 0 #generate list of abundants less than number which all integers greater than it can be created by the sum of abundant number for number in range(1, 28125): if sumofpd(number) > number: abundants.append(number) print number print abundants for number in range(1, 28124): print number canbesummed = False for abundant in abundants: if abundant < number: result = number - abundant if result in abundants: canbesummed = True break if not canbesummed: cantbesummedsum = cantbesummedsum + number print "Sum: " + str(cantbesummedsum)
775354f0027e52973d7fe0570a0168e63c665ec2
Python-Learn-Training/Python_Learn_1
/Learn-Training/random-statistics.py
1,198
3.78125
4
# 隨機模組 import random ########################################### # 隨機選取 choice&sample # data=random.choice([1,4,6,10,20]) #隨機選取 # data=random.sample([1,4,6,10,20],3) #隨機選取3筆 # print(data) ########################################### # 隨機調換順序(洗牌) shuffle # data=[1,5,6,10] # random.shuffle(data) # print(data) ########################################### # 隨機取得亂數 random&uniform # data=random.random() #0 ~ 1之間的隨機亂數 # data=random.uniform(0.0 ,1.0) #0.0 ~ 1.0 之間的隨機亂數 代表0.0~1.0之間的數字出現是相等的 # data=random.uniform(60 ,100) # print(data) ########################################### # 取得常態分配亂數 normalvariate # 平均數100 , 標準差10 , 得到的資料 [多數] 在90 ~ 110之間 # data=random.normalvariate(100,10) # print(data) # 平均數0 , 標準差5 , 得到的資料 [多數] 在 -5 ~ 5之間 # data=random.normalvariate(0,5) # print(data) ########################################### # 統計模組 statistics import statistics as stat # data=stat.median([1,2,3,4,5,4,100]) #中位數 median data=stat.stdev([1,2,3,4,5,4,100]) #標準差 stdev print(data)
a9cf35cfcc4b2eccda75811a7af8b3c5a1ca53e2
Aierhaimian/LeetCode
/Queue/0232_ImplementQueueUsingStack/queue_by_stack.py
1,212
4.4375
4
#!/usr/bin/env python3 # -*-coding: utf-8 -*- """ Version: 0.1 Author: Earl """ """ Time Complexity: O(2n) Space Complexity: O(2n) """ class MyQueue: def __init__(self): """ Initialize your data structure here. """ input_stack = [] output_stack = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ input_stack.append(x); def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ tmp = peek() output_stack.pop() return tmp def peek(self) -> int: """ Get the front element. """ if not output_stack: while input_stack: output_stack.append(input_stack.pop()) return output_stack[-1] def empty(self) -> bool: """ Returns whether the queue is empty. """ return (not input_stack) and (not output_stack) # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty() if __name__ == "__main__":
8e8fc74768d12bf8cb021954668873693d3a1b72
emeee/simple-binary-search-tree
/BST.py
3,261
3.671875
4
from node import Node class BST: def __init__(self): self.root = None self.size = 0 def length(self): return self.size def insert(self, key, val): if self.root: self._insert(key, val, self.root) else: self.root = Node(key ,val) self.size += 1 def _insert(self, key, val, currentNode): if key < currentNode.getKey(): if currentNode.getLeftChild(): self._insert(key, val, currentNode.getLeftChild(), parent=currentNode) else: currentNode.setLeftChild(Node(key, val)) else: if currentNode.getRightChild(): self._insert(key, val, currentNode.getRightChild(), parent=currentNode) else: currentNode.setRightChild(Node(key, val)) def get(self, key): if self.root: return self._get(key, self.root) else: return None def _get(self, key, currentNode): if not currentNode: return None elif key < currentNode.getKey(): return self._get(key, currentNode.getLeftChild()) elif key > currentNode.getKey(): return self._get(key, currentNode.getRightChild()) elif key == currentNode.getKey(): return currentNode def delete(self, key): if self.size > 1: nodeToRemove = self._get(key, self.root) if nodeToRemove: self._delete(nodeToRemove) self.size -= 1 else: raise('Key not found') elif self.size == 1 and self.root.key == key: self.root = None self.size = 0 else: raise('Empty tree') def _delete(self, key, currentNode): #Simple delete if currentNode.isLeaf(): if currentNode == currentNode.parent.getLeftChild(): currentNode.parent.setLeftChild = None else: currentNode.parent.setRightChild = None #Replace de node with its child if currentNode.hasOneChild(): if currentNode.getLeftChild(): if currentNode.parent.getLeftChild() == currentNode: currentNode.parent.setLeftChild(currentNode.getLeftChild()) else: currentNode.parent.setRightChild(currentNode.getLeftChild()) else: if currentNode.parent.getLeftChild() == currentNode: currentNode.parent.setLeftChild(currentNode.getRightChild()) else: currentNode.parent.setRightChild(currentNode.getRightChild()) #TODO: HasTwoChild def printPreOrder(self, node): if node is not None: print node.data self.printPreOrder(node.left) self.printPreOrder(node.left) def printInOrder(self, node): if node is not None: self.printPreOrder(node.left) print node.data self.printPreOrder(node.left) def printInOrder(self, node): if node is not None: self.printPreOrder(node.left) self.printPreOrder(node.left) print node.data
7defa3430066cb81cb821a8b7ea92b5205c1c417
SergeyHess/kek
/binarySearch.py
288
3.890625
4
def binary_search(arr, value): top = len(arr) - 1 bott = 0 mid = len(a) // 2 while arr[mid] != value and bott <= top: bott = mid + 1 if value > arr[mid] else top = mid - 1 mid = (top + bott) // 2 print('No value') if bott > top else print(mid)
a1e93ffb4724066747c1d1421f67b16b2e81b30c
debrekXuHan/core_python
/chap3/read_modified.py
377
4.1875
4
#!/usr/bin/env python 'readTextFile.py -- read and display text file' import os # attempt to open file for reading while True: fname = input('Enter a filename: ') if not os.path.exists(fname): print('ERROR: %s does not exist\n' % fname) else: break # display contents to the sceen fobj = open(fname, 'r') for eachLine in fobj: print(eachLine, end = '') fobj.close()
136cc2404cb01fb3a2a4862ca82051d43f301e0d
SkrGitRepo/MyPythonDjango
/PYTHON_TRANING/CG_Python_Training/Day1/VariableArgument.py
221
4
4
def Var(*arg): print arg Var(4,6,'hello') #------------------------- #Mult(1,2,3,4) = (1*2*3*4) def Mult(*arg): mul =1 for num in arg: mul = mul*num print mul Mult(5,2,3,4)
771e7f001e4b0cff78390b28d316534ad441f2e0
konradluberapolsl/Algorytmy
/Zad2/Zad2.1 Kolejka/Zad2.1.py
1,430
4.03125
4
class Queue: def __init__(self, capacity): self.Queue = [] self.capacity = int(capacity) def __str__(self): if self.is_empty(): return "kolejka jest pusta" else: return str(self.Queue) def size_of_queue(self): return len(self.Queue) def is_empty(self): if self.size_of_queue() == 0: return True else: return False def is_full(self): if self.size_of_queue() == self.capacity: return True else: return False # dodaje nowy element na końcu def push_element(self, item): if not self.is_full(): self.Queue.append(item) else: print("kolejka jest pełna") # usuwa pierwszy element def pop_element(self): if not self.is_empty(): self.Queue.pop(0) else: print("kolejka jest pusta") kolejka = Queue(5) kolejka.push_element(1) print(kolejka) kolejka.push_element(2) print(kolejka) kolejka.push_element(3) print(kolejka) kolejka.push_element(4) print(kolejka) kolejka.push_element(5) print(kolejka) kolejka.push_element(6) kolejka.pop_element() print(kolejka) kolejka.pop_element() print(kolejka) kolejka.pop_element() print(kolejka) kolejka.pop_element() print(kolejka) kolejka.pop_element() print(kolejka)
4b44d25c71da627c2cb2c268f6f6070bc7f81636
bojan-popovic-devtech/UdemyPython
/Section 6 - Program Flow/IfChallenge.py
506
4.25
4
#Write a small program to ask for a name and an age. #When both values have been entered, check if the person #is the right age to go on an 18-30 holiday ( they must be over 18 and under 31) #If they are, welcome them to the holiday, otherwise print #a (polite) message refusing them entry name = input("Please enter your name: ") age = int(input ("Please enter your age: ")) if 18 <= age < 31: print("Welcome to 18-30 Holiday !") else: print("Sorry but you are not eligible for 18-30 Holiday")
784bf76695b67e8d3c076b9cd811a1cb1d72ca6f
khaveesh/DAA-DoubleHelix
/anarc05b_double_helix.py
2,036
3.96875
4
"""Author - Khaveesh N IMT2018036. Solves the ANARC05B problem in SPOJ.""" import typing from dataclasses import dataclass @dataclass class DoubleHelix: """Class to solve the double helix problem.""" first: typing.List[int] second: typing.List[int] iter_first = 0 iter_second = 0 sum1 = 0 sum2 = 0 def solve(self) -> int: """Solves the double helix for the given input arrays. Returns: The maximum sum possible. """ length: typing.Tuple[int, int] = (self.first.pop(0), self.second.pop(0)) while self.iter_first < length[0] and self.iter_second < length[1]: self._solve_helper() while self.iter_first < length[0]: self._inc_first() while self.iter_second < length[1]: self._inc_second() return max(self.sum1, self.sum2) def _solve_helper(self) -> None: if self.first[self.iter_first] < self.second[self.iter_second]: self._inc_first() elif self.first[self.iter_first] > self.second[self.iter_second]: self._inc_second() else: # Intersection Point self._inc_first() self._inc_second() # Assigning the maximum of sum1 & sum2 to both if self.sum1 > self.sum2: self.sum2 = self.sum1 else: self.sum1 = self.sum2 def _inc_first(self) -> None: self.sum1 += self.first[self.iter_first] self.iter_first += 1 def _inc_second(self) -> None: self.sum2 += self.second[self.iter_second] self.iter_second += 1 if __name__ == "__main__": while True: # Convert string input to list of ints FIRST: typing.List[int] = list(map(int, input().split())) if FIRST[0] == 0: # End condition break SECOND: typing.List[int] = list(map(int, input().split())) # Create an instance of the class and call solve function print(DoubleHelix(FIRST, SECOND).solve())
6f6593de948aa86144b6b386e1220ff7d19d0d00
vinayhg87/SeleniumUdemy
/Classes/MethodOverloading.py
763
3.9375
4
# In Python, overloading is not an applied concept. # we need to use a package like pythonlangutil to get the method overloading functionality or use the below technique. # None is a keyword which is equivalent to null. # Python does not support method overloading, that is, it is not possible to define more than one method with the same name in a class in python. # This is because method arguments in python do not have a type. class methodOverLoading(object): def test1(self, input1=None, input2 = None): if (input1 is not None) and (input2 is not None): print("from test1(input1, input2) %s" % str(input1)) else: print("from no arg method") obj = methodOverLoading() obj.test1("hello", "hello2") obj.test1()
2324ee5121b21c3411493e6c7316e7af75efadaf
danielmmetz/euler
/euler006.py
829
3.921875
4
""" The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ def answer(seqmax): """ returns the difference between the sum of squares of the first seqmax natural numbers and the square of the sum. """ seq = xrange(1, seqmax + 1) return sum(seq) ** 2 - sum(x ** 2 for x in seq) if __name__ == '__main__': assert answer(10) == 2640, 'failed small test with {}'.format(answer(10)) print answer(100)
45e76d81b85d837979f07126a032f75f7644d4c8
zzarbttoo/TMT
/YJ/20200629_2_1.py
935
3.546875
4
#풀이 1 def solution(phone_book): answer = True phone_book = sorted(phone_book) for i in range(0, len(phone_book)): for j in range (i+1, len(phone_book)): if phone_book[j].startswith(phone_book[i]): #바로 return 을 하면 효율성 테스트를 통과할 수 있다 return False return answer #sorted를 하지 않을 경우 이 두개를 구분할 수 없다(순차적으로 비교하기 때문) print(solution(["119", "1192456"])) print(solution(["1192456", "119"])) print(solution(["11"])) print(solution(["119", "97674223", "1195524421"])) print(solution(["123","456","789"])) print(solution(["12","123","1235","567","88"])) #API 확인을 생활화하자! : https://docs.python.org/ko/3/library/index.html # 다중 반복문 탈출 : https://m.blog.naver.com/PostView.nhn?blogId=upssuyo&logNo=80092174516&proxyReferer=https:%2F%2Fwww.google.com%2F
43dc2bd7661fbb4b1e0c1fc3ee4d3c4706337eb8
minccia/python
/python3/exerciciosOOP/pessoa.py
902
3.78125
4
class Pessoa: def __init__(self, nome, idade, peso, altura): self.nome = nome self.idade = idade self.peso = peso self.altura = altura def envelhecer(self): self.idade += 1 print(f'A pessoa envelheceu mais um ano, e agora tem {self.idade} anos.') if self.idade < 21: self.altura += 0.05 print(f'Pela pessoa ter menos de 21 anos, ela também cresceu 0,5 centímetros, e agora tem {self.altura:.2f} de altura.') def engordar(self): self.peso += 1 print(f'A pessoa engordou 1kg, e agora possui {self.peso} kilos.') def emagrecer(self): self.peso -= 1 print(f'A pessoa emagreceu 1kg, e agora possui {self.peso} kilos.') def crescer(self): self.altura += 0.05 print(f'A pessoa cresceu 0,5 centíḿetros, e agora possui {self.altura:.2f} de altura.')
262823bab54e7c7fd1b9f441819687bf061ec238
asmitamahamuni/python_programs
/fibonacci_series.py
511
3.953125
4
# Print Fibonacci Series using Iterrator, Recurssion and Generator # iterative def fibi(n): a, b = 0, 1 for i in range(0,n): a, b = b, a+b return a # recursive def fibr(n): if n == 0: return 0 if n == 1: return 1 return fibr(n-2)+fibr(n-1) for i in range(10): print (fibi(i), fibr(i)) def fib_generator(n): a, b = 0, 1 for i in range(n): yield "({},{})".format(i,a) a, b = b, a+b # loop through the generator for item in fib_generator(10): print(item)