blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
4afad10bff966b08e4f0aab782049901a3fb66dc
BalintNagy/GitForPython
/Checkio/01_Elementary/checkio_elementary_11_Even_the_last.py
1,261
4.21875
4
"""\ Even the last You are given an array of integers. You should find the sum of the elements with even indexes (0th, 2nd, 4th...) then multiply this summed number and the final element of the array together. Don't forget that the first element has an index of 0. For an empty array, the result will always be 0 (zero). Input: A list of integers. Output: The number as an integer. Example: checkio([0, 1, 2, 3, 4, 5]) == 30 checkio([1, 3, 5]) == 30 checkio([6]) == 36 checkio([]) == 0 How it is used: Indexes and slices are important elements of coding. This will come in handy down the road! Precondition: 0 ≤ len(array) ≤ 20 all(isinstance(x, int) for x in array) all(-100 < x < 100 for x in array) """ def checkio(array): """ sums even-indexes elements and multiply at the last """ index = 0 sumofevens = 0 try: for i in array: if index%2 == 0: sumofevens += i index += 1 return sumofevens * array[len(array)-1] except IndexError: return 0 print(checkio([0, 1, 2, 3, 4, 5])) print(checkio([1, 3, 5])) print(checkio([6])) print(checkio([]))
92067b660f1df00f7d622b49388994c892145033
BalintNagy/GitForPython
/OOP_basics_1/01_Circle.py
572
4.125
4
# Green Fox OOP Basics 1 - 1. feladat # Create a `Circle` class that takes it's radius as cinstructor parameter # It should have a `get_circumference` method that returns it's circumference # It should have a `get_area` method that returns it's area import math class Circle: def __init__(self, radius): self.radius = radius def get_circumference(self): return 2 * self.radius * math.pi def get_area(self): return pow(self.radius, 2) * math.pi karika = Circle(5) print(karika.get_circumference()) print(karika.get_area())
301046cea95790013af1c2bf157aeb0b35423256
BalintNagy/GitForPython
/Checkio/01_Elementary/checkio_elementary_01_Say_hi.py
802
4.03125
4
"""\ 1. Say hi In this mission you should write a function that introduce a person with a given parameters in attributes. Input: Two arguments. String and positive integer. Output: String. Example: say_hi("Alex", 32) == "Hi. My name is Alex and I'm 32 years old" say_hi("Frank", 68) == "Hi. My name is Frank and I'm 68 years old" """ def say_hi(name, age): """ Hi! """ # 3.5 ota a literal string interpolation a javasolt, rengeteg dologra jó, ebben az esetben pl nem kellene castolgatni külön az integert # >>> value = 4 * 20 # >>> f'The value is {value}.' # 'The value is 80.' return "Hi. My name is " + name + " and I'm " + str(age) + " years old" szoveg = say_hi("Frank", 68) print(szoveg)
3b33c74b4f0f669da47500eeda6d9f734fb07371
BalintNagy/GitForPython
/FileIO/crypto_4encoded.py
820
3.75
4
# Create a method that decrypts texts/encoded_zen_lines.txt # Write the file's content into a new file with a name of # "decryt4_[the current timestamp]" where the timestamp format shoud be 'hhmmss' def crypto_4encoded(file_name): import datetime, string f = open(file_name, 'r') f2 = open('texts/decrypt4_' + datetime.datetime.now().strftime('%H%M%S') + '.txt', 'w') for raw_row in f.readlines(): decrypted_row = [] for raw_word in raw_row.split(): decrypted_word = '' for i in raw_word: decrypted_word += sorted(string.printable)[sorted(string.printable).index(i) - 1] decrypted_row.append(decrypted_word) f2.write(' '.join(decrypted_row) + '\n') f2.close() f.close() crypto_4encoded('texts/encoded_zen_lines.txt')
7852ff2dfef25e356a65c527e94ee88d10c74a0b
BalintNagy/GitForPython
/Checkio/01_Elementary/checkio_elementary_16_Digits_multiplication.py
929
4.40625
4
"""\ Digits Multiplication You are given a positive integer. Your function should calculate the product of the digits excluding any zeroes. For example: The number given is 123405. The result will be 1*2*3*4*5=120 (don't forget to exclude zeroes). Input: A positive integer. Output: The product of the digits as an integer. Example: checkio(123405) == 120 checkio(999) == 729 checkio(1000) == 1 checkio(1111) == 1 How it is used: This task can teach you how to solve a problem with simple data type conversion. Precondition: 0 < number < 10^6 """ def checkio(number: int) -> int: numberlist = list(str(number)) product = 1 for i in numberlist: if int(i) != 0: product = product * int(i) return product print(checkio(123405)) print(checkio(999)) print(checkio(1000)) print(checkio(1111)) # szép, könnyen olvasható
285b869b5b961c2722caf04449494a2e618c3a94
r21gh/knapsack-problem
/knapsack.py
584
3.828125
4
# Reza Ghanbari # Advanced algorithm course # Knapsack problem using dynamic programming # Compatibiltiy with python 2 and 3 def knapSack(W, wt, val, n): K = [[0 for x in range(W+1)] for x in range(n+1)] for i in range(n+1): for w in range(W+1): if i==0 or w==0: K[i][w] = 0 elif wt[i-1] <= w: K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]) else: K[i][w] = K[i-1][w] return K[n][W] val = [20, 30, 40] wt = [5, 10, 30] W = 30 n = len(val) print(knapSack(W , wt , val , n))
3546d609dc4bf6c769a437d8879c2c2d66fd3873
marcelofilhogit/URI
/1007.py
209
3.578125
4
def diferenca(): num1 = int(input()) num2 = int(input()) num3 = int(input()) num4 = int(input()) diferenca = (num1 * num2) - (num3 * num4) print("DIFERENCA =",diferenca) diferenca()
2b43c7e421a09ffa58dc89db962958161e9fe679
brianmego/project_euler
/python/4.py
550
4
4
#!/usr/bin/env python LARGEST = 999 SMALLEST = 100 def is_palindrome(i): return str(i) == str(i)[::-1] def has_three_digit_factors(i): for j in range(LARGEST, SMALLEST - 1, -1): if i % j == 0: quotient = i / j if SMALLEST <= quotient <= LARGEST: return True return False def main(): for i in range(LARGEST**2, SMALLEST, -1): if is_palindrome(i): if has_three_digit_factors(i): print(i) break if __name__ == '__main__': main()
ae11fe032a6e96a1914af1e66b753bd3e7721be1
ferseg/ia-1-2015
/src/regex/DataFile.py
611
3.75
4
import re def open_file(): file = open("input.txt","r"); return file; def read_file(file): data_file = file.read(); return data_file; #get all matches of the re in data def get_babylon_tower(data): babylon_tower = re.findall(r"\b(F[1-4])(=)([POGYH],[POGYH],[POGYH],[POGYH])((,)([POGYH]))?\b",data); return babylon_tower; #print all the matches of the babylon_tower format def get_babylon_tower_rows(babylon_tower): for row in babylon_tower: print(row) def test(): get_babylon_tower_rows(get_babylon_tower(read_file(open_file()))); test();
805d278e385be0aec5a6160f0e5127bd0b5cb224
untbr/game_programming
/materials/state.py
4,464
3.828125
4
""" 主要な状態における処理をまとめたモジュール インスタンス作成後、順次メソッドを呼び出すことにより処理を行っていく """ import itertools import sys import typing from enum import Enum from typing import NamedTuple import pygame from pygame.locals import * # 定数読み込み class States(Enum): """状態の定義""" TITLE = 0 # タイトル画面 USER = 1 # ユーザー名入力画面 TYPE = 2 # ゲームモードタイプ選択画面 MODE = 3 # ゲームモード選択画面 PLAY = 4 # プレイ画面 RESULT = 5 # 結果画面 class TupleState(NamedTuple): """Statesと選択肢の数を格納するタプルの定義""" name: Enum # States number_of_choices: int # 選択肢の数 class State: """状態遷移を管理するクラス""" def __init__(self) -> None: self.is_running = False # 状態遷移の有無によって画面の更新をするかどうかに使う self.state = None # TupleStatesを格納する変数 self.states = [ TupleState(States.TITLE, 2), TupleState(States.USER, 0), TupleState(States.TYPE, 2), TupleState(States.MODE, 3), TupleState(States.PLAY, 0), TupleState(States.RESULT, 0), ] # 選択肢が1つ以上あるStatesのリスト self.has_choices_state = [ i.name for i in self.states if i.number_of_choices != 0 ] self.iter_states = itertools.cycle(self.states) # 無限ループのイテレータの生成 self.transition() # 状態遷移してself.stateをTITLEにする def transition(self) -> None: """実際に状態遷移をするメソッド""" self.state = next(self.iter_states) # 次の状態に遷移する self.selector = SelectorFocus(self.state.number_of_choices) self.is_running = False # 再描画の必要を知らせる def event(self) -> None: """キーダウンに応じた状態の遷移を管理するメソッド""" for event in pygame.event.get(): if event.type == QUIT: # 閉じるボタン押下 pygame.quit() # Pygame終了(ウィンドウを閉じる) sys.exit(0) # 処理終了 elif ( event.type == KEYDOWN and event.key == K_RETURN or event.type == USEREVENT ): if self.state.name == States.TITLE and self.selector.position == 1: pygame.event.post(pygame.event.Event(QUIT)) continue self.transition() # 次に遷移する # 選択画面の矢印キー操作 elif event.type == KEYDOWN and self.state.name in self.has_choices_state: if event.key in self.selector.call_trigger.keys(): self.selector.call_trigger[event.key]() self.is_running = False class SelectorFocus: """ ゲームタイプや難易度の選択で、上下の矢印キーを押下した際に 選択肢をフォーカスする位置を決めるためのクラス """ def __init__(self, length_of_list: int): """選択肢の数をもらう""" self.length_of_list = length_of_list - 1 self.__focus_pos = 0 # 最初は0番目をフォーカスする # 呼び出し条件のキーとオブジェクトIDの辞書 self.call_trigger = {K_DOWN: self.down, K_UP: self.up} def down(self) -> int: """ 下矢印が押されたときに呼ばれるメソッド 選択肢の数よりself.focus_posが大きくならないように制御する """ if self.__focus_pos < self.length_of_list: self.__focus_pos += 1 return self.__focus_pos def up(self) -> int: """ 上矢印が押されたときに呼ばれるメソッド self.focus_posが0より小さくならないように制御する """ if self.__focus_pos > 0: self.__focus_pos -= 1 return self.__focus_pos @property def position(self) -> int: """フォーカスするべき位置を返すプロパティ""" return self.__focus_pos
8b2be7d66fae92613138f2071fee3164b88812ff
Dimitrov-M/landTree
/landTree.py
4,498
3.515625
4
#!/usr/bin/python import argparse class Node(): def __init__(self, id, name, parent_id=None, parent=None, is_root=False): self.id = id self.name = name self.parent_id = parent_id self.parent = parent self.children = [] self.land = [] self.is_root = is_root def __str__(self): return 'Node: {}'.format(self.id) def __repr__(self): return 'Node: {}'.format(self.id) def get_descendants(self): descendants = [] for child in self.children: descendants.append(child) descendants.extend(child.get_descendants()) return descendants def get_root(self): if not self.is_root: return self.parent.get_root() else: return self def get_level(self, level=0): if not self.is_root: level += 1 return self.parent.get_level(level) else: return level def get_all_land(self): descendants_land = self.land for node in self.get_descendants(): descendants_land.extend(node.land) return descendants_land def print_node(self): return self.get_level()*' | ' + '{}; {}; owner of {} land parcels'.format( self.id, self.name, len(self.get_all_land()) ) def print_tree(self, mode='full_tree', nodes_to_print=[]): if mode == 'full_tree': current_node = '' if self.get_root().id == self.id: current_node = ' ***' print(self.get_root().print_node() + current_node) for node in self.get_root().get_descendants(): if node.id == self.id: current_node = ' ***' else: current_node = '' print(node.print_node() + current_node) elif mode == 'expand': print(self.print_node() + ' ***') for node in self.get_descendants(): if node.id == self.id: current_node = ' ***' else: current_node = '' print(node.print_node() + current_node) elif mode == 'from_root': if not self.is_root: nodes_to_print.append(self) return self.parent.print_tree(mode, nodes_to_print) else: print(self.get_root().print_node()) nodes_to_print.reverse() for node in nodes_to_print: if node == nodes_to_print[-1]: print(node.print_node() + ' ***') else: print(node.print_node()) def main(): nodes = {} parser = argparse.ArgumentParser() parser.add_argument('company_id', type=str, help='id of company to find lands') parser.add_argument('-m', '--mode', type=str, choices=['full_tree', 'from_root', 'expand'], default='full_tree', help='land tree parsing mode') args = parser.parse_args() company_id = args.company_id mode = args.mode with open("./company_relations.csv") as csv: next(csv) # header for line in csv: id, name, parentId = line.strip().split(",") if parentId == '': nodes[id] = Node(id, name, is_root=True) else: nodes[id] = Node(id, name, parentId) # Refactoring this loop resulted in runtime improvement of more than a second for node_id in nodes: try: nodes[node_id].parent = nodes[nodes[node_id].parent_id] nodes[nodes[node_id].parent_id].children.append(nodes[node_id]) except KeyError: pass with open("./land_ownership.csv") as csv: next(csv) # header for line in csv: landId, companyId = line.strip().split(",") nodes[companyId].land.append(landId) print('--------------------') print('Company ID -', company_id) print('Tree parsing mode -', mode) print('--------------------') valid, message = validate(company_id, nodes) if not valid: print('***') print(message) print('***') else: nodes[company_id].print_tree(mode) def validate(company_id, nodes): if not nodes.get(company_id, False): return False, 'There is no information for the selected company' return True, '' if __name__ == "__main__": main()
12f12b5e598d78e83c01f3c59aae0e131df6a59a
MegaYEye/Cambridge_Coursework
/NLP/Analysis.py
2,261
3.578125
4
import math,sys class Evaluation(): """ general evaluation class implemented by classifiers """ def crossValidate(self,corpus,i): """ function to perform 10-fold cross-validation for a classifier. each classifier will be inheriting from the evaluation class so you will have access to the classifier's train and test functions. 1. read reviews from corpus.folds and store 9 folds in train_files and 1 in test_files 2. pass data to self.train and self.test e.g., self.train(train_files) 3. repeat for another 9 runs making sure to test on a different fold each time @param corpus: corpus of movie reviews @type corpus: MovieReviewCorpus object """ # reset predictions self.predictions=[] # TODO Q3 folds = corpus.folds indexes = range(10) if i == 0: x = indexes else: y = indexes[i:] z = indexes[0:i] x = y + z self.train(folds[x[0]]+folds[x[1]]+folds[x[2]]+folds[x[3]]+folds[x[4]]+folds[x[5]]+folds[x[6]]+folds[x[7]]+folds[x[8]]) self.test(folds[x[9]]) def getStdDeviation(self): """ get standard deviation across folds in cross-validation. """ # get the avg accuracy and initialize square deviations avgAccuracy,square_deviations=self.getAccuracy(),0 # find the number of instances in each fold fold_size=len(self.predictions)/10 # calculate the sum of the square deviations from mean for fold in range(0,len(self.predictions),fold_size): square_deviations+=(self.predictions[fold:fold+fold_size].count("+")/float(fold_size) - avgAccuracy)**2 # std deviation is the square root of the variance (mean of square deviations) return math.sqrt(square_deviations/10.0) def getAccuracy(self): """ get accuracy of classifier. @return: float containing percentage correct """ # note: data set is balanced so just taking number of correctly classified over total # "+" = correctly classified and "-" = error return self.predictions.count("+")/float(len(self.predictions))
c62db966daf446d63bd9d19206c0719295b3f714
mura-wx/mura-wx
/python/latihan pyhton/membuatfile.py
1,604
3.828125
4
# # cara membuat file pada python # # untuk mencegah error kita biasakan menggunakan try except # # membuat dan mengisi file # try : # sebuah_file = open("absen.txt", 'w') # print ("nama file yang telah di buat".ljust(30),":", sebuah_file.name) # print("mode pembacaan".ljust(30),":", sebuah_file.mode) # print("apakah file sudah di tutup".ljust(30),":", sebuah_file.closed) # sebuah_file.write("1. Muhamad Rafli\n") # sebuah_file.write("2. bagus sanjaya\n") # sebuah_file.write("3. ahmad solihin\n") # except IOError : # print("proses gagal", IOError) # # membaca file # try : # sebuah_file = open("absen.txt", 'r') # print ("isi dari file :\n" + sebuah_file.read()) # print ("posisi pointer pada file".ljust(30),":", sebuah_file.tell()) # print("posisi pointer berubah ke awal".ljust(30),":", sebuah_file.seek(0,0)) # except IOError : # print("gagal membaca file") # # # membaca file baris per baris # # try : # # sebuah_file = open("absen.txt", 'r') # # print ("\nmembaca file baris per baris\n") # # for line in sebuah_file : # # print (line) # # sebuah_file.close() # # print("apakah file sudah di tutup".ljust(30),":", sebuah_file.closed) # except IOError : # print("gagal membaca file") # print("\nmengganti nama file\n") import os # os.rename('absen.txt', 'daftar_hadir') # untuk merubah nama dari sebuah file # os.mkdir("direktori baru") # untuk membuat direktori # print(os.getcwd()) #untuk mengecek direktori saat ini # os.rmdir("direktori baru")
65879b26b356882b641c2c48a9a77c5244bc3d60
mura-wx/mura-wx
/python/latihan pyhton/mengambil input user.py
290
3.84375
4
# cara mengambil imput user # data yang di masukan akan bertipe str data = input("masukan data:") print (data, ",type", type(data)) # data yang di masukan akan bertipe int jika di masukan nilai int data_int = int(input("masukan data:")) print (data_int, ",type", type(data_int))
d5353aa98262d9de8b540c9ae863bde41ab0cda9
mura-wx/mura-wx
/python/Practice Program/basic program/chekPositifAndNegatif.py
306
4.15625
4
try : number=int(input("Enter Number : ")) if number < 0: print("The entered number is negatif") elif number > 0: print("The entered number is positif") if number == 0: print("number is Zero") except ValueError : print('The input is not a number !')
514087b467c86fedd4a91f571f641bb627cca40e
mura-wx/mura-wx
/python/Practice Program/basic program/PythonPrograToAddTwoNumbers.py
78
3.578125
4
x = 15 y = 10 sum = x + y print("sum {0} and {1} is {2}".format(x,y,sum))
19c053e08eda876c8a587fd372a87ba470767646
Mariamapa/EDAI
/Examen/semaforo.py
1,395
3.546875
4
#Medidor de covid #Limpiar pantalla import os os.system("cls") #Libreria que nos servira para leer datos desde una base de datos import pandas as pd import numpy as np #Limpiamos pantalla #Modulo que permite imprimir el texto en colores from colorama import Fore, Back, Style, init init() print("\n\t\t\t\tBienvenido al indicador de covid \n\n\n\n") #Función que leera la base de datos df = pd.read_csv('bd.csv') #Definición de variables inf=[(df['Indicador']<0.8),(df['Indicador']>=0.8)] res=['Negativo','Positivo'] df['Resultado']=np.select(inf,res) inf=len(df[df['Resultado']=='Positivo']) #Nos dara el numero de infectados y el color del semaforo if inf==0: print(Fore.GREEN + "El semaforo esta en verde, no hay infectados ") elif inf>=1 and inf<=30: print("El número de infectados es",inf) print(Fore.YELLOW + "El semaforo esta en amarillo, Tome sus precauciones ") elif inf>=31 and inf<=70 : print("El número de infectados es",inf) print(Back.WHITE+ Fore.RED + Style.BRIGHT + "El semaforo esta en naranja, siga las medidad de sanidad "+ Back.RESET) elif inf>=71 and inf<=100: print("El número de infectados es",inf) print(Fore.RED + "El semaforo se encuentra en rojo, QUEDESE EN CASA ") #Promedio de los infectados print("\nEl promedio de edad de personas infectadas",df['Edad'].mean().round(0),"años.")
eb2522f1e9b0a999086d2adc360d408db588d6b0
dgallab/exercises_in_python
/python-based interpreter/error.py
541
3.515625
4
#Daniel Gallab #CPSC 326-02 #Assignment 2 #when an error is found in the lexer, #this class is called, and a message #describing the error is printed class Error(Exception): def __init__ (self, message, line, column): #message should specify error self.message = message self.line = line self.column = column def __str__(self): #prints error s = '' s += 'error:' + self.message s += 'at line' + str(self.line) s += 'column' + str(self.column) return s
b45e6f6b1e8bb428e0e3fd5b6985687e64812a1c
Alihussain-khan/HangMan-Game-Python
/hangman game.py
2,638
4.1875
4
import random def get_word(): words= [ 'Woodstock', 'Gray', 'Hello', 'Gopher', 'Spikepike', 'green', 'blue', 'Willy', 'Rex', 'yes', 'Roo', 'Littlefoot', 'Baagheera', 'Remy', 'good', 'Kaa', 'Rudolph', 'Banzai', 'Courage', 'Nemo', 'Nala', 'other', 'Sebastin', 'lago', 'head', 'car', 'Dory', 'Pumbaa', 'Garfield', 'Manny', 'bubble', 'ball', 'Flik', 'Marty', 'Gloria', 'Donkey', 'Timon', 'Baloo', 'Thumper', 'Bambi', 'Goofy', 'Tom', 'Sylvester', 'Jerry', 'Tiger'] return random.choice(words).upper() def Check(word,guesses,guess): guess=guess.upper() status='' i=0 matches = 0 for letter in word: if letter in guesses: status += letter else: status += '*' if letter == guess: matches += 1 if matches > 1: print ('yes! The word contains', matches, '"'+guess + '"' + 's') elif matches == 1: print ('Yes! The word containes the letter"'+ guess + '"') else: print('Sorry. the word does not cpontain the letter " '+ guess + '"') return status def main(): word = get_word() guesses=[] guessed = False print ('The word contains',len(word) ,'letters.') while not guessed: text= 'please enter one letter or whole word ' guess = input(text) guess = guess.upper() if(len(guesses)>=8): print("GAME OVER") break; if guess in guesses: print ('you already guessed"' + guess + '"') elif len(guess) == len(word): guesses.append(guess) if guess == word: guessed = True else: print('Sorry, thst is incorrect') elif len(guess) == 1: guesses.append(guess) result = Check(word,guesses,guess) if result == word: guessed = True else: print (result) else: print('invalid entry') print ('The word is', word + '! you took ',len(guesses),'tries.') main()
22f7069e46536953bbb80f19c882623c4bb6540c
mnahuelanca/pythonBasico
/tablaMultiplicar10.py
1,449
3.96875
4
menu = """ Bienvenido, seleccione la tabla de multiplicar que necesita ✔ 2 3 4 5 6 7 8 9 10 """ opcion = input(menu) if opcion =="2": for i2 in range(1, 11): resultado2 = 2*i2 print("2 x " + str(i2) + " es igual a: " + str(resultado2)) elif opcion =="3": for i3 in range(1, 11): resultado3 = 3*i3 print("3 x " + str(i3) + " es igual a: " + str(resultado3)) elif opcion =="4": for i4 in range(1, 11): resultado4 = 4*i4 print("4 x " + str(i4) + " es igual a: " + str(resultado4)) elif opcion =="5": for i5 in range(1, 11): resultado5 = 5*i5 print("5 x " + str(i5) + " es igual a: " + str(resultado5)) elif opcion =="6": for i6 in range(1, 11): resultado6 = 6*i6 print("6 x " + str(i6) + " es igual a: " + str(resultado6)) elif opcion =="7": for i7 in range(1, 11): resultado7 = 7*i7 print("7 x " + str(i7) + " es igual a: " + str(resultado7)) elif opcion =="8": for i8 in range(1, 11): resultado8 = 8*i8 print("8 x " + str(i8) + " es igual a: " + str(resultado8)) elif opcion =="9": for i9 in range(1, 11): resultado9 = 9*i9 print("9 x " + str(i9) + " es igual a: " + str(resultado9)) elif opcion =="10": for i10 in range(1, 11): resultado10 = 10*i10 print("10 x " + str(i10) + " es igual a: " + str(resultado10)) else: print("Elige una opcion correcta")
75dee3e2c6cc5d618a01fec6769cca8ddb497758
sobostion/sudoku-solver
/hard.py
7,238
3.609375
4
#!/usr/bin/python # sudoku solver from prettytable import * # initialise sudoku puzzle rows = {} rows[0] = [9, 1, None, 3, None, None, None, None, 2] rows[1] = [None, None, None, 8, None, None, 4, None, None] rows[2] = [None, None, 4, None, 7, None, None, None, None] rows[3] = [None, None, 6, None, None, 3, None, None, None] rows[4] = [3, None, 8, 4, None, 5, 2, None, 6] rows[5] = [None, None, None, 2, None, None, 5, None, None] rows[6] = [None, None, None, None, 9, None, 7, None, None] rows[7] = [None, None, 5, None, None, 8, None, None, None] rows[8] = [1, None, None, None, None, 2, None, 6, 4] # need a way of getting columns def getColumns(): columns = {} for k in range(0, 9): columns[k] = [] for i in range(0, 9): for j in range(0, 9): columns[i].append(rows[j][i]) return columns columns = getColumns() # need a way of getting blocks def getBlocks(): # initialise blocks dictionary blocks = {} for i in range(0, 9): blocks[i] = [] for k in [0, 3, 6]: j = 0 for i in [0, 3, 6]: blocks[k + j] += rows[k][i:i + 3] + \ rows[k + 1][i:i + 3] + rows[k + 2][i:i + 3] j = j + 1 return blocks blocks = getBlocks() # now for actually solving the puzzle # check which numbers we need to find in a row def findMissingRowIndexes(row_num): absent_index = [] count = 0 for item in rows[row_num]: if item == None: absent_index.append(count) count += 1 return absent_index def possibleNumsRow(row_num): absent_nums = [] possible_nums = {} # find absent numbers in row for number in range(1, 10): if number not in rows[row_num]: absent_nums.append(number) # get indexes of absent numbers absent_index = findMissingRowIndexes(row_num) blocks = getBlocks() # reset blocks for missingIndex in absent_index: # find which block the number is in if row_num < 3: # first three blocks if missingIndex < 3: possible_nums[missingIndex] = [ x for x in absent_nums if x not in blocks[0]] elif missingIndex < 6: possible_nums[missingIndex] = [ x for x in absent_nums if x not in blocks[1]] elif missingIndex < 9: possible_nums[missingIndex] = [ x for x in absent_nums if x not in blocks[2]] elif row_num < 6: # second row of blocks if missingIndex < 3: possible_nums[missingIndex] = [ x for x in absent_nums if x not in blocks[3]] elif missingIndex < 6: possible_nums[missingIndex] = [ x for x in absent_nums if x not in blocks[4]] elif missingIndex < 9: possible_nums[missingIndex] = [ x for x in absent_nums if x not in blocks[5]] elif row_num < 9: # third row of blocks if missingIndex < 3: possible_nums[missingIndex] = [ x for x in absent_nums if x not in blocks[6]] elif missingIndex < 6: possible_nums[missingIndex] = [ x for x in absent_nums if x not in blocks[7]] elif missingIndex < 9: possible_nums[missingIndex] = [ x for x in absent_nums if x not in blocks[8]] # at this point we have possible numbers when taking into account blocks # now we need to take columns into account # each key of the possible_nums dictionary is a column nunber # we can remove any values that already exist in that column columns = getColumns() # reset columns for when function is used again for column, possibles in possible_nums.items(): possible_nums[column] = [ x for x in possibles if x not in columns[column]] return possible_nums def blockIndex2Row(block, index): row_num = 0 # reset for i in [0, 3, 6]: if block in [i, i + 1, i + 2]: for j in [0, 3, 6]: if index in [j, j + 1, j + 2]: return row_num # we have found the row else: row_num += 1 # not this row, try next row else: row_num += 3 def enterAnswer(): # enter values into rows # if only 1 possible in row, fill in for row in range(0, 9): for column, possibles in possibleNumsRow(row).items(): if len(possibles) == 1: rows[row][column] = possibles[0] # fill in columns with only one left columns = getColumns() for column in range(0, 9): if columns[column].count(None) == 1: index = columns[column].index(None) # also the row number absent_num = [x for x in range(1, 10) if x not in columns[column]] rows[index][column] = absent_num[0] # reset blocks with new rows blocks = getBlocks() # if block has 1 missing value, fill it in for block in range(0, 9): if blocks[block].count(None) == 1: index = blocks[block].index(None) absent_num = [x for x in range(1, 10) if x not in blocks[block]] # at this point the block has been filled, but we still need to update the value in rows # otherwise getBlocks() will reset to the original blocks # we know the index of the None and can translate this to row/column row_num = blockIndex2Row(block, index) # let's update the row with the new value # there could be multiple None values per row, so we must be careful # we have to make sure the None is the one inside this block when we replace it # let's get the indexes of all the None values none_index = [i for i, j in enumerate(rows[row_num]) if j == None] if block in [0, 3, 6]: none_index = [x for x in none_index if x < 3] if block in [1, 4, 7]: none_index = [x for x in none_index if x > 2 and x < 6] if block in [2, 5, 8]: none_index = [x for x in none_index if x > 5 and x < 9] rows[row_num][none_index[0]] = absent_num[0] return 0 def noneCount(): # counts how many empty squares are left count = 0 for i in range(0, 9): for item in rows[i]: if item == None: count += 1 return count def prettyPrint(): columns = getColumns() table = PrettyTable() table.hrules = ALL table.add_column(" ", range(0, 9)) for i in [str(x) for x in range(0, 9)]: table.add_column(i, columns[int(i)]) return table def results(): # print "ORIGINAL" # print prettyPrint() rows_before = 0 # initialise with different values, rows_after = 1 # doesn't matter what they are while(rows_before != rows_after): rows_before = noneCount() enterAnswer() rows_after = noneCount() print "FINAL" print prettyPrint() results() print "POSSIBLES" for i in range(0, 9): print i, possibleNumsRow(i)
cc14ca5628cd444a90a9a42ef75bd7a8e7f90e82
enric-blackbird/hangman
/hangman.py
2,174
4.09375
4
from random import choice import words def get_unique_letters(word): unique_letters = set() for letter in word: unique_letters.add(letter) return unique_letters def ask_dificulty_level(): selected_difficulty = '' while (selected_difficulty in words.difficulty_levels) == False: selected_difficulty = input('Please select your difficulty level: easy, medium, hard: ') selected_difficulty = selected_difficulty.lower() return selected_difficulty def get_random_word(difficulty_level): return choice(words.difficulty_levels[difficulty_level]) def generate_discovered_word(secret_word, requested_letters): discovered_so_far = '' for letter in secret_word: if (letter in requested_letters): discovered_so_far += ' ' + letter + ' ' else: discovered_so_far += ' _ ' return discovered_so_far remaining_lifes = 7 difficulty_level = ask_dificulty_level() secret_word = get_random_word(difficulty_level) requested_letters = set() remaining_letters = get_unique_letters(secret_word) while remaining_lifes > 0 and len(remaining_letters) > 0: print(generate_discovered_word(secret_word, requested_letters)) print('Remaining lifes:', remaining_lifes) requested_letter = input('What letter would you like to try now? ') if len(requested_letter) != 1 or requested_letter.isalpha() == False: print('Please choose a single letter.') continue requested_letter = requested_letter.upper() if requested_letter in requested_letters: print('You already used that letter.') continue if requested_letter in secret_word: print('Awesome! ' + requested_letter + ' is a secret letter!') remaining_letters.remove(requested_letter) else: print('Oh no! ' + requested_letter + ' is not in the secret word!') remaining_lifes -= 1 requested_letters.add(requested_letter) if (remaining_lifes == 0): print('It is OK to be a loser.') elif (remaining_lifes == 7): print('Dude you are amazing!') else: print('Congratulations, you won!') print('The secret word was: ' + secret_word)
25060ecf890a624e8e1796f4951a97a94eb47196
zuxinlin/leetcode
/leetcode/editor/cn/[543]二叉树的直径-diameter-of-binary-tree.py
1,549
3.984375
4
#!/bin/env python # coding: utf-8 # 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。 # # # # 示例 : # 给定二叉树 # # 1 # / \ # 2 3 # / \ # 4 5 # # # 返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。 # # # # 注意:两结点之间的路径长度是以它们之间边的数目表示。 # Related Topics 树 # 👍 693 👎 0 # leetcode submit region begin(Prohibit modification and deletion) # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ self.ans = 1 def dfs(root): # 访问到空节点了,返回0 if not root: return 0 L = dfs(root.left) # 左儿子为根的子树的深度 R = dfs(root.right) # 右儿子为根的子树的深度 self.ans = max(self.ans, L + R + 1) return max(L, R) + 1 # 返回该节点为根的子树的深度 dfs(root) return self.ans - 1 # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution()
8741f275c7cfbcb9f0dadcceda1fdc91926e3733
zuxinlin/leetcode
/leetcode/697.DegreeofanArray.py
845
3.71875
4
#! /usr/bin/env python # coding: utf-8 import collections ''' 题目: 主题: 解题思路: ''' class Solution(object): ''' ''' def findShortestSubArray(self, nums): ''' :type nums: List[int] :rtype: int ''' firstDict, lastDict = {}, {} for index, element in enumerate(nums): firstDict.setdefault(element, index) lastDict[element] = index counter = collections.Counter(nums) degree = max(counter.values()) return min(lastDict[element] - firstDict[element] + 1 for element in counter if counter[element] == degree) if __name__ == '__main__': solution = Solution() assert solution.findShortestSubArray([1, 2, 2, 3, 1]) == 2 assert solution.findShortestSubArray([1, 2, 2, 3, 1, 4, 2]) == 6
9289b58e5d5a049b05736f21fe29c74fd5f62d2c
zuxinlin/leetcode
/leetcode/editor/cn/[剑指 Offer 32 - I]从上到下打印二叉树-cong-shang-dao-xia-da-yin-er-cha-shu-lcof.py
1,208
3.796875
4
#! /usr/bin/env python # coding: utf-8 # 从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。 # # # # 例如: # 给定二叉树: [3,9,20,null,null,15,7], # # 3 # / \ # 9 20 # / \ # 15 7 # # # 返回: # # [3,9,20,15,7] # # # # # 提示: # # # 节点总数 <= 1000 # # Related Topics 树 广度优先搜索 # 👍 82 👎 0 # leetcode submit region begin(Prohibit modification and deletion) # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] queue = [root] result = [] while queue: node = queue.pop(0) result.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return result # leetcode submit region end(Prohibit modification and deletion)
f04f02ec17452f7dab054f977cfa93ef3e4dcd44
zuxinlin/leetcode
/leetcode/editor/cn/[剑指 Offer 68 - I]二叉搜索树的最近公共祖先-er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof.py
2,089
3.546875
4
#! /usr/bin/env python # coding: utf-8 # 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。 # # 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大( # 一个节点也可以是它自己的祖先)。” # # 例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5] # # # # # # 示例 1: # # 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 # 输出: 6 # 解释: 节点 2 和节点 8 的最近公共祖先是 6。 # # # 示例 2: # # 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 # 输出: 2 # 解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。 # # # # 说明: # # # 所有节点的值都是唯一的。 # p、q 为不同节点且均存在于给定的二叉搜索树中。 # # # 注意:本题与主站 235 题相同:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a # -binary-search-tree/ # Related Topics 树 # 👍 122 👎 0 # leetcode submit region begin(Prohibit modification and deletion) # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if not root or p == root or q == root: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if left and right: # 左右都不空,返回根节点 return root elif left: # 在左子树 return left elif right: # 在右子树 return right # leetcode submit region end(Prohibit modification and deletion)
2d0dd49df325cedf34a9f57348c14e5fe1f5ec6f
zuxinlin/leetcode
/leetcode/669.TrimaBinarySearchTree.py
1,598
3.90625
4
#! /usr/env python # coding: utf-8 ''' 二叉搜索数,移除所有节点值小于l或者大于r的节点 ''' class TreeNode(object): ''' 树节点类 ''' def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def trimBST(self, root, L, R): ''' :type root: TreeNode :type L: int :type R: int :rtype: TreeNode ''' if not root: return None if root.val < L: return self.trimBST(root.right, L, R) if root.val > R: return self.trimBST(root.left, L, R) root.left = self.trimBST(root.left, L, R) root.right = self.trimBST(root.right, L, R) return root def first(self, root): ''' 前序遍历 ''' if not root: return print root.val, '->', self.first(root.left) self.first(root.right) def level(self, root): ''' 层次遍历 ''' queue = [root] while queue: current = queue.pop(0) print current.val, '->', if current.left: queue.append(current.left) if current.right: queue.append(current.right) def main(): ''' main函数 ''' solution = Solution() root = solution.constructMaximumBinaryTree([3, 2, 1, 6, 0, 5]) # 前序遍历 solution.first(root) print # 层次遍历 solution.level(root) if __name__ == '__main__': main()
96fdb3f37819683bdc6483b8d2d4d790ca65ef40
zuxinlin/leetcode
/leetcode/editor/cn/[面试题 02.01]移除重复节点-remove-duplicate-node-lcci.py
1,403
3.8125
4
#! /usr/bin/env python # coding: utf-8 # 编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。 # # 示例1: # # # 输入:[1, 2, 3, 3, 2, 1] # 输出:[1, 2, 3] # # # 示例2: # # # 输入:[1, 1, 1, 1, 2] # 输出:[1, 2] # # # 提示: # # # 链表长度在[0, 20000]范围内。 # 链表元素在[0, 20000]范围内。 # # # 进阶: # # 如果不得使用临时缓冲区,该怎么解决? # Related Topics 链表 # 👍 101 👎 0 # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeDuplicateNodes(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head # 虚拟头结点 s, cur, v = set(), head, ListNode(0) v.next = head pre = v while cur: if cur.val in s: pre.next = cur.next cur = cur.next else: s.add(cur.val) pre, cur = cur, cur.next return v.next # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution()
428a526f19452e625231d84df58b073afdf67f2c
zuxinlin/leetcode
/leetcode/editor/cn/[1143]最长公共子序列-longest-common-subsequence.py
2,256
3.703125
4
#! /usr/bin/env python # coding: utf-8 # 给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0 。 # # 一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。 # # # 例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。 # # # 两个字符串的 公共子序列 是这两个字符串所共同拥有的子序列。 # # # # 示例 1: # # # 输入:text1 = "abcde", text2 = "ace" # 输出:3 # 解释:最长公共子序列是 "ace" ,它的长度为 3 。 # # # 示例 2: # # # 输入:text1 = "abc", text2 = "abc" # 输出:3 # 解释:最长公共子序列是 "abc" ,它的长度为 3 。 # # # 示例 3: # # # 输入:text1 = "abc", text2 = "def" # 输出:0 # 解释:两个字符串没有公共子序列,返回 0 。 # # # # # 提示: # # # 1 <= text1.length, text2.length <= 1000 # text1 和 text2 仅由小写英文字符组成。 # # Related Topics 动态规划 # 👍 527 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def longestCommonSubsequence(self, text1, text2): """ :type text1: str :type text2: str :rtype: int """ # 状态转移:dp[i][j] # 1. text1[i] == text2[j]: dp[i][j]= dp[i-1][j-1] + 1 # 2. text1[i] != text2[j]: dp[i][j] = max(dp[i][j-1], dp[i-1][j]) row, column = len(text1), len(text2) dp = [list(0 for _ in range(column + 1)) for _ in range(row + 1)] for i in range(1, row + 1): for j in range(1, column + 1): if text1[i - 1] == text2[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]) return dp[row][column] if __name__ == '__main__': solution = Solution() print(solution.longestCommonSubsequence('abcde', 'ace')) # leetcode submit region end(Prohibit modification and deletion)
8a7fba97f2e5895d65f3181d82455883cbe5eeee
zuxinlin/leetcode
/leetcode/204.CountPrimes.py
741
3.828125
4
#! /usr/bin/env python # coding: utf-8 ''' 题目: 统计素数 https://leetcode-cn.com/problems/count-primes/ 主题: hash table & math 解题思路: 1. 利用数组缓存是否素数 ''' class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ no_prime = [False] * n count = 0 for i in range(2, n): if not no_prime[i]: count += 1 for j in range(i, n/i+1): if i * j < n: no_prime[i*j] = True else: break return count if __name__ == '__main__': solution = Solution() print ord('0') - ord('P')
65dbb54f88d96fab2bf6953724336d932e81db30
zuxinlin/leetcode
/leetcode/editor/cn/[剑指 Offer 30]包含min函数的栈-bao-han-minhan-shu-de-zhan-lcof.py
1,676
4.03125
4
#! /usr/bin/env python # coding: utf-8 # 定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。 # # # # 示例: # # MinStack minStack = new MinStack(); # minStack.push(-2); # minStack.push(0); # minStack.push(-3); # minStack.min(); --> 返回 -3. # minStack.pop(); # minStack.top(); --> 返回 0. # minStack.min(); --> 返回 -2. # # # # # 提示: # # # 各函数的调用总次数不超过 20000 次 # # # # # 注意:本题与主站 155 题相同:https://leetcode-cn.com/problems/min-stack/ # Related Topics 栈 设计 # 👍 123 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.a = [] self.b = [] # 存储栈非严格降序 def push(self, x): """ :type x: int :rtype: None """ self.a.append(x) if not self.b or x <= self.b[-1]: self.b.append(x) def pop(self): """ :rtype: None """ if self.a.pop() == self.b[-1]: self.b.pop() def top(self): """ :rtype: int """ return self.a[-1] def min(self): """ :rtype: int """ return self.b[-1] # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(x) # obj.pop() # param_3 = obj.top() # param_4 = obj.min() # leetcode submit region end(Prohibit modification and deletion)
dacb6006963fb1c724b4ad5116424a33cb90a7ce
zuxinlin/leetcode
/leetcode/editor/cn/[面试题 02.05]链表求和-sum-lists-lcci.py
1,638
3.84375
4
#! /usr/bin/env python # coding: utf-8 # 给定两个用链表表示的整数,每个节点包含一个数位。 # # 这些数位是反向存放的,也就是个位排在链表首部。 # # 编写函数对这两个整数求和,并用链表形式返回结果。 # # # # 示例: # # 输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295 # 输出:2 -> 1 -> 9,即912 # # # 进阶:思考一下,假设这些数位是正向存放的,又该如何解决呢? # # 示例: # # 输入:(6 -> 1 -> 7) + (2 -> 9 -> 5),即617 + 295 # 输出:9 -> 1 -> 2,即912 # # Related Topics 链表 数学 # 👍 65 👎 0 # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ carry = 0 cur = v = ListNode(0) while l1 and l2: carry, val = divmod(l1.val + l2.val + carry, 10) cur.next = ListNode(val) cur, l1, l2 = cur.next, l1.next, l2.next if l2: l1 = l2 while l1: carry, val = divmod(l1.val + carry, 10) cur.next = ListNode(val) cur, l1 = cur.next, l1.next if carry: cur.next = ListNode(carry) return v.next # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution()
daa3502ee43661ba21929fe62a20aa19e8ae5c77
zuxinlin/leetcode
/leetcode/303.RangeSumQuery-Immutable.py
1,081
4.0625
4
#! /usr/bin/env python # coding: utf-8 """ Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note: You may assume that the array does not change. There are many calls to sumRange function. 最大抢劫数额,限制是不能抢相邻两家 状态转移方程:dp[i] = max(dp[i-2] + nums[i], dp[i-1]),表示当前到i最大利润 """ class Solution(object): def __init__(self, nums): """ :type nums: List[int] """ self.sum = {-1:0} for i,num in enumerate(nums): self.sum[i] = self.sum[i-1] + num def sumRange(self, i, j): """ :type i: int :type j: int :rtype: int """ return self.sum[j] - self.sum[i-1] if __name__ == '__main__': solution = Solution([-2, 0, 3, -5, 2, -1]) assert solution.sumRange(0, 2) == 1 assert solution.sumRange(2, 5) == -1 assert solution.sumRange(0, 5) == -3
e1fba9ce8a9ce41bc5864cea8930bc5ad1048ea1
zuxinlin/leetcode
/leetcode/94.BinaryTreeInorderTraversal.py
1,332
3.96875
4
#! /usr/bin/env python # coding: utf-8 ''' 题目: 二叉树中序遍历 https://leetcode-cn.com/problems/binary-tree-inorder-traversal/ 主题: hash table & stack & tree 解题思路: 1. 深度优先遍历,左 根 右 ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def inorder(self, root, result): if root is None: return self.inorder(root.left, result) result.append(root.val) self.inorder(root.right, result) def inorder_stack(self, root): if root is None: return stack = [] current = root result = [] while current or stack: if current: stack.append(current) current = current.left else: current = stack.pop() result.append(current.val) current = current.right return result def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ result = [] self.inorder(root, result) return result # return self.inorder_stack(root) if __name__ == '__main__': pass
ed87906929d09c5cfa80fb0f94ad3470b06eafd4
zuxinlin/leetcode
/leetcode/editor/cn/[剑指 Offer 49]丑数-chou-shu-lcof.py
1,657
3.8125
4
#! /usr/bin/env python # coding: utf-8 # 我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。 # # # # 示例: # # 输入: n = 10 # 输出: 12 # 解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。 # # 说明: # # # 1 是丑数。 # n 不超过1690。 # # # 注意:本题与主站 264 题相同:https://leetcode-cn.com/problems/ugly-number-ii/ # Related Topics 数学 # 👍 150 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def nthUglyNumber(self, n): """ :type n: int :rtype: int """ # 最小堆 # factors = [2, 3, 5] # seen = {1} # heap = [1] # # for i in range(n - 1): # curr = heapq.heappop(heap) # for factor in factors: # nxt = curr * factor # if nxt not in seen: # seen.add(nxt) # heapq.heappush(heap, nxt) # # return heapq.heappop(heap) # 动态规划 dp = [0] * (n + 1) dp[1] = 1 p2 = p3 = p5 = 1 for i in range(2, n + 1): num2, num3, num5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 dp[i] = min(num2, num3, num5) if dp[i] == num2: p2 += 1 if dp[i] == num3: p3 += 1 if dp[i] == num5: p5 += 1 return dp[n] # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution()
5330a27b9dc92edc83b382e554775bdcdd4f98b8
zuxinlin/leetcode
/leetcode/editor/cn/[202]快乐数-happy-number.py
1,116
3.5625
4
#! /usr/bin/env python # coding: utf-8 # 编写一个算法来判断一个数 n 是不是快乐数。 # # 「快乐数」定义为: # # # 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。 # 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。 # 如果 可以变为 1,那么这个数就是快乐数。 # # # 如果 n 是快乐数就返回 true ;不是,则返回 false 。 # # # # 示例 1: # # # 输入:19 # 输出:true # 解释: # 12 + 92 = 82 # 82 + 22 = 68 # 62 + 82 = 100 # 12 + 02 + 02 = 1 # # # 示例 2: # # # 输入:n = 2 # 输出:false # # # # # 提示: # # # 1 <= n <= 231 - 1 # # Related Topics 哈希表 数学 # 👍 583 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def isHappy(self, n): """ :type n: int :rtype: bool """ # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution()
343df813e7d0b24a99281b4a3bbb5c77baabf2ae
zuxinlin/leetcode
/leetcode/169.MajorityElement.py
847
3.75
4
#! /usr/bin/env python # coding: utf-8 ''' 题目: 主要元素 https://leetcode-cn.com/problems/majority-element/ 主题: array & divide and conquer & bit manipulation 解题思路: 1. 排序 ''' class Solution(object): def majorityElement(self, nums): ''' :type nums: List[int] :rtype: int ''' # return sorted(num)[len(num)/2] # 用字典存储每个元素出现次数,并且记录当前出现最多的元素以及个数 d = {} count = 0 target = 0 for i in nums: d[i] = d[i] + 1 if d.has_key(i) else 1 if d[i] > count: target = i count = d[i] return target if __name__ == '__main__': solution = Solution() nums = [3, 3, 4] assert 2 == solution.majorityElement(nums)
f1cd2a2c2f65e75ed8e51bb80695654d0318922c
zuxinlin/leetcode
/leetcode/editor/cn/[88]合并两个有序数组-merge-sorted-array.py
2,402
4.09375
4
#! /usr/bin/env python # coding: utf-8 # 给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。 # # 初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。你可以假设 nums1 的空间大小等于 m + n,这样它就有足够的空间保存来自 nu # ms2 的元素。 # # # # 示例 1: # # # 输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 # 输出:[1,2,2,3,5,6] # # # 示例 2: # # # 输入:nums1 = [1], m = 1, nums2 = [], n = 0 # 输出:[1] # # # # # 提示: # # # nums1.length == m + n # nums2.length == n # 0 <= m, n <= 200 # 1 <= m + n <= 200 # -109 <= nums1[i], nums2[i] <= 109 # # Related Topics 数组 双指针 # 👍 931 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead. """ # 排序 # nums1[m:] = nums2 # nums1.sort() # 双指针 + 开辟新空间 # result = [] # p1, p2 = 0, 0 # # while p1 < m or p2 < n: # if p1 == m: # result.append(nums2[p2]) # p2 += 1 # elif p2 == n: # result.append(nums1[p1]) # p1 += 1 # elif nums1[p1] <= nums2[p2]: # result.append(nums1[p1]) # p1 += 1 # elif nums1[p1] > nums2[p2]: # result.append(nums2[p2]) # p2 += 1 # # nums1[:] = result # 逆向双指针 p1, p2, tail = m - 1, n - 1, m + n - 1 while p1 >= 0 or p2 >= 0: if p1 == -1: nums1[tail] = nums2[p2] p2 -= 1 elif p2 == -1: nums1[tail] = nums1[p1] p1 -= 1 elif nums1[p1] > nums2[p2]: nums1[tail] = nums1[p1] p1 -= 1 else: nums1[tail] = nums2[p2] p2 -= 1 tail -= 1 # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution()
76b5171706f347c58c33eed212798f84c6ebcfd1
zuxinlin/leetcode
/leetcode/350.IntersectionOfTwoArraysII.py
1,434
4.1875
4
#! /usr/bin/env python # coding: utf-8 ''' ''' class Solution(object): ''' Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in any order. Follow up: What if the given array is already sorted? How would you optimize your algorithm? What if nums1's size is small compared to nums2's size? Which algorithm is better? What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? ''' def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ result = [] cache = {} # 先用哈希表存储一个数组统计情况,另外一个数组查表即可 for i in nums1: if i in cache: cache[i] += 1 else: cache[i] = 1 for i in nums2: if i in cache and cache[i] > 0: result.append(i) cache[i] -= 1 return result if __name__ == '__main__': solution = Solution() assert solution.intersect([1, 2, 2, 1], [2]) == [2, ] assert solution.intersect([3, 1, 2], [1, 1]) == [1, ]
438d018c965882d506f8779738bec7d716e76ed8
zuxinlin/leetcode
/leetcode/editor/cn/[125]验证回文字符串-valid-palindrome.py
1,127
3.734375
4
#! /usr/bin/env python # coding: utf-8 # 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 # # 说明:本题中,我们将空字符串定义为有效的回文串。 # # 示例 1: # # 输入: "A man, a plan, a canal: Panama" # 输出: true # # # 示例 2: # # 输入: "race a car" # 输出: false # # Related Topics 双指针 字符串 # 👍 372 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ # 边界条件 if not s or len(s) <= 1: return True # 预处理,过滤无关字符 s = [c.lower() for c in s if c.isalnum()] l, r = 0, len(s) - 1 while l < r: if s[l] != s[r]: return False else: l += 1 r -= 1 return True # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution()
28ef9964b87c016a7c38fc035839c9441a2eecd4
zuxinlin/leetcode
/leetcode/editor/cn/[415]字符串相加-add-strings.py
1,215
3.71875
4
#!/bin/env python # coding: utf-8 # 给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。 # # # # 提示: # # # num1 和num2 的长度都小于 5100 # num1 和num2 都只包含数字 0-9 # num1 和num2 都不包含任何前导零 # 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式 # # Related Topics 字符串 # 👍 360 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def addStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ # return str(int(num1) + int(num2)) # 按位模拟加法 res = "" i, j, carry = len(num1) - 1, len(num2) - 1, 0 while i >= 0 or j >= 0: n1 = int(num1[i]) if i >= 0 else 0 n2 = int(num2[j]) if j >= 0 else 0 carry, tmp = divmod(n1 + n2 + carry, 10) res = str(tmp % 10) + res i, j = i - 1, j - 1 return "1" + res if carry else res # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution()
18fa265d0986d4525e31166b13c334d55b3dd85c
zuxinlin/leetcode
/leetcode/editor/cn/[剑指 Offer 32 - II]从上到下打印二叉树 II-cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof.py
1,565
3.921875
4
#! /usr/bin/env python # coding: utf-8 # 从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。 # # # # 例如: # 给定二叉树: [3,9,20,null,null,15,7], # # 3 # / \ # 9 20 # / \ # 15 7 # # # 返回其层次遍历结果: # # [ # [3], # [9,20], # [15,7] # ] # # # # # 提示: # # # 节点总数 <= 1000 # # # 注意:本题与主站 102 题相同:https://leetcode-cn.com/problems/binary-tree-level-order-tra # versal/ # Related Topics 树 广度优先搜索 # 👍 101 👎 0 # leetcode submit region begin(Prohibit modification and deletion) # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] queue = [root] result = [] while queue: temp = [] length = len(queue) # 一层层遍历 for _ in range(length): node = queue.pop(0) temp.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) result.append(temp) return result # leetcode submit region end(Prohibit modification and deletion)
e3d7fd79863b8438f5aaef3fcbda61641c80ca37
zuxinlin/leetcode
/leetcode/268.MissingNumber.py
939
4.09375
4
#! /usr/bin/env python # coding: utf-8 ''' Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Example 1: Input: [3,0,1] Output: 2 Example 2: Input: [9,6,4,2,3,5,7,0,1] Output: 8 连续整数数组,其中丢失一个数字,求丢失的数字 1. 求和 2. 异或 ''' class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ # 加法求解 # return (1 + len(nums)) * len(nums) / 2 - sum(nums) # 异或求解 n = len(nums) first, second = 0, 0 for i in range(n+1): first ^= i for i in nums: second ^= i return first^second if __name__ == '__main__': solution = Solution() assert solution.missingNumber([3, 0, 1]) == 2 assert solution.missingNumber([9, 6, 4, 2, 3, 5, 7, 0, 1]) == 8
25d0f4a1de46904cc9db08dae89edd2d07f417ec
zuxinlin/leetcode
/leetcode/516.LongestPalindromicSubsequence.py
1,483
4
4
#! /usr/bin/env python # coding: utf-8 """ Longest Palindromic Subsequence """ class Solution(object): """ Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000. Example 1: Input: "bbbab" Output: 4 One possible longest palindromic subsequence is "bbbb". Example 2: Input: "cbbd" Output: 2 One possible longest palindromic subsequence is "bb". """ def longestPalindromeSubseq(self, s): """ :type s: str :rtype: int """ if s == s[::-1]: return len(s) l = len(s) ''' the longest palindromic subsequence's length of substring(i, j) 1. dp[i][j] = dp[i+1][j-1] + 2 if s.charAt(i) == s.charAt(j) 2. dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]) 3. Initialization:dp[i][i] = 1 ''' dp = [[0] * l for _ in xrange(l)] for i in xrange(l - 1, -1, -1): dp[i][i] = 1 for j in xrange(i + 1, l): if s[i] == s[j]: dp[i][j] = dp[i + 1][j - 1] + 2 else: dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) return dp[0][l - 1] if __name__ == '__main__': solution = Solution() assert solution.longestPalindromeSubseq('bbbab') == 4 assert solution.longestPalindromeSubseq('aaa') == 3 assert solution.longestPalindromeSubseq('cbbd') == 2
071594b3527b32d58737a50a969ed3e691a43c91
zuxinlin/leetcode
/leetcode/editor/cn/[剑指 Offer 10- II]青蛙跳台阶问题-qing-wa-tiao-tai-jie-wen-ti-lcof.py
1,009
3.65625
4
#! /usr/bin/env python # coding: utf-8 # 一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。 # # 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。 # # 示例 1: # # 输入:n = 2 # 输出:2 # # # 示例 2: # # 输入:n = 7 # 输出:21 # # # 示例 3: # # 输入:n = 0 # 输出:1 # # 提示: # # # 0 <= n <= 100 # # # 注意:本题与主站 70 题相同:https://leetcode-cn.com/problems/climbing-stairs/ # # # Related Topics 递归 # 👍 153 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def numWays(self, n): """ :type n: int :rtype: int """ a, b = 1, 2 for _ in range(1, n): a, b = b, a + b return a % 1000000007 # leetcode submit region end(Prohibit modification and deletion)
2cb4b271197773e4b76e68c5fb60045e0648d9d6
zuxinlin/leetcode
/amcat/CellCompete.py
645
3.515625
4
#! /usr/bin/env python # coding: utf-8 import collections def cellCompete(states, days): # WRITE YOUR CODE HERE n = len(states) temp = [state for state in states] while days > 0: days -= 1 temp[0] = 0 ^ states[1] temp[n - 1] = 0 ^ states[n - 2] for i in range(1, n - 1): temp[i] = states[i - 1] ^ states[i + 1] states = [i for i in temp] return states def main(): assert cellCompete([1, 0, 0, 0, 0, 1, 0, 0], 1) == [0, 1, 0, 0, 1, 0, 1, 0] assert cellCompete([1, 1, 1, 0, 1, 1, 1, 1], 2) == [0, 0, 0, 0, 0, 1, 1, 0] if __name__ == '__main__': main()
dd6cb3ae7e51e31504e81eb9b01b2d58be5f8e08
zuxinlin/leetcode
/leetcode/editor/cn/[剑指 Offer 63]股票的最大利润-gu-piao-de-zui-da-li-run-lcof.py
1,517
3.703125
4
#! /usr/bin/env python # coding: utf-8 # 假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少? # # # # 示例 1: # # 输入: [7,1,5,3,6,4] # 输出: 5 # 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 # 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。 # # # 示例 2: # # 输入: [7,6,4,3,1] # 输出: 0 # 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 # # # # 限制: # # 0 <= 数组长度 <= 10^5 # # # # 注意:本题与主站 121 题相同:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-s # tock/ # Related Topics 动态规划 # 👍 116 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ # 边界条件 if not prices: return 0 # dp[i] = max{dp[i-1], prices[i] - min(price[:i-1])} cost, profit = float("+inf"), 0 for price in prices: cost = min(cost, price) profit = max(profit, price - cost) return profit # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution() print(solution.maxProfit([7, 1, 5, 3, 6, 4]))
3a1b76483d65f82c140c227ee11c7037ca44a361
zuxinlin/leetcode
/leetcode/17.LetterCombinationsOfAPhoneNumber.py
1,190
3.734375
4
#! /usr/bin/env python # coding: utf-8 ''' 题目: 电话号码字母组合 主题: string & backtracking 解题思路: 方法1:递归,dfs 方法2:回溯 ''' class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ key_map = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} result = [] if len(digits) == 0: return result # elif len(digits) == 1: # return list(key_map[digits[0]]) # else: # pre = self.letterCombinations(digits[:-1]) # return [i + j for i in pre for j in key_map[digits[-1]]] def dfs(index=0, path=''): # 得到解空间 if len(path) == len(digits): result.append(path) else: # 每一步解的取值范围 for i in key_map[digits[index]]: dfs(index + 1, path + i) dfs() return result if __name__ == '__main__': solution = Solution() print solution.letterCombinations('23')
319d3ec8c62018aefd7e9fa2afae5a84ca4e27d0
zuxinlin/leetcode
/leetcode/997.FindTheTownJudge.py
1,286
3.8125
4
#! /usr/bin/env python # coding: utf-8 ''' 题目: 找出小镇法官 主题: graph 解题思路: 1. 两个字典存储 ''' class Solution(object): ''' ''' def findJudge(self, N, trust): """ :type N: int :type trust: List[List[int]] :rtype: int """ # 边界 if N == 1 and trust == []: return 1 # 统计路径 start_dict = {} end_dict = {} # 输入存储到字段 for (start, end) in trust: end_dict[end] = 1 + end_dict[end] if end in end_dict else 1 start_dict[start] = 1 + \ start_dict[start] if start in start_dict else 1 # 1. 法官不信任任何人;2. 其他人都信任法官;3. 只有一个法官 for person in range(1, N + 1): if person in end_dict and end_dict[person] == N - 1 and person not in start_dict: return person return -1 if __name__ == '__main__': solution = Solution() assert solution.findJudge(N=2, trust=[[1, 2]]) == 2 assert solution.findJudge(N=3, trust=[[1, 3], [2, 3]]) == 3 assert solution.findJudge(N=3, trust=[[1, 3], [2, 3], [3, 1]]) == -1 assert solution.findJudge(N=3, trust=[[1, 2], [2, 3]]) == -1
c37d715af7df27127e2c79e04331704190be7502
zuxinlin/leetcode
/leetcode/88.MergeSortedArray.py
1,105
3.953125
4
#! /usr/bin/env python # coding: utf-8 from itertools import combinations ''' 题目: 合并有序数组 主题: array & two pointers 解题思路: 1. 两个尾指针,比较大小 ''' class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead. """ first_index = m - 1 second_index = n - 1 index = m + n - 1 while first_index >= 0 and second_index >= 0: if nums1[first_index] >= nums2[second_index]: nums1[index] = nums1[first_index] first_index -= 1 else: nums1[index] = nums2[second_index] second_index -= 1 index -= 1 while second_index >= 0: nums1[index] = nums2[second_index] index -= 1 second_index -= 1 if __name__ == '__main__': solution = Solution()
37e1234e8f39adc280dc20a3c39ea86f93143b0e
zuxinlin/leetcode
/leetcode/110.BalancedBinaryTree.py
1,342
4.28125
4
#! /usr/bin/env python # coding: utf-8 ''' Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example 1: Given the following tree [3,9,20,null,null,15,7]: 3 / \ 9 20 / \ 15 7 Return true. Example 2: Given the following tree [1,2,2,3,3,null,null,4,4]: 1 / \ 2 2 / \ 3 3 / \ 4 4 Return false. 判断一颗二叉树是否是平衡二叉树,主要是左右子树高度差有没有大于1 ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def dfs(self, root): if root is None: return 0 left = self.dfs(root.left) right = self.dfs(root.right) if left == -1 or right == -1 or abs(left - right) > 1: return -1 else: return max(left, right) + 1 def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ if self.dfs(root) == -1: return False else: return True if __name__ == '__main__': pass
738fb0bedabe6835435b64429a5038d11e4f8103
zuxinlin/leetcode
/leetcode/editor/cn/[剑指 Offer 59 - II]队列的最大值-dui-lie-de-zui-da-zhi-lcof.py
1,588
3.875
4
#! /usr/bin/env python # coding: utf-8 # 请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都 # 是O(1)。 # # 若队列为空,pop_front 和 max_value 需要返回 -1 # # 示例 1: # # 输入: # ["MaxQueue","push_back","push_back","max_value","pop_front","max_value"] # [[],[1],[2],[],[],[]] # 输出: [null,null,null,2,1,2] # # # 示例 2: # # 输入: # ["MaxQueue","pop_front","max_value"] # [[],[],[]] # 输出: [null,-1,-1] # # # # # 限制: # # # 1 <= push_back,pop_front,max_value的总操作数 <= 10000 # 1 <= value <= 10^5 # # Related Topics 栈 Sliding Window # 👍 233 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class MaxQueue(object): def __init__(self): self.queue = [] def max_value(self): """ :rtype: int """ return max(self.queue) if self.queue else -1 def push_back(self, value): """ :type value: int :rtype: None """ self.queue.append(value) def pop_front(self): """ :rtype: int """ if self.queue: return self.queue.pop(0) else: return -1 # Your MaxQueue object will be instantiated and called as such: # obj = MaxQueue() # param_1 = obj.max_value() # obj.push_back(value) # param_3 = obj.pop_front() # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution()
b9f2df924557a27b03345e5fe1824fceaa96f275
zuxinlin/leetcode
/leetcode/167.TwoSumII.py
1,547
3.890625
4
#! /usr/bin/env python # coding: utf-8 """ Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2 """ class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ # 采用字典存储第一个数的下标 # d = {} # l = len(numbers) # # for i in xrange(l): # d[numbers[i]] = i # # for i in xrange(l): # if target - numbers[i] in d: # return [i + 1, d[target - numbers[i]] + 1] # 采用二分查找,从两点出发 l = len(numbers) i, j = 0, l - 1 while i < j: s = numbers[i] + numbers[j] if s < target: i += 1 elif s > target: j -= 1 else: return [i + 1, j + 1] if __name__ == '__main__': solution = Solution() print solution.twoSum([2, 7, 11, 15], 9) assert solution.twoSum([2, 7, 11, 15], 9) == [1, 2]
016268ffd0f3cf0fe5e4f98784af536ef6e44096
jlyang1990/LeetCode
/160. Intersection of Two Linked Lists.py
892
3.5
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ import gc gc.collect() pA = headA pB = headB countA = 0 countB = 0 while pA: countA += 1 pA = pA.next while pB: countB += 1 pB = pB.next pA = headA pB = headB if countA - countB > 0: for i in range(countA - countB): pA = pA.next if countB - countA > 0: for i in range(countB - countA): pB = pB.next while pA != pB: pA = pA.next pB = pB.next return pA
7903a699ca0f6c37c0f1199f27faf3cefc2b5e63
jlyang1990/LeetCode
/070. Climbing Stairs.py
289
3.59375
4
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ # Fibonacci current = 1 previous = 1 for i in range(n-1): current, previous = current+previous, current return current
2e349c5ef936fdea0a6650bc9bad9707702c1053
jlyang1990/LeetCode
/202. Happy Number.py
479
3.5
4
class Solution(object): def isHappy(self, n): """ :type n: int :rtype: bool """ numSet = {n} num = n while num != 1: num = self.getHappy(num) if num in numSet: return False numSet.add(num) return True def getHappy(self, n): result = 0 while n > 0: result += (n%10)**2 n /= 10 return result
f133a17bb2e55d558ffdb96382c3546afdb740fb
jlyang1990/LeetCode
/334. Increasing Triplet Subsequence.py
727
3.65625
4
class Solution(object): def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ first = float("inf") # smallest (valid) first element in triplet # or (potential) first element in triplet (for searching for better "second") up to i-1 second = float("inf") # smallest (valid) second element in triplet up to i-1 # nums[i] must be larger than "second" to complete a triplet for i in nums: if i < first: first = i if i > first and i < second: second = i if i > second: return True return False
d98ea080f041891a11878de57678dd7934e4e0ac
jlyang1990/LeetCode
/147. Insertion Sort List.py
835
3.96875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype: ListNode """ new_head = ListNode(None) pointer = new_head current = head while current: while pointer.next and pointer.next.val < current.val: pointer = pointer.next current.next, pointer.next, current, pointer = pointer.next, current, current.next, new_head ''' temp = current.next current.next = pointer.next pointer.next = current current = current.next pointer = new_head ''' return new_head.next
0b964656ec5993bab9abcdf6f733ca44bda8b2f5
jlyang1990/LeetCode
/020. Valid Parentheses.py
550
3.515625
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ dic = {} dic["("] = ")" dic["{"] = "}" dic["["] = "]" stack = [] for current in s: if current in dic: stack.append(current) else: if len(stack) == 0: return False previous = stack.pop() if dic[previous] != current: return False return len(stack) == 0
d7201ef1d96bf2d235c159a5422af0581c21a6ef
MadyDixit/ProblemSolver
/Dynamic Programming/Longest_Sub_Sequence.py
2,642
4.09375
4
''' Find the Longest Common Subsequence Length Using Recursion. ''' def LCSLenghtR(x, y): ''' :param x: First String :param y: Second String :return: Length of Common SubSequence ''' #If length of string is 0 then return 0 if(len(x) == 0 or len(y) == 0): return 0 #if last element matches of the Array then if x[-1] == y[-1]: return LCSLenghtR(x[:-1],y[:-1]) + 1 #else if the last element don't match then return max(LCSLenghtR(x,y[:-1]), LCSLenghtR(x[:-1],y)) ''' Find the Longest Common Subsequence using Dynamic Programming (Bottom-UP Approach (Tabulation)). ''' def lcsDP(X, Y): # find the length of the strings m = len(X) n = len(Y) # declaring the array for storing the dp values L = [[None] * (n + 1) for i in range(m + 1)] print(L) """Following steps build L[m + 1][n + 1] in bottom up fashion Note: L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]""" for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: L[i][j] = 0 elif X[i - 1] == Y[j - 1]: L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) # L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1] return L[m][n] # end of function lcs ''' Find the Longest Common Sequence using Dynamic Programming using Memoization. ''' def lcs(X, Y, m, n, dp): # base case if (m == 0 or n == 0): return 0 # if the same state has already been # computed if (dp[m - 1][n - 1] != -1): return dp[m - 1][n - 1] # if equal, then we store the value of the # function call if (X[m - 1] == Y[n - 1]): # store it in arr to avoid further repetitive # work in future function calls dp[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp) return dp[m - 1][n - 1] else: # store it in arr to avoid further repetitive # work in future function calls dp[m - 1][n - 1] = max(lcs(X, Y, m, n - 1, dp), lcs(X, Y, m - 1, n, dp)) return dp[m - 1][n - 1] if __name__ == '__main__': maximum = 1000 x = 'ABCBDAB' y = 'BDCABA' m = len(x) n = len(y) print('The Longest Subsequqence in given String ',x,' and ',y,' is ',LCSLenghtR(x,y)) print('The Longest Subsequqence in given String ',x,' and ',y,' is ',lcsDP(x,y)) dp = [[-1 for _ in range(maximum)]for _ in range(m)] print('The Longest Subsequqence in given String ',x,' and ',y,' is ',lcs(x,y,m,n,dp))
7a750725399d333e2cd1b46add1b8cc0c02b1522
MadyDixit/ProblemSolver
/Google/Coding/UnivalTree.py
1,039
4.125
4
''' Task 1: Check weather the Given Tree is Unival or Not. Task 2: Count the Number of Unival Tree in the Tree. ''' ''' Task 1: ''' class Tree: def __init__(self,x): self.val = x self.left = None self.right = None def insert(self, data): if self.val: if self.val > data: if self.left is None: self.left = Tree(data) else: self.left.insert(data) else: if self.right is None: self.right = Tree(data) else: self.right.insert(data) else: return False class Tasker: def is_unival(self,root): return unival_helper(root, root.val) def unival_helper(self, root, value): if root is None: return True elif root.val == value: return self.unival_helper(root.left, value) and self.unival_helper(root.right, value) return False if __name__ == '__main__':
eba5ab73e093a8be458110cc4b3dce7c40b9dbaf
Anveshan3175/RaspberriPi
/GPIOlib/button_1.py
265
3.640625
4
from gpiozero import Button button = Button(2) # button is connected to BCM 2 . Connect +ve of button to GPIO2 and -ve to GND of Raspberri while True: if button.is_pressed: print("BUtton is pressed") else: print("Button is not pressed ")
13f3c6634009bd5a31f8744220f1073d85a7e882
Retzudo/invasions.retzudo.com
/invasions.py
1,558
3.59375
4
from datetime import datetime, timedelta import pytz class InvasionTimer: invasion_delta = timedelta(hours=18, minutes=30) invasion_duration = timedelta(hours=6) def __init__(self, now=None): if now is None: now = datetime.now(tz=pytz.utc) self.now = now @property def next_invasion_date(self): """Return the next invasion date. Invasions start every 18.5 hours and last 6 hours.""" # This is our base date. We now an invasion happened at that point (UTC). invasion_date = datetime(2017, 5, 2, 6, 30, 0, tzinfo=pytz.utc) while True: # Add 18.5h hours to the first know date # as long as it's smaller than the current date. if invasion_date >= self.now: return invasion_date invasion_date += InvasionTimer.invasion_delta @property def last_invasion_date(self): """Return the date of the last invasion.""" return self.next_invasion_date - InvasionTimer.invasion_delta @property def invasion_running(self): """Return True or False if an invasion is currently going on.""" invasion_date = self.last_invasion_date return invasion_date <= self.now <= invasion_date + InvasionTimer.invasion_duration @property def invasion_time_left(self): """Return the time left on an invasion if there's one going on.""" if self.invasion_running: return (self.last_invasion_date + InvasionTimer.invasion_duration) - self.now
795dce14cdc68a508ea2551d371008dad787024f
tsimur/crafts
/search_resize/search_and_resize.py
640
3.59375
4
# Search all files in folder with subfolders then resize and save in specify folder. It means that the files are images # in the .jpeg format import os from PIL import Image path = 'path to folder with subfolders' dist = 'path to folder wherer you wont to save converted files' dirs = [f for f in sorted(os.listdir(path))] a = 0 size = 1024, 1024 for dir_name in dirs: current_dir = path + dir_name files = os.listdir(path=current_dir) for file in files: image = Image.open(current_dir + '/' + file) image.thumbnail(size) image.save(dist + dir_name + file, "JPEG") print(dist + dir_name + file)
074fe8b725238cbe5eb7b8735d1c873923825db8
pldorini/python-exercises
/desafios/desafio 22.py
365
3.796875
4
nome = str(input('Nome completo: ')).strip() print('Seu nome em letras maiúsculas é {}'.format(nome.upper())) print('Seu nome em letras minusculas é {}'.format(nome.lower())) print("Seu nome tem ao todo {} letras".format(len(nome) - nome.count(' '))) lista = nome.split() print('O seu primeiro nome é {} e possui {} letras'.format(lista[0], len(lista[0])))
5d1d297267c4f08716c8262af86a6a9c27949039
pldorini/python-exercises
/desafios/desafio 20.py
272
3.71875
4
import random um = str(input('Primeiro aluno: ')) dois = str(input('Segundo aluno: ')) tres = str(input('Terceiro aluno: ')) quatro = str(input('Quarto aluno: ')) lista = [um, dois, tres, quatro] random.shuffle(lista) print('A ordem de apresentação será ') print(lista)
3fdbb3af33dd04e23b0ccf2492c8f66c701d936a
pldorini/python-exercises
/desafios/desafio 65.py
578
3.78125
4
c = '' a = cont = soma = maior = media = menor = 0 while c != 'n': c = str(input('Quer digitar mais valores, [s/n]? ')).lower().strip() if c == 's': n = float(input('Digite um valor: ')) soma += n cont += 1 if n < a: menor = n elif n > a: maior = n a = n media = soma / cont if c == 'n': print('Fim do programa.') break print('A media de todos os {} valores é de {:.2f}'.format(cont, media)) print('enquanto o maior valor foi {} e o menor foi {}'.format(maior, menor))
c7eac4a972e857fd9489d84f0f08d14f23f448c8
pldorini/python-exercises
/desafios/desafio 18.py
268
3.828125
4
import math n = float(input('Valor do ângulo: ')) sen = math.sin(math.radians(n)) cos = math.cos(math.radians(n)) tan = math.tan(math.radians(n)) print('O valor do seno de {} é {:.2f}, o valor do cosseno é {:.2f} e sua tangente é {:.2f}'.format(n, sen, cos, tan))
6fe89f958c96058692b1c8e2be8ef49877503f36
pldorini/python-exercises
/desafios/desafio 30.py
121
4
4
n = int(input('Digite um numero inteiro: ')) if n%2==0: print('O numero é par') else: print('O numero é impar')
99d5ad9036f39ddea80b1d4178581510f9dec5b0
pldorini/python-exercises
/desafios/desafio 40.py
308
3.8125
4
n1 = float(input('Nota da p1: ')) n2 = float(input('Nota da p2: ')) media = (n1 + n2) / 2 if media < 5: print('Sua média foi de {}, REPROVADO.'.format(media)) elif media < 7: print('Sua media foi de {}. RECUPERAÇÃO'.format(media)) else: print('Sua média foi de {}. APROVADO'.format(media))
d99281def64d41d40d3264d3aabe241a14e4c3bc
pldorini/python-exercises
/desafios/desafio 87.py
692
3.65625
4
lista = [ [0, 0, 0 ], [0, 0, 0], [0, 0, 0] ] spares = somac = maior = 0 for l in range(0, 3): for c in range(0, 3): lista[l][c] = int(input(f'Digite um valor para {l, c}: ')) print('-='*25) for l in range(0, 3): for c in range(0, 3): print(f'[{lista[l][c]:^5}]', end='') print() print('-='*25) par = [] for l in range(0, 3): for c in range(0, 3): if lista[l][c] % 2 == 0: par.append(lista[l][c]) for v in par: spares += v print(f'A soma dos numeros pares é {spares}') for l in range(0, 3): somac += lista[l][2] print(f'A soma dos elementos da terceira coluna é {somac}') print(f'O maior valor da segunda linha é {max(lista[1])}')
ab46e36000c9a98face451c7e2dbc387bd09526c
pldorini/python-exercises
/desafios/desafio 103.py
289
3.6875
4
def ficha(nome, gol): print(f' O jogador {nome} fez {gol} gol(s) no campeonato') n = str(input('Nome do Jogador: ')) g = str(input('Numero de gols: ')) if g.isnumeric(): g = int(g) else: g = 0 if n.strip() == '': n = '<Desconhecido>' ficha(n, g) else: ficha(n, g)
dcab7748453c619890b5472acefac45c3b2fb15b
pldorini/python-exercises
/desafios/desafio 26.py
285
3.90625
4
x = str(input('Digite uma frase: ')).strip().upper() print('A letra', '"a"', 'aparece {} vezes'.format(x.count('A'))) print('A letra "a" aparece na posição {} na primeira vez'.format(x.find('A')+1)) print('A letra "a" aparece na posição {} na ultima vez'.format(x.rfind('A')+1))
9c749d809605b4d6342a8ff41334a4b510a28bac
pkray91/laravel
/function/p11.py
79
3.53125
4
def sum(*b): c = 0 for x in b: c = c+x #print(c) print(c) sum(2,2,3,4,5)
e5a098ea96c6ae7fa002678f3db41e24cad21731
pkray91/laravel
/list/removelist.py
220
3.71875
4
list = ["apple", "banana", "cherry",'guava','banana']; #list.pop(2); #list.pop();will remove last value #list.remove('banana'); #del list[0:2];To delete multiple values #list.clear(); mylist=list.copy(); print(mylist);
02d2c723586f0b98c48dde041b20e5ec86809fae
pkray91/laravel
/string/string.py
1,254
4.4375
4
print("Hello python"); print('Hello python'); x = '''hdbvfvhbfvhbf''' y = """mdnfbvnfbvdfnbvfvbfm""" print(y) print(x) a='whO ARE you Man'; print(a); print(a.upper()); print(a.lower()); print(len(a)); print(a[1]); #sub string not including the given position. print(a[4:8]); #The strip() method removes any whitespace from the beginning or the end: b=" hello "; print(b); print(b.strip()); print(b.replace('h','l')); #The split() method splits the string into substrings if it finds instances of the separator: print(a.split(' ')); print(a.split('a')); #As we learned in the Python Variables chapter, we cannot combine strings and numbers like this: #The format() method takes unlimited number of arguments, and are placed into the respective placeholders: age=36; c='I am going home {}'; print(c.format(age)); quant=20; age=28; mobile=898767898; txt='total men was {} and their age was {} and have only one mobile no is {}'; print(txt.format(quant,age,mobile)); age=36; c='I am going home {}'; print(c.format(age)); quant=20; age=28; mobile=898767898; txt='total men was {2} and their age was {0} and have only one mobile no is {1}'; print(txt.format(quant,age,mobile)); #reverse the string. rev= 'hello python'[::-1]; print(rev);
0bddbc86afd48fbdb488be7f1bc28d3622a6677c
pkray91/laravel
/loop/star/prime2.py
137
4.125
4
num = int(input("Enter a number:-")) for x in range(2,num): if(num%x==0): print('not prime') break else: print('number is prime')
122824735c955da08bc9b1a52beeddddda16d4e6
pkray91/laravel
/cinput/p1.py
64
3.5625
4
print("enter your name") x= input(); print("hello dear " + x);
31e333d434cb484995f4cac6ba1c6617cd7286e0
pkray91/laravel
/oops/insmethod2.py
824
3.625
4
#instant method which is work with instant var #class method which is work with class var #static method ->which not work with class or instant var and #work for some difference purpose is callled static metod class student: school = "DAV" def __init__(self,m1,m2,m3): self.m1 = m1 self.m2 = m2 self.m3 = m3 def get_m1(self): return self.m1 @classmethod#decorator def get_school(cls): return cls.school @staticmethod def info(): print("I am static method and with other things like fectorial and all") def avg(self):#instant method which is work for obj(this is two type accesor method and mutator method) return (self.m1 + self.m2 + self.m3)/3 s1 = student(20,30,40); s2 = student(30,40,50); print(s1.avg()); print(s2.avg()); print(s1.get_school()) s1.info()
2bd8036e81a181e025079d9a7b994bdd1e3f8a95
pkray91/laravel
/loop/table.py
67
3.859375
4
for x in range(1,11): a = "5 X {} =>" print(a.format(x),x*5)
9079f259263abeb9d14d3ea21ce3aa54befdc327
pkray91/laravel
/oops/ooverloading.py
478
3.9375
4
'''a= 5; b= 10; c= '20' d='50' print(a+b); print(int.__add__(a,b)); print(str.__add__(c,d));''' class student: def __init__(self,m1,m2): self.m1 = m1 self.m2 = m2 def __add__(self,other): m1 = self.m1 + other.m1; m2 = self.m2 + other.m2; s3 = student(m1,m2); return s3; s1= student(33,55) s2= student(44,34) s3= s1+s2;#(student__add__(s1,s2))it wiil not add because our student dont have the add methode for students. print(s3.m1); print(s3.m2);
5539edcc841528d1fc071b5f0cf9745ca5a36d9a
pkray91/laravel
/oops/encapsulation.py
499
3.828125
4
class car: def __init__(self,color,speed): self.__speed = speed self.__color = color # def set_speed(self,value): # self.__speed = value # def get_speed(self): # return self.__speed # def set_color(self,value): # self.__color = value # def get_color(self): # return self.__color ford = car('red',200); honda = car('green',300); audi = car('blue',400); ford.set_speed(500); ford.set_color('purole'); ford.__speed=600; print(ford.get_speed()) print(ford.get_color())
e7ff13ed4f9552c927e7966a538d10d5e485cd37
pkray91/laravel
/lambda/p1.py
211
3.8125
4
#A lambda function is a small anonymous function. #lambda arguments : expression.(syntax) #A lambda function can take any number of arguments, # but can only have one expression x= lambda a: a+10; print(x(10))
b441974e584a0612f27557dc90fbc5c3467d375f
VISH01AL/sqlite3_learn
/Bank mangament/mainprogram.py
6,909
3.875
4
import sqlite3 def create_connection(db_file): conn = None try: conn = sqlite3.connect(db_file) except Error as e: print(e) return conn def accexist(accno,c): c.execute("""select accno from customer where accno=:accno""",{'accno':accno}) li=c.fetchone() if li: return True else: return False def option1(): with conn: c=conn.cursor() accno=None fname=None lname=None bal=None try: accno=int(input('enter accno:')) fname=input('enter fname:') lname=input('enter lname:') bal=int(input('enter first time deposit:')) except: print("<<<please entet valid details>>>") return if not accexist(accno,c): c.execute("""Insert into customer values(:accno,:fname,:lname,:bal)""", {'accno':accno,'fname':fname,'lname':lname,'bal':bal}) conn.commit() print("<<<transcation successful>>>") else: print("<<<accno is taken please enter another unique accno>>>") def option2(): with conn: c=conn.cursor() accno=None try: accno=int(input('enter accno:')) dep=int(input('enter deposit amount:')) if dep<0: print("please enter positive deposit") return except: print("<<<please enter valid details>>>") return c.execute("""select bal from customer where accno=:accno""",{'accno':accno}) li=c.fetchall() if len(li)==0: print("<<<accno not found please enter a valid accno>>>") else: c.execute("""update customer set bal=:bal where accno=:accno""", {'bal':li[0][0]+dep,'accno':accno}) conn.commit() print("<<<transcation successful>>>") def option3(): with conn: c=conn.cursor() accno=None try: accno=int(input('enter accno:')) wit=int(input('enter withdrawl amount:')) if wit<0: print("<<<please enter positive withdraw>>>") return except: print("<<<please enter valid details>>>") return c.execute("""select bal from customer where accno=:accno""",{'accno':accno}) li=c.fetchall() if li[0][0]<wit: print("<<<you don't have sufficient balance>>>") print("<<<your balance is:",li[0][0],">>>") return if len(li)==0: print("<<<accno not found please enter a valid accno>>>") else: c.execute("""update customer set bal=:bal where accno=:accno""", {'bal':li[0][0]-wit,'accno':accno}) conn.commit() print("<<<transcation successful>>>") def option4(): with conn: c=conn.cursor() try: accno=int(input('enter your accno:')) except: print("<<<please enter a valid accno>>>") c.execute("select bal from customer where accno=:accno", {'accno':accno}) li=c.fetchall() if len(li)==0: print('<<<please enter a valid accno>>>') else: print("the accno balance is:",li[0][0]) print("<<<transcation successful>>>") def option5(): with conn: c=conn.cursor() c.execute("select * from customer") li=c.fetchall() print("accno fname lname balance") for x in li: print(x) print("<<<transcation successful>>>") def option6(): with conn: c=conn.cursor() accno=None try: accno=int(input('enter your accno to be deleted:')) except: print("<<<please enter a valid accno>>>") if accexist(accno,c): c.execute("""Delete from customer where accno=:accno""", {'accno':accno}) conn.commit() print("<<<account deleted>>>") else: print("<<<account could not be found>>>") def option7(): with conn: c=conn.cursor() accno=None fname=None lname=None bal=None try: accno=int(input('enter your accno:')) fname=input('enter fname for update:') lname=input('enter lname for update:') bal=int(input('enter new balance:')) except: print("<<<please enter a valid accno>>>") if not accexist(accno,c): print("<<<accno does not exist>>>") else: c.execute("""select * from customer where accno=:accno""",{'accno':accno}) li=c.fetchone() c.execute("""update customer set fname=:fname,lname=:lname,bal=:bal where accno=:accno""", {'fname':fname,'lname':lname,'bal':bal,'accno':accno}) conn.commit() print("<<<account details updated from",li,"to",fname," ",lname," ",bal,">>>") print("transaciton completed") def main(): print("WELCOME TO BANK") while True: print("press an number") print("NEW ACCOUNT-1") print("DEPOSIT AMOUNT-2") print("WITHDRAW AMOUNT-3") print("BALANCE ENQUIRY-4") print("ALL ACCOUNT HOLDER LIST-5") print("CLOSE AN ACCOUNT-6") print("MODIFY AN ACCOUNT-7") print("EXIT-8") option=None try: option=int(input()) except: print("--------------please enter a valid option------------") if option>8: print("--------------please enter a valid option------------") continue elif option==1: option1() elif option==2: option2() elif option==3: option3() elif option==4: option4() elif option==5: option5() elif option==6: option6() elif option==7: option7() else: break if __name__=='__main__': #used for first time creation of database and table ''' conn=create_connection('Customer.db') c=conn.cursor() c.execute("create table customer (accno integer,fname text,lname text,bal integer)") conn.commit() conn.close() ''' conn=create_connection('Customer.db') main() #to show all the data in tables ''' with conn: c=conn.cursor() c.execute("select * from customer") print(c.fetchall()) '''
02856d48e4fedd6645699e7fc4929e80e1ffac7e
561nano/Python_Change_Calculator
/value-count.py
1,299
3.734375
4
# Provide the count of each value (highest to lowest) countOfValue = {100: 2, 50: 10, 20: 10, 10: 10, 5: 10, 1: 10, .25: 10, .10: 1, .05: 10, .01: 10} # Provide the change need to return changeNeeded = 200.98 # The list that will give you the change you need, what is left in the register and if there is not enough money in # the draw to give you the total that is missing def i_need_change(count_of_value, change_needed): change_back = [] for i in count_of_value.keys(): changeCount = change_needed / i if changeCount >= 1 and count_of_value[i] >= int(changeCount): change_back.append((i, int(changeCount))) change_needed = change_needed - (i * int(changeCount)) count_of_value[i] = count_of_value[i] - int(changeCount) elif changeCount >= 1 and count_of_value[i] > 0: change_back.append((i, count_of_value[i])) change_needed = change_needed - (i * count_of_value[i]) count_of_value[i] = 0 if 0.009 <= change_needed <= 0.01: change_needed = 0.00 return {"count_of_value": count_of_value, "change_back": change_back, "change_needed": change_needed} x = i_need_change(countOfValue, changeNeeded) print(x["count_of_value"]) print(x["change_back"]) print(x["change_needed"])
64b3b105be12ab35fb7f6ae74f390d12cc479da2
PropeReferio/practice-2
/pp16.py
821
3.875
4
# Write a password generator in Python. Be creative with how you generate passwords # - strong passwords have a mix of lowercase letters, uppercase letters, numbers, # and symbols. The passwords should be random, generating a new password every time # the user asks for a new password. Include your run-time code in a main method. import random chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-.,;?' ranpass = ''.join([chars[random.randint(0, len(chars) - 1)] for _ in range(0, random.randint(11,17))]) #selects a char at random #Repeats random selection at least 10 times, up to 16 times # ranpass = '' # for _ in range(random.randint(10,17)): # ranpass += chars[random.randint(0, end - 1)] print(ranpass)
8f145d94b26e5f8fa733c0e349a5154f82b8b004
PropeReferio/practice-2
/try_except.py
496
3.5625
4
try: f = open('corrupt.txt') # var = bad_var if f.name == 'corrupt.txt': raise Exception except FileNotFoundError: print('Sorry, that file doesn\'t exist.') except NameError as e: print('There was a problem with a variable name: ', e) except Exception: print('Error!') else: #This block fires when the try block has no problem print(f.read()) f.close() finally: #This always happens, regardless of errors # Useful for closing files, closing connections, etc. print('We\'re done!!')
eb14ce689ed798211cb801ecae29892e0c23297c
PropeReferio/practice-2
/spiral.py
1,428
4.03125
4
# This problem was asked by Amazon. # Given a N by M matrix of numbers, print out the matrix in a clockwise spiral. # For example, given the following matrix: matrix = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]] # You should print out the following: # 1 # 2 # 3 # 4 # 5 # 10 # 15 # 20 # 19 # 18 # 17 # 16 # 11 # 6 # 7 # 8 # 9 # 14 # 13 # 12 spiral = [(0, 1), (1, 0), (0, -1), (-1, 0)] z = 0 direction = spiral[z] #This might not work, direction might not change as z changes visited = [[False for _ in range(len(matrix[0]))] for _ in range(len(matrix))] y, x = 0, 0 while True: # if all([all(lst) for lst in visited]): # Time: O(n**2), where n is total # number of elements in matrix. We can get down to O(4n) by checking all # 4 sides for visited before we move. # break print(matrix[y][x]) visited[y][x] = True if y + direction[0] >= len(matrix) or x + direction[1] >= len(matrix[0])\ or x + direction[1] < 0 or visited[y+direction[0]][x+direction[1]]: z = (z + 1) % 4 direction = spiral[z] y += direction[0] x += direction[1] if visited[y][x]: break #This is even better. If we've just changed direction because the next #node was visited or out of bounds, and the NEW next node is ALSO visited #or out of bounds, then we've visited every node. O(n).
d00abf93039f9475fa21b3159bc0d093bc5b2312
janthenelli/Python-Phrase-Hunters
/phrasehunter/game.py
2,887
3.859375
4
# Create your Game class logic in here. import random import re from phrase import Phrase from phraseslist import RANDOM_PHRASES class Game: def __init__(self, phrases): self.phrases = [Phrase(phrase) for phrase in phrases] self.selected_phrase = random.choice(self.phrases) self.lives = 5 self.game_active = True def current_game_state(self, state): if state == 'start': self.game_active = True elif state == 'stop': self.game_active = False return self.game_active def get_player_input(self): no_input = True while no_input: answer = input("Please guess a letter: ") if not re.search(r'[a-z]', answer, re.IGNORECASE): print(f"'{answer}' is not a valid guess, try again.\n") elif len(answer) != 1: print(f"'{answer}'' is too long. Please enter only one character per guess.\n") else: no_input = False return answer.lower() def check_win_loss(self): if self.lives == 0: self.current_game_state('stop') print('Oh no, you have run out of guesses!') elif self.selected_phrase.solved: self.current_game_state('stop') print(self.selected_phrase.show_phrase()) print('\nCongratulations! You guessed the phrase correctly!') def play_game(self): print("\nWelcome to Phrase Hunters!\n") while self.game_active: print(self.selected_phrase.show_phrase() + '\n') player_guess = self.get_player_input() print('\n') if player_guess not in self.selected_phrase.phrase: self.lives -= 1 print("Oops, that's not in the phrase. You now have {} lives left out of 5\n".format(self.lives)) self.check_win_loss() else: for letter in self.selected_phrase.characters_in_phrase: letter.check_char_guessed(player_guess) self.selected_phrase.check_phrase_solved() self.check_win_loss() self.ask_to_replay() def ask_to_replay(self): while True: replay = input("\nWould you like to play again? Y/N: ") if replay.lower() == 'y': self.current_game_state('start') break elif replay.lower() == 'n': self.current_game_state('stop') print("\nThanks for playing!\n") break else: print("Please enter either 'Y' or 'N'\n") if self.game_active: self.restart_game() def restart_game(self): new_game = Game(RANDOM_PHRASES) new_game.play_game()
0ee9e3d684e4a810701066ada2cc0daf04347abf
WebClub-NITK/Hacktoberfest-2k20
/Algorithms/14_disjoint_set/disjoint-set.py
989
4.1875
4
# Python3 program to implement Disjoint Set Data Structure for union and find. class DisjSet: def __init__(self, n): self.rank = [1] * n self.parent = [i for i in range(n)] # Finds set of given item x def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def Union(self, x, y): xset = self.find(x) yset = self.find(y) if xset == yset: return if self.rank[xset] < self.rank[yset]: self.parent[xset] = yset elif self.rank[xset] > self.rank[yset]: self.parent[yset] = xset else: self.parent[yset] = xset self.rank[xset] = self.rank[xset] + 1 # Driver code obj = DisjSet(5) obj.Union(0, 2) obj.Union(4, 2) obj.Union(3, 1) if obj.find(4) == obj.find(0): print('Yes') else: print('No') if obj.find(1) == obj.find(0): print('Yes') else: print('No')
e4ea5fe333cb183973ef2d48773931461168d86b
WebClub-NITK/Hacktoberfest-2k20
/Algorithms/64_Schools_Covid_19/schools.py
2,651
3.96875
4
"""Solution to Schools During Covid-19 problem.""" import io import sys from typing import Iterable, List, Set, Tuple class NoSolutionError(Exception): """Raised when there is no solution.""" pass class SchoolClass: """School class with number of students and friendships.""" def __init__(self, num_students: int, friendships: List[Set[int]]): self.num_students = num_students self.friendships = friendships # Friends of n are stored in n - 1 @classmethod def from_iter(cls, it: Iterable[Tuple[int, int]]): num_students, num_friendships = next(it) friendships = [set() for _ in range(num_students)] for _ in range(num_friendships): student, friend = next(it) friendships[student - 1].add(friend) friendships[friend - 1].add(student) return cls(num_students, friendships) @classmethod def from_list(cls, l: List[Tuple[int, int]]): return SchoolClass.from_iter(iter(l)) def make_groups(self) -> Tuple[Set[int], Set[int]]: """Make two groups with no friendship in each group. Returns a valid solution if there is any, otherwise raise NoSolutionError. """ groups = [set(), set()] # Group n is stored in index n - 1 unvisited = set(range(1, self.num_students + 1)) while unvisited: to_visit = [(unvisited.pop(), 0)] while to_visit: student, group = to_visit.pop() groups[group].add(student) other_group = group ^ 1 # Toggle index between 0 and 1 for friend in self.friendships[student - 1]: if friend in groups[group]: raise NoSolutionError if friend in unvisited: to_visit.append((friend, other_group)) unvisited.remove(friend) return groups def print_groups(self, out: io.TextIOBase = sys.stdout) -> None: """Make two groups with no friendship in each group and print solution. If there is no solution, print -1. """ try: groups = self.make_groups() for student in range(1, self.num_students + 1): if student in groups[0]: group = 1 elif student in groups[1]: group = 2 else: raise Exception( f'Student {student} is not listed in any group.') out.write(f'{student} {group}\n') except NoSolutionError: out.write('-1\n')
011bc9a9a3822a5d01088c5d77b0deedeedfe53a
dannydijkzeul/datascienceTest
/datascienceTest.py
7,324
3.6875
4
''' Authors: Danny Dijkzeul 10554386 ''' class Article(): # Creates article object with all information of the articles content def __init__(self, docno, docid, date, section, length, headline): self.docno = docno self.docid = docid self.date = date self.section = section self.length = length self.headline = headline self.byline = "" self.text = "" self.graphic = "" # Add byline content to article object def addByline(self, byline): self.byline = byline # Add text content to article object def addText(self, text): self.text = text # Add graphic content to article object def addGraphic(self, graphic): self.graphic = graphic # Returns an array of all words that where found in a single article def getAllText(self): text = self.docno + " " + self.docid + " " + self.date text += " " + self.section + " " + self.length + " " + self.headline text += " " + self.byline + " " + self.text + " " + self.graphic # Remove puncuation using regex text = re.sub(r'[^\w\s]',' ',text) # Make the string fully lowercase text.lower() # Split the text into an array self.wordArray = text.split(" ") return self.wordArray def createArticleObjects(args): articles = [] # Open given file with open(args.file) as f: line = f.readline().rstrip('\n') while line: if line == "<doc>": docno = f.readline().rstrip('\n').split(' ')[1] docid = f.readline().rstrip('\n').split(' ')[1] # This array contains information of the article which is # date, section, length, headline in that order informationArray = [] # Loop through the first part of the document and fill the # informationArray for i in range(0,3): next(f) next(f) info = f.readline().rstrip('\n') informationArray.append(info) for i in range(0,2): next(f) line = f.readline().rstrip('\n') # Add headline to informationArray and check for mutliple line # headline if line == "<headline>": line = f.readline() headline = "" while line != "</headline>": if "p>" not in line: headline += line line = f.readline().rstrip('\n') informationArray.append(headline) # Creates the article object using the informationArray article = Article(docno, docid, informationArray[0], informationArray[1],informationArray[2],informationArray[3]) articles.append(article) line = f.readline().rstrip('\n') # Checks for the byline in the article and adds these to the # article object if line == "<byline>": line = f.readline() byline = "" while line != "</byline>": if "p>" not in line: byline += " " + line line = f.readline().rstrip('\n') article.addByline(byline) # Checks for the text in the article and adds these to the # article object if line == "<text>": line = f.readline() text = "" while "</text>" not in line: if "p>" not in line: text += " " + line line = f.readline().rstrip('\n') article.addText(text) # Checks for the grahic in the article and adds these to the # article object if line == "<graphic>": line = f.readline() graphic = "" while "</graphic>" not in line: if "p>" not in line: graphic += " " + line line = f.readline().rstrip('\n') article.addGraphic(graphic) return articles def createWordDict(articles): # Creates a dict where new keys always have an empty list as value wordDict = defaultdict(list) for i in range(0, len(articles)): # Counts all words in the array given by getAllText countedWords = Counter(articles[i].getAllText()) # Adds the count to the defaultdict with the correct article number for j in countedWords.keys(): wordDict[j].append([i+1, countedWords[j]]) # Delete empty word del wordDict[""] return wordDict def findSimilarWords(wordDict): deletedKeys = [] for i in wordDict.keys(): for j in wordDict.keys(): # Use the Levenshtein Distance algorithm with fuzzy wuzzy package # to find the similarities between words. When 90% is similar # The wordcount is added togehter if fuzz.ratio(i,j) > 90 and i is not j: wordDict[i] = addWordsCounts(wordDict[i], wordDict[j]) # Check if word was not already know if j not in deletedKeys: deletedKeys.append(j) # Delete the words that were added togehter for a in deletedKeys: del wordDict[a] return wordDict def addWordsCounts(wordCount1, wordCount2): for i in range(0, len(wordCount2)): for j in range(0, len(wordCount1)): # Adds count if the word was in the same document if wordCount1[j][0] == wordCount2[i][0]: wordCount1[j][1] += wordCount2[i][1] break # Adds count if the word did not appear in other documents elif (j == len(wordCount1)-1) and wordCount1[j][0] != wordCount2[i][0]: wordCount1.append(wordCount2[i]) return wordCount1 def makeHistogram(wordDict): countedWords = [] # Extract all wordcounts from the word dictonairy for i in wordDict.keys(): oneWordOccurance = 0 for j in wordDict[i]: oneWordOccurance += j[1] countedWords.append(oneWordOccurance) # Create numpy array for the histogram countedWords = np.asarray(countedWords) # Make histogram hist, bins = np.histogram(countedWords, bins = max(countedWords)) plt.hist(hist, bins) plt.title("histogram") plt.show() # program entry point. if __name__ == '__main__': import sys import argparse import re from collections import Counter, defaultdict from fuzzywuzzy import fuzz import numpy as np from matplotlib import pyplot as plt # Argparser which takes the file as argument p = argparse.ArgumentParser() p.add_argument('--file', help='article that needs to be parsed', default='article.txt') args = p.parse_args(sys.argv[1:]) articles = createArticleObjects(args) wordDict = createWordDict(articles) wordDict = findSimilarWords(wordDict) makeHistogram(wordDict) # print(wordDict)
5098ab1579cf8a763bf49349ad48a14a245744bc
Hermotimos/EvaluationsDB
/db_setup.py
5,180
3.84375
4
""" Create 'evaluations' database with random evaluations for predefined titles. Steps: 1. Creates database (drops one if exists). 2. Creates tables (movies_evaluations, tvseries_evaluations, pcgames_evaluations, boardgames_evaluations). 3. Populates tables with random number of random-score evaluations for predefined lists of titles. TODO: - implement XML and JSON data types - implement XPath and JsonPath queries within SQL """ import mysql.connector from random import random # CONNECT TO MySQL AND CREATE DATABASE password = input('Enter password to connect to database:\n') mydb = mysql.connector.connect(host='localhost', user='root', passwd=password) mycursor = mydb.cursor() mycursor.execute("DROP DATABASE IF EXISTS evaluations") mycursor.execute("CREATE DATABASE evaluations") mycursor.execute("SHOW DATABASES") for db in mycursor: print('database: ', db[0]) mydb = mysql.connector.connect(host='localhost', user='root', passwd=password, database='evaluations') mycursor = mydb.cursor() # CREATE TABLES tables_to_create = ['movies_evaluations', 'tvseries_evaluations', 'pcgames_evaluations', 'boardgames_evaluations'] for table in tables_to_create: mycursor.execute("DROP TABLE IF EXISTS {}".format(table)) for table in tables_to_create: mycursor.execute("CREATE TABLE {} " "(" "evaluation_id INT AUTO_INCREMENT PRIMARY KEY," "title VARCHAR(200) NOT NULL," "score TINYINT(2) NOT NULL," "creation_time DATETIME DEFAULT CURRENT_TIMESTAMP" ")".format(table)) mycursor.execute("SHOW TABLES") for table in mycursor: print('table: ', table[0]) # POPULATE TABLES WITH RANDOM NUMBER OF EVALUATIONS HAVING RANDOM EVALUATION SCORE def generate_evaluations(titles): """Returns list of erandom evaluations for titles provided as arg. Parameters ---------- titles (any iterable type): Iterable with titles. Returns ------- list: Returns list of 2-element tuples [(str, int), (str, int), ...] where int is a random number 1-10. """ random_evaluations = [] for title in titles: n = 0 while n <= round(random()*(10-1)+1, 0): random_evaluations.append((title, round(random()*(10-1)+1, 0))) n += 1 return random_evaluations movies_titles = [ 'Blade Runner', 'Contact', 'Interstellar', 'Truman Show', 'Arrival', 'Solaris', 'Ex Machina', 'Eternal Sunshine of The Spotless Mind', 'Her', 'Moon', 'Dune' ] tvseries_titles = [ 'The Wire', 'The Shield', 'Battlestar Galactica', 'Twin Peaks', 'True Detective', 'Game of Thrones', 'The Expanse', 'Altered Carbon', 'Deadwood', 'Sons of Anarchy', 'Taboo' ] pcgames_titles = [ 'Medieval Total War', 'Shogun Total War', 'Shogun 2 Total War', 'Medieval 2 Total War', 'Rome Total War', 'Diablo', 'Diablo 2', 'Icewind Dale 2', 'Fallout', 'Heroes of Might And Magic III', 'Quake III: Arena', ] boardgames_titles = [ 'Battlestar Galactica', 'Game of Thrones', 'Carcassonne', 'Dixit', 'Magiczny Miecz', 'The Settlers of Catan' ] random_evals_movies = generate_evaluations(movies_titles) random_evals_tvseries = generate_evaluations(tvseries_titles) random_evals_pcgames = generate_evaluations(pcgames_titles) random_evals_boardgames = generate_evaluations(boardgames_titles) insert_into_movies_evaluations = "INSERT INTO movies_evaluations (title, score) VALUES (%s, %s)" insert_into_tvseries_evaluations = "INSERT INTO tvseries_evaluations (title, score) VALUES (%s, %s)" insert_into_pcgames_evaluations = "INSERT INTO pcgames_evaluations (title, score) VALUES (%s, %s)" insert_into_boardgames_evaluations = "INSERT INTO boardgames_evaluations (title, score) VALUES (%s, %s)" all_evals = [ random_evals_movies, random_evals_tvseries, random_evals_pcgames, random_evals_boardgames ] all_insert_statements = [ insert_into_movies_evaluations, insert_into_tvseries_evaluations, insert_into_pcgames_evaluations, insert_into_boardgames_evaluations ] for elem in range(4): mycursor.executemany(all_insert_statements[elem], all_evals[elem]) mydb.commit()
5af8b2dfcff4a09b489bf1e1dbaa3718fd41bc45
dipprog/Competitive-Programming
/DSA/4. Divide And Conquer/binary_search_dac.py
474
4.03125
4
def binary_search(A, start, end, X): if start <= end: middle = (start + end)//2 if A[middle] == X : return middle if X < A[middle]: return binary_search(A, start, middle-1, X) if X > A[middle] : return binary_search(A, middle+1, end, X) return -1 # number not found if __name__ == '__main__': array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] index = binary_search(array, 0, 9, 10) print(index)
316fe989c7fda250ec21acf42374d85ce43d6e2b
dipprog/Competitive-Programming
/Sorting/insertion_sort.py
273
3.90625
4
def insertion_sort(A): for i in range(len(A)): j=i while (j > 0) and (A[j-1] > A[j]): A[j-1], A[j] = A[j], A[j-1] j = j-1 if __name__ == '__main__': ar = [4, 8, 1, 3, 10, 9, 2, 11, 5, 6] insertion_sort(ar) print(ar)
7ca1555260cf8076aa6202d3512a2267b67116e0
dipprog/Competitive-Programming
/Heap And Priority Queue/max_priority_queue.py
2,633
3.5
4
heap_size = 0 tree_array_size = 20 INF = 100000 # Get right child def get_right_child(A, index): if ((2*index + 1) < len(A)) and (index >=1): return (2*index + 1) return -1 # Get left child def get_left_child(A, index): if ((2*index) < len(A)) and (index >=1): return (2*index) return -1 # Get parent def get_parent(A, index): if (index < len(A)) and (index > 1): return index//2 return -1 # MAX-HEAPIFY function def max_heapify(A, index): left_child_index = get_left_child(A, index) right_child_index = get_right_child(A, index) # Find largest among them largest = index if (left_child_index > 0) and (left_child_index <= heap_size): if A[left_child_index] > A[largest]: largest = left_child_index if (right_child_index > 0) and (right_child_index <= heap_size): if A[right_child_index] > A[largest]: largest = right_child_index # if node is not the largest and node is not a heap if largest != index: A[index], A[largest] = A[largest], A[index] max_heapify(A, largest) # Build MAX-HEAP function def build_max_heap(A): for i in range(heap_size//2, 0, -1): max_heapify(A,i) # ***************************Max-Prioriry Queue Operation************************** # Get Maximum def maximum(A): return A[1] # Extract Maximum def extract_maximum(A): global heap_size maxE = A[1] A[1] = A[heap_size] heap_size = heap_size -1 max_heapify(A, 1) return maxE # Increase Key def increase_key(A, i, key): A[i] = key while (i > 1) and (A[get_parent(A,i)] < A[i]): A[i], A[get_parent(A,i)] = A[get_parent(A,i)], A[i] i = get_parent(A, i) # Decrease Key def decrease_key(A, i, key): A[i] = key max_heapify(A,i) # Insert Key def insert(A, key): global heap_size heap_size = heap_size+1 A[heap_size] = -1*INF increase_key(A, heap_size, key) # Driving function if __name__ == '__main__': A = [None]*tree_array_size insert(A, 20) insert(A, 15) insert(A, 8) insert(A, 10) insert(A, 5) insert(A, 7) insert(A, 6) insert(A, 2) insert(A, 9) insert(A, 1) print(A[1:heap_size+1]) increase_key(A, 5, 22) print(A[1:heap_size+1]) print(maximum(A)) print(extract_maximum(A)) print(A[1:heap_size+1]) print(extract_maximum(A)) print(extract_maximum(A)) print(extract_maximum(A)) print(extract_maximum(A)) print(extract_maximum(A)) print(extract_maximum(A)) print(extract_maximum(A)) print(extract_maximum(A)) print(extract_maximum(A))
926e03d025b30bb6437458666d62d68a8f916cdb
derekcswong/BlackJack
/tests/test_Hand.py
751
3.78125
4
import unittest from Card import Card from Hand import Hand class TestHand(unittest.TestCase): def test_add_card(self): hand = Hand() c1 = Card("Spades", "Two") c2 = Card("Hearts", "Jack") hand.add_card(c1) self.assertEqual(hand.value, 2) hand.add_card(c2) self.assertEqual(hand.value, 12) def test_ace_adjust(self): hand = Hand() c1 = Card("Spades", "Jack") c2 = Card("Spades", "Queen") hand.add_card(c1) hand.add_card(c2) ace = Card("Spades", "Ace") hand.add_card(ace) self.assertEqual(31, hand.value) hand.ace_adjust() self.assertEqual(21, hand.value) if __name__ == '__main__': unittest.main()
e83a435f773d23999da8569f04e7d4c4f4a7829a
WoshoForegun/1-to-10
/brosly.py
57
3.5
4
i = 1 while i<=10: if i != 5: print(i) i=i+1
e6a64eed1788c406cc17469d221c3caa55e7d89a
zarifmahmud/DoodleMyWorld
/voice_doodle.py
4,056
3.9375
4
""" Functions to recognize and process voice commands """ import security import azure.cognitiveservices.speech as speechsdk from draw import grid_fill, grid_draw, erase_image def speech_recognize() -> str: """ Using Microsoft Azure to convert your speech into text. It will process after you finish speaking. """ speech_key, service_region = security.azure_speech_key, "eastus" speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region) # Creates a recognizer with the given settings speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config) print("Say something...") result = speech_recognizer.recognize_once() # Checks result. if result.reason == speechsdk.ResultReason.RecognizedSpeech: print("Recognized: {}".format(result.text)) return result.text elif result.reason == speechsdk.ResultReason.NoMatch: print("No speech could be recognized: {}".format(result.no_match_details)) elif result.reason == speechsdk.ResultReason.Canceled: cancellation_details = result.cancellation_details print("Speech Recognition canceled: {}".format(cancellation_details.reason)) if cancellation_details.reason == speechsdk.CancellationReason.Error: print("Error details: {}".format(cancellation_details.error_details)) return "" def keyword_finder(speech: str) -> list: """ Attempts to find command phrases in the speech transcript. ex: >>> keyword_finder("Nose at 6.3.") >>> ["Nose", (6,3), 0] """ said = speech if said[:-1] == "Erase": return ["Erase", (-1, -1), 0] # Get in form of number dot number potential = (said[-4], said[-2]) said = said.strip() noun = said.split()[0] print(said) if speech[-2].isdigit(): digit = int(speech[-2]) print(digit + 2) if "row" in said or "road" in said or "across" in said: return [noun, (0, digit), 1] elif "column" in said or "down" in said: return [noun, (digit, 0), 2] if potential[0].isdigit() and potential[1].isdigit(): coordinate = (int(potential[0]), int(potential[1])) output = [noun, coordinate, 0] print(coordinate) return output def speech_to_doodle(to_draw=""): """ Speak to draw, using Azure voice recognition You can use voice commands to erase the image, place an image onto a part of the grid, or fill a row or column with something. Keywords: - Erase, to erase the drawing - NOUN on X dot Y, to place a noun at that coordinate. i.e. "Crocodile at 3.4." - NOUN across/down point X/Y, to fill a row or column i.e. "Skyscraper across .5." (You can use dot or point interchangeably. You actually often don't need either, but it helps Azure detect that you're saying a number like 1, rather than a homonym like "won".) """ if to_draw == "": to_draw = keyword_finder(speech_recognize()) if to_draw is not None: noun = to_draw[0].lower() noun = speech_correction(noun) xcor = to_draw[1][0] ycor = to_draw[1][1] fill = to_draw[2] if noun == "erase": erase_image("image.png") elif fill == 1: grid_fill(True, ycor, noun) elif fill == 2: grid_fill(False, xcor, noun) else: grid_draw(xcor, ycor, noun) return to_draw else: print("Sorry! Couldn't catch that.") def speech_correction(noun: str) -> str: """ Corrects common misheard words, and creates shortcut phrases. If you have any, add it to the dictionary! """ misheard_dict = {"son": "sun", "shirt": "t-shirt", "smiley": "smiley face", "year": "ear", "frying": "frying pan", "free": "tree", "suck": "sock", "nodes": "nose"} return misheard_dict[noun] if noun in misheard_dict else noun
b1ce850e7188a0ccd18b09d749deed9d4f24e16d
jnomellini/Python-For-Managers
/variables.py
260
3.734375
4
# Variables are just nicknames # They're plain, lowercase words name = "Mattan Griffel" orphan_fee = 200 teddy_bear_fee = 121.80 total = orphan_fee + teddy_bear_fee print(name, "the total will be", total) print(f"{name} the total will be {total:.2f}")