blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
9d48bbc8f03270734ddd5c063434720beeaf4a25
kotteeshwaran/mini_proj
/guess_the_word.py
1,770
3.859375
4
import random from collections import Counter with open('C:/Users/dkott/Documents/Python/PROJECTS/list_words.txt','r') as file: myword= file.read().splitlines() words=random.choice(myword) print(words) flag = 0 char ='' letterguessed='' chance=13 correct = 0 print("Find the fruit") print() for dash in myword: #it is used to print the dashes print("-",end='') print() try: while chance!=0 and flag==0: print() chance-=1 try: guess = str(input('Enter a charcter:')) except: print("Enter only letter") continue #validation of guess if not guess.isalpha(): print("Enter only Letter") continue elif len(guess)>1: print("Enter a single character") continue elif guess in letterguessed: print("Already guessed letter") continue if guess in words: value = words.count(guess) for _ in range(value): letterguessed+=guess for char in words: if char in letterguessed and (Counter(letterguessed) != Counter(words)): print(char, end = ' ') correct += 1 elif Counter(letterguessed) == Counter(words): print("Congragulations") print("The word is:{}".format(words)) flag=1 break break else: print('-',end='') if chance<=0 and (Counter(letterguessed)!=Counter(words)): print('Your chances are over') print("The Word is {}".format(words)) except KeyboardInterrupt: exit()
c39f001dd24f4f1cc30ddd35e6dc116152e549ba
AgustinZavalaA/Huffman
/Huffman.py
8,920
3.625
4
from Node import Node import os import shutil class Huffman: def __init__(self): self.root = Node() self.frecTable = {} self.encoTable = {} self.encoText = "" self.encoTree = "" pass def setFrecuencyTable(self, s): # Get all the characters from a given string. # if it find it in the dictionary "frecTable" # it will add 1 to the frecuency if the char # is new to the table it will set it to 1 # so the next time it is encountered it will # add 1 otherwise it wont start the dictionary for c in s: if c in self.frecTable: self.frecTable[c] += 1 else: self.frecTable[c] = 1 # Sort the dictionary self.frecTable = dict(sorted(self.frecTable.items(), key=lambda item: item[1])) pass def setEncodingTable(self, node, path=[], append=2): # this method create the encoding table # it traverse the binary tree from root # to leaf, when it encounters a leaf it # save the encoding table if node is None: return path.append(append) if node.left is None and node.right is None: self.encoTable[node.data] = path[1:] self.setEncodingTable(node.left, path, 0) self.setEncodingTable(node.right, path, 1) path.pop() pass def setEncodedString(self, inputStr): for c in inputStr: # This line append every char in the # input string but it also replace every # bracket comma and space self.encoText += str(self.encoTable[c]) self.encoText = self.encoText.translate({ord(i): None for i in "[], "}) pass def setEncodedTree(self, node): if node is None: return if node.left is None and node.right is None: #self.encoTree += "1" self.encoTree += node.data else: self.encoTree += "0" self.setEncodedTree(node.left) self.setEncodedTree(node.right) pass def printFrecuencyTable(self): for key, value in self.frecTable.items(): print("%c : %d" % (key, value)) pass def printEncodingTable(self): for key, value in self.encoTable.items(): print("%c : %s" % (key, str(value))) pass def printEncodedString(self, inputStr): print("\"%s\" Is equivalent to \n%s" % (inputStr, self.encoText)) pass def printEncodedTree(self): print("Encoded Tree = %s" % self.encoTree) def setBinaryTree(self): Forest = [] for key, value in self.frecTable.items(): Forest.append(Node(value, key)) while len(Forest) > 1: newNode = Node(Forest[0].getWeight() + Forest[1].getWeight()) if Forest[0].getWeight() > Forest[1].getWeight(): newNode.left = Forest[1] newNode.right = Forest[0] else: newNode.left = Forest[0] newNode.right = Forest[1] Forest = Forest[2:] Forest.append(newNode) Forest.sort(key=lambda n: n.weight) #print(Forest[0]) #print(Forest) self.root = Forest[0] pass def readNode(self, iter_s): c = next(iter_s, -1) if c is not -1: if c is not "0": return Node(data=c) else: left = self.readNode(iter_s) right = self.readNode(iter_s) return Node(l=left, r=right) def saveFile(self, fName): # Writes the tree in a file fOut = open(fName + "/" + fName + ".tree", "w") fOut.write(self.encoTree) fOut.close() # writes the encoded text in a different file, it uses the # flag wb to write binaries fOut = open(fName + "/" + fName + ".etxt", "wb") # This is a little messy, but it converts the encoded text # that is a string of 0 and 1 to binaries with the function # int(x,2) the second parameter convert the string to a binary # number, then with the method to_byte from the int class it # creates a byte stream to write in the file fOut.write((int(self.encoText[::-1], 2).to_bytes(int(len(self.encoText)/8)+1, 'little'))) fOut.close() pass def decodeText(self, nBits): tmp = self.root i=0 for c in self.encoText: if tmp.left == None and tmp.right == None: print(tmp.data, end="") tmp = self.root if c == "0": tmp = tmp.left else: tmp = tmp.right #i += 1 #if nBits == i: # break pass def menu(self): while True: self.root = Node() self.frecTable = {} self.encoTable = {} self.encoText = "" self.encoTree = "" os.system('clear') print("**** Menu *****") print("1.- Compress Input Text") print("2.- Compress File Text") print("3.- Decompress File") print("4.- Exit") opt = int(input(">> ")) while opt < 1 or opt > 4: opt = int(input("Wrong option. Try again\n>> ")) if opt in (1,2): os.system('clear') if opt == 1: print("Write text to compress") inputStr = input(">> ") else: print("Write direction to text file to compress") inputStr = input(">> ") with open(inputStr, "r") as f: inputStr = f.read() self.setFrecuencyTable(inputStr) self.setBinaryTree() self.setEncodingTable(self.root) self.setEncodedString(inputStr) self.setEncodedTree(self.root) self.encoTree = str(len(inputStr)) + "," + self.encoTree while True: os.system('clear') print("1.- Show frecuency table") print("2.- Show binary tree") print("3.- Show char encoding") print("4.- Show efficiency") print("5.- Save to file") print("6.- Exit without saving") opt2 = int(input(">> ")) os.system('clear') while opt2 < 1 or opt2 > 6: opt2 = int(input("Wrong option. Try again\n>> ")) if opt2 == 1: self.printFrecuencyTable() if opt2 == 2: self.root.printTree() self.printEncodedTree() if opt2 == 3: self.printEncodingTable() self.printEncodedString(inputStr) if opt2 == 4: print("Descompressed text ~= %d B" % (len(inputStr))) print("Compressed text (tree + text) ~= %d B" % (len(self.encoTree)+len(self.encoText)/8+1)) print("Efficiency ~= %.2f" % ((len(inputStr)) / int((len(self.encoTree)+len(self.encoText)/8+1)))) if opt2 == 5: fName = input("Write name of archive\n>> ") if os.path.exists(fName): shutil.rmtree(fName) os.mkdir(fName) self.saveFile(fName) break if opt2 == 6: break input("Press enter key to continue...\n") elif opt == 3: fName = input("Write name of the directory\n>> ") with open(fName + "/" + fName + ".etxt" , "rb") as f: textInBytes = f.read() with open(fName + "/" + fName + ".tree" , "r") as f: bits = f.read() nChar = bits.split(sep=",")[0] self.encoTree = bits.split(sep=",",maxsplit=1)[1] # convert the bits to a string the same way self.encoText = format(int.from_bytes(textInBytes, 'little'), str(int(int(nChar)/8)+1) + 'b')[::-1] # Creates an iterable to recursively call the next method iter_s = iter(self.encoTree) self.root = self.readNode(iter_s) self.decodeText(nChar) input("\nPress enter key to continue...\n") else: os.system('clear') exit() pass
b1f8b68feb02a2389c75908bc1d7ddca9a25c4e1
GitdoPedro/Exercicios-Python
/Capítulo 8 - Funções/8.9.py
205
3.765625
4
def show_magicians(names): for name in names: print(name.title() + " is a magician!\n") magicians = ['mister m','fu manchu','dai vernon','david blaine'] show_magicians(magicians)
617b0b81f3c5ca52ec255b528b15d6862aa34f52
maria-gabriely/Maria-Gabriely-POO-IFCE-INFO-P7
/Presença/Atividade 02/Lista_Encadeada.py
227
4.25
4
# 3) Lista Encadeada (A retirada e a inserção de elementos se faz em qualquer posição da Lista). Lista3 = [1,2,3,4,'a','c','d'] print(Lista3) x = 'b' Lista3.insert(5,x) print(Lista3) Lista3.pop(2) print(Lista3)
fbd6cac4a84349538d828d3e330d6a5e2ac145b4
krishna-prasath/guvi
/addeveorodd.py
89
3.734375
4
a,b=map(int,input().split()) a=a+b if a%2==0: print("even") else: print("odd")
a811a8efc98a5681af089b22a31317696d54cb5e
ifedavid/GA-for-QAP
/GeneratePopulation.py
758
4.15625
4
import random # function to generate new population def Generate_Initial_Population(problem_size, population_size) -> list: """Generate list of random data Parameters ---------- problem_size : int size of the problem i.e no of location/facilites population_size : int number of data we want in our list Returns ------- list return list of data """ population = [] for i in range (population_size): # create list with size == problem size and random values ranging from 0 - problem_size x = random.sample(range(problem_size), problem_size) population.append([x, 0]) #print("Initial Population - ") #print(population) return population
cfc6d6930ad60aee71a1099b74b2ab1017cffbca
zhongyuchen/programmeren
/pset6/mario.py
299
4
4
from cs50 import get_int # get int while True: height = get_int("Height: ") if height >= 0 and height <= 23: break # print pyramid for i in range(height): print(" " * (height - i - 1), end="") print("#" * (i + 1), end="") print(" " * 2, end="") print("#" * (i + 1))
b710573b9add54c1053373d4ce08f5447247f264
pvarsh/pr_informatics
/assignment-3/submission_1/problem1.py
1,019
3.75
4
################################## # Principles of Urban Informatics # Assignment 3: Problem 1 # Peter Varshavsky ################################## import sys import csv from datetime import datetime def problem1(fileName): tweets = [] fmtIn = "%a %b %d %H:%M:%S %Z %Y" fmtOut = "%B %d %Y, %H:%M:%S" maxDate = datetime.strptime("Dec 01 1900", "%b %d %Y") minDate = datetime.strptime("Dec 01 5000", "%b %d %Y") count = 0 with open(fileName, 'r') as f: reader = csv.reader(f) for line in reader: count += 1 tweetDateTime = datetime.strptime(line[1], fmtIn) if tweetDateTime < minDate: minDate = tweetDateTime if tweetDateTime > maxDate: maxDate = tweetDateTime print 'There were %d tweets between %s and %s' %(count, datetime.strftime(minDate, fmtOut),datetime.strftime(maxDate, fmtOut)) def main(argv): tweets = problem1(argv[0]) if __name__ == '__main__': main(sys.argv[1:])
74e255a25d4f57f23aff4fc54114ce8971eb7914
john-bhat/python-basics
/quicksort.py
817
3.953125
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 06 07:47:41 2017 @author: admin """ ''' Quick Sort ''' def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) / 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] print(left ,middle ,right) return quicksort(left) + middle + quicksort(right) print quicksort([3,4,8,7,6,1,2]) def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) / 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(right)+ middle +quicksort(left) print quicksort([3,6,8,1,2,3,7,8,12,22,10,1,2,1])
1aa272603e04b0aec507d9e328d0b64279831391
rainsparks/PythonDivisibility
/PythonDivisibility.py
361
4.21875
4
#Author: Rain Erika H. Angelito #Program that ask for a positive integer to list the divisible numbers less # than it. x=input('Input an integer: ') i=0 if int(x)>0: while i<int(x): i=i+1 if(int(x)%i==0 and int(x)!=i): print(str(i)) else: print('Please input a positive integer')
83a542d50dd63334cd2faaa22a1dcb59ca688859
beethree/pp4e
/ex15a.py
486
4.125
4
# learn python the hard way : exercise 15a # The line below imports the sys module to get command line args #from sys import argv # The line below defines two variables passed via argv #script, filename = argv # The line below defines a variable and issues a command #txt = open(filename) #print "Here's your file %r:" % filename #print txt.read() print "Type the filename again:" file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read() txt_again.close()
adb1cb37129f6d48471fd54839f068b915c30fdd
mauricesandoval/Tech-Academy-Course-Work
/Python/Python3Drills/syntax-whitespace.py
883
4.28125
4
#!/usr/bin/python3 # significance of indentation examples def main(): print("This is the syntax.py file.") # Indent shows print statement is # associated with the main function if __name__ == "__main__": main() ''' This will not work due to improper indentation: def main(): print("This is the syntax.py file.") print("This is another line") if __name__ == "__main__": main() ''' def main(): print("This is the syntax.py file.") print("This is another line") # prints first. Runs before main() is called if __name__ == "__main__": main() def main(): print("This is the syntax.py file.") # prints first print("This is another line") if __name__ == "__main__": main() # works when their is just one line of code def main(): print("This is the syntax.py file.") if __name__ == "__main__": main()
8a48c5fbc9f0ab7b7a9e6e2a589153af9ffe033b
tomorroworthedayafter/workbooks-pw
/pw/n2.1.py
1,436
3.515625
4
#Предварительная обработка данных import numpy as np from sklearn import preprocessing input_data = np.array([[2.1, -1.9, 5.5], [-1.5, 2.4, 3.5], [0.5, -7.9, 5.6], [5.9, 2.3, -5.8]]) # Применение методов предварительной обработки # Бинаризация data_binarized = preprocessing.Binarizer(threshold = 0.5).transform(input_data) print("\tБинаризация\n", data_binarized) # Среднее удаление print("\n\tСреднее удаление\nmean = ", input_data.mean(axis = 0)) # Средние значение print("Standart deviation = ", input_data.std(axis = 0)) # Среднее отклонение data_scaled = preprocessing.scale(input_data) print("standart deviation = ", data_scaled.std(axis = 0)) # Пересчет data_scaler_minmax = preprocessing.MinMaxScaler(feature_range=(0,1)) data_scaled_minmax = data_scaler_minmax.fit_transform(input_data) # Вычисление -> преобразование print ("\n\tПересчет\n", data_scaled_minmax) #Нормализация data_normalized_l1 = preprocessing.normalize(input_data, norm = 'l1') print("\n\tL1 нормализация\n", data_normalized_l1) data_normalized_l2 = preprocessing.normalize(input_data, norm = 'l2') print("\n\tL2 нормализация\n", data_normalized_l2)
4f47d1c8196457ca26a129436202e3f03e4e34f7
sam007961/luxor
/luxor/scene/style.py
415
3.609375
4
from typing import Union from enum import Enum class Unit(Enum): Px = 1 class Color: def __init__(self, r: int, g: int, b: int, a: int) -> None: self.r = r self.g = g self.b = b self.a = a class Length: def __init__(self, value: Union[int, float], unit: Unit) -> None: self.value = value self.unit = unit PropertyValue = Union[str, Color, Length]
477c3b9973480b96fa71db5fbd66bcde48e5d991
GargiGuptagd/June2020-Leetcode-Challenge
/June 11/Solution.py
414
3.625
4
class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ for i in range(0,len(nums)): for j in range(0,len(nums)-i): if j+1<len(nums)-i: if nums[j+1]<nums[j]: nums[j],nums[j+1]=nums[j+1],nums[j] return nums
d09c97a5271536197cafb180fd910822818bce2f
htlcnn/FAMILUG
/Python/wordcounter2.py
1,301
3.875
4
#!/usr/bin/env python2 import sys class WordData(): """Class for creating object contain counter and happend line numbers of a word""" def __init__(self, word, line): self.counter = 1 self.word = word self.happened_lines = [line] def __repr__(self): lines = " ".join(str(line) for line in self.happened_lines) return str(self.counter) + " " + self.word + " " + lines def increase_counter(self): self.counter += 1 def add_happened_line(self, line): if line not in self.happened_lines: self.happened_lines.append(line) def count_words(filename): fin = open(filename, 'r') lines = fin.readlines() d = {} #count word and line for (number, line) in enumerate(lines): #get line number line_number = number + 1 for w in line.split(): #Lower case lower = w.lower() if lower in d: d[lower].increase_counter() d[lower].add_happened_line(line_number) else: d[lower] = WordData(lower, line_number) datas = d.values() #sort desc by counter, then asc by word datas.sort(key=lambda wdata : (-wdata.counter, wdata.word)) #print out for data in datas: print data def main(): if len(sys.argv) != 2: print 'Use: python wordcounter.py word.in' sys.exit(1) filename = sys.argv[1] count_words(filename) if __name__ == '__main__': main()
b4982a6cbd1e8b5595bad0c868edd82765069e41
Durgadevi23/guvi1
/code-katta/Basics/add_input_find_even.py
208
4.03125
4
#Program to add the input and find odd or even #Get two input from user N,M=map(int,input().split()) #add both the input A=N+M #check condition for even or odd if(A%2==0): print("even") else: print("odd")
26458a62938356e749547bc0ea6b2544e2b96a98
SirJimPanse/Bachelor-HSRM-Medieninformatik
/Programmieren3/Python/OnlineTest/ws11-12/a3_generatoren.py
817
3.578125
4
import types, random def gen(): i = 1 while True: yield i yield i+3 i += 1 def secondonly(gen): i = 0 l = [] if type(gen) == types.ListType: while i < len(gen): if gen[i] in gen[:i] and gen[i] not in l: l.append(gen[i]) i += 1 for k in l: yield k else: while True: g = gen.next() l.append(g) if l.count(g) == 2: yield g def count(gen): i = 1 l = [] if type(gen) == types.ListType: for x in gen: l.append(x) yield '('+":".join((str(x),str(l.count(x))))+')' else: while True: g = gen.next() l.append(g) yield '('+":".join((str(g),str(l.count(g))))+')'
7d12e9c253bbe32c88fb3c1d68bd1789ccbbb720
AyrtonDev/Curso-de-Python
/Exercicios/ex054.py
793
3.9375
4
from datetime import date data = date.today().year maiorIdade = 0 menorIdade = 0 for c in range(1, 8): pessoa = int(input('Em que ano a {}ª pessoa nasceu? '.format(c))) if (data - pessoa) >= 21: maiorIdade += 1 else: menorIdade += 1 print('') if maiorIdade == 0: print('Não tivemos pessoas maiores de idade') elif maiorIdade == 1: print('Ao todo tivemos {} pessoa maior de idade'.format(maiorIdade)) else: print('Ao todo tivemos {} pessoas maiores de idade'.format(maiorIdade)) if menorIdade == 0: print('Não tivemos pessoas menores de idade') elif menorIdade == 1: print('Ao todo tivemos {} pessoa menor de idade'.format(menorIdade)) else: print('Ao todo tivemos {} pessoas menores de idade'.format(menorIdade))
2193ce9b4e26011b515a0a8aeb6207ec7df18f93
tangkevkev/adventofcode2020
/src/sol3a.py
355
3.65625
4
fileObj = open('../input/input3.txt', 'r') lines = fileObj.read().splitlines() rows = len(lines) cols = len(lines[0]) print("rows: " , rows) print("cols: " , cols) cur_col = 0 count_trees = 0 for i in range(0, rows-1): cur_row = i+1 cur_col = (cur_col + 3)%cols if lines[cur_row][cur_col] == '#': count_trees += 1 print(count_trees)
60c7b81fcf569f3af5fcd103f9aaa6d44527f73c
GabrielXia/inf280_acm
/leetcode/maximum_gap.py
881
3.5625
4
def radix_sort(nums): res = nums for i in range(31): q0 = list() q1 = list() for j in res: bin_j = bin(j)[2:] if i >= len(bin_j) or bin_j[-(i+1)] == '0': q0.append(j) elif bin_j[-(i+1)] == '1': q1.append(j) res = [] for q in q0: res.append(q) for q in q1: res.append(q) #import pdb; pdb.set_trace() return res class Solution: def maximumGap(self, nums): """ :type nums: List[int], int 32 bit :rtype: int """ if len(nums) < 2: return 0 else: res = radix_sort(nums) maxv = 0 for i in range(len(res) -1): if (res[i + 1] - res[i]) > maxv: maxv = res[i + 1] - res[i] return maxv
d39abf0ecf9e32107bfe87ffc58ed1ca525bda32
isabellexiao/TurtlesData
/0508_SQLProj_IX.py
2,611
4.21875
4
import csv import wikipedia as w import sys import sqlite3 import csv conn = sqlite3.connect ('TurtlesData.db') c = conn.cursor() def Characteristics(): print('''Good choice! Here you can learn about the characteristics of the turtles. Type 1 to learn the caraspace length of all female turtles. Type 2 to learn all the ages of the turtles found in pond 'ALM'. Type 3 to learn all the mass of the turtles captured by hoops. Or, you can quit by typing 4.''') characteristicschoice = (int(raw_input("Please choose a choice. Type your choice here:"))) while characteristicschoice != 4: if characteristicschoice == 1: query=c.execute("SELECT turtinfo.Sex,sizeinfo.Cara_Len from turtinfo JOIN sizeinfo ON turtinfo.T_ID=sizeinfo.T_ID where turtinfo.sex='F'") for row in list(query): asciiRow = [] print row for item in row: if type(item) == type(u"hi"): asciiRow.append(item.encode('ascii')) else: asciiRow.append(item) print (asciiRow) if characteristicschoice == 2: query=c.execute("SELECT capinfo.Pond, turtinfo.Age from capinfo JOIN turtinfo ON capinfo.T_ID = turtinfo.T_ID where capinfo.Pond = 'ALM'") for row in list(query): asciiRow = [] print row for item in row: if type(item) == type(u"hi"): asciiRow.append(item.encode('ascii')) else: asciiRow.append(item) print (asciiRow) if characteristicschoice == 3: query=c.execute("SELECT sizeinfo.Mass, capinfo.Trap_Type from sizeinfo JOIN capinfo ON sizeinfo.S_ID = capinfo.S_ID where capinfo.Trap_Type = 'Hoop'") for row in c.execute(query): asciiRow = [] print row for item in row: if type(item) == type(u"hi"): asciiRow.append(item.encode('ascii')) else: asciiRow.append(item) print (asciiRow) # else: # print("That is not a valid option. Please choose another.") characteristicschoice = int(raw_input("Please choose a choice. Type your choice here:")) menu() def menu(): print("Welcome! Here you can learn about turtles!") print w.summary("Turtles", sentences = 3) print ('''Below are the available options that you can learn about: a. Characteristics Or, type Q to quit!''') choice = raw_input("Please choose an option. Type your option here: ") while choice.upper() != "Q": if choice.upper() == "A": Characteristics() else: print("Error. Please choose an available option.") choice = raw_input("Please choose another option. Type your option here: ") sys.exit(0) print("Thank you for using our program! Have a nice day! Goodbye!") menu()
56946d10f86612697bbeb8c46ef2f31b8e357cee
gaotianze/Network-Flows-learning-notes
/《Network_Flows》_代码复现/Chapter III/search_depth_first.py
1,246
3.671875
4
# 基于个人理解的深度优先算法 20210520 TianzeGao def search_depth_first(g, s): s -= 1 marked_nodes = [s] node_list = [s] current_node=s while len(node_list) != 0: for arc in range(0, len(g[0])): if g[current_node][arc] == 1: g[current_node][arc] = 0 for node in range(current_node + 1, len(g)): if g[node][arc] == -1: if node not in marked_nodes: node_list.insert(0,node) marked_nodes.append(node) current_node = node_list[0] break if 1 not in g[current_node]: node_list.remove(current_node) if len(node_list) != 0: current_node = node_list[0] print("可达点为:") print(sorted([i+1 for i in marked_nodes])) return 0 if __name__ == '__main__': G = [[1, 1, 0, 0, 0, 0, 0, 0, 0], [-1, 0, 1, 1, 1, 0, 0, 0, 0], [0, -1, -1, 0, 0, 1, 0, 0, 0], [0, 0, 0, -1, 0, -1, 1, -1, 0], [0, 0, 0, 0, -1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, -1, 0, -1]] search_depth_first(G, 1) # 输入G矩阵和几号点
2992b3ac8bbc4332c26628ec14779add4136ef81
davll/practical-algorithms
/LeetCode/7-reverse_integer.py
779
3.984375
4
def copysign(x,y): x = abs(x) if y >= 0: return x else: return -x class Solution: def reverse(self, x): """ :type x: int :rtype: int """ # check if x > (2**31-1) or x < -(2**31): return 0 # compute tmp, result = abs(x), 0 while tmp > 0: result = (result * 10) + (tmp % 10) tmp = tmp // 10 result = copysign(result, x) # check overflow if result > (2**31-1) or result < -(2**31): return 0 else: return result """ if __name__ == "__main__": x = int(input("enter a number ")) print("input = " + str(x)) s = Solution() y = s.reverse(x) print("ans = " + str(y)) """
f293dc7d59e52b0af20848bad2e25d033472e803
naveen-ku/Competitive-Programming
/python/plusminus.py
891
4.15625
4
#!/bin/python3 #Given an array of integers, calculate the fractions of its elements that are positive, # negative, and are zeros. Print the decimal value of each fraction on a new line. import math import os import random import re import sys # Complete the plusMinus function below. def plusMinus(arr,n): # pass count_p = 0 count_n = 0 count_z = 0 for i in range(n): if arr[i] > 0: count_p +=1 ans1 = count_p/n print("%.6f" %ans1) for j in range(n): if arr[j] < 0: count_n +=1 ans2 = count_n/n print("%.6f" %ans2) for k in range(n): if arr[k] == 0: count_z +=1 ans3 = count_z/n print("%.6f" %ans3) if __name__ == '__main__': n = int(input()) arr = list(map(int, input().rstrip().split())) if len(arr) !=n: exit('Try again') plusMinus(arr,n)
320592b06029209b5e222861b2b00e2ec51d5176
NidhinAnisham/PythonAssignments
/python_l1_assignments_topgear-master/1.py
300
3.984375
4
#upper limit not included mylist = range(4) seclist = mylist print seclist #4 is appended to existing list mylist.append(4) print seclist #makes copy of mylist to seclist seclist = mylist[:] print seclist #5 is appended to my list but not to seclist as it is a copy mylist.append(5) print seclist
6bb1cb4efa03b1b1f0fa7146ce2f215b768b1e49
JLew15/Python
/ATMProject/Bank.py
451
3.65625
4
class ATM: balance = 20.00 def deposit(amount): print(str.format("Depositing {:.2f}",amount)) ATM.balance += amount return ATM.balance def withdraw(amount): if ATM.balance >= amount: print(str.format("Withdrawing {:.2f}", amount)) ATM.balance -= amount else: print("Insufficient Funds") return ATM.balance def getBalance(): return ATM.balance
7218f793a4e391f7eb825bebc88c6018f61e28f9
Spiridd/python
/stepic/qsort.py
445
3.71875
4
''' minimalistic implementation of quick sort show only 4 times slower performance than inner sort (timsort) ''' import random def qsort(v): return qsort([x for x in v[1:] if x < v[0]]) + [v[0]] +\ qsort([x for x in v[1:] if x >= v[0]]) \ if len (v) > 1 else v def main(): size = 1000000 vec = random.sample(range(size), size) #vec.sort() vec = qsort(vec) if __name__ == '__main__': main()
201500a0167258fcd0e894d303e43536151a65e7
emilianoNM/Tecnicas3
/Reposiciones/MedinaOrtizRobertoArturo/12-9/4-18.py
112
3.609375
4
a=[] for i in range (0,5): a+=[input('Ingresa un numero: ')] a=map(int,a) for i in range (0,5): print '*'*a[i]
d0d7ff37bf0a6f26efc5021ba1151f2c31795e7e
yura-seredyuk/ItStep
/ITS #7/DZ/treasures.py
4,367
3.515625
4
from math import sqrt from tkinter import * from tkinter import messagebox as mb import random WIDTH, HEIGHT = 500, 500 HEADER_S = 50 FONT = "Comic Sans MS" count_lives = 10 game_over = False treasure_x = random.randint(0, WIDTH) treasure_y = random.randint(HEADER_S, HEIGHT) treasure_radius = 20 root = Tk() root.title("Остров сокровищ") # окно по центру экрана root.geometry(f'+{root.winfo_screenwidth()//2-WIDTH//2}+{root.winfo_screenheight()//2-(HEIGHT+HEADER_S)//2}') root.iconbitmap('icon.ico') # конка приложения root.config(cursor='none') # скрыть курсор root.resizable(False, False) # запретить растягивать # Игровое поле canvas canvas = Canvas(width=WIDTH, height=HEIGHT + HEADER_S, highlightthickness=0) canvas.grid(row=0, column=0) # Карта landscape = PhotoImage(file='landscape.png') canvas.create_image(0, 0, image=landscape, anchor="nw", tag="map") # Cтатус бар status_bar = PhotoImage(file='status_bar.png.') canvas.create_image(0, 0, image=status_bar, anchor="nw") # Вывод количества попыток canvas.create_text(95, 25, text=f"Попытки: ", font=(FONT, 20), fill="white") lives = canvas.create_text(180, 25, text=f"{count_lives}", font=(FONT, 20), fill="white") # Вывод расстояния попыток canvas.create_text(WIDTH - 145, 25, text=f"Расстояние: ", font=(FONT, 20), fill="white") distance = canvas.create_text(WIDTH - 45, 25, text="---", font=(FONT, 20), fill="white") # Лопата вместо курсора shovel_cursor = PhotoImage(file='shovel.png') canvas.create_image(-50, 0, image=shovel_cursor, anchor="nw", tag="shovel") mb.showinfo(title="Цель игры", message="Найдите сокровище на карте. Количество попыток ограничено.") # Перемещение мышки def mouse_move(e): canvas.delete("shovel") canvas.create_image(e.x+1, e.y+1, image=shovel_cursor, anchor="nw", tag="shovel") # Рестарт игры def restart_game(e): global count_lives, game_over, treasure_x, treasure_y canvas.delete("restart_button") canvas.delete("text") count_lives = 10 game_over = False treasure_x = random.randint(0, WIDTH) treasure_y = random.randint(HEADER_S, HEIGHT) canvas.itemconfig(distance, text="---") canvas.itemconfig(lives, text=count_lives) # Клик мышки def mouse_click(e): global count_lives, game_over # если игра окончена или клик по статусбару, ничего не делать if e.y <= HEADER_S or game_over: return # Отнимаем попытку count_lives -= 1 canvas.itemconfig(lives, text=f"{count_lives}") # Если попыток не осталось, игра окончена if not count_lives: game_over = True canvas.delete("mark") canvas.create_text(WIDTH / 2, HEIGHT / 2 - 30, text="ИГРА ОКОНЧЕНА", fill="red", font=(FONT, 40), tags="text") canvas.create_text(WIDTH / 2, HEIGHT / 2 + 30, text="сыграть еще раз", fill="blue", font=(FONT, 20), tags="restart_button") return # Расчет дистанции a = max(treasure_x, e.x) - min(treasure_x, e.x) b = max(treasure_y, e.y) - min(treasure_y, e.y) distance_calc = sqrt(a ** 2 + b ** 2) if distance_calc <= treasure_radius: # Победа game_over = True canvas.delete("mark") canvas.create_text(WIDTH / 2, HEIGHT / 2 - 30, text="ПОБЕДА", fill="red", font=(FONT, 40), tags="text") canvas.create_text(WIDTH / 2, HEIGHT / 2 + 30, text="сыграть еще раз", fill="blue", font=(FONT, 20), tags="restart_button") else: # Ставим отметку canvas.create_text(e.x, e.y, text="x", fill="red", font=(FONT, 20), tag="mark") # Обновляем дистанцию canvas.itemconfig(distance, text=f"{distance_calc - treasure_radius:.0f}") canvas.bind('<Motion>', mouse_move) canvas.tag_bind("map", '<Button-1>', mouse_click) canvas.tag_bind("restart_button", '<Button-1>', restart_game) root.mainloop()
83e891e5e3c0641f5cc756a6ea00d9de7e19eeb3
aaryan6789/cppSpace
/String/sort_characters_by_frequency.py
1,340
4.21875
4
""" 451. Sort Characters By Frequency Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters. """ # // Time Complexity: O(n) # // O(26log(n)) = O(log(n)) For Construction and extraction from heap # // O(n) For storing the frequency in hashmap. import collections def frequencySort(s): """ :type s: str :rtype: str """ # Count up the occurances. counts = collections.Counter(s) # Build up the string builder. string_builder = [] for letter, freq in counts.most_common(): # letter * freq makes freq copies of letter. # e.g. "a" * 4 -> "aaaa" string_builder.append(letter * freq) return "".join(string_builder)
54d8e78081d1e0adb05bc5660f1634156029608c
Athenian-ComputerScience-Fall2020/functions-practice-yesak1
/multiplier.py
782
4.40625
4
''' Adapt the code from one of the functions above to create a new function called 'multiplier'. The user should be able to input two numbers that are stored in variables. The function should multiply the two variables together and return the result to a variable in the main program. The main program should output the variable containing the result returned from the function. ''' def multiplier(): # Stores two numbers in two variables. num1 = int(input("enter a number")) num2 = int(input("enter another number")) # Adds the variable contents together and returns the total to the main program return num1 * num2 # Calls the adder function and stores the data returned output_num = multiplier() # Outputs the data in the outputNum variable print(output_num)
7a07b4caee454fcd079d9716a7327fc2f0ccb4ab
zision/Learn-Python
/randomTest1.py
699
4.0625
4
# random模块 import random print(random.random()) # 生成0到1随机浮点数 print(random.uniform(1, 100)) # 生成指定范围内随机浮点数 print(random.randint(1, 100)) # 生成指定范围内随机整数 print(random.randrange(10, 100, 2)) # 从指定序列中获取一个随机数 print(random.choice('Py大法好!')) # 随机选取 print(random.choice(('a', 'b', 'c'))) # 可以是字符串,元组,列表等 list1 = [1, 2, 3, 4, 5, 6] random.shuffle(list1) # 将列表中元素打乱(洗牌) print(list1) list2 = [i**2 for i in range(0, 10)] print(list2) print(random.sample(list2, 3)) # 随机获取指定数量的片段 print(list2) # 不会修改原有列表
afdec2da5dab3597f99b32b02febccf0476890c0
NestorMonroy/Cursos-Platzi
/python-practico/comprehensions.py
930
4.03125
4
""" Estructura que permite generar una secuencia apartir de otras secuencias list [element fotrr element in element_list if element_meets_condition] dictionary {key: element for element in element_list if element_meets_condition } set {element for element in element_list if element_meets_condition} """ lista_de_numeros = list(range(100)) pares = [numero for numero in lista_de_numeros if numero % 2 == 0 ] print(pares) student_uid = [1, 2, 3] students = ['Joel', 'Juan', 'Jose'] #zip regresa un itirador de tuplas students_with_uid = {uid: student for uid, student in zip(student_uid, students)} print(students_with_uid) import random random_numbers = [] for i in range(10): random_numbers.append(random.randint(1, 3)) print(random_numbers) # se pueden eliminar los repetidos con set comprehension non_repeated = {number for number in random_numbers} print(non_repeated)
568cbb6f74d7984c0a383560cdd8605bd696e7e2
VinayPatelGitHub/ChessSimulator
/Chess/chess A2-3-2.py
3,980
3.515625
4
import pygame import os import time import random pygame.font.init() WIDTH, HEIGHT = 780, 780 WIN = pygame.display.set_mode((WIDTH,HEIGHT)) pygame.display.set_caption("Chess - A2") LIGHT_SQUARE = pygame.image.load(os.path.join("PicsA2", "light square.png")) DARK_SQUARE = pygame.image.load(os.path.join("PicsA2", "dark square.png")) HIGHLIGHTED_SQUARE = pygame.image.load(os.path.join("PicsA2", "highlighted square.png")) DARK_PAWN = pygame.image.load(os.path.join("PicsA2", "dark pawn.png")) font = pygame.font.SysFont('comicsans', 60) class Button(): def __init__(self, color, x,y,width,height, text=''): self.color = color self.x = x self.y = y self.width = width self.height = height self.text = text ##def draw(self,win,outline=None): #Call this method to draw the button on the screen ##pygame.draw.rect(win, self.color, (self.x,self.y,self.width,self.height),0) ##if self.text != '': ##font = pygame.font.SysFont('comicsans', 60) ##text = font.render(self.text, 1, (0,0,0)) ##win.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2))) def isOver(self, pos): #Pos is the mouse position or a tuple of (x,y) coordinates if pos[0] > self.x and pos[0] < self.x + self.width: if pos[1] > self.y and pos[1] < self.y + self.height: return True return False class Position(): def __init__(self,x,y,piece): self.x=x self.y=y self.piece=None class Piece: def __init__(self, x, y): self.x = x self.y = y self.piece_img = DARK_PAWN def draw(self, window): window.blit(self.piece_img, (self.x, self.y)) def main(): piece = Piece(90, 90) run = True toggle = 0 button1 = Button((0,255,0), 500,500,90,90, 'fm') def background(): WIN.blit(LIGHT_SQUARE, (0,0)) WIN.blit(DARK_SQUARE,(90,0)) WIN.blit(LIGHT_SQUARE,(90,90)) WIN.blit(DARK_SQUARE,(0,90)) WIN.blit(DARK_SQUARE,(630,630)) NUMBER_MAP = { 1 : ("A"), 2 : ("B"), 3 : ("C"), 4 : ("D"), 5 : ("E"), 6 : ("F"), 7 : ("G"), 8 : ("H") } for n in range(1, 9): WIN.blit(font.render(NUMBER_MAP[n], 1, (255,255,255)), ((n-1)*90 + 20, 730)) #lettering = ' A B C D E F G H' #text = font.render(lettering, 1, (255,255,255)) #WIN.blit(text, (0, 730)) for n in range (1,9): WIN.blit(font.render(f"{n}", 1, (255,255,255)), (740, (n-1)*90 + 20)) while run: pygame.time.Clock().tick(60) if toggle == 0: background() piece.draw(WIN) for event in pygame.event.get(): pos = pygame.mouse.get_pos() if event.type == pygame.QUIT: run = False pygame.quit() quit() if event.type == pygame.MOUSEBUTTONDOWN: if pos[0] < 720 and pos [1] < 720: x1 = int(pos[0]/90)*90 y1 = int(pos[1]/90)*90 if toggle == 0: toggle = 1 WIN.blit(HIGHLIGHTED_SQUARE,(x1,y1)) print ('toggle= ', toggle) continue if toggle == 1: toggle = 0 print ('toggle= ', toggle) pygame.display.update() main()
75cf86e14bc4cbc9d0f9f116e85fb8b7616a1405
naye0ng/Algorithm
/OnlineCodingTest/Programmers/더하기배열.py
408
3.765625
4
def get_all_sum(numbers, i, result = 0, depth = 0) : if depth == 2 : global answer answer.append(result) else : for k in range(i, len(numbers)) : get_all_sum(numbers, k+1, result+numbers[k], depth+1) answer = [] def solution(numbers): global answer answer = [] get_all_sum(numbers, 0) return sorted(list(set(answer))) print(solution([2,1,3,4,1]))
1e0db8fa8ff434b447e530f2a8034bae78a1572f
RahatIbnRafiq/leetcodeProblems
/Heap/451. Sort Characters By Frequency.py
387
3.640625
4
import heapq class Solution(object): def frequencySort(self, s): s = list(s) d = dict() for char in s: d[char] = d.get(char,0)+1 heap = [(x[1],x[0]) for x in d.items()] heapq.heapify(heap) heap = heapq.nlargest(len(heap),heap) return ''.join(x[1]*x[0] for x in heap) s = Solution() print s.frequencySort("tree")
5d8cd5707ce99661a333c9974f65231cb4ea7650
Maschenka77/100_Day_Python
/day_10_project_calculator.py
2,795
4.28125
4
def ask_first(): """Asks about the first number.""" first_num = int(input("What is your first number? ")) return first_num def ask_operator(): """Asks about the operator you want to calculate with.""" operator = input("Please choose an operator (+,-,*,/,**) ") return operator def ask_second(): """Asks about the second number.""" second_num = int(input("What is the second number? ")) return second_num def ask_continue(): """Asks if the user wants to continue computing with the previous result, start a new result or exit the program.""" question = input("Type 'y' if you want to continue calculating with your result. Type 'n' if you want to start a new calculation. Type 'exit' if you want to exit the program. ") return question def add(n1,n2): return n1+n2 def sub(n1,n2): return n1-n2 def mult(n1,n2): return n1*n2 def div(n1,n2): return n1/n2 def power(n1,n2): return n1**n2 #To Do: Somehow pack the if, elif statements in a function def program(): """Asks numbers and the operator and gives the user a choice whether the user wants to continue calculating with the result of a computation, start a new conputation or exit the program.""" try: first_num = ask_first() second_num = ask_second() op = ask_operator() if op == '+': result = add(first_num,second_num) elif op == '-': result = sub(first_num,second_num) elif op == '*': result = mult(first_num,second_num) elif op == '/': result = div(first_num,second_num) elif op == '**': result = power(first_num,second_num) print(str(first_num) + " " + op + " " + str(second_num) + " = " + str(result)) except ValueError: print("Something was wrong with your input.") program() cont = True while cont==True: ans = ask_continue() if ans == 'n': program() elif ans == 'exit': return None elif ans == 'y': second_num = ask_second() op = ask_operator() x = result if op == '+': result = add(result, second_num) elif op == '-': result = sub(result, second_num) elif op == '*': result = mult(result, second_num) elif op == '/': result = div(result, second_num) elif op == '**': result = power(result, second_num) print(str(x) + " " + op + " " + str(second_num) + " = " + str(result)) else: print("Invalid input.") continue program()
71297f0a15644f8e049d4d72847dbc14e4e7ba0f
QIAOZHIBAO0104/My-Leetcode-Records
/124. Binary Tree Maximum Path Sum.py
1,076
3.96875
4
''' https://leetcode.com/problems/binary-tree-maximum-path-sum/ A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any path. Example 1: Input: root = [1,2,3] Output: 6 Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. ''' ''' Time:O(n) Space:O(H) ''' class Solution: def maxPathSum(self, root: TreeNode) -> int: def traverse(node): nonlocal res if not node: return 0 left = max(traverse(node.left), 0) right = max(traverse(node.right), 0) current = node.val + left + right res = max(res, current) return node.val + max(left, right) res = float('-inf') traverse(root) return res
9adb1da90962ea87fe6a8937872847ca43ba8b2a
dheerajshetty/oopljpl
/quizzes/Quiz4.py
2,022
3.921875
4
#!/usr/bin/env python """ OOPL JPL: Quiz #4 """ """ ---------------------------------------------------------------------- 1. Define my_reduce() such that it emulates reduce(). Hint: p = iter(a) iter(p) is p """ import operator def reduce_1 (bf, a, *z) : if (not a) and (not z) : raise TypeError("reduce() of empty sequence with no initial value") if len(z) > 1 : raise TypeError("reduce expected at most 3 arguments, got 4") p = iter(a) if not z : v = p.next() else : v = z[0] try : while True : v = bf(v, p.next()) except StopIteration : pass return v def reduce_2 (bf, a, *z) : if (not a) and (not z) : raise TypeError("reduce() of empty sequence with no initial value") if len(z) > 1 : raise TypeError("reduce expected at most 3 arguments, got 4") if not z : a = iter(a) v = a.next() else : v = z[0] for w in a : v = bf(v, w) return v def test_reduce (f) : try : assert f(operator.add, []) == 0 assert False except TypeError, e : assert len(e.args) == 1 assert e.args == ('reduce() of empty sequence with no initial value',) try : assert f(operator.add, [], 0, 0) == 0 assert False except TypeError, e : assert len(e.args) == 1 assert e.args == ('reduce expected at most 3 arguments, got 4',) assert f(operator.add, [2, 3, 4]) == 9 # 2 + 3 + 4 assert f(operator.sub, [2, 3, 4]) == -5 # 2 - 3 - 4 assert f(operator.mul, [2, 3, 4]) == 24 # 2 * 3 * 4 assert f(operator.add, [], 0) == 0 assert f(operator.sub, [], 0) == 0 assert f(operator.mul, [], 1) == 1 assert f(operator.add, [2, 3, 4], 0) == 9 # 0 + 2 + 3 + 4 assert f(operator.sub, [2, 3, 4], 0) == -9 # 0 - 2 - 3 - 4 assert f(operator.mul, [2, 3, 4], 1) == 24 # 1 * 2 * 3 * 4 test_reduce(reduce_1) test_reduce(reduce_2) test_reduce(reduce)
12f7c99504d006efb31f052ee14cd3a4d70cb72b
gammaseeker/Learning-Python
/old_repo/Project Euler/Euler7.py
876
3.984375
4
#Joey Jiemjitpolchai import math def isPrime2(num): if(num < 2): return False if(num ==2): return True if(num%2==0): return False ctr = 3 while(ctr**2 <= num): if(num % ctr == 0): return False else: ctr += 2 return True def isPrime(n): for i in range(2, round(math.sqrt(n))+1): if n%i == 0: return False return True primeNum = 1 num = 1 while(primeNum < 10001): num += 2 if(isPrime(num)): primeNum += 1 print(num) upper = 10001 ctr = 1 list1 = [2] while(len(list1) < upper): ctr += 2 i = 0 primeBool = True while(list1[i]**2 <= ctr): if(ctr % list1[i] == 0): primeBool = False break i += 1 if(primeBool): list1.append(ctr) print(ctr)
635c3da86fa0f03404c500100e3b024aea4973b4
nehatomar12/Data-structures-and-Algorithms
/Searching_and_Sorting/sort.py
2,494
3.90625
4
arr = [50,80,20,40,70,30,10,60] #arr = [1,2,3,4] print(("Bef Array: ", arr, "length: ", len(arr))) def bubble_sort(): for passnum in range(len(arr)-1, 0, -1): for i in range(passnum): if arr[i] > arr[i+1]: arr[i+1],arr[i] = arr[i],arr[i+1] print(("After Swap: ", arr)) #bubble_sort() def selection_sort(): for i in range(0,len(arr)-1): for j in range(i+1, len(arr)): if arr[i] > arr[j]: arr[i] , arr[j] = arr[j] , arr[i] print(("After swap :", arr)) #selection_sort() def insertion_sort(): # traverse full array from 1 to len(arr) for i in range(1, len(arr)): # copy value of i in key and get pos to traverse # if value is greater than key shift the values of j and last copy key to j key = arr[i] pos = i-1 while pos >= 0 and key < arr[pos]: arr[pos+1] = arr[pos] pos -= 1 arr[pos+1] = key print(("After swap :", arr)) insertion_sort() def merge(left, right): result = [] i ,j = 0 , 0 while i < len(left) and j < len(right): if (left[i] < right[j]): result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 # if one list is full added and other has elemnets result += left[i:] result += right[j:] return result def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr)/2 left = merge_sort(arr[0:mid]) right = merge_sort(arr[mid:]) return merge(left, right) #print("After sort: ", merge_sort(arr) def linear_serch_rec(arry, size, index ,data): if index == size: print("Not found") return if arry[index] == data: print(("found element: ", arry[index])) return else: linear_serch_rec(arry,size,index+1,data) #linear_serch_rec(arr, len(arr), 0 , 60) def linear_serach(data): for i in range(len(arr)): if arr[i] == data: print(("Found: ", arr[i])) return print("Not found") #linear_serach(10) def binary_serach(data): arrq = arr.sort() print(("Arr after sort: ",arr)) left = 0 right = len(arrq)-1 while left <= right: mid = (left+right)/2 if arr[mid] == data: print(("found: ", arr[mid])) return if arr[mid] < data: left = arr[mid+1] else: right = arr[mid-1] #binary_serach(20)
c830973dac493de6ff5ad2c71f79720d31102b46
Nora-Wang/Leetcode_python3
/Binary Search/050. Pow(x, n).py
1,872
3.5
4
Implement pow(x, n), which calculates x raised to the power n (xn). Example 1: Input: 2.00000, 10 Output: 1024.00000 Example 2: Input: 2.10000, 3 Output: 9.26100 Example 3: Input: 2.00000, -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 Note: -100.0 < x < 100.0 n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1] code: leetcode version class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ #特判 if x == 1 or n == 0: return 1 #当n为负数时 if n < 0: x = 1 / x n = -n result = 1 temp = x while n: #n为奇数时eg:n=5,result = temp,即result = x,这时因多的一个x已被记录进result,所以n的值会变成偶数,即n=4 #接下来就是两两组对,将剩余的值都赋给temp=x^4 #****当n为1时,又会进入if语句,这时就会将之前算的x^4再乘给result,即result=x * x^4; #即这句话可以使得最后一层循环直接将实现temp*result,这样最后return的时候不需要另外*temp if n % 2: result *= temp n -= 1 temp *= temp n /= 2 return result lintcode version: class Solution: """ @param x {float}: the base number @param n {int}: the power number @return {float}: the result """ def myPow(self, x, n): if n == 0 or x == 1: return 1 if n < 0: x = 1 / x n = abs(n) temp = x result = 1 while n != 0: if n % 2 == 1: result *= temp n -= 1 temp *= temp n /= 2 return result
be2556452424d6106a94b2c41825331f0f55220a
taylorzhangyx/pythonTutorial
/EssentialTraining/playground/chapter3/types.py
353
3.625
4
#!/usr/bin/env python3 x = ''' multiline string {1:<012} seven {0:>23} '''.format(11,22) print('x is {}'.format(x)) print(type(x)) a = 1 print('a is {}'.format(a)) print(type(a)) b = 2.2 print('b is {}'.format(b)) print(type(b)) c = .1+ .1+ .1- .3 d = 11 / 3 e = 11 //3 print(f'c is {c}, d is {d}, e is {e}') print(f'{type(c)} {type(d)} {type(e)}')
09e484069ae320396d7e31bece427efeb1bd9701
JuanMaRo/Python-programming-exercises
/q017.py
562
3.59375
4
#deposit, withdrawal def account(): dep = 0 while True: command = str(input(''' [d] deposito [w] retiro [s] salir ''')) if command == 'd': d = int(input('deposito de $')) dep += d print('deposito de ${}'.format(dep)) elif command == 'w': w = int(input('retiro de $')) dep -= w print('deposito de ${}'.format(dep)) else: break if __name__ == '__main__': account()
0c28c306c1b1d2be48435cab0ad3996372b85909
manasi2905/Space-Invader
/main.py
4,009
3.5
4
import math import random import pygame # Intialize the pygame pygame.init() # create a screen of width=800 pixels, height=600 pixels screen = pygame.display.set_mode((800, 600)) # Background music #pygame.mixer.music.load('Game-Menu.mp3') #pygame.mixer.music.play() # Background image background = pygame.image.load("background.jpg") # change the caption of the screen pygame.display.set_caption("Space Invaders") # change the icon of the screen icon = pygame.image.load('/home/manasi/PycharmProjects/space_invader/alien.png') pygame.display.set_icon(icon) # Player image playerImg = pygame.image.load('spaceship.png') playerX = 370 playerY = 480 playerX_change = 0 # Enemy image enemyImg = [] enemyX = [] enemyY = [] enemyX_change = [] enemyY_change = [] num_of_enemies= 6 for i in range(num_of_enemies): enemyImg.append(pygame.image.load('ufo.png')) enemyX.append(random.randint(0, 735)) enemyY.append(random.randint(50, 150)) enemyX_change.append(1.2) enemyY_change.append(40) # Bullet image bulletImg = pygame.image.load('bullet.png') bulletX = 0 bulletY = 480 bulletX_change = 0 bulletY_change = 3 # ready = you can't see the bullet # fire - bullet is currently moving bullet_state = "ready" # score score_value = 0 font = pygame.font.Font('freesansbold.ttf', 32) textX = 10 textY =10 def show_score(x,y): score = font.render("Score: " + str(score_value), True, (255, 255, 255)) screen.blit(score, (x,y)) def player(x, y): screen.blit(playerImg, (x, y)) def enemy(x, y, i): screen.blit(enemyImg[i], (x, y)) def fire(x, y): # X+16 = center of spaceship # y+10 = a little above spaceship screen.blit(bulletImg, (x + 16, y + 10)) def isCollision(enemyX, enemyY, bulletX, bulletY): distance = math.sqrt(math.pow(enemyX - bulletX, 2) + math.pow(enemyY - bulletY, 2)) if distance < 27: return True else: return False # Game loop running = True while running: # changing background colour screen.fill((0, 0, 0)) # background image screen.blit(background, (0, 0)) # check all the event taking place for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # if keystroke is pressed check whether its right/left if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: playerX_change = -2 if event.key == pygame.K_RIGHT: playerX_change = 2 if event.key == pygame.K_SPACE: if bullet_state is "ready": bulletX = playerX bullet_state = "fire" if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: playerX_change = 0 # player playerX = playerX + playerX_change # setting boundary if playerX <= 0: playerX = 0 if playerX >= 736: # 800-64 playerX = 736 # enemy movement for i in range(num_of_enemies): enemyX[i] = enemyX[i] + enemyX_change[i] # setting boundary if enemyX[i] <= 0: enemyX_change[i] = 1.2 enemyY[i] = enemyY[i] + enemyY_change[i] if enemyX[i] >= 736: enemyX_change[i] = -1.2 enemyY[i] = enemyY[i] + enemyY_change[i] # collision collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY) if collision: bulletY = 480 bullet_state = "ready" score_value = score_value + 1 enemyX[i] = random.randint(0, 735) enemyY[i] = random.randint(50, 150) enemy(enemyX[i], enemyY[i], i) # allows multiple bullets if bulletY <= 0: bulletY = 480 bullet_state = "ready" # bullet movement if bullet_state is "fire": fire(bulletX, bulletY) bulletY = bulletY - bulletY_change player(playerX, playerY) show_score(textX, textY) pygame.display.update()
9e9cca89499a9ede9a1d8f9619a49b5d97b3ef64
lennon-phys/bentham_assessment
/bentham.py
4,037
3.703125
4
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap CLEAR = 0 RED = 1 BLUE = 2 class Town: def __init__(self, w, h, similarity): self.w = w self.h = h # The cutoff point at which a house relocates if the fraction of similarly # coloured neighbouring houses to all neighbouring houses is too low. self.similarity = similarity self.grid = np.zeros((w, h)) # Represents the entire town. self.not_clear = [] # Keeps track of which tiles have coloured houses on them. self.clear = [] # Keeps track of which tiles do NOT have coloured houses. def init_grid(self, red_f, blue_f): sites = self.w * self.h # Add all of the positions to the list of clear tiles. for x in range(self.w): for y in range(self.h): self.clear.append((x, y)) # Randomly distribute red and blue houses across the town. self.add_fraction(RED, red_f) self.add_fraction(BLUE, blue_f) # Randomly distributes houses across the town until a certain fraction of them are coloured. def add_fraction(self, colour, fraction): number = 0 sites = self.w * self.h while number < fraction * sites: # Place a coloured house on a random site. self.random_place(colour) number +=1 # Places a coloured house at a random empty position. def random_place(self, colour): # Select a random empty tile. i = np.random.randint(len(self.clear)) x, y = self.clear[i] self.clear.pop(i) self.not_clear.append((x, y)) self.grid[x][y] = colour # Returns the fraction of neighbours with the same colour house. def fraction(self, colour, x, y): fraction = 0 r, b = self.neighbours(x, y) if r == 0 and b == 0: fraction = 0 elif colour == RED: fraction = r / (r + b) elif colour == BLUE: fraction = b / (r + b) return fraction # Calculates the number of red and blue neighbours that a house has. # (The function checks all 8 surrounding tiles). def neighbours(self, x, y): r = 0 b = 0 for xOffs in [-1, 0, 1]: for yOffs in [-1, 0, 1]: xpos = (x + xOffs + self.w) % self.w ypos = (y + yOffs + self.h) % self.h # Ignore the house we are at. if(xpos != x or ypos != y): if self.grid[xpos][ypos] == RED: r += 1 elif self.grid[xpos][ypos] == BLUE: b += 1 return r, b def update(self): # Select a random house in the town. i = np.random.randint(len(self.not_clear)) x, y = self.not_clear[i] # The house relocates to a random empty tile if the fraction of similarly # coloured neighbouring houses to all neighbouring houses is too low. if self.fraction(self.grid[x][y], x, y) < self.similarity: colour = self.grid[x][y] # Remove the house at (x, y). self.grid[x][y] = CLEAR self.clear.append((x, y)) self.not_clear.pop(i) # Place a house of the same colour at a random position. self.random_place(colour) town = Town(w = 100, h = 100, similarity = 0.63) town.init_grid(red_f = 0.43, blue_f = 0.43) # Simulate the town. for _ in range(300000): town.update() # Plot the final town. fig = plt.figure(figsize=(5,5)) img = plt.imshow(town.grid, interpolation='nearest') cmap = LinearSegmentedColormap.from_list('cmap', ['lightgrey', 'blue', 'red']) img.set_cmap(cmap) plt.axis('off') plt.show()
fec1591e927fd7e86fe4fc1ed7ed62a2955531b6
kimifdw/python-tips
/structure/algorithms/mergesort.py
721
4
4
# 合并排序 def MergeSort(list): if len(list)>1: mid = len(list)//2 left = list[:mid] right = list[mid:] MergeSort(left) MergeSort(right) a = 0 b = 0 c = 0 while a < len(left) and b < len(right): if left[a] < right[b]: list[c] = left[a] a = a +1 else: list[c] = right[b] b = b + 1 c = c + 1 while a < len(left): list[c] = left[a] a = a + 1 c = c + 1 while b < len(right): list[c] = right[b] b = b + 1 c = c + 1 return list
384657c33ca75636ec5b5589ab68a8bf03236639
SantiagoVargasVe/testSlang
/main.py
1,155
4.0625
4
def calculateNGrams(text,n): n_grams= [] if len(text)<n: raise Exception("Integer larger than text, not available N-gram for this") else: index = 0 while n+index<= len(text): n_grams.append(text[index:n+index]) index +=1 print(f'this are the {n}-grams',n_grams) return (n_grams) def gettingFrecuency(array): words = dict() one_of_most_frecuent=array[0] for word in array: if not word in words: words[word] =0 words[word] +=1 if words[one_of_most_frecuent] < words[word]: one_of_most_frecuent = word return one_of_most_frecuent, words def mostFrequentNgram(text,n): array = calculateNGrams(text,n) one_of_most_frecuent,words = gettingFrecuency(array) most_times = words [one_of_most_frecuent] most_frecuent = '' for word, times in words.items(): if words[word] == most_times: most_frecuent= word break print(most_frecuent, f'is the most frecuent {n}-gram') return most_frecuent if __name__ == '__main__': mostFrequentNgram('to be or not to be',2)
0e76bf8f004121e66df74c04b5c8c7fb24ddfb1b
SupriyaPT/PythonPrograms
/Basics/lis_comprehension2.py
374
3.828125
4
''' Replace negative number with zero to change a member value instead of filtering it out, we need to add a condition at start new_list = [expression (if conditional) for member in iterable] ''' original_prices = [1.25, -9.45, 10.22, 3.78, -5.92, 1.16] prices = [i if i > 0 else 0 for i in original_prices] print("After replacing negative number with 0:") print(prices)
c32c578536d95b0b93a1ce6e750b7e945b9f8d00
hstein1/Password-Saver
/admin.py
623
3.59375
4
import user class Admin: def __init__(self): self.__accounts = {} def is_account(self, username): return username in self.__accounts def new_account(self, username, password): if not self.is_account(username): self.__accounts[username] = user.User(username, password) def correct_password(self, username, password): if self.is_account(username): return self.__accounts[username].get_password() == password def admin_login(self, username, password): return username == 'hankstein' and password == 'steiner' def print_accounts(self): print(self.__accounts)
17d80a37ab97abca6185e46198f64d09c8c518d2
ms0680146/leetcode-python
/Sliding Window/209_Minimum_Size_Subarray_Sum.py
1,756
3.53125
4
''' Input: target = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: The subarray [4,3] has the minimal length under the problem constraint. ------------------------------------------------------------------ 觀察 brute force 的規則: 2 23 231 2312 --> greater than or equal 7 --> 計算 subarray_len 23124 --> 不用計算 231243 --> 不用計算 3 31 312 3124 --> greater than or equal 7 31243 --> 不用計算 1 12 124 --> greater than or equal 7 1243 --> 不用計算 2 24 243 --> greater than or equal 7 4 43 --> greater than or equal 7 --------------------------------------------------------- 一開始 windowStart 指向 2,然後 windowEnd 會慢慢擴張, 當擴張到 [2,3,1,2] 這個情況時,因為 sum 已經 >= 7, 所以 windowStart 會開始右移。 也就是說,原本暴力法會考慮的 [2,3,1,2,4] 跟 [2,3,1,2,4,3] 就不會被考慮到。 就是因為這種情況,直觀下會覺得我們這樣不就少考慮到很多情況嗎? 但大家可以再仔細想想,我們現在要求的是 sum >= s 的最小 subarray, 如果 [2,3,1,2] 已經滿足條件了, 我們繼續看 [2,3,1,2,4] 跟 [2,3,1,2,4,3] 又有什麼意義呢? 畢竟這兩個 subarray 都大於 [2,3,1,2] 啊! ''' def minSubArrayLen(target, nums): start = 0 window_sum = 0 global_len_of_subarray = float('inf') local_len_of_subarray = 0 for i in range(len(nums)): window_sum += nums[i] while window_sum >= target: local_len_of_subarray = i - start + 1 global_len_of_subarray = min(local_len_of_subarray, global_len_of_subarray) window_sum -= nums[start] start += 1 return global_len_of_subarray if global_len_of_subarray != float('inf') else 0
80ece89c6c06cf5b1e203abb5e686f8b85709516
musahibrahimali/PythonGUI
/calculator/calculator.py
5,561
3.546875
4
import tkinter as tk from tkinter import ttk class Calculator(): def __init__(self, parent): self.parent = parent self.parent.title('Calculator') self.parent.iconbitmap('calculator/icono.ico') # calculator\icono.ico self.add = False self.sub = False self.div = False self.mul = False self.CreateEntry() self.CreateButtons() def CreateEntry(self): self.entry = tk.ttk.Entry(self.parent, width=43) self.entry.grid(row=0, column=0, columnspan=3, padx=10, pady=10) def CreateButtons(self): self.Button_7 = tk.Button(self.parent, text='7', padx=40, pady=20, bg='gray', fg='white', command= lambda: self.ButtonClick(7)) self.Button_7.grid(row=1, column=0) self.Button_8 = tk.Button(self.parent, text='8', padx=40, pady=20, bg='gray', fg='white', command= lambda: self.ButtonClick(8)) self.Button_8.grid(row=1, column=1) self.Button_9 = tk.Button(self.parent, text='9', padx=40, pady=20, bg='gray', fg='white', command= lambda: self.ButtonClick(9)) self.Button_9.grid(row=1, column=2) self.Button_4 = tk.Button(self.parent, text='4', padx=40, pady=20, bg='gray', fg='white', command= lambda: self.ButtonClick(4)) self.Button_4.grid(row=2, column=0) self.Button_5 = tk.Button(self.parent, text='5', padx=40, pady=20, bg='gray', fg='white', command= lambda: self.ButtonClick(5)) self.Button_5.grid(row=2, column=1) self.Button_6 = tk.Button(self.parent, text='6', padx=40, pady=20, bg='gray', fg='white', command= lambda: self.ButtonClick(6)) self.Button_6.grid(row=2, column=2) self.Button_1 = tk.Button(self.parent, text='1', padx=40, pady=20, bg='gray', fg='white', command= lambda: self.ButtonClick(1)) self.Button_1.grid(row=3, column=0) self.Button_2 = tk.Button(self.parent, text='2', padx=40, pady=20, bg='gray', fg='white', command= lambda: self.ButtonClick(2)) self.Button_2.grid(row=3, column=1) self.Button_3 = tk.Button(self.parent, text='3', padx=40, pady=20, bg='gray', fg='white', command= lambda: self.ButtonClick(3)) self.Button_3.grid(row=3, column=2) self.Button_add = tk.Button(self.parent, text='+', padx=40, pady=20, bg='purple', fg='white', command=self.AddButton) self.Button_add.grid(row=4, column=0) self.Button_0 = tk.Button(self.parent, text='0', padx=40, pady=20, bg='gray', fg='white', command= lambda: self.ButtonClick(0)) self.Button_0.grid(row=4, column=1) self.Button_subtract = tk.Button(self.parent, text='-', padx=40, pady=20, bg='purple', fg='white', command=self.SubButton) self.Button_subtract.grid(row=4, column=2) self.Button_divide = tk.Button(self.parent, text='/', padx=41, pady=20, bg='purple', fg='white', command=self.DivButton) self.Button_divide.grid(row=5, column=0) self.Button_multiply = tk.Button(self.parent, text='x', padx=40, pady=20, bg='purple', fg='white', command=self.MulButton) self.Button_multiply.grid(row=5, column=1) self.Button_clear = tk.Button(self.parent, text='CE', padx=35, pady=20, bg='brown', fg='white', command=self.ClearField) self.Button_clear.grid(row=5, column=2) self.Button_equal = tk.Button(self.parent, text='=', padx=135, pady=20, bg='orange', fg='white', command=self.CalculateResults) self.Button_equal.grid(row=6, column=0, columnspan=3) def ClearField(self): self.entry.get() self.entry.delete(0, 'end') def ButtonClick(self, number): self.current = self.entry.get() self.entry.delete(0, 'end') self.entry.insert(0, str(self.current) + str(number)) def AddButton(self): try: self.first = self.entry.get() self.first = float(self.first) self.entry.delete(0, 'end') self.add = True except ValueError: pass def SubButton(self): try : self.first = self.entry.get() self.first = float(self.first) self.entry.delete(0, 'end') self.sub = True except ValueError: pass def MulButton(self): try : self.first = self.entry.get() self.first = float(self.first) self.entry.delete(0, 'end') self.mul = True except ValueError: pass def DivButton(self): try: self.first = self.entry.get() self.first = float(self.first) self.entry.delete(0, 'end') self.div = True except ValueError: pass def CalculateResults(self): try : self.second = self.entry.get() self.second = float(self.second) self.entry.delete(0, 'end') if self.add == True: self.result = self.first + self.second self.add = False elif self.sub == True: self.result = self.first - self.second self.sub = False elif self.mul == True: self.result = self.first * self.second self.mul = False elif self.div == True: self.result = self.first / self.second self.div = False self.entry.insert(0, str(self.result)) except ValueError: pass if __name__ == "__main__": root = tk.Tk() MyApp = Calculator(root) root.mainloop()
3069b78664240798645944da6d92972c3debe891
fatihemregit/python-works2
/karekterkontrol.py
405
3.75
4
kelime=str(input("Kelimeyi giriniz:")) yasak=set() yasakliharfler=("ÇçıİöÖ") yasaksayi=int(0) for i in kelime: if i in yasakliharfler: yasak.add(i) if len(yasak)==0: print("kullanılan yasaklı harfler: ") print("girilen kelimedeki yasaklı harf sayısı:",0) elif len(yasak)>=1: print("kullanılan yasaklı harfler:",yasak) print("girilen kelimedeki yasaklı harf sayısı:",len(yasak))
4613de4ed71352d97ad9094b000fe38e150b249d
maxbergmark/misc-scripts
/codereview/codereview_triangles.py
1,611
3.96875
4
import sys def triangle(height): print() max = (height * 2) - 1 mid = 0 while max > height: statement = " " * max + "/" + " " * mid + "\\" print(statement) max -= 1 mid += 2 statement = " " * max + "/" + "_" * mid + "\\" max -= 1 print(statement) small = 0 while max > 0: statement = " " * max + "/" + " " * small + "\\" + " " * mid + "/" + " " * small + "\\" print(statement) mid -= 2 max -= 1 small += 2 statement = " " * max + "/" + "_" * small + "\\" + " " * mid + "/" + "_" * small + "\\" print(statement) pass def create_triangle(n): triangle = "" for i in range(n): triangle += ' '*(2*n-i-1) + '/' + ' _'[i==n-1]*2*i + '\\' + "\n" for i in range(n, 2*n): triangle += ' '*(2*n-i-1) + '/' + ' _'[i==2*n-1]*(2*i-2*n) + '\\' triangle += ' '*(4*n-2*i-2) + '/' + ' _'[i==2*n-1]*(2*i-2*n) + '\\' triangle += '\n' return triangle def create_triangle_array(n): arr = [[' ' for i in range(4*n)] for j in range(2*n)] for i in range(2*n): arr[i][2*n-i-1] = '/' arr[i][2*n+i] = '\\' for i in range(n, 2*n): arr[i][i] = '\\' arr[i][4*n-i-1] = '/' for i in range(2*n-2): arr[n-1][n+1+i] = '_' arr[2*n-1][2*n+1+i] = '_' arr[2*n-1][1+i] = '_' return '\n'.join([''.join(row) for row in arr]) def create_print_array(n): arr = [['*' for i in range(n)] for j in range(n)] return '\n'.join([''.join(row) for row in arr]) # print(create_triangle(2)) # print(create_triangle(5)) print(create_triangle_array(40)) quit() # for i in range(10): # print(i) # triangle(i)
3feb86bfdcd6a1e1464cda5144d8288db767e06a
rbirdic/gui_python
/gui_with_grid_canvas.py
4,280
3.5
4
# -*- coding: utf-8 -*- try: import Tkinter as tk # Python 2 import ttk except ImportError: import tkinter as Tkinter # Python 3 import tkinter.ttk as ttk import tkFont # using grid # +------+-------------+ # | btn1 | btn2 | # +------+------+------+ # | btn3 | btn3 | btn4 | # +-------------+------+ def rounded_rect(canvas, x, y, w, h, c): canvas.create_arc(x, y, x+2*c, y+2*c, start= 90, extent=90, style="arc") canvas.create_arc(x+w-2*c, y+h-2*c, x+w, y+h, start=270, extent=90, style="arc") canvas.create_arc(x+w-2*c, y, x+w, y+2*c, start= 0, extent=90, style="arc") canvas.create_arc(x, y+h-2*c, x+2*c, y+h, start=180, extent=90, style="arc") canvas.create_line(x+c, y, x+w-c, y ) canvas.create_line(x+c, y+h, x+w-c, y+h ) canvas.create_line(x, y+c, x, y+h-c) canvas.create_line(x+w, y+c, x+w, y+h-c) def callback1(): print "Izabrali ste Espresso!" def callback2(): print "Izabrali ste Espresso sa mlekom!" def callback3(): print "Izabrali ste Nes sa šlagom!" def callback4(): print "Izabrali ste Čaj od nane!" def callback5(): progress.step(20) def callback6(): print "Izabrali ste Čaj od nane!" root = tk.Tk() # tkFont.BOLD == 'bold' helv36 = tkFont.Font(family='Helvetica', size=12, weight=tkFont.BOLD) photo1 = tk.PhotoImage(file="rsz_download.gif") photo2 = tk.PhotoImage(file="rsz_latteart.gif") photo3 = tk.PhotoImage(file="rsz_exps.gif") photo4 = tk.PhotoImage(file="rsz_tea-png-file.gif") btn1 = tk.Button(text='Espresso', compound=tk.LEFT, image=photo1, font=helv36, borderwidth=7, command=callback1) progress = ttk.Progressbar(orient=tk.HORIZONTAL,length=100, mode='determinate') btn3 = tk.Button(text='Nes sa šlagom', compound=tk.LEFT, image=photo3, font=helv36, borderwidth=7, command=callback3) btn4 = tk.Button(text='Čaj od nane', compound=tk.LEFT, image=photo4, font=helv36, borderwidth=7, command=callback4, background='white') btn5 = tk.Button(text='btn5', compound=tk.LEFT, image=photo1, font=helv36, command=callback4, borderwidth=7) btn6 = tk.Button(text='Espresso', compound=tk.LEFT, image=photo1, font=helv36, command=callback4, borderwidth=7) btn7 = tk.Button(text='Espresso sa mlekom', compound=tk.LEFT, image=photo2, font=helv36, command=callback4, borderwidth=7) btn8 = tk.Button(text='Nes sa šlagom', compound=tk.LEFT, image=photo3, font=helv36, command=callback4, borderwidth=7) btn9 = tk.Button(text='btn4', compound=tk.LEFT, image=photo1, font=helv36, command=callback4, borderwidth=7) btn10 = tk.Button(text='btn5', compound=tk.LEFT, image=photo1, font=helv36, command=callback4, borderwidth=7) btn11 = tk.Button(text='btn4', compound=tk.LEFT, image=photo1, font=helv36, command=callback4, borderwidth=7) btn12 = tk.Button(text='btn5', compound=tk.LEFT, image=photo1, font=helv36, command=callback4, borderwidth=7) root.rowconfigure((0,6), weight=1) # make buttons stretch when root.columnconfigure((0,1), weight=1) # when window is resized volumeUp = tk.Button(height=1, width=5, text='◄◄', borderwidth=10, fg = 'black', bg='light blue', command=callback5).grid(row=0,column=0) volumeDown =tk.Button(height=1, width=5, text='►', borderwidth=10, fg = 'black', bg='light blue', command=callback5).grid(row=0,column=1) # tk.Label(root, text="First", font=helv36).grid(row=0, columnspan=2) progress.grid(row=1, column=0, columnspan=1, sticky='EWNS', padx=10, pady=10) btn3.grid(row=2, column=0, columnspan=1, sticky='EWNS', padx=10, pady=10) btn4.grid(row=3, column=0, columnspan=1, sticky='EWNS', padx=10, pady=10) btn5.grid(row=4, column=0, columnspan=1, sticky='EWNS', padx=10, pady=10) btn6.grid(row=5, column=0, columnspan=1, sticky='EWNS', padx=10, pady=10) btn1.grid(row=6, column=0, columnspan=1, sticky='EWNS', padx=10, pady=10) btn8.grid(row=1, column=1, columnspan=1, sticky='EWNS', padx=10, pady=10) btn9.grid(row=2, column=1, columnspan=1, sticky='EWNS', padx=10, pady=10) btn10.grid(row=3, column=1, columnspan=1, sticky='EWNS', padx=10, pady=10) btn11.grid(row=4, column=1, columnspan=1, sticky='EWNS', padx=10, pady=10) btn12.grid(row=5, column=1, columnspan=1, sticky='EWNS', padx=10, pady=10) btn7.grid(row=6, column=1, columnspan=1, sticky='EWNS', padx=10, pady=10) root.mainloop()
e02917a28372e8efc44726ea1e8f52273b63085d
ChrisPOconnell/python
/Assignment1.py
1,038
3.875
4
__author__ = 'ChrisP' print("Welcome to the catalog prep program!") print("This program will be used to correct the catalog spread sheets") print() provnum=0 provlist=list() while provnum < 3 or provnum >10: provnum=eval(input("How many Provinces are in this year's catalog? ")) if provnum < 3 or provnum > 10: print("Please enter a single digit number between 3 and 10 ") #Unfortunately if someone enters a letter here the program crashes. #to be fixed in a later version print("Great, you have",provnum,"Provinces to work with this year. That should be easy :)") print() print("Next let's collect the 3 letter Province abbreviations.") indx=0 while (indx< provnum): prov=input("Please enter the three digit Province abbreviation, then press ENTER: ") if len(prov)!=3: print("Sorry, the Province abbreviation must be 3 letters!") elif len(prov)==3: provlist.append(prov) indx= indx+1 print("You have",provnum,"Provinces this year. They are:") print(provlist)
b0b5ffaa28e2ac7c71d5497a93d7662b5511d176
CianLR/CA117-LabProblems
/Lab11.1/file_111.py
1,334
3.546875
4
class File: FILE_PERMISSIONS = 'rwx' def __init__(self, name, owner, size=0, permissions=''): self.name = name self.owner = owner self.size = size self.permissions = ''.join(sorted(permissions)) def __str__(self): ret = 'File: {}\n'.format(self.name) ret += 'Owner: {}\n'.format(self.owner) ret += 'Permissions: {}\n'.format(self.get_permissions()) ret += 'Size: {} bytes'.format(self.size) return ret def has_access(self, name, permis): if name == self.owner: return "Access granted" elif permis in self.permissions: return "Access granted" return "Access denied" def enable_permission(self, name, permis): if name != self.owner: print('Access denied') return if permis in self.FILE_PERMISSIONS and permis not in self.permissions: self.permissions = ''.join(sorted(self.permissions + permis)) def disable_permission(self, name, permis): if name != self.owner: print('Access denied') return self.permissions = self.permissions.replace(permis, '') def get_permissions(self): if self.permissions == '': return 'null' else: return self.permissions
21944b3ec4c942122cf869c5d7f4113dd3978072
cikent/Portfolio
/CodeSamples-Python/LPTHW-PythonCourse-ex09-PrintingPrintingPrinting-VariableNewLinePrintFunction.py
678
4.125
4
# Here's some new strange stuff, remember to type it exactly. # declare the variable days days = "Mon Tue Wed Thu Fri Sat Sun" # declare the variable months, parse the string with '\n' for new line months = "\nJan\nFeb\nMar\"\nApr\nMay\nJun\nJul\nAug" # print to screen a string + the value of the variable days print("Here are the days: ", days) # print to screen a string + the value of the variable months print("Here are the months: ", months) # print a multiple line String using 3 double-quotes print(""" There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. """)
6ee693a898f56a5ec8a7246af8a8216bf843fcbc
Motwg/adventofcode-2020
/day22/game.py
2,136
3.65625
4
from day22.player import Player class Game: def __init__(self, no_game, p_one, p_two): self.round = 0 self.no_game = no_game assert isinstance(p_one, Player) assert isinstance(p_two, Player) self.one = p_one self.two = p_two def start(self): while self.one.get_no_cards() > 0 and self.two.get_no_cards() > 0: self.next_round() # print(list(self.one.cards), self.one.prev_cards) for one_deck, two_deck in zip(self.one.prev_cards, self.two.prev_cards): if one_deck == list(self.one.cards) and two_deck == list(self.two.cards): print('REPEATED') return 1 if self.one.get_no_cards() == 0: return 2 elif self.two.get_no_cards() == 0: return 1 def next_round(self): self.round += 1 if self.no_game == 1: print('\nGAME {} ROUND {}'.format(self.no_game, self.round)) print('DECK ONE: {}'.format(self.one.cards)) print('DECK TWO: {}'.format(self.two.cards)) first = self.one.next_card() second = self.two.next_card() if self.no_game == 1: print('PLAY ONE: {}'.format(first)) print('PLAY TWO: {}'.format(second)) # sub game if first <= self.one.get_no_cards() and second <= self.two.get_no_cards(): print('STARTING SUB GAME') new_one_deck = self.one.cards.copy() new_two_deck = self.two.cards.copy() player_one = Player([new_one_deck.popleft() for _ in range(first)]) player_two = Player([new_two_deck.popleft() for _ in range(second)]) sub_game = Game(self.no_game + 1, player_one, player_two) winner = sub_game.start() if winner == 1: self.one.won(first, second) elif winner == 2: self.two.won(second, first) # normal game else: if first > second: self.one.won(first, second) else: self.two.won(second, first)
cb92e38fb53880696cb016a10d483073d03cba58
Malak-Ghanom/Python
/Class_Assignment/CA09/q3.py
531
4.1875
4
#You are given a sentence as input. Return a list of all words of even length. #Input: Print every word in this sentence that has an even number of letters. #Return: ['word', 'in', 'this', 'sentence', 'that', 'an', 'even', 'number', 'of'] sentence = "every word in this sentence that has an even number of letters" even_words=[word for word in sentence.split() if len(word) % 2 == 0 ] # for word in sentence.split(): # if len(word) % 2 == 0: # even_words.append(word) print(f"list of enen words is : {even_words}")
0ca31b5d04cd32c0232ef63b8abe610a31779821
windyIsMe/leetcode
/python/p146.py
1,505
3.640625
4
# -*- coding: utf-8 -* class Node: def __init__(self, k, v): self.key = k self.val = v self.prev = None self.next = None class LRUCache: ''' Use dict and doubleLinkedList to store ''' def __init__(self, capacity: int): self.capacity = capacity self.dic = dict() self.head = Node(0, 0) self.tail = Node(0, 0) self.head.next = self.tail self.tail.prev = self.head def get(self, key: int) -> int: if key in self.dic: n = self.dic[key] self.__remove(n) self.__append(n) return n.val else: return -1 def put(self, key: int, value: int) -> None: if key in self.dic: self.__remove(self.dic[key]) n = Node(key, value) self.__append(n) self.dic[key] = n if len(self.dic) > self.capacity: n = self.head.next self.__remove(n) del self.dic[n.key] def __remove(self, node): p = node.prev n = node.next p.next = n n.prev = p def __append(self, node): p = self.tail.prev p.next = node node.next = self.tail node.prev = p self.tail.prev = node if __name__ == '__main__': cache = LRUCache(2) cache.put(1, 1); cache.put(2, 2); cache.get(1) cache.put(3, 3) cache.get(2) cache.put(4, 4) cache.get(1) cache.get(3) cache.get(4)
2a51954c534f6a5cfcb44b03d868a3e4611b3a88
GitXin/LeetCode
/reverse_integer.py
227
3.546875
4
class Solution: def reverse(self, x): arr = list(str(abs(x))) arr.reverse() y = int(''.join(arr)) if x < 0: y = -y return 0 if y < -2**31 + 1 else y else: return 0 if y > 2**31 - 1 else y
a58864e1ce8d56f79032d7666cf427a155b1d35f
lisazacarias/bookRankings
/vote.py
5,066
3.640625
4
from csv import reader from collections import defaultdict from six import next from argparse import ArgumentParser TEST_MODE = False class BookRanker: def __init__(self, inputFile, colsToDelete, question): self.tallies = {} self.inputFile = inputFile self.colsToDelete = colsToDelete self.question = question class TallyObj: def __init__(self, title, tallies): self.title = title self.tallies = tallies def __gt__(self, other): if TEST_MODE: print() print(self.title) print(other.title) def compareTallies(lastPlace, scoreSelf, scoreOther): while lastPlace > 1: # Kind of treating rank as "displeasure points". Not quite # sure if that works perfectly, but it works well enough scoreSelf += self.tallies[lastPlace] scoreOther += other.tallies[lastPlace] if scoreSelf != scoreOther: if TEST_MODE: print("Found after scoring with {place}".format(place=lastPlace)) return scoreSelf > scoreOther lastPlace -= 1 # If their scores are equal, just go alphabetically if TEST_MODE: print("Found alphabetically") return self.title > other.title if not isinstance(other, type(self)): return False lastPlaceSelf = max(self.tallies, key=int) lastPlaceOther = max(other.tallies, key=int) # The idea is to pick books that everyone can tolerate reasonably # well, so the "loser" is the book that's most hated by anyone if lastPlaceSelf != lastPlaceOther: if TEST_MODE: print("found by last place") return lastPlaceSelf > lastPlaceOther startingScoreSelf = self.tallies[lastPlaceSelf] startingScoreOther = other.tallies[lastPlaceOther] if startingScoreSelf != startingScoreOther: if TEST_MODE: print("found by last place tally") return startingScoreSelf > startingScoreOther return compareTallies(lastPlaceSelf - 1, startingScoreSelf, startingScoreOther) def vote(self): with open(self.inputFile) as rankFile: resultReader = reader(rankFile) header = next(resultReader) # Date column is unnecessary for col in self.colsToDelete: header.pop(col) for title in header: self.tallies[title] = defaultdict(int) for row in resultReader: # Discarding date column again for col in self.colsToDelete: row.pop(col) # Keeps track of how many nth place votes each title has, of the # form {title: {n: tally}} where n is some rank (like 1 for first # place) for idx, rank in enumerate(row): self.tallies[header[idx]][int(rank)] += 1 tallyObjs = [] for title, tallyDict in self.tallies.items(): # Get rid of Microsoft Form question title which shows up in every # entry for some reason... tallyObjs.append(self.TallyObj(title.replace(self.question, ""), tallyDict)) # Abuse the overloaded operator to figure out the ordering tallyObjs = sorted(tallyObjs) tallyObjs.reverse() n = 1 while tallyObjs: print("BOOK {N}:".format(N=n)) print("\t{TITLE}\n".format(TITLE=tallyObjs.pop().title) .replace("[", "").replace("]", "")) n += 1 if __name__ == "__main__": parser = ArgumentParser(description="This is a script to order book club " "books given a CSV of ranked choice " "votes per participant") parser.add_argument('-i', '--input', help='Input CSV (will be rankings.csv by default)', default="rankings.csv") parser.add_argument('-c', '--columns', help='Column indices to ignore in input file (will be 0 by default)', type=int, nargs='+', default=[0]) parser.add_argument('-q', '--question', help='Question string from the form to delete from titles' ' (will be \'Please rank your choices \' by default)', default="Please rank your choices ") args = parser.parse_args() BookRanker(inputFile=args.input, colsToDelete=args.columns, question=args.question).vote()
51a6ee2d9fff2397beedd05a7468e83c4d3f5ae2
JesseNicholas00/IdeaBag
/DistanceBetweenTwoCities.py
579
4.0625
4
class Coordinate(): def __init__(self,x_value,y_value): self.x_value = float(x_value) self.y_value = float(y_value) def Distance(self,other): x = (self.x_value - other.x_value)**2 y = (self.y_value - other.y_value)**2 return x + y cityA = Coordinate(input("Give me cityA's x coordinate "),input("Give me cityA's y coordinate ")) cityB = Coordinate(input("Give me cityB's x coordinate "),input("Give me cityB's y coordinate ")) print("The distance between those cities is " + str(Coordinate.Distance(cityA,cityB)))
21db7c0e9ce1eea9fe05d0eb1effd82cd58212e4
ajaydinakar/DataMining
/Assignments/scrape_data/run.py
1,723
3.625
4
#********************************************************************************* # Ajay Dinakar Kandavalli # CMPS-5443 Data mining # Assignment-1 # Scraping Data from a website # Language :python3, # website choosed is www.allaboutcircuits.com(embedded systems projects website) #********************************************************************************* #importing libraries import bs4 from urllib.request import urlopen as ureq from bs4 import BeautifulSoup as soup f=open("projects.csv","w") f.write("project Name, Published Time, Year, Author \n") #interating multiple pages and #getting the url stored in variable for WPagenumb in range( 0, (5+1)*20, 20)[0:]:#as each page is multiple of 20 WPagenumb=str(WPagenumb) #ex:p20,p40,p60 etc in url #first webpage if WPagenumb is 0: url="https://www.allaboutcircuits.com/projects/category/embedded/" #pages other than first webpage else: url="https://www.allaboutcircuits.com/projects/category/embedded/"+ "P" + WPagenumb + "/" #opening connection and accessing the web page uclient=ureq(url) page_html=uclient.read() uclient.close() #parse the html data page=soup(page_html,"html.parser") projects=page.findAll("div",{"class":"row archive-container"}) for project in projects: projectTitle=(project.findNext("div",{"class":"col-lg-12 article-heading"}).h3.text) projectTime=(project.findNext("span",{"class":"meta-timespan"}).text) projectAuthor=(project.findNext("a",{"class":"article-author"}).text) f.write(projectTitle +", " + projectTime+", "+ projectAuthor + "\n") f.close()
334c8d42471d9394c6ab0835ce1c1d96d5f5e695
chenchen1104/leetcode
/leetcode/算法/8数学/168.py
317
3.515625
4
columnNumber = 701 excellist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" data = [] while columnNumber > 0: data.append(columnNumber % 26) columnNumber = columnNumber // 26 print(data,columnNumber) data.reverse() print(data) excelname = "" for i in data: excelname += excellist[i - 1] print(excelname)
79e412dd7f4ff6709e3aab5c2a75a1a016c8abb3
Nomercy-ops/UserRegistrationProblem
/Test/UserValidation.py
2,486
3.734375
4
""" @Author: Rikesh Chhetri @Date: 2021-07-05 @Last Modified by: Rikesh Chhetri @Last Modified time: 2021-07-05 07:03:30 @Title : Program Aim is to validate user entered details using regular expression. """ import re from RegexPattern import RegexPattern as regex_pattern from LogHandler import logger class ValidateUser: def ValidateName(input): """ Description: This method is used for validating name with regex pattern. Return: It return a valid true if name is valid and false if it's invalid. Parameter: It takes input as a parameter. """ try: if (re.match(re.compile(regex_pattern.NAME_PATTERN),input)): return True else: return False except Exception as e: logger.error(e) def ValidateEmail(emailInput): """ Description: This method is used for validating email with regex pattern. Return: It return a valid if email is valid and invalid if it's invalid. Parameter: It takes input as a parameter. """ try: if (re.match(re.compile(regex_pattern.EMAIL_PATTERN),emailInput)): return True else: return False except Exception as e: logger.error(e) def ValidatePhoneNumber(phoneInput): """ Description: This method is used for validating phone number with regex pattern. Return: It return a valid if phone number is valid and invalid if it's invalid. Parameter: It takes input as a parameter. """ try: if (re.match(re.compile(regex_pattern.PHONE_PATTERN),phoneInput)): return True else: return False except Exception as e: logger.error(e) def ValidatePassword(passwordInput): """ Description: This method is used for validating password with regex pattern. Return: It return a valid if password is valid and invalid if it's invalid. Parameter: It takes input as a parameter. """ try: if (re.match(re.compile(regex_pattern.PASSWORD_PATTERN),passwordInput)): return True else: return False except Exception as e: logger.error(e)
2e9269503e4a7ffabe4ead8b10a35b8988387627
UC-Design/11055-PfD-2019-2
/Exercises/u3190538/Week 11/NameReader.py
226
3.84375
4
nameFile = open("one.txt") for lines in nameFile: print(lines) newFile = open("two.txt", "wt") nameFile = open("one.txt") for lines in reversed(list(nameFile)): newFile.write(lines) newFile.close() nameFile.close()
1993c94c10048a84a29b3da5a2539b7af6581395
iamlaboniraz/my-google-foobar-experience
/level03_01_Prepare_the_Bunnies_Escape.py
1,949
3.703125
4
def Search(search,map): LRUD = [] q = [] Dictionary = {} q.append(search) string = str(search[0])+','+str(search[1]) Dictionary[string]=1 while(0<len(q)): present = q.pop(0) LRUD.append([present[0]-1,present[1]]) LRUD.append([present[0]+1,present[1]]) LRUD.append([present[0],present[1]+1]) LRUD.append([present[0],present[1]-1]) for i in LRUD: string1 = str(i[0])+','+str(i[1]) string2 = str(present[0])+','+str(present[1]) if i[0]<0 or i[1]<0 or i[0]>len(map)-1 or i[1]>len(map[0])-1: continue if string1 not in Dictionary: if map[i[0]][i[1]] == 0: q.append(i) Dictionary[string1] = Dictionary[string2]+1 return Dictionary def Find(i,map): list_ = [] integer = i.split(",") node = [int(integer[0]),int(integer[1])] L = str(node[0]-1)+','+str(node[1]) if L in map: list_.append(map[L]) R = str(node[0]+1)+','+str(node[1]) if R in map: list_.append(map[R]) U = str(node[0])+','+str(node[1]+1) if U in map: list_.append(map[U]) D = str(node[0])+','+str(node[1]-1) if D in map: list_.append(map[D]) if len(list_) == 0: return else: return min(list_) def solution(map): # Your code here MinimumPath = [] length1,length2 = len(map),len(map[0]) Allwall = [] starting = Search([0,0],map) ending = Search([length1-1, length2-1],map) for i in range(0,length1): for j in range(0,length2): if map[i][j] == 1: Allwall.append((str(i)+','+str(j))) for i in Allwall: start,end = Find(i,starting),Find(i,ending) if start and end: MinimumPath.append(start + end) return min(MinimumPath)+1 map = [[0,1,1], [1,0,0], [1,0,0]] print(solution(map))
bd3dd5d52f154be23631e07429c62b2515e19220
JerryMazeyu/python_study
/singleton_4.py
702
3.5625
4
# 类方法是一种在类中但对类进行交互的方法,不同于实例方法,类方法第一个参数是cls。 class Singleton(object): def __init__(self, x): self.x = x @classmethod def instance(cls, *args, **kargs): if not hasattr(cls, "_instance"): print("im here") # cls._instance = Singleton(*args, **kargs) cls._instance = object.__new__(cls) else: print("im here!!") # print(cls._instance) # print(getattr(cls, "_instance")) return cls._instance a1 = Singleton.instance(2) a2 = Singleton.instance(4) print(a1 is a2) # True print(a2) # 2 print(a2.x) # 依旧是 2
b7f655ef6e732c6c7894fb9510f80f091de01ad4
hicaro/practice-python
/fibonacci/fibonacci.py
240
4.03125
4
""" Function to print the n first numbers of the fibonacci series """ def fibonacci(number): a = 0 b= 1 for i in range(1, int(number)): print str(a); aux = a + b; a = b; b = aux; fibonacci(10)
674717a6ccc1b460505b353b08342bfa8eed52f8
GambuzX/Cybersecurity_Practice
/overthewire/krypton/krypton2/caesar_cipher.py
274
3.53125
4
#!/bin/python encrypted = "OMQEMDUEQMEK" start_offset = 65 rotation = -12 letter_count = 26 decrypted = "" for c in encrypted: if c == ' ': decrypted += ' ' else: decrypted += chr(((ord(c) - start_offset + rotation) % letter_count) + start_offset) print(decrypted)
a4be2baa2aec4167f661d5707b95fb53874f10e5
antonioramos1/codingbat-python
/List-2/sum13.py
239
3.5625
4
def sum13(nums): new_list = nums while 13 in new_list: if new_list[-1] == 13: del new_list[-1] else: del new_list[new_list.index(13)+1], new_list[new_list.index(13)] return sum(new_list)
0829eceeccf3a694a09d46cfac6af37bb4225a71
Tonykane923/BudkovQA24
/ДЗ № 13 Задание 2.py
1,111
3.953125
4
# Пользователь вводит арифметическую операцию: сложение, вычитание, умножение или деление line = input("Введите арифметическое выражение: ") i = 0 # Вводим первый аргумент и пишем цикл arg1 = [] while True: if line[i] in '1234567890': arg1.append(line[i]) i += 1 else: break arg1 = int(''.join(arg1)) if line[i] not in '+-/*': raise ValueError op = line[i] i += 1 # Вводим второй аргумент и пишем цикл arg2 = [] while True: try: if line[i] in '1234567890': arg2.append(line[i]) i += 1 except IndexError: break arg2 = int(''.join(arg2)) print(arg1, op, arg2) # Для сложения if op == '+': print(arg1 + arg2) # Для вычитания elif op == '-': print(arg1 - arg2) # Для умножения elif op == '*': print(arg1 * arg2) # Для деления elif op == '/': print(arg1 - arg2)
debc31195a67e53587d170b09cde09c1a03ed748
rchfrnkln/PythonAscension
/src/Deck.py
961
3.8125
4
''' Created on Jun 15, 2017 @author: KrzyMoose ''' import random from Hand import Hand class Deck: def __init__(self, cards): self._deck = cards self._graveyard = Hand() self.shuffle() def draw_card(self): if(self.get_size() == 0): self.shuffle_graveyard_into_deck() if(self.get_size() == 0): return None return self._deck.pop() def peek(self): return self._deck[0] def put_card_on_top(self, card): self._deck.insert(0, card) def add_to_graveyard(self, card): self._graveyard.add_card(card) def shuffle(self): random.shuffle(self._deck) def shuffle_graveyard_into_deck(self): while(self._graveyard.get_size() != 0): self._deck.append(self._graveyard.remove_card(0)) self.shuffle() def get_size(self): return len(self._deck)
30376116a7a4ddb90b8b4f865c1bffbb08004535
gabriellaec/desoft-analise-exercicios
/backup/user_332/ch20_2019_03_13_17_30_26_550250.py
205
3.90625
4
def pergunta_nome (NOME): if (NOME == "Chris"): print("Todo mundo odeia o Chris") else: print("Ola, {}".format(NOME)) NOME = str(input("Qual eh seu nome?")) print(pergunta_nome(NOME))
ace6376a6a3f7a4ed6a9e4a78d247195fae813a0
monpro/algorithm
/src/linked-lists/swap-node.py
956
3.65625
4
from utils.Node import ListNode class Solution: def swapNodes(self, head, v1, v2): dummy = ListNode(0, head) cur = dummy p1 = None p2 = None while cur.next is not None: if cur.next.val == v1: p1 = cur if cur.next.val == v2: p2 = cur cur = cur.next if p1 is None or p2 is None: return dummy.next n1 = p1.next n2 = p2.next n1_nextnode = n1.next n2_nextnode = n2.next if p1.next == p2: p1.next = n2 n2.next = n1 n1.next = n2_nextnode elif p2.next == p1: p2.next = n1 n1.next = n2 n2.next = n1_nextnode else: p1.next = n2 n2.next = n1_nextnode p2.next = n1 n1.next = n2_nextnode return dummy.next
0c07b612e9035bfc892894fea34fd7e5fec3db76
flashfinisher7/ML_Fellowship
/Week3/LinearAlgebra/TransposeMatrix.py
373
3.578125
4
Y = [[5, 8, 1], [6, 7, 3], [4, 5, 9]] result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] def transpose_matrix(matrix): # iterate through rows for i in range(len(matrix)): # iterate through column for j in range(len(matrix[0])): result[j][i] = matrix[i][j] transpose_matrix(Y) for r in result: print(r)
8846477892e7061f7267987b2be94bbf6308f02d
DanielJHaar/Python_Practice_Jan2020
/Using the GeoJson API.py
1,031
4.03125
4
#Calling a JSON API #In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geojson.py. The program will prompt for #a location, contact a web service and retrieve JSON for the web service and parse that data, and retrieve the first place_id from the JSON. #A place ID is a textual identifier that uniquely identifies a place as within Google Maps. import urllib.request, urllib.parse, urllib.error import json #Test Value and Desired Variable serviceurl = 'http://py4e-data.dr-chuck.net/json?' address = input('Enter location: ') #Connecting to url url = serviceurl + urllib.parse.urlencode({'address': address, 'key': 42}) print('Retrieving', url) #Requesting data from URL and reading data data = urllib.request.urlopen(url).read() print('Retrieved', len(data), 'characers') #Loading data from UTF-8 into JSON format and identifying the piece to be selected jsdata = json.loads(data) place_id = jsdata["results"][0]["place_id"] print('Place ID: ',place_id)
eeab2c1bd5550fa7d770ffc21cb3d994a4cfbcb3
Jagepard/PyDesignPatterns-Iterator
/Iterator.py
320
3.71875
4
""" author : Jagepard <jagepard@yandex.ru> license https://mit-license.org/ MIT """ class Iterator: def __init__(self, bucket): self.bucket = bucket def iterateItems(self): for element in self.bucket: print(element.getName() + ' ' + str(element.getPrice()) + ' ' + element.getDescription())
f7f901fb917788b3db8c43220a8de0b5b9595b23
steveayers124/PythonStandardLibraryEssentialTraining
/Ex_Files_Python_Standard_Library_EssT/Exercise Files/Chapter 3/03_02/tempfiles_finished.py
884
3.875
4
# Working with temporary files import os import tempfile # get information about the temp data environment print('gettempdir():', tempfile.gettempdir()) print('gettempprefix():', tempfile.gettempprefix()) # create a temporary file using mkstemp() (tempfh, tempfp) = tempfile.mkstemp(".tmp", "testTemp", None, True) f = os.fdopen(tempfh, "w+t") f.write('This is some text data') f.seek(0) print(f.read()) f.close() os.remove(tempfp) # create a temp file using the TemporaryFile class with tempfile.TemporaryFile(mode="w+t") as tfp: tfp.write('This is some text data') tfp.seek(0) print(tfp.read()) # create a temporary directory using the TemporaryDirectory class with tempfile.TemporaryDirectory() as tdp: path = os.path.join(tdp, "tempfile.txt") tfp = open(path, "w+t") tfp.write("This is a temp file in temp dir") tfp.seek(0) print(tfp.read())
072332a854df97b20db81439060b80f70ad829a7
juanm707/SonomaStateCourseWork
/cs454/projtest/prob2/main.py
2,636
3.859375
4
import queue def main(): n = int(input("Enter a number between 1 and 99999 inclusive: ")) # user input while n < 1 or n > 99999: n = int(input("Must enter a number between 1 and 99999 inclusive: ")) # user input print("Enter the digits permitted, pressing enter after each one (ENTER -1 TO STOP): ") digit = 99 digits_allowed = [] while digit != -1: digit = int(input()) if (digit < 0 or digit > 9) and digit != -1: print("Must enter a digit from 0 through 9!") else: digits_allowed.append(digit) # user input del digits_allowed[-1] # remove the -1 digits_allowed = list(set(digits_allowed)) m = len(digits_allowed) # number of symbols final = [0 for _ in range(n)] # 0 is only accepting state final[0] = 1 label = [0 for _ in range(n)] parent = [0 for _ in range(n)] transition_table = [[-1 for _ in range(10)] for _ in range(n)] for i in range(n): for j in range(10): for k in range(len(digits_allowed)): if j != digits_allowed[k]: pass else: concat = str(i) + str(digits_allowed[k]) transition_table[i][j] = int(concat) % n # STEP 1 q = queue.Queue(0) found = False # STEP 2 visited = [0 for _ in range(n)] # STEP 3 q.put(0) # insert start state into q visited[0] = 1 # STEP 4 while not q.empty(): current = q.get() for k in range(m): _next = transition_table[current][digits_allowed[k]] if _next == -1: continue elif final[_next] == 1: label[_next] = digits_allowed[k] parent[_next] = current found = True break else: if visited[_next] == 0: parent[_next] = current visited[_next] = 1 label[_next] = digits_allowed[k] q.put(_next) if found: break print("Inputs: k = " + str(n) + ", Digits permitted: ", end='') digits_allowed.sort() print(digits_allowed, sep=", ") # STEP 5 if not found: print("Output: No solution") else: string = str(label[0]) current = parent[0] while current != 0: string += str(label[current]) current = parent[current] print("Output: ", end="") print(string[::-1]) if __name__ == "__main__": """ This is executed when run from the command line """ main()
b9e67c180bd93727a9ab7184e22045cfe21864e6
HectorIGH/Competitive-Programming
/Misc/A/05_Anton_and_polyhedrons.py
226
3.65625
4
from functools import reduce n = int(input()) elements = [input() for _ in range(n)] poly = {'Tetrahedron' : 4, 'Cube' : 6, 'Octahedron' : 8, 'Dodecahedron' : 12, 'Icosahedron' : 20} print(sum([poly[i] for i in elements]))
3268242ecd93e7967ff718aa4041e6f032c64a34
kr-MATAGI/coursera
/2-NLP_with_Probabilistic_Models/Week_1/Assignment/Autocorrect/process_data.py
1,086
3.578125
4
# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) # GRADED FUNCTION: process_data def process_data(file_name): """ Input: A file_name which is found in your current directory. You just have to read it in. Output: words: a list containing all the words in the corpus (text file you read) in lower case. """ words = [] # return this variable correctly ### START CODE HERE ### regex = re.compile("\w+") with open(file_name, 'r') as file: while True: line = file.readline() if not line: break line = str(line.strip()).replace('b\'', '').lower() line = regex.findall(line) for item in line: words.append(item) ### END CODE HERE ### return words #DO NOT MODIFY THIS CELL word_l = process_data('shakespeare.txt') vocab = set(word_l) # this will be your new vocabulary print(f"The first ten words in the text are: \n{word_l[0:10]}") print(f"There are {len(vocab)} unique words in the vocabulary.")
373497525c6a71b0aeeda477fa7b70038ca666c7
pvanh80/intro-to-programming
/round05/num_series.py
236
4.03125
4
def increasing_list(n): i=0 while i<=n : if i%2==0: print(i) i+=1 def decreasing_list(n): i=n while i>=0 : if i%2==0: print(i) i-=1 def main(): n=100 increasing_list(n) decreasing_list(n) main()
d8f87e071983c5d564f79090dc02463d483f08fe
n1k3c/pphs-aproksimacijabrojae
/cpu.py
301
3.828125
4
import numpy as np import time def factorial(n): if n==0: return 1 else: return n*factorial(n-1) n = int(input("Unesi broj iteracija: ")) c = np.zeros(n, dtype=np.float32) start=time.time() for x in range (0,n): c[x] = 1/factorial(x) result = sum(c) end=time.time() print(result, end-start)
1ac449a6745f8e6821a82f52206f090670f7b9f5
ShaneyMantri/Algorithms
/DP/Jump_Game_II.py
815
3.90625
4
""" Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. Example: Input: [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. """ ## TLE DP 91/92 import sys class Solution: def jump(self, nums: List[int]) -> int: n = len(nums) dp = [sys.maxsize]*n dp[0]=0 for i in range(n): jump = nums[i] j = i+1 while jump>0 and j<n: dp[j] = min(dp[j], dp[i]+1) jump-=1 j+=1 return dp[-1]
689735b4be8008b6a13616caaed02cf2c8ee64b0
sfujiwara/ProjectEuler
/Python/eulermath/prime.py
690
3.78125
4
# -*- coding: utf-8 -*- import numpy as np # import math # def sieve(n): # # 0-nが素数か否かのフラグ # is_prime = [True]*(n+1) # # 0, 1 は素数ではない # is_prime[0], is_prime[1] = False, False # for i in xrange(2, int(math.sqrt(n))+1): # if is_prime[i]: # for j in xrange(i*2, n+1, i): # is_prime[j] = False # return [i for i in xrange(n+1) if is_prime[i]] def sieve(n): is_prime = np.ones(n+1, dtype=bool) is_prime[0], is_prime[1] = False, False for i in xrange(2, int(np.sqrt(n)+1)): if is_prime[i]: is_prime[np.arange(i*2, n+1, i)] = False return np.where(is_prime)[0]
fb605e58820b955c6e045ed486899380b8908735
jonathanshuai/solid
/dependency_inversion_principle/exporter.py
2,430
3.859375
4
"""This Exporter class is to look at Dependency Inversion Principle. The dependency inversion principle says that a dependency should be on abstractions not concretions. A. High-level modules should not depend upon low-level modules. Both should depend upon abstractions. B. Abstractions should not depend on details. Details should depend upon abstractions. Here's an example to drive the point home: """ class FileSaver: def __init__(self, pdf_exporter): self.pdf_exporter = pdf_exporter def save_file(self): self.pdf_exporter.convert_to_pdf() self.pdf_exporter.pdf_export() print("Saving file...") class PDFExporter: def __init__(self): pass def convert_to_pdf(self): print("Converting to pdf...") def pdf_export(self): print("Exporting as pdf...") pdf_exporter = PDFExporter() file_saver = FileSaver(pdf_exporter) file_saver.save_file() print('-' * 15) # Here's an example of an FileSaver class which takes a PDFExporter. It then # depends on the low-level module and calls things like convert_to_pdf and pdf_export. # Instead of relying on that, we should abstract the process, and have the # lower level modules implement these abstractions. class FileSaver: def __init__(self, exporter): self.exporter = exporter def save_file(self): print("Saving file...") self.exporter.export() class Exporter: def __init__(self): pass def export(self): pass class PDFExporter(Exporter): def __init__(self): super(PDFExporter, self).__init__() def convert_to_pdf(self): print("Converting to pdf...") def export(self): self.convert_to_pdf() print("Exporting as pdf...") class CSVExporter(Exporter): def __init__(self): super(CSVExporter, self).__init__() def export(self): print("Exporting as csv...") pdf_exporter = PDFExporter() file_saver = FileSaver(pdf_exporter) file_saver.save_file() csv_exporter = CSVExporter() file_saver = FileSaver(csv_exporter) file_saver.save_file() # Now, we can see that instead of FileSaver having to know about the details of different # export methods, we can abstract them as an Exporter and implement them separately. # Our high level FileSaver no longer has to think about how these exports are going to be # implemented, and we've successfully moved dependencies out.
6527175d9ebeee04819df86121e3c0d1c2c66e32
ZeeshanJ99/Deloitte-Python
/handling_files/lambda_larks.py
1,429
4.34375
4
# Lambda functions # def add(n1, n2): # return n1 + n2 # # # print(add(2, 4)) # # add = lambda n1, n2: n1 + n2 # print(add(2, 4)) # anonymous function - when you dont # want to write a full function out # Map - takes in a function, map needs a function and an iterable # def double_add_one(n): # return (n * 2) + 1 # nums = [1, 2, 3, 4, 5] # new_nums = list(map(double_add_one, nums)) # print(list(new_nums)) # # new_nums = list(map(lambda n: (n * 2) + 1, nums)) # print(new_nums) savings = [234.00, 555.00, 674.00, 78.00] # savings = each saving plus 10% # implement this using map and a lambda function new_savings = list(map(lambda s: (s * 1.1), savings)) print(new_savings) # Filter - keeps the ones that are true def is_even(n): return n % 2 == 0 print(list(filter(is_even, nums))) # write the above using a lambda function print(list(filter(lambda x: x % 2 == 0, nums))) print(list(filter(lambda y: y > 200, filter( lambda x: x % 2 == 0, range(210) )))) # if its simple enough to express in # 1 line of code use a lambda # AND NOW FOR SOMETHING COMPLETELY DIFFERENT # List Comprehension - flattened for loop, # does similar to lambda savings = [234.00, 555.00, 674.00, 78.00] bonus = [x + x/10 for x in savings] print(bonus) large_savings = [x for x in savings if x > 500] print(large_savings) large_savings_bonus = [x + x/10 for x in savings if x > 500] print(large_savings_bonus)
85392c65fbc51f26d59af60bea16e9e893dd934b
tucksa/PythonPractice
/decorators.py
1,691
4.9375
5
#decorators => allows you to tack on extra functionality to an already existing function #example layout: # @some_decorator # def simple_func(): # do suff # return something #In python, you can return a function from a function and save it to a variable def say_hello(): print('you are running the hello func') def greet(): print('It is nice to meet you!') return greet #now you can save greet as a variable greetings and call it anywhere greetings = say_hello() greetings() #this returns the 'it is nice to meet you' phrase from running the greet function within say_hello #you can also pass a funtion into another function as an argument def hello_world(): print('Hello World!') def other(some_func): print('Here is the work of my other function') print(some_func()) other(hello_world) #this prints out the initial print statement in other func and the print statement in the argument func 'hello_world' #Using this we can create a decorator def new_decorator(original_func): #think of this as wrapping your original code in other coder def wrap_func(): print('Some extra code before the original function') original_func() print('Some extra code after the original function') return wrap_func def func_needs_decorator(): print('I want to be decorated') decorated_func = new_decorator(func_needs_decorator) decorated_func() #instead of all that though you can just use the @ @new_decorator def func_needs_decorator(): print('I want to be decorated') func_needs_decorator() #this returns the same thing as decorated_func() #it allows you to easily turn off or on these added decorations
e42e54440aabc273f838c9e0ae2c0b3a95dd5dda
wreyesus/Learning-to-Code
/python/python_crash_course/chapter_11/test_cities.py
502
3.796875
4
import unittest from city_functions import some_place class NameCityCountry(unittest.TestCase): def test_city_country(self): """ Do we receive 'Lima, Peru' as output """ nice_name = some_place('lima', 'peru') self.assertEqual(nice_name, 'Lima, Peru') def test_population(self): """ Do we receive population as output? """ nice_name = some_place('lima', 'peru', 1000000) self.assertEqual(nice_name, 'Lima, Peru - population 1000000') unittest.main()
39f79b30cf6cf07669266e7f48d3903b6a08aafb
jrmartinez96/operaciones_aritmetica_compis
/methods/tokenization.py
356
3.984375
4
def tokenization(operation): i = 0 characters = [""] for character in operation: try: float(characters[i] + character) characters[i] = characters[i] + character except: characters.append(character) characters.append("") i = len(characters) - 1 return characters
d5d57fbe91e557a47fb063b630a306b280ac358b
shreyash05/python_programs
/Touple.py
372
3.75
4
def main(): arr = (11,21,23.5,"Hello") print(type(arr)) for i in range(len(arr)): print(arr[i]) #arr[0] = 12 #NA arr = (10,20,30,) print("Type of arr is",type(arr)) brr = (10) #it considered as integer without "," print("Type of brr is",type(brr)) crr = (10,) print("Type of crr is",type(crr)) if __name__ == '__main__': main()
f1061c3c5291e147946b3640b3c7f012cae2075a
rafalpa/test
/two_fer.py
191
3.609375
4
def two_fer(name="you"): # return "One for {}, one for me.".format(name) if name == "Alice": return f"One for Alice, one for me." else: return f"One for {name!!!"
96224657f0586a6410d144fb10154cd2988b47ec
Olaolutosin/phythosin
/Exercises/Line.py
943
4.34375
4
from __future__ import print_function # to make sure that the print statement works with both Python 2 and 3. """ Class to represents a line (y = ax + b) that passes two points. """ class Line: def __init__(self, p1, p2): self.p1, self.p2 = p1, p2 x1, y1 = p1 x2, y2 = p2 if x2 != x1: self.a = (y2 - y1) / float(x2 - x1) self.b = y1 - self.a * x1 else: raise Exception('Vertical line x = %s' % x1) def y(self, x): a, b = self.a, self.b return a * x + b # or use __call__ method to make the class callable def __call__(self, x): a, b = self.a, self.b return a * x + b # test it if __name__ == "__main__": line = Line((0, 0), (10, 10)) x = 5 print("The value of y at x=%s is %s: " % (x, line.y(x))) # use y method print("The value of y at x=%s is %s: " % (x, line(x))) # use __call__ method
2d77c227ed3d28262a10733d6e2019f25d6f61ef
mariiamatvienko/python-homework
/laboratory2/lab2.2task.py
359
3.859375
4
'''з'ясувати, чи існує цифра 2 у введеному числі''' import re def int_validator(message): n = input(message) while not bool(re.match(r'^\d+$', n)): n = input(message) return str(n) n = int_validator("enter digit: ") if "2" in n: print("number 2 exists") else: print("number 2 does not exist")
eb9b85e9e4a7808ef1a8b990dd5c86f9b20fcda6
mrfox321/leetcode
/leetcode/p97.py
801
3.546875
4
class TreeNode(): def __init__(self,x): self.val = x self.right = None self.left = None def genBST(nums): if len(nums) == 1: x = TreeNode(nums[0]) return [x] if len(nums) == 0: return [None] listoftrees = [] for num in nums: left = [x for x in nums if x < num] right = [x for x in nums if x > num] leftdummy = genBST(left) rightdummy = genBST(right) print len(leftdummy),len(rightdummy),left,right for lefty in leftdummy: for righty in rightdummy: rootdummy = TreeNode(num) rootdummy.left = lefty rootdummy.right = righty listoftrees.append(rootdummy) print len(listoftrees) return listoftrees
060be937dbf0e5d75448cf84f7304f8dd0789f45
Jacquesvdberg92/SoloLearn-Python-3-Tutorial
/04. Exeptions & Files/02. Exception Handling/Exception Handling/Exception_Handling.py
1,438
4.65625
5
# Exception Handling # To handle exceptions, and to call code when an exception occurs, you can use a try/except statement. # The try block contains code that might throw an exception. # If that exception occurs, the code in the try block stops being executed, and the code in the except block is run. # If no error occurs, the code in the except block doesn't run. # For example: try: num1 = 7 num2 = 0 print (num1 / num2) print("Done calculation") except ZeroDivisionError: print("An error occurred") print("due to zero division") #An error occurred #due to zero division # In the code above, the except statement defines the type of exception to handle (in our case, the ZeroDivisionError). # A try statement can have multiple different except blocks to handle different exceptions. # Multiple exceptions can also be put into a single except block using parentheses, # to have the except block handle all of them. try: variable = 10 print(variable + "hello") print(variable / 2) except ZeroDivisionError: print("Divided by zero") except (ValueError, TypeError): print("Error occurred") #Error occurred # An except statement without any exception specified will catch all errors. # These should be used sparingly, as they can catch unexpected errors and hide programming mistakes. # For example: try: word = "spam" print(word / 0) except: print("An error occurred") #An error occurred