blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2eccb0fe1805da5cf5d30cb42524bb40cf4a22c1
stackpearson/cs-notes
/lambda_questions/fibonacciSimpleSum2.py
2,805
4.1875
4
def fibonacciSimpleSum2(n): fib_numbers = generate_fibonacci(n) print(fib_numbers) fib_numbers = set(fib_numbers) # O(len(fib_numbers)) time and space # loop for all numbers for first in fib_numbers: # This is O(len(fib_numbers)) = O(log n) because fib numbers almost double each iteration # # "fix" a first number # # loop through the rest # for second in fib_numbers: # O(len(fib_numbers)) # # try adding them together and see if the sum == n # if first + second == n: # return True # # Instead of doing a linear search, we could do a binary search, # # where we guess the middle, if the sum of the two numbers is > n, look left, # # else if sum < n, look right and repeat until we find a a number diff = n - first # does diff exist in fib_numbers? if diff in fib_numbers: # this is O(1) lookup in a set return True return False # helper function to generate fibonacci numbers # only go up to n def generate_fibonacci(n): # F(n) = F(n - 1) + F(n - 2) # F(0) = 0 # F(1) = 1 fib_numbers = [0, 1] # Create a list with two elements, 0 and 1 cur_fib_number = 1 # keep generating fib numbers until the next fib number is > n while cur_fib_number <= n: fib_numbers.append(cur_fib_number) cur_fib_number = fib_numbers[-1] + fib_numbers[-2] return fib_numbers # MY VERSION AND NOTES def fibonacciSimpleSum2(n): # need to find a way to generate fib numbers all the way up to end # then need to find a way to access each # we've generated so we can determine if they can sum to n fibNums = generateFib(n) fibNums = set(fibNums) # need to loop over our set and see if we find a combination of numbers that sums to n # if we do, then n can be represented by the sum of 2 fib numbers for firstNum in fibNums: for secondNum in fibNums: if firstNum + secondNum == n: return True # if we've made it through the entire set and no numbers sum to n, then return false return False # need to generate our fib numbers to recurse through def generateFib(n): # initiate first fib sequence of 0 and 1, then programatically make the rest of them fibNums = [0, 1] #set where we're going to start generating the next fib # newFibNum = 1 while newFibNum <= n: fibNums.append(newFibNum) # F(n) = F(n-1) + F(n-2) # next fib number = last fib # in the list + 2nd to the last fib # in the list # for [0, 1] f = 0 + 1 = 1 # for [0, 1, 1] f = 1 + 1 or 2 # for [0, 1, 1, 2] f = 1 + 2 or 3 etc etc newFibNum = fibNums[-1] + fibNums[-2] return fibNums
589a82a73dda707a468a905449b7e5f50ea212f6
ssmores/hackerrank
/thirtydaysofcoding/day06.py
2,327
4.15625
4
"""30 days of coding for HackerRank. Day 6: Let's Review by AllisonP Objective Today we're expanding our knowledge of Strings and combining it with what we've already learned about loops. Check out the Tutorial tab for learning materials and an instructional video! Task Given a string, S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line (see the Sample below for more detail). Note: 0 is considered to be an even index. Input Format The first line contains an integer, T (the number of test cases). Each line i of the T subsequent lines contain a String, S. Constraints 1 <= T <= 10 2 <= length of S <= 1000 Output Format For each String Sj (where 0 <= j <= T -1 ), print Sj's even-indexed characters, followed by a space, followed by Sj's odd-indexed characters. Sample Input 2 Hacker Rank Sample Output Hce akr Rn ak Explanation Test Case 0: S = "Hacker" S[0] = 'H' S[1] = 'a' S[2] = 'c' S[3] = 'k' S[4] = 'e' S[5] = 'r' The even indices are 0, 2, 4, and the odd indices are 1, 3, 5. We then print a single line of 2 space-separated strings; the first string contains the ordered characters from S's even indices (Hce), and the second string contains the ordered charactesr from S's odd indices (akr). Test Case 1: S = 'Rank' S[0] = 'R' S[1] = 'a' S[2] = 'n' S[3] = 'k' The even indices are 0 and 2, and the odd indices are 1 and 3. We then print a single line of 2 space-separated strings; the first string contains the ordered characters from S's even indices (Rn), and the second string contains the ordered charactesr from S's odd indices (ak). ************** Featured solutions Python 2 t = int(raw_input()) for _ in range(t): line = raw_input() first = "" second = "" for i, c in enumerate(line): if (i & 1) == 0: first += c else: second += c print first, second ************** """ # Enter your code here. Read input from STDIN. Print output to STDOUT T = int(raw_input().strip()) for i in xrange(T): T_temp = map(str,raw_input().strip()) evens = '' odds = '' for j in xrange(len(T_temp)): if j % 2 == 0 or j == 0: evens += T_temp[j] else: odds += T_temp[j] print evens, odds
a82102d910f69fab9884705b1a3e1614d2119852
zhangswings/py_pro
/com/pdsu/Class_control.py
3,003
4.28125
4
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- ''' 访问限制 ''' # 如果要让内部属性不被外部访问,可以把属性的名称前加上两个下划线__, # 在Python中,实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问,所以,我们把Student类改一改: class Student(object): def __init__(self,name,score): self.__name=name self.__score=score def print_score(self): print '%s: %s' % (self.__name,self.__score) def get_name(self): return self.__name def get_score(self): return self.__score def set_score(self, score): self.__score = score # 改完后,对于外部代码来说,没什么变动,但是已经无法从外部访问实例变量.__name和实例变量.__score了: bart = Student('Bart Simpson', 98) # print bart.__name # AttributeError: 'Student' object has no attribute '__name' # 这样就确保了外部代码不能随意修改对象内部的状态,这样通过访问限制的保护,代码更加健壮。 # 但是如果外部代码要获取name和score怎么办?可以给Student类增加get_name和get_score这样的方法: print bart.get_name() # 如果又要允许外部代码修改score怎么办?可以给Student类增加set_score方法: ''' class Student(object): ... def set_score(self, score): self.__score = score ''' bart.set_score(100) print bart.get_name(),bart.get_score() # 你也许会问,原先那种直接通过bart.score = 59也可以修改啊,为什么要定义一个方法大费周折?因为在方法中,可以对参数做检查,避免传入无效的参数: ''' class Student(object): ... def set_score(self, score): if 0 <= score <= 100: self.__score = score else: raise ValueError('bad score') ''' # 需要注意的是,在Python中,变量名类似__xxx__的,也就是以双下划线开头,并且以双下划线结尾的,是特殊变量, # 特殊变量是可以直接访问的,不是private变量,所以,不能用__name__、__score__这样的变量名。 # 有些时候,你会看到以一个下划线开头的实例变量名,比如_name,这样的实例变量外部是可以访问的, # 但是,按照约定俗成的规定,当你看到这样的变量时,意思就是,“虽然我可以被访问,但是,请把我视为私有变量,不要随意访问”。 # 双下划线开头的实例变量是不是一定不能从外部访问呢?其实也不是。 # 不能直接访问__name是因为Python解释器对外把__name变量改成了_Student__name,所以,仍然可以通过_Student__name来访问__name变量: print bart._Student__name # 但是强烈建议你不要这么干,因为不同版本的Python解释器可能会把__name改成不同的变量名。 # 总的来说就是,Python本身没有任何机制阻止你干坏事,一切全靠自觉。
92524194484ebe2da98a5fd35554d3bcc7aac678
injulkarnilesh/python_tryout
/email_slicer.py
304
3.609375
4
email = input("What is your email id? : ").strip(); at_ret_index = email.index("@") user_name = email[:at_ret_index] domain = email[at_ret_index + 1 : ] output_message = "With {} as your email, you got user name {} and domain {}" result = output_message.format(email, user_name, domain) print(result)
7d6708b4775cdea1d794628df78266cf3c6c8174
AhmetTuncel/CodeKata
/CodeKata/6_Rank/Replace_With_Alphabet_Position_Kata.py
516
4.3125
4
""" Welcome. In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. a being 1, b being 2, etc. As an example: """ alphabet = 'abcdefghijklmnopqrstuvwxyz' def alphabet_position(text): text = text.lower() result = '' for i in text: if i.isalpha() == True: result = result + ' ' + str(alphabet.index(i) + 1) return result.lstrip(' ')
232ab1268be20d5654fe5ae815a8342a5a20e7ef
samhenryowen/samhenryowen.github.io
/CS260/projects/runestone/ch5/ch5e3.py
717
3.953125
4
def binarySearch(alist, item): if len(alist) == 0: return False else: midpoint = len(alist) // 2 if alist[midpoint] == item: return True else: if item < alist[midpoint]: newlist = [] for _ in range(0,midpoint): newlist.append(alist[_]) return binarySearch(newlist, item) else: newlist = [] for _ in range(midpoint+1, len(alist)): newlist.append(alist[_]) return binarySearch(newlist, item) testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42, ] print(binarySearch(testlist, 3)) print(binarySearch(testlist, 13))
08812460a49058e4230f76a481b4343b2e98641d
damiati-a/CURSO-DE-PYTHON
/Mundo 2/ex041.py
471
3.90625
4
# Classificando atletas from datetime import date atual = date.today().year nasc = int(input('Qual o ano de nascimento? ')) idade = atual - nasc print('O atleta tem {} anos'.format(idade)) if idade <= 9: print('Classificação MIRIM') elif idade <= 14: print('Classificação INFANTIL') elif idade <= 19: print('Classificação JÙNIOR') elif idade <= 25: print('Classificação SÊNIOR') else: print('Classificação MASTER')
bd31b1bb9a9381596417f9556f60b3b9ff817419
jinshah-bs/Function_2
/intro.py
1,133
4.03125
4
# print("Hello") lists = [1, 5, 8, 0, 45] sorte_list = sorted(lists, reverse=True) # print(sorte_list) # lists.sort() # def addition(x, y, k): # b = 11 # sum_num = x + y*k + b # print(sum_num) # print("b within the function is {}".format(b)) # return sum_num # # a = 10.0 # b = 3.0 # number = addition(a, b, 25) # print(number) # print("b outside the function is {}".format(b)) # def is_palinadrome(string): # rev_string = string[::-1] # return rev_string.casefold() == string.casefold() # # def is_sen_paliandrome(string): # name = '' # for char in string: # if char.isalnum(): # name += char # return is_palinadrome(name) # # # name = str(input("Enter something: ")) # if is_sen_paliandrome(name): # print(f"The name {name} is a plaientrome") # else: # print("Get lost") def addition(x:float, y:float)-> float: """ This function will add two numbers and return the sum :param x: any 'float' value :param y: any 'float' value :return: the sum which is a 'float' """ return x + y a = 10.0 b = 3.0 sum = addition(a, b) print(sum)
73a30c551adfac21c631469ac9c402e7a92cc2db
ItanuRomero/Projeto-Interdisciplinar
/Projeto/Administrator.py
5,331
3.734375
4
from database import * def initialize_administrator(): while True: options = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] print('\nO que você gostaria de fazer?\n') print('1 - Visualizar todas as categorias') print('2 - Inserir nova categoria') print('3 - Remover uma categoria') print('\n') print('4 - Visualizar perguntas de uma categoria') print('5 - Inserir uma nova pergunta para uma categoria') print('6 - Remover uma pergunta') print('\n') print('7 - Visualizar respostas de uma pergunta') print('8 - Inserir uma nova resposta para uma pergunta') print('9 - Remover uma resposta') print('\n') print('10 - SAIR') userChoice = str(input('\n')) if userChoice not in options: print('\nCódigo inserido não é inválido\n') if userChoice == '1': print(f'\nOpção selecionada: {userChoice} - Visualizar todas as categorias\n') categories = select_all_categories() print('ID \tDescrição') for item in range(len(categories)): print(f'{categories[item][0]} \t{categories[item][1]}') elif userChoice == '2': print(f'\nOpção selecionada: {userChoice} - Inserir nova categoria\n') insert_category(str(input('Insira o nome da categoria: '))) print('\nCategoria inserida\n') elif userChoice == '3': print(f'\nOpção selecionada: {userChoice} - Remover uma categoria\n') categoryId = str(input('Insira o ID da categoria: ')) category = select_category_by_id(categoryId) if not category: print('\nCategoria não encontrada') else: delete_category(categoryId) print('\nCategoria removida') elif userChoice == '4': print(f'\nOpção selecionada: {userChoice} - Visualizar perguntas de uma categoria\n') categoryId = str(input('Insira o ID da categoria: ')) category = select_category_by_id(categoryId) if not category: print('\nCategoria não encontrada') else: questions = select_all_questions_by_category(categoryId) print(f'\nCategoria selecionada: {category[0][1]}') print('\nID \tPergunta') for item in range(len(questions)): print(f'{questions[item][0]} \t{questions[item][1]}') elif userChoice == '5': print(f'\nOpção selecionada: {userChoice} - Inserir uma nova pergunta para uma categoria\n') categoryId = str(input('Insira o ID da categoria: ')) category = select_category_by_id(categoryId) if not category: print('\nCategoria não encontrada') else: print(f'\nCategoria selecionada: {category[0][1]}') question = str(input('Informe a pergunta: ')) insert_question(categoryId, question) print('\nPergunta inserida') elif userChoice == '6': print(f'\nOpção selecionada: {userChoice} - Remover uma pergunta\n') questionId = str(input('Insira o ID da pergunta: ')) question = select_question_by_id(questionId) if not question: print('\nPergunta não encontrada') else: delete_question(questionId) print('\nPergunta removida') elif userChoice == '7': print(f'\nOpção selecionada: {userChoice} - Visualizar respostas de uma pergunta\n') questionId = str(input('Insira o ID da pergunta: ')) question = select_question_by_id(questionId) if not question: print('\nPergunta não encontrada') else: print(f'\nPergunta selecionada: {question[0][1]}') answers = select_all_answers_by_question_id(questionId) print('\nID \tResposta') for item in range(len(answers)): print(f'{answers[item][0]} \t{answers[item][1]}') elif userChoice == '8': print(f'\nOpção selecionada: {userChoice} - Inserir uma nova resposta para uma pergunta\n') questionId = str(input('Insira o ID da pergunta: ')) question = select_question_by_id(questionId) if not question: print('\nPergunta não encontrada') else: print(f'\nPergunta selecionada: {question[0][1]}') answer = str(input('Informe a resposta: ')) insert_answer(questionId, answer) print('\nResposta inserida') elif userChoice == '9': print(f'\nOpção selecionada: {userChoice} - Inserir uma nova resposta para uma pergunta\n') answerId = str(input('Insira o ID da resposta: ')) answer = select_answer_by_id(answerId) if not answer: print('\nResposta não encontrada') else: delete_answer(answerId) print('\nResposta removida') elif userChoice == '10': break
f8c2381c60e156221b084e78a7f9a2a8b6f3480a
alimat2244/read-file-course
/main.py
253
3.640625
4
# This is a sample Python script. # written by Sadiat Adegbite # Enter a file name you want opened print("This program is written by Sadiat Adegbite") textfile = open(r"C:\Users\alima\OneDrive\Documents\Fruits.txt",'r') for i in textfile: print(i, end="")
3183a2a59f2cf6455338f60f4a1819b21aede81d
glambertation/ToGraduate
/Leetcode/python/coins/300/378.py
1,283
3.984375
4
''' Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. Example: matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, return 13. Note: You may assume k is always valid, 1 ≤ k ≤ n2. ''' ''' 1.可以建堆,然后pop k次 2.可以二分,最小值是左上matrix【0】【0】,最大值是右下matrix【n-1】【n-1】 取这个中间值 作为mid 算一下mid是第几大的数 然后再和k比较 然后这里再二分 ''' class Solution(object): def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ start = matrix[0][0] end = matrix[-1][-1] mid = 0 while start < end: mid = start + (end - start)/2 count = 0 for i in range(len(matrix)): j = len(matrix[i]) - 1 while j >= 0 and matrix[i][j] > mid : j -= 1 count += j + 1 if count < k: start = mid +1 else: end = mid return start
a51999bdc3287955be104c3cb3346a14e3114b0d
oywc410/MYPG
/python3/入门/06字典/05字典内置函数&方法.py
1,017
3.8125
4
""" len(dict) 计算字典元素个数,即键的总数。 str(dict) 输出字典以可打印的字符串表示。 type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。 1 radiansdict.clear() 删除字典内所有元素 2 radiansdict.copy() 返回一个字典的浅复制 3 radiansdict.fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值 4 radiansdict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值 5 key in dict 如果键在字典dict里返回true,否则返回false 6 radiansdict.items() 以列表返回可遍历的(键, 值) 元组数组 7 radiansdict.keys() 以列表返回一个字典所有的键 8 radiansdict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default 9 radiansdict.update(dict2) 把字典dict2的键/值对更新到dict里 10 radiansdict.values() 以列表返回字典中的所有值 """
3e7606a2d13fe87fe7cd88a7c9cb39391a48a3b2
ZJU-RoboCup/BotecBeast
/leju_lib_pkg/src/lejufunc/utils.py
366
3.546875
4
#coding=utf-8 def is_number(number): try: return float(number) except: return None def judge_range_number(number, min, max): number = is_number(number) if number is not None: if min <= number <= max: return number raise ValueError("参数错误, 应为数字类型, 范围为[{}, {}]".format(min, max))
4aa4bdec0f7eae29b3d21139fed1657ae7538f5c
freakraj/python_projects
/whileraj_solu.py
235
3.671875
4
name =input("please enter your name : ") # harshit temp_var="" i=0 while i<len(name): if name[i] not in temp_var: temp_var +=name[i] print(f"{name[i]} : {name.count(name[i])}") i +=1
139d48048b47406931482cb7d40147df15560118
JenZhen/LC
/lc_ladder/Adv_Algo/dp/LC_377_Combination_Sum_IV.py
1,581
3.671875
4
#! /usr/local/bin/python3 # https://www.lintcode.com/problem/combination-sum-iv/description # Example # 给出一个都是正整数的数组 nums,其中没有重复的数。从中找出所有的和为 target 的组合个数。 # # 样例 # 样例1 # # 输入: nums = [1, 2, 4] 和 target = 4 # 输出: 6 # 解释: # 可能的所有组合有: # [1, 1, 1, 1] # [1, 1, 2] # [1, 2, 1] # [2, 1, 1] # [2, 2] # [4] # 样例2 # # 输入: nums = [1, 2] 和 target = 4 # 输出: 5 # 解释: # 可能的所有组合有: # [1, 1, 1, 1] # [1, 1, 2] # [1, 2, 1] # [2, 1, 1] # [2, 2] # 注意事项 # 一个数可以在组合中出现多次。 # 数的顺序不同则会被认为是不同的组合。 """ Algo: DP D.S.: Solution: Corner cases: """ class Solution2: """ @param nums: an integer array and all positive numbers, no duplicates @param target: An integer @return: An integer """ def backPackVI(self, nums, target): # write your code here if not nums or not target: return 0 n = len(nums) f = [0] * (target + 1) f[0] = 1 for i in range(1, target + 1): for num in nums: print("num: " + str(num)) if i >= num: f[i] += f[i - num] return f[-1] # Test Cases if __name__ == "__main__": testcases = [ { "nums": [1,2,4], "target": 4 }, ] solution2 = Solution2() for t in testcases: nums = t["nums"] target = t["target"] print(solution2.backPackVI(nums, target))
90f258e25fd3f055850a61b3e820b0bcf98099e8
alexisshaw/python2perl
/tests/toSubmit/demo09.py
157
3.5625
4
#!/usr/bin/python __author__ = 'Alexis Shaw' array = [5,4,3,2,1] string = "Hello how are you" print sorted(array) print sorted([5,4,3,2,1]) print len(string)
50d6f4436dab9117a84c5537e73cde136fb74f1a
samaritanhu/swe_fall
/swe241p/Exercise2/InsertionSort.py
1,187
3.796875
4
#!/usr/bin/env python # coding: utf-8 # University of California, Irvine # Master of Software Engineering, Donald Bren School of Information and Computer Science # Created by: Xinyi Hu # Date : 2020/10/09 # Contact : [email protected] # Target : Realize InsertionSort # Reference : The algorithm design manual class InsertionSort: def __init__(self, arr): self.arr = arr def SortingProcess(self): for i in range(len(self.arr)): j = i while (self.arr[j] < self.arr[j - 1]) and j > 0: self.arr[j], self.arr[j - 1] = self.arr[j - 1], self.arr[j] j = j - 1 return def SortingProcess2(self): for i in range(1, len(self.arr)): current = self.arr[i] pre_index = i - 1 while pre_index >= 0 and self.arr[pre_index] > current: self.arr[pre_index + 1] = self.arr[pre_index] pre_index -= 1 self.arr[pre_index + 1] = current def PrintOutput(self): print(self.arr) if __name__ == "__main__": arr = [2, 5, 3, 1, 10, 4] ISort = InsertionSort(arr) ISort.SortingProcess2() ISort.PrintOutput()
09c0574e2383a2c68ddf850b4335469b18342da9
idobleicher/pythonexamples
/examples/variable_scopes/global_scope_example_3.py
692
4.28125
4
#We only need to use global keyword in a function if we want to do # assignments / change them. global is not needed for printing and accessing #Any variable which is changed or created inside of a function is local, if it hasn’t been declared as a global variable. #To tell Python, that we want to use the global variable, we have to use the keyword “global”, as can be seen in the following example: # This function modifies global variable 's' def f(): global s print (s) s = "Look for Geeksforgeeks Python Section" print(s) # Global Scope s = "Python is great!" f() print (s) #Python is great! #Look for Geeksforgeeks Python Section #Look for Geeksforgeeks Python Section
b9a0b0512e2a83a0a11e882b43083b270235f637
bohdan167/My-Games
/Connect Four/Text Mode/model.py
1,743
3.5625
4
import numpy as np ROW_COUNT = 6 COLUMN_COUNT = 7 def create_board(): board = np.zeros((ROW_COUNT, COLUMN_COUNT)) return board def valid_move(board, move): if (0 <= move <= 6) and board[0][move] == 0: return True else: return False def get_next_row(board, move): r = len(board) for i in range(r-1, -1, -1): if board[i][move] == 0: return i def player_move(board, row, col, ply): board[row][col] = ply def winning_move(board, row, col, piece): # Horizontal check for c in range(COLUMN_COUNT - 3): if board[row][c] == board[row][c+1] == board[row][c+2] == board[row][c+3] == piece: return True # Vertical check for r in range(ROW_COUNT - 3): if board[r][col] == board[r+1][col] == board[r+2][col] == board[r+3][col] == piece: return True # Diagonal Right Down check for i in range(0, 3): for j in range(0, 4): if board[i][j] == board[i+1][j+1] == board[i+2][j+2] == board[i+3][j+3] == piece: return True # Diagonal Left Down for i in range(0, 3): for j in range(3, COLUMN_COUNT): if board[i][j] == board[i+1][j-1] == board[i+2][j-2] == board[i+3][j-3] == piece: return True # Diagonal Right Up for i in range(3, ROW_COUNT): for j in range(0, 4): if board[i][j] == board[i-1][j+1] == board[i-2][j+2] == board[i-3][j+3] == piece: return True # Diagonal Left Up for i in range(3, ROW_COUNT): for j in range(3, COLUMN_COUNT): if board[i][j] == board[i-1][j-1] == board[i-2][j-2] == board[i-3][j-3] == piece: return True return False
e3524ac737dda91438024c5103619196a8b2f61c
hsonetta/OCR
/Front_end/input.py
1,898
3.515625
4
""" Loads the desired input image, language model and calls function to recognize text. """ import numpy as np import streamlit as st from PIL import Image import cv2 from ocr_wrapper import detect_text, crop_img, recognize_text from data import * import easyocr import time @st.cache(suppress_st_warning=True) def load_ocr(): ocr_reader = easyocr.Reader(['en'], detector=True, recognizer=False, gpu=False, download_enabled=False, model_storage_directory='model_file', user_network_directory='user_network') return ocr_reader def image_input(lang_models_name): content_name = st.sidebar.selectbox("Choose the images:", content_images_name) content_file = content_images_dict[content_name] if st.sidebar.checkbox('Upload'): content_file = st.sidebar.file_uploader("Choose an Image", type=["png", "jpg", "jpeg"]) if content_file is not None: #Image for display image = Image.open(content_file) image = np.array(image) #pil to cv image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) else: st.warning("Upload an Image OR Untick the Upload Button)") st.stop() ocr_reader = load_ocr() start = time.time() #detect text text_coordinates = detect_text(image, ocr_reader) #pass base64 image (base64 str) #crop small images crop_images = crop_img(image, text_coordinates) #pass cv2 image for cropping (cv2 image, [[[x0,y0],[x1,y1],[x2,y2],[x3,y3]]]) #recognize text text, conf_score, inf_time = recognize_text(crop_images) #cropped numpy images (list) end = time.time() inf_time = round(end - start, 3) st.markdown('**Image:**') st.image(image, width=400, channels='BGR') st.write('**Recognized Text**: ', text) st.write('**Confidence Score:** ', conf_score) st.write('**Inference Time (sec):** ', inf_time)
875c6f49e9ce07ab69ee36918cc6b3b4c2755c1e
gimquokka/problem-solving
/Programers/Lv_2/전화번호 목록/ref.py
169
3.6875
4
def solution(phone_book): phone_book.sort() for p1, p2 in zip(phone_book, phone_book[1:]): if p2.startswith(p1): return False return True
660851f5fcbceca5371134ab5c2d8b3bc4233e9b
charles161/python
/intersection.py
195
4
4
list1=input('Enter the space separated elements for list 1 : ').split(' ') list2=input('Enter the space separated elements for list 2 : ').split(' ') print(list(set(list1).intersection(list2)))
57453238c82722cbf17305333ab649ecc1414555
roushan5mishra/HackerRank_Python
/timeConversion.py
493
3.953125
4
#!/bin/python import sys def timeConversion(s): # Complete this function temp1 = s[-2:] temp2 = int(s[:2]) if temp1.upper() == 'PM': if temp2 < 12: temp2 +=12 elif temp2 == 12: temp2 = 12 elif temp1.upper() == 'AM': if temp2 < 12: temp2 = s[:2] elif temp2 == 12: temp2 = '00' return str(temp2)+s[2:-2] s = raw_input().strip() result = timeConversion(s) print(result)
e83fcbe5590d069bd7e5dca9eeee31b5e7af9991
GHubgenius/DevSevOps
/2.python/0.python基础/day12/代码/day12/01 昨日回顾.py
1,704
3.640625
4
''' 编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件), 要求登录成功一次,后续的函数都无需再输入用户名和密码。 ''' # 可变类型,无需通过global引用,可直接修改 user_info = { 'user': None # username } # 不可变类型,需要在函数内部使用global对其进行修改 user = None def login(): # 判断用户没有登录时,执行 # 登录功能 # global user username = input('请输入账号: ').strip() password = input('请输入密码: ').strip() with open('user.txt', 'r', encoding='utf-8') as f: for line in f: print(line) name, pwd = line.strip('\n').split(':') # [tank, 123] if username == name and password == pwd: print('登录成功!') user_info['user'] = username else: print('登录失败!') def login_auth(func): # func ---> func1, func2, func3 def inner(*args, **kwargs): # 已经登录,将被装饰对象直接调用并返回 if user_info.get('user'): res = func(*args, **kwargs) # func() ---> func1(), func2(), func3v return res # 若没登录,执行登录功能 else: print('请先登录...') login() return inner # func1,2,3 都需要先登录才可以使用,若登录一次, # 后续功能无需再次登录,绕过登录认证 @login_auth def func1(): print('from func1') pass @login_auth def func2(): print('from func2') pass @login_auth def func3(): print('from func3') pass while True: func1() input('延迟操作...') func2() func3()
2d3cf1f1e3d3722b8daee2c85408c7d326589317
shivasupraj/LeetCode
/107. Binary Tree Level Order Traversal II.py
709
3.75
4
# 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 levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ result = [] def levelOrderBottom(root, index): if root is None: return if index > len(result)-1: result.append([]) result[index].append(root.val) levelOrderBottom(root.left, index+1) levelOrderBottom(root.right, index+1) levelOrderBottom(root, 0) return result[::-1]
715ea88ed53d02f3f0962e26d583f9abaa3a0474
setyo-dwi-pratama/python-basics
/21.fungsi_rekursi&lambda.py
4,272
4.0625
4
# FUNGSI REKURSI DAN LAMDBDA print("===============1. FUNGSI REKURSI===============") # Fungsi rekursi adalah fungsi yang memanggil dirinya sendiri secara berulang. Jadi di dalam tubuh fungsi kita memanggil fungsi itu sendiri # CONTOH. Di dalam matematika, kita mengenal tentang faktorial. Faktorial adalah perkalian bilangan asli berturut – turut dari n sampai dengan 1. Faktorial n dinotasikan dengan n! dimana n! = n (n – 1)(n – 2)(n – 3) ... (3)(2)(1). Faktorial adalah contoh dari fungsi rekursi # Contoh fungsi rekursi # Menentukan faktorial dari bilangan def faktorial(x): """Fungsi rekursi untuk menentukan faktorial bilangan""" if x == 1: return 1 else: return (x * faktorial(x-1)) bil = 4 print("Faktorial dari", bil, " adalah", faktorial(bil)) # Pada contoh di atas, fungsi faktorial() memanggil dirinya sendiri secara rekursi. Ilustrasi proses dari fungsi di atas adalah seperti berikut: # faktorial(4) #4 * faktorial(3) #4 * 3 * faktorial(2) #4 * 3 * 2 * 1 #4 * 3 * 2 #4 * 6 # 24 # CATATAN : Rekursi fungsi berakhir saat bilangan sudah berkurang menjadi 1. Ini disebut sebagai kondisi dasar (base condition). Setiap fungsi rekursi harus memiliki kondisi dasar. Bila tidak, maka fungsi tidak akan pernah berhenti (infinite loop) # Keuntungan Menggunakan Rekursi: # 1.Fungsi rekursi membuat kode terlihat lebih clean dan elegan # 2.Fungsi yang rumit bisa dipecah menjadi lebih kecil dengan rekursi # 3.Membangkitkan data berurut lebih mudah menggunakan rekursi ketimbang menggunakan iterasi bersarang # Kerugian Menggunakan Rekursi # 1.Terkadang logika dibalik rekursi agak sukar untuk diikuti # 2.Pemanggilan rekursi kurang efektif karena memakan lebih banyak memori # 3.Fungsi rekursi lebih sulit untuk didebug print("===============2. FUNGSI LAMBDA===============") # Salah satu fitur python yang cukup berguna adalah fungsi anonim. Dikatakan fungsi anonim karena fungsi ini tidak diberikan nama pada saat didefinisikan # Pada fungsi biasa kita menggunakan kata kunci def untuk membuatnya, sedangkan fungsi anonim ini kita menggunakan kata kunci lambda. Oleh karena itu, fungsi anonim ini dikenal juga dengan fungsi lambda # Format Fungsi Lambda: # Lambda argument : expression # Fungsi lambda bisa mempunyai banyak argumen, tapi hanya boleh memiliki satu ekspresi. Ekspresi tersebutlah yang dikembalikan sebagai hasil dari fungsi. Fungsi lambda bisa kita simpan di dalam variabel untuk digunakan kemudian # Program menggunakan lambda 1 argumen def kuadrat(x): return x*x # Output: 9 print(kuadrat(3)) # Lambda dengan 2 argumen def kali(x, y): return x*y # Output: 12 print(kali(4, 3)) # Penggunaan Fungsi Lambda print("===============Pengguna Fungsi Lambda===============") # Lambda digunakan pada saat kita membutuhkan fungsi anonim untuk saat yang singkat. Di Python, fungsi lambda sering digunakan sebagai argumen untuk fungsi yang menggunakan fungsi lain sebagai argumen seperti fungsi filter(), map(), dan lain-lain print("===============Pengguna Fungsi Lambda dengan Fungsi filter()===============") # Fungsi filter mengambil dua buah argumen, yaitu satu buah fungsi dan satu buah list # Sesuai dengan namanya filter (penyaring), fungsi akan menguji semua anggota list terhadap fungsi, apakah dan mengambil hasil yang bernilai True. Hasil keluarannya adalah sebuah list baru hasil filter. Berikut adalah contohnya: # Filter bilangan ganjil dari list my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] list_ganjil = list(filter(lambda x: x % 2 != 0, my_list)) # Output: [1, 3, 5, 7, 9] print(list_ganjil) print("===============Pengguna Fungsi Lambda dengan Fungsi map()===============") # Fungsi map() mengambil dua buah argumen, yaitu satu buah fungsi dan satu buah list. # Fungsi map() akan memetakan atau memanggil fungsi dengan satu persatu anggota list sebagai argumennya. Hasilnya adalah list baru hasil dari keluaran fungsi terhadap masing-masing anggota list. Berikut adalah contohnya: # Program untuk menghasilkan kuadrat bilangan my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] kuadrat = list(map(lambda x: x*x, my_list)) # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ] print(kuadrat)
68ae40f164c2302c65e257be74c0933602170ae6
jabhax/python-data-structures-and-algorithms
/OOP/Adapter.py
2,334
4.28125
4
# Design Patterns ''' Adapter Pattern works as a bridge between two incompatible interfaces. This pattern involves a single class, which is responsible for joining the functionalities of Independent or Incompatible Interfaces. It converts the interface of a class into another interface based on some requirement. The pattern includes a polymorphism which names one name and multiple forms. Say for a shape class which can use as per the requirements gathered. Example: A real life example could be the case of a card reader, which acts as an adapter between memory card and a laptop. You plug in the memory card into the card reader and the card reader into the laptop so that memory card can be read via the laptop. ''' class EUSocketInterface: def voltage(self): pass def is_live(self): pass def is_neutral(self): pass def is_earth(self): pass class Socket(EUSocketInterface): # Adaptee def voltage(self): return 240 def is_live(self): return 1 def is_neutral(self): return -1 def is_earth(self): return 0 class USASocketInterface: # Target Interface def voltage(self): pass def is_live(self): pass def is_neutral(self): pass def is_earth(self): pass class Adapter(USASocketInterface): # Adapter __socket = None def __init__(self, socket): self.__socket = socket def voltage(self): return 120 def is_live(self): return self.__socket.is_live() def is_neutral(self): return self.__socket.is_neutral() class Device: # Client __adapter = None def __init__(self, adapter): self.__adapter = adapter def power_on(self): if self.__adapter.voltage() > 120: msg = (f'Danger!!! Voltage = { self.__adapter.voltage() }V exceeds' f' max voltage of 120V') else: msg = ((f'Device successfully powered on and is live!') if (self.__adapter.is_live() and self.__adapter.is_neutral() == -1) else (f'Device is powered off.')) print(msg) def main(): # Plug in socket = Socket() adapter = Adapter(socket) device = Device(adapter) # power on Device device.power_on() return 0 if __name__ == '__main__': main()
f89ce38b0c9aa62878f4c946aa9cd42d5e513933
sumeetmankar171/HTP
/archive/check_time_string.py
966
3.578125
4
__author__ = 'mlucas' import sys def check_time_str(time_str): hour = time_str[0:2] mins = time_str[2:4] secs = time_str[4:6] fsec = time_str[6:] c_hour = hour c_mins = mins c_secs = secs if int(secs) > 59: c_secs = '00' if int(mins) < 59: c_mins = str(int(mins) + 1).zfill(2) else: c_mins = '00' if int(hour) < 23: c_hour = str(int(hour) + 1).zfill(2) else: c_hour = '00' else: c_secs = secs if int(mins) > 59: c_mins = '00' if int(hour) < 23: c_hour = str(int(hour) + 1).zfill(2) else: c_hour = '00' if int(hour) > 23: c_hour = '00' c_time_str = c_hour + c_mins + c_secs + fsec print c_time_str return c_time_str current_time_str = raw_input('Enter Time String: ') checked_time_str = check_time_str(current_time_str) sys.exit()
9b8faea2b631b28a1ca3a54f78bf42e2717e0f46
originalhumanbeing/algorithm-training
/python/longest_palindrom.py
1,050
4.21875
4
# 앞뒤를 뒤집어도 똑같은 문자열을 palindrome이라고 합니다. # longest_palindrom함수는 문자열 s를 매개변수로 입력받습니다. # s의 부분문자열중 가장 긴 palindrom의 길이를 리턴하는 함수를 완성하세요. # 예를들어 s가 토마토맛토마토이면 7을 리턴하고 토마토맛있어이면 3을 리턴합니다. def is_palindrom(s): return s == s[::-1] assert (is_palindrom('토마토')) assert (not is_palindrom('토마토마')) def longest_palindrom(s): if not s: # 매개변수가 ""일 때? return 0 if is_palindrom(s): return len(s) longest_val = 1 for st_idx in range(0, len(s)): for end_idx in range(st_idx + 1, len(s)+1): word = s[st_idx: end_idx] if is_palindrom(word): longest_val = max(longest_val, len(word)) return longest_val print(longest_palindrom('토마토맛토마토')) print(longest_palindrom('토마토맛있어')) print(longest_palindrom("맛있어토마토"))
3d36c4de6c1a80327f8b4c982ee255b355d513a3
prinned/prog
/palchk.py
562
4.0625
4
'''This program finds the largest palindrome which is a product of two 3-digit numbers. E2018/''' import math def palchk(i): #checks whether i is a palindrome ja = "" for m in range(0,len(str(i))//2): ja += str(i)[m] #ja = first half of number jb = "" for m in range(math.ceil(len(str(i))/2),len(str(i))): jb += str(i)[m] #jb = second half of number if(ja==jb[::-1]): return True bg=0 for i in range(100,1000): for j in range(100,1000): if palchk(i*j) and i*j > bg: bg = i*j print(bg)
edab1f6596c0790d81f3d0f70168a2ae50eb4bfd
danielsbezerra/python
/if-odd-even.py
297
4.0625
4
#!/bin/python3 N = int(input()) R = range(0,101) if N in R: if N%2 != 0: #odd print("Weird") elif N in range(2,5): print("Not Weird") elif N in range(6,21): print("Weird") elif N > 20: print("Not Weird") else: print(f"{N} out of range(0,101)")
f0725ac023a6653a29aabe9df21035016fd1ff1d
rhondaregister/Exercises
/countPairs/countPairs.py
386
3.953125
4
''' A function to determine the number of pairs in an array. ''' number_of_socks = 9 sock_colorways = [10, 20, 20, 10, 10, 30, 50, 10, 20] def countPairs(n, ar): pairs = [] count = 0 for i in ar: if i in pairs: pass else: pairs.append(i) num = ar.count(i) pair = int(num / 2) count += pair return count x = countPairs(number_of_socks, sock_colorways) print(x)
ae566c005a8256a4f8db53cb1899c2fcfb4346b7
linkeshkanna/ProblemSolving
/EDUREKA/Course.3/Case.Study.1.Programs/factorial.py
429
4.28125
4
class factorial: def calculateFactorial(object, value1): value = int(value1) if value == 1: return value else: return value * object.calculateFactorial(value - 1) if __name__ == "__main__": value = input("Please Enter a Number : ") object = factorial() fact = object.calculateFactorial(value) print("Factorial Of Number " + str(value) + " is : " + str(fact))
c69814982c6636a3e910a8759b11f864cc9ea9df
KrishnadevAD/Python
/u6.py
538
3.96875
4
print("enter the first number") firstNumber=int(input()) print("enter the second number") SecondNumber=int(input()) print(str(firstNumber)+" + "+str(SecondNumber)+"= "+str(firstNumber+SecondNumber)) print(str(firstNumber)+"-" +str(SecondNumber)+"= "+str(firstNumber-SecondNumber)) print(str(firstNumber)+" * "+str(SecondNumber)+"= "+str(firstNumber*SecondNumber)) print(str(firstNumber)+"/" +str(SecondNumber)+"= "+str(firstNumber/SecondNumber)) print(str(firstNumber)+"%" +str(SecondNumber)+"= "+str(firstNumber%SecondNumber))
c06406f5666f6e0d64efa105ae2da1beb06e2212
a-utkarsh/python-programs
/Numpy/slicing_indexing.py
569
4.03125
4
import numpy as np a = np.arange(10) print(a) s = slice(2,7,2) print (a[s]) # array to begin with a = np.array([[1,2,3],[3,4,5],[4,5,6]]) print(a.ndim) print ('Our array is:') print (a) print ('\n') # this returns array of items in the second column print ('The items in the second column are:') print (a[...,2]) print ('\n') # Now we will slice all items from the second row print ('The items in the second row are:' ) print (a[2,...]) print ('\n') # Now we will slice all items from column 1 onwards print ('The items column 1 onwards are:') print (a[...,:1])
32774ecded41feb3dc3e865f33b01f13a1685ed8
PonMorin/CP3-Pon-Morin
/Lecture53_Pon_M.py
128
3.75
4
def vatCal(totalPrice): result=totalPrice+(totalPrice*7/100) return result print(vatCal(int(input("Enter Number: "))))
a119b6f1537c49b603ba005b5c7119be0ed8cb4f
phatnguyenuit/Python
/dictionary.py
858
3.890625
4
#coding:utf-8 ''' dictionary dạng {key:value, key2:value2,....,key_n:value_n} truy cập giá trị của dictionary dictionary['key'] cập nhật giá trị của key bằng cách gán lại giá trị cho dictionary['key'] xoá del ten_dictionary[key] hoặc del ten_dictionary để xoá tất cả #dict.clear() #dict.copy() return a copy #dict.get(key,default=None) #dict.items() trả về tất cả cặp key-value #dict.update(dict2) update dict2 to dict ''' dictA = {'name': 'PhatNguyen', 'age' :23, 'gender' : 'male'}; print 'for loop with key and value by dict.iteritems()' for key, value in dictA.iteritems(): print key,' : ',value print 'for loop with key by dict.iterkeys()' for key in dictA.iterkeys(): print key,' : ', dictA[key] print 'for loop with key by dict.itervalues()' for value in dictA.itervalues(): print value
e614847ff6c548d56322f1956604dd8a0a9ca53f
muhammadahsan21/100DaysOfLearningDataScience
/ThinkStats_Book/think_stats_exercise2_2.py
1,648
3.84375
4
import thinkstats_survey as survey import think_Stats_First as first def mean(number_list): return float(sum(number_list)/len(number_list)) def variance(number_list): mean_of_list=mean(number_list) return mean(([(x-mean_of_list)**2 for x in number_list])) def stddev(number_list): variance_of_list=variance(number_list) return variance_of_list**0.5 def main(): table = survey.Pregnancies() table.ReadRecords() print ('Number of pregnancies', len(table.records)) first_born_prglength_list=[entry.prglength*7 for entry in table.records if entry.birthord==1] other_born_prglength_list=[entry.prglength*7 for entry in table.records if entry.birthord!=1] # Calculate Standard Deviation for first_born and non_firstborn # Standard Deviation is squareroot of (sum of (x-mean))/n first_born_prglength_mean=mean(first_born_prglength_list) other_born_prglength_mean=mean(other_born_prglength_list) print("Mean Preg length in days for first born :" ,first_born_prglength_mean) print("Mean Preg length in days for other born :",other_born_prglength_mean) first_born_prglength_var=variance(first_born_prglength_list) other_born_prglength_var=variance(other_born_prglength_list) print("variance of Preg length in days for first born :",first_born_prglength_var) print("variance of Preg length in days for other born :",other_born_prglength_var) print("Std Dev of Preg length in days for first born :",stddev(first_born_prglength_list)) print("Std Dev of Preg length in days for other born :",stddev(other_born_prglength_list)) if __name__ == '__main__': main()
0c1dc3b9e4defb77ee0e1537a5f96e164b38016f
CDidier80/Code-Challenges-Algos-Interviews-Cool-Solutions
/challenges-and-interview-problems/WARM-UPS/are-you-playing-banjo/banjo.py
620
4.3125
4
# Create a function which answers the question "Are you playing banjo?". # If your name starts with the letter "R" or lower case "r", you are playing banjo! # The function takes a name as its only argument, and returns one of the following strings: # name + " plays banjo" # name + " does not play banjo" # solution 1 def areYouPlayingBanjo(name): return f"{name}{' plays' if name[0].lower() == 'r' else ' does not play'} banjo" # solution 2 def areYouPlayingBanjo2(name): if name[0] == "r" or name[0] == "R": return f"{name} plays banjo" else: return f"{name} does not play banjo"
ae300c15ef006d668905472f994081dccd259e90
ZhanlinWang/hpc_work
/lec4/sqrtx.py
443
3.703125
4
#!/bin/python ''' Module for approximating sqrt. More ... ''' 'Why not come here' from numpy import * x = 100. def sqrt2(x, debug=False): ''' more details ''' s = 1. kmax = 100 tol = 1.e-14 for k in range(kmax): if debug: print "Before iteration %s, s = %20.15f" % (k,s) s0 = s s = 0.5 * (s + x/s) delta_s = s - s0 if abs(delta_s/x) < tol: break if debug: print "After %s iteration, s=%20.15f" % (k+1,s) return s
3e36dccfc4f5626851d9d45e2ccaf62a2246c88c
amirtha4501/Guvi
/AbsoluteBeginner/AbsoluteLearner5.py
180
4.1875
4
# Calculate circumference import math radius = float(input()) if radius >= 0: circumference = 2 * math.pi * radius print('%.2f' % circumference) else: print("Error")
7616aafe667f56da41b7c7fc5a73bd8bbaba4bb4
wrthls/bmstu-5sem
/AA/lab_01/print_matrix.py
200
3.796875
4
def print_matrix(matrix): for j in range(len(matrix)): print(" ", end='') for k in range(len(matrix[j])): print(matrix[j][k], ' ', end='') print() print()
9218816be9ea8ac47eb870342bdfdc4c3af761bd
Raccoon987/aliev.me
/tree_git.py
19,784
3.921875
4
''' create binary heap - list realization - acts like tree ''' class BinaryHeap: def __init__(self, size): self.heapList = [0] self.currentSize = 0 self.maxSize = size #max number of elements in heap # inserting element with it futher migration to the correct "binary heap" place def elementUp(self, i): while i // 2 > 0: if self.heapList[i] < self.heapList[i // 2]: temp = self.heapList[i // 2] self.heapList[i // 2] = self.heapList[i] self.heapList[i] = temp i = i // 2 def insert(self, elem): # before insertion of the new element - look at the heap size - if it is too big than delete root if self.currentSize >= self.maxSize: self.delRoot() self.heapList.append(elem) self.currentSize += 1 self.elementUp(self.currentSize) # deleting root element, by means of replacing with the last element of the list. # and futher migration to the correct "binary heap" place def findMinChild(self, i): if i*2 + 1 > self.currentSize: return i*2 else: if self.heapList[i*2] < self.heapList[i*2 + 1]: return i*2 else: return i*2 + 1 def elementDown(self, i): while i*2 <= self.currentSize: position = self.findMinChild(i) if self.heapList[i] > self.heapList[position]: temp = self.heapList[i] self.heapList[i] = self.heapList[position] self.heapList[position] = temp i = position def delRoot(self): rootval = self.heapList[1] self.heapList[1] = self.heapList[self.currentSize] self.currentSize -= 1 self.heapList.pop() self.elementDown(1) return rootval # creating binary heap from arbitrary list def buildHeap(self, lst): self.currentSize += len(lst) self.heapList += lst[:] i = self.currentSize // 2 while (i > 0): self.elementDown(i) i = i - 1 # keep heap less than self.maxSize for i in range(self.currentSize - self.maxSize): self.delRoot() # sort method using heap def heapSort(self, lst): self.buildHeap(lst) return [self.delRoot() for i in range(self.currentSize)] ''' class that makes max binary heap - max element at the root place ''' class MaxBinHeap(BinaryHeap): def __init__(self, size): BinaryHeap.__init__(self, size) #inserting element with it futher migration to the correct "binary heap" place #revrite method to put max element closer to the root def elementUp(self, i): while i // 2 > 0: if self.heapList[i] > self.heapList[i // 2]: temp = self.heapList[i // 2] self.heapList[i // 2] = self.heapList[i] self.heapList[i] = temp i = i // 2 def elementDown(self, i): while i*2 <= self.currentSize: position = self.findMaxChild(i) if self.heapList[i] < self.heapList[position]: temp = self.heapList[i] self.heapList[i] = self.heapList[position] self.heapList[position] = temp i = position def findMaxChild(self, i): if i*2 + 1 > self.currentSize: return i*2 else: if self.heapList[i*2] < self.heapList[i*2 + 1]: return i*2 + 1 else: return i*2 ''' Queue with priority - realize it on the base of MaxBinHeap. new element put at the end of the list. if its number is big - it moves to the bigining of the list. begining of the list - place where the root element(the bigest number) stays - place where we make dequeue operation. ''' class PriorityQueue(MaxBinHeap): def __init__(self, size): MaxBinHeap.__init__(self, size) def enqueue(self, element): self.insert(element) def dequeue(self): self.delRoot() def isEmpty(self): return self.currentSize == 0 def size(self): return self.currentSize class TreeNode: def __init__(self, key, val, leftCh=None, rightCh=None, parent=None): self.key = key self.value = val self.leftChild = leftCh self.rightChild = rightCh self.parent = parent self.balanceFactor = 0 def __iter__(self): if self: if self.hasLeftChild(): for i in self.leftChild: yield i yield self.key if self.hasRightChild(): for j in self.rightChild: yield j def hasLeftChild(self): return self.leftChild def hasRightChild(self): return self.rightChild def isLeftChild(self): return self.parent and self.parent.leftChild == self def isRightChild(self): return self.parent and self.parent.rightChild == self def isRoot(self): return not self.parent def isLeaf(self): return (not self.rightChild) and (not self.leftChild) def hasAnyChildren(self): return self.rightChild or self.leftChild def hasBothChildren(self): return self.rightChild and self.leftChild def replaceNodeData(self, key, val, leftCh=None, rightCh=None): self.key = key self.value = val self.leftChild = leftCh self.rightChild = rightCh if self.hasRightChild(): self.rightChild.parent = self if self.hasLeftChild(): self.leftChild.parent = self def findSuccessor(self): # helper method to find successor of deleted node that has both left and right child successor = None # if remove node has right child, than successor - min key in the right subtree if self.hasRightChild(): successor = self.rightChild.findMin() else: if self.parent: # if node has no right child but node is a left child of his parent, that this # parent will be successor if self.isLeftChild(): successor = self.parent # if node has no right child but node is a right child of his parent, than # successor will be his parent successor (excepting current node) # else: # self.parent.rightChild = None # successor = self.parent.findSuccessor() # self.parent.rightChild = self elif self.isRightChild(): self.parent.rightChild = None successor = self.parent.findSuccessor() self.parent.rightChild = self return successor # min key will be the most left of all seccessors def findMin(self): current = self while current.hasLeftChild(): current = current.leftChild return current def spliceOut(self): if self.isLeaf(): if self.isLeftChild(): self.parent.leftChild = None else: self.parent.rightChild = None elif self.hasAnyChildren(): if self.hasLeftChild(): if self.isLeftChild(): self.parent.leftChild = self.leftChild else: self.parent.rightChild = self.leftChild self.leftChild.parent = self.parent else: if self.isLeftChild(): self.parent.leftChild = self.rightChild else: self.parent.rightChild = self.rightChild self.rightChild.parent = self.parent ''' Binary Tree Search Left child always less than root, right child > than root ''' class BinarySearchTree: def __init__(self): self.root = None self.size = 0 def __len__(self): return self.size def __setitem__(self, key, val): self.put(key, val) def __getitem__(self, key): return self.get(key) def __contains__(self, key): if self.get(key): return True else: return False def __delitem__(self, key): self.delete(key) # walking the tree def walking_tree(self, node): if node: print(node.key, node.value) self.walking_tree(node.leftChild) # print (node.key, node.value) self.walking_tree(node.rightChild) # print (node.key, node.value) # put element to the binary search tree def put(self, key, val): # try to find element in the tree that already has suck key check = self._get(key, self.root) # if yes - change its value if check: check.value = val else: if self.root: self._put(key, val, self.root) else: self.root = TreeNode(key, val) self.size += 1 def _put(self, key, val, currNode): if key < currNode.key: if currNode.hasLeftChild(): self._put(key, val, currNode.leftChild) else: currNode.leftChild = TreeNode(key, val, parent=currNode) else: if currNode.hasRightChild(): self._put(key, val, currNode.rightChild) else: currNode.rightChild = TreeNode(key, val, parent=currNode) # get element from the tree def get(self, key): if self.root: res = self._get(key, self.root) if res: return res.value else: return None else: return None def _get(self, key, currNode): if not currNode: return None elif currNode.key == key: return currNode elif key < currNode.key and currNode.hasLeftChild(): return self._get(key, currNode.leftChild) elif key > currNode.key and currNode.hasRightChild(): return self._get(key, currNode.rightChild) # delete element from the tree def delete(self, key): if self.size > 1: # find element removeNode = self._get(key, self.root) if removeNode: self.remove(removeNode) self.size -= 1 else: raise KeyError('Error, key not in tree') elif self.size == 1 and self.root.key == key: self.root = None self.size = 0 else: raise KeyError('Error, key not in tree') def remove(self, removeNode): # Node has no children if removeNode.isLeaf(): if removeNode.isLeftChild(): removeNode.parent.leftChild = None else: removeNode.parent.rightChild = None # node has 2 children elif removeNode.hasBothChildren(): successor = removeNode.findSuccessor() removeNode.key = successor.key removeNode.value = successor.value # deleting successor at his old place successor.spliceOut() # node has 1 children elif removeNode.hasAnyChildren(): if removeNode.hasLeftChild(): if removeNode.isLeftChild(): removeNode.parent.leftChild = removeNode.leftChild removeNode.leftChild.parent = removeNode.parent elif removeNode.isRightChild(): removeNode.parent.rightChild = removeNode.leftChild removeNode.leftChild.parent = removeNode.parent else: # remove node is root removeNode.replaceNodeData(removeNode.leftChild.key, \ removeNode.leftChild.value, \ removeNode.leftChild.leftChild, \ removeNode.leftChild.rightChild) else: # remove node has right child if removeNode.isLeftChild(): removeNode.parent.leftChild = removeNode.rightChild removeNode.rightChild.parent = removeNode.parent # removeNode.parent.leftChild = removeNode.rightChild elif removeNode.isRightChild(): removeNode.parent.rightChild = removeNode.rightChild removeNode.rightChild.parent = removeNode.parent # removeNode.parent.rightChild = removeNode.rightChild else: # remove node is root removeNode.replaceNodeData(removeNode.rightChild.key, \ removeNode.rightChild.value, \ leftCh=removeNode.rightChild.leftChild, \ rightCh=removeNode.rightChild.rightChild) ''' REALIZATION OF BALANCED TREE. height(letft subtree) - height(right subtree) = 0, +-1. subclass of BinarySearchTree ''' class BalancedSearchTree(BinarySearchTree): def __init__(self): # super(BalancedSearchTree, self).__init__() BinarySearchTree.__init__(self) # overloading _put() method def _put(self, key, val, currNode): if key < currNode.key: if currNode.hasLeftChild(): self._put(key, val, currNode.leftChild) else: currNode.leftChild = TreeNode(key, val, parent=currNode) # use updateBalance method to maintain balance in tree self.updateBalance(currNode.leftChild) else: if currNode.hasRightChild(): self._put(key, val, currNode.rightChild) else: currNode.rightChild = TreeNode(key, val, parent=currNode) # use updateBalance method to maintain balance in tree self.updateBalance(currNode.rightChild) def updateBalance(self, node): if node.balanceFactor > 1 or node.balanceFactor < -1: self.rebalance(node) # return # updating balance factor of the new node parent if node.parent != None: if node.isLeftChild(): node.parent.balanceFactor += 1 elif node.isRightChild(): node.parent.balanceFactor -= 1 # if balance factor of subtree = 0 than balance factor of it's tree does not change if node.parent.balanceFactor != 0: self.updateBalance(node.parent) def rebalance(self, node): if node.balanceFactor < 0: if node.rightChild.balanceFactor > 0: self.rotateRight(node.rightChild) self.rotateLeft(node) else: self.rotateLeft(node) elif node.balanceFactor > 0: if node.leftChild.balanceFactor < 0: self.rotateLeft(node.leftChild) self.rotateRight(node) else: self.rotateRight(node) def rotateLeft(self, root): newRoot = root.rightChild root.rightChild = newRoot.leftChild if newRoot.leftChild != None: newRoot.leftChild.parent = root newRoot.parent = root.parent if root.isRoot(): self.root = newRoot else: if root.isLeftChild(): root.parent.leftChild = newRoot else: root.parent.rightChild = newRoot newRoot.leftChild = root root.parent = newRoot root.balanceFactor = root.balanceFactor + 1 - min(newRoot.balanceFactor, 0) newRoot.balanceFactor = newRoot.balanceFactor + 1 + max(root.balanceFactor, 0) def rotateRight(self, root): newRoot = root.leftChild root.leftChild = newRoot.rightChild if newRoot.rightChild != None: newRoot.rightChild.parent = root newRoot.parent = root.parent if root.isRoot(): self.root = newRoot else: if root.isLeftChild(): root.parent.leftChild = newRoot else: root.parent.rightChild = newRoot newRoot.rightChild = root root.parent = newRoot root.balanceFactor = root.balanceFactor - 1 - max(newRoot.balanceFactor, 0) newRoot.balanceFactor = newRoot.balanceFactor - 1 + min(root.balanceFactor, 0) # nonrecursive tree traversal using findSuccessor method # BUT NOT SYMMETRIC!!! def fun(tree): i = 0 start = tree.root.findMin() print start.key, start.value while i < tree.size - 1: i += 1 start = start.findSuccessor() print start.key, start.value if __name__ == "__main__": ''' testing BinaryHeap class ''' binheap = BinaryHeap(20) for element in [14, 9, 5, 19, 11, 18, 21, 27, 7, 30, 1, 6, 25, 12, 18, 100]: binheap.insert(element) print(binheap.heapList) binheap.buildHeap([8,20,6,2,3]) print("binary heap size: ", binheap.currentSize) print("binary heap list: ", binheap.heapList) for i in range(2): print("new root: ", binheap.delRoot()) print("binary heap size: ", binheap.currentSize) print("binary heap list: ", binheap.heapList) binheap = BinaryHeap(10) binheap.buildHeap([2,5,4,7,6,22,21,15,14]) print("testing buildHeap() method: ", binheap.heapList) print("sorted list: ", binheap.heapSort([17, 14, 9, 5, 19, 11, 18, 21, 27, 7, 30, 1, 6, 25, 12, 18, 100])) ''' testing BinaryHeap class ''' maxbinheap = MaxBinHeap(20) for element in [14, 9, 5, 19, 11, 18, 21, 27, 7, 30, 1, 6, 25, 12, 18, 100]: maxbinheap.insert(element) print(maxbinheap.heapList) print("testing buildHeap() method: ", maxbinheap.buildHeap([17, 14, 9, 5, 19, 11, 18, 21, 27, 7, 30, 1, 6, 25, 12, 18, 100])) ''' testing Priority queue class ''' priqueheap = PriorityQueue(10) for element in [14, 9, 5, 19, 11, 18, 21, 27, 7, 30]: priqueheap.insert(element) print(priqueheap.heapList) for element in [1, 6, 25, 12, 18, 100]: priqueheap.insert(element) print(priqueheap.heapList) priqueheap.dequeue() print(priqueheap.heapList) ''' testing binary search tree ''' def binschtr_test(searchtree_type): mytree = searchtree_type mytree[3] = "walrus" mytree[4] = "racoon" mytree[6] = "lizard" mytree[2] = "beaver" mytree[5] = "cat" mytree[1] = "hamster" mytree[10] = "duck" # print(mytree.root.key) # print(mytree.root.hasLeftChild()) # print(mytree.root.rightChild.value) print("------------") mytree.walking_tree(mytree.root) # for i in mytree.root: # print(i, mytree[i]) mytree.__delitem__(6) print("------------") mytree.walking_tree(mytree.root) # for i in mytree.root: # print i, mytree[i] print("------------") # print(mytree.root.rightChild.rightChild.value) binschtr_test(BinarySearchTree()) ''' testing balanced search tree ''' mytree = BalancedSearchTree() mytree[1] = 'walrus' mytree[2] = 'beaver' mytree[3] = 'rat' mytree[4] = 'racoon' mytree[5] = 'lizard' mytree[6] = 'cat' mytree[7] = 'duck' mytree.walking_tree(mytree.root) print(mytree.root.leftChild.leftChild.value) mytree[6] = "owl" mytree.walking_tree(mytree.root) fun(mytree)
91120deff3b5ec130c32d7088be70c042429101a
13excite/other
/find_local_max.py
944
3.53125
4
import sys my_list = [] for num in sys.stdin.read().split(): my_list.append(num) def localMaxLst(lstIn): if len(lstIn) == 0: return [] # no results from empty list lst = [] # init -- no results yet m = lstIn[0] # the first element as the maximum... candidate = True # ... candidate for elem in lstIn[1:-1]: # through elements from the second one if elem > m: m = elem # better candidate candidate = True elif elem == m: # if equal, local maximum was lost candidate = False elif elem < m: # if lower then possible candidate to output if candidate: lst.append(m) m = elem # start again... candidate = False # being smaller it cannot be candidate if candidate: # if the peak at the very end lst.append(m) return lst for elem in set(localMaxLst(my_list)): print elem
07d3da584c63240f89b1fd9a1387890548b3b3b2
omatveyuk/interview
/bubble_sort.py
816
4.34375
4
"""Bubble sort. 6 5 3 8 7 2 5 3 6 7 2 8 3 5 2 6 7 8 3 2 5 6 7 8 2 3 5 6 7 8 The big numbers bubble to the top. After the first pass through the list, the biggest number will be all the way to the right. After the second pass, the second highest number will be second from the right, and so on. >>> bubble_sort([6, 5, 3, 8, 7, 2]) [2, 3, 5, 6, 7, 8] >>> bubble_sort([2, 3, 4, 7]) [2, 3, 4, 7] """ def bubble_sort(alist): """Given a list, sort it using bubble sort.""" for i in range(len(alist) - 1): for j in range(len(alist) - 1): if alist[j] > alist[j + 1]: alist[j], alist[j + 1] = alist[j + 1], alist[j] return alist if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print "\n*** ALL TEST PASSED. W00T! ***\n"
429e29b039ca7de7ef998560c290100621386467
arsamigullin/problem_solving_python
/leet/Design/add_and_search_word.py
1,791
3.78125
4
# this is my solution class WordDictionary: def __init__(self): """ Initialize your data structure here. """ self.root = dict() def addWord(self, word: str) -> None: """ Adds a word into the data structure. """ node = self.root for ch in word: if ch not in node: node[ch] = dict() node = node[ch] node['#'] = '#' def search(self, word: str) -> bool: """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. """ # print(self.root) node = self.root def find(w, i, n): if i == len(w): return '#' in n if w[i] == '.': for k, v in n.items(): if k == '#': continue if find(w, i + 1, v): return True else: if w[i] not in n: return False return find(w, i + 1, n[w[i]]) return False return find(word, 0, node) # this is another solution class WordDictionary: def __init__(self): self.root = {} def addWord(self, word): node = self.root for char in word: node = node.setdefault(char, {}) node[None] = None def search(self, word): def find(word, node): if not word: return None in node char, word = word[0], word[1:] if char != '.': return char in node and find(word, node[char]) return any(find(word, kid) for kid in node.values() if kid) return find(word, self.root)
fa24009fdf0b7667851a18b06552003fb049a331
terpator/study
/Условные операторы/domashka_2 - переделанное.py
1,001
4.0625
4
""" Есть девятиэтажный дом, в котором 4 подъезда. Номер подъезда начинается с единицы. На одном этаже 4 квартиры. Напишите программу которая, получит номер квартиры с клавиатуры, и выведет на экран, на каком этаже, какого подъезда расположенна эта квартира. Если такой квартиры нет в этом доме, то нужно сообщить об этом пользователю. """ apart_number = int(input("Введите номер квартиры (1-144): ")) if apart_number < 1 or apart_number > 144: print("Такой квартиры нет в этом доме") else: pod_ezd = ((apart_number - 1) // 36) + 1 etazh = (((apart_number - 1) % 36) // 4) + 1 print("Подъезд №: ", pod_ezd) print("Этаж №: ", etazh)
13850bd3ff5bf2b980192a78a437934aaaca81a6
leejongcheal/algorithm_python
/파이썬 알고리즘 인터뷰/ch9 스택, 큐/20.유효한 괄호.py
614
3.75
4
class Solution: def isValid(self, s: str) -> bool: stack = [] # 와 요런식으로 깔끔하게 ㅋㅋ table = { ")":"(", "}":"{", "]":"[" } for char in s: if char not in table: stack.append(char) # 나는 not stack 을 따로 두었는데 이런식으로 깔끔하게 elif not stack or table[char] != stack.pop(): return 0 # 비어 있으면 1 리턴 아니면 0리턴을 이런식으로 return len(stack) == 0 print(Solution().isValid(")("))
51fef7a2a36a99f47e3b6dcd6ae07ba21cf8d375
ulysses316/python-practicas
/gasolineras.py
795
3.609375
4
import requests def distancia(): o=raw_input("Dame el punto de origen: ") d=raw_input("Dame el destino deseado: ") a=requests.get(params={"origins": o, "destinations":d}, url="https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&key=AIzaSyBfI7bob5KZFrPC4kQ-tzZzE63airiYsqU").json() print "La distancia entre los destinos es: ",a["rows"][0]["elements"][0]["distance"]["text"] print "El tiempo estimado de viaje es: ",a["rows"][0]["elements"][0]["duration"]["text"] w=a["rows"][0]["elements"][0]["distance"]["text"][0:3] km=float(w) cantidad_inicial=float(raw_input("Cuanta gasolina tenias al empezar el viaje: ")) x=cantidad_inicial/km y=km/cantidad_inicial print "Gastas %.3f litros por kilometro "%(x) print "Recorres %.3f kilometros por litro"%(y) distancia()
b34c2cd48622c0cceae73eefef06892b6179b673
git-vish/Soft-Computing-Lab
/BackProp_XOR_keras.py
621
3.65625
4
import numpy as np import keras # STEP-1: initializing data xt = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) yt = np.array([[0], [1], [1], [0]]) # STEP-2: creating nn model model = keras.models.Sequential() model.add(keras.layers.Dense(32, input_dim=2, activation='relu')) model.add(keras.layers.Dense(1, activation='sigmoid')) model.compile(loss='mean_squared_error', optimizer='rmsprop') # STEP-3: learning model.fit(xt, yt, epochs=1000) # STEP-4: printing results y_hat = model.predict(xt) print('\nResults: ') print('x1 \t x2 \t xor') for x, y in zip(xt, y_hat): print(x[0], '\t', x[1], '\t', round(y[0], 3))
cad0ad725150d9b3652ccdae0b0a0deb5475f4d9
khadimniass/MesPremiersCodesPythons
/ordre.py
368
3.828125
4
p=int(input("entrez le nombre premier p: ")) x=int(input("entrez l'entier x: ")) i=1;ord=0 while(True): if(x**i%p==1): ord=i break i+=1 print("ordre de ",ord) def ordre(p,x): p,x=int(p),int(x) compteur,ordr=1,0 while(True): if (x**compteur%p==1): ordr=compteur break compteur+=1 return ordr
6f7f39782c84bd72cc7e3509b1cdaf941b01c67d
Arocchi03/python_HWchallenge
/Python_homework/Python_challenge/PyPoll/main.py
1,469
3.53125
4
import csv import os Voter_ID = 0 County = 0 total_votes = 0 percentage_votes = [] num_votes = [] Candidate_list = [] Candidate_winner=[] #Reading data csvpath = os.path.join("PyPoll/Resources/election_data.csv") with open (csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) # Starting For loop for column in csvreader: #print(row) #The total number of votes cast Voter_ID = Voter_ID + 1 #Voter_ID += 1 #The total amount of "Candidate" over the entire period #Candidate_list += int(column[2]) #Candidate_list = Candidate_list + int(column[2]) # Candidate_list.append(str(column[2])) # my_final_list = set(Candidate_list) # print(list(my_final_list)) #print(Candidate_list) candidate_name= column[2] if candidate_name not in Candidate_list: Candidate_list.append(candidate_name) #print(Candidate_list) #The percentage of votes each candidate won for votes in num_votes: percentage = (votes/total_votes) * 100 percentage = round(percentage) percentage = "%.3f%%" % percentage percentage_votes.append(percentage) #print(percentage_votes) #The winner of the election based on popular vote winner = max(num_votes) index = num_votes.index(winner) winning_candidate = Candidate_list[index] #print(Candidate_winner)
c9d875bd877e21f2eced12faeadc62176eed25ec
WGrace824/GenCyber-2016
/CaesarCipher.py
1,353
4.03125
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 8 09:38:56 2016 @author: student Caesar Cipher 1. Name your function with 2 parameters, a str and a int 2. """ def Caesar_Cipher(Message, shift): Cipher = "" for char in Message: if ord(char) > 64 and ord(char) < 91: if ord(char) + shift < 91: char = chr(ord(char) + shift) else: char = chr(ord(char) - (26 - shift)) elif ord(char) > 96 and ord(char) < 123 : if (ord(char) + shift) < 123: char = chr(ord(char) + shift) else: char = chr(ord(char) - (26 - shift)) else: char = " " Cipher += char print(Cipher) Caesar_Cipher("Pokemon Go", 14) def Caesar_Decrypt(Code): for i in range(26): Decrypt = "" for char in Code: asc = ord(char) if asc > 64 and asc < 91: asc-=i if asc < 65: asc+=26 Decrypt +=chr(asc) elif ord(char) > 96 and ord(char) < 123 : asc -= i if asc < 97: asc+=26 Decrypt += chr(asc) else: Decrypt += char print(i, Decrypt) return(i) Caesar_Decrypt("Dcysacb Uc")
93e6febe467806de50a08903c46e7d00df61185e
DmytroLopushanskyy/Lab3
/json_parse/task2_json_parse.py
1,661
3.828125
4
import json import copy def decode_json(path): """ (str) -> dict Decode json file into a dictionary """ with open(path, 'r', encoding='UTF-8') as f: decode_data = json.load(f) return decode_data def parse_json(data): """ (dict) -> None Parse dictionary with user input """ operation_data = copy.deepcopy(data) while True: options = "" if type(operation_data) == dict: for el in operation_data.keys(): if type(el) == list: options += "<масив довжиною %s>. " \ "Вкажіть номер від 0 до %s" \ % (len(el), len(el) - 1) else: options += str(el) + ", " elif type(operation_data) == list: options = "<масив довжиною %s>. Вкажіть номер від 0 до %s, " \ % (len(operation_data), len(operation_data) - 1) else: print("Шуканий елемент:", operation_data) return print("Доступні опції вибору: " + options[:-2]) chosen = input("Введіть ключ з переліку вище: ") try: try: chosen = int(chosen) except: pass operation_data = operation_data[chosen] except: print("Введено неправильний ключ! " "Спробуйте ще раз!") if __name__ == "__main__": output = decode_json("friends.json") parse_json(output)
db140a884a420eb0b53cd4d09ff462a6e1d96a2c
michlee1337/practice
/Fundamentals/stackQs2.py
2,100
3.9375
4
# implement stack through min heap priority q class MinHeap(): def __init__(self): self.heap = [] self.size = 0 # parent: (i-1)//2 # left child: (i*2)+1 # right Child: (i*2)+2] def bubbleUp(self,i): # while parent exists for this index if i <= 0: return(0) while i//2 >= 0: # check with parent, if larger, switch and repeat w new index if self.heap[i] < self.heap[(i-1)//2]: temp = self.heap[(i-1)//2] self.heap[(i-1)//2] = self.heap[i] self.heap[i] = temp self.bubbleUp((i-1)//2) # else, end and return else: return(0) def bubbleDown(self,i): if (i*2)+1 >= self.size: return(0) while i < self.size: if self.heap[i] > self.heap[(i*2)+1]: temp = self.heap[i] self.heap[i] = self.heap[(i*2)+1] self.heap[(i*2)+1] = temp self.bubbleDown((i*2)+1) if ((i*2)+2) >= self.size: return(0) elif self.heap[i] > self.heap[(i*2)+2]: temp = self.heap[i] self.heap[i] = self.heap[(i*2)+2] self.heap[(i*2)+2] = temp self.bubbleDown((i*2)+2) else: return(0) def insert(self,x): self.heap.append(x) self.size += 1 self.bubbleUp(self.size-1) def extract(self): ret = self.heap[0] self.heap[0] = self.heap.pop() self.size -= 1 self.bubbleDown(0) if __name__ == "__main__": my_heap = MinHeap() my_heap.insert('7') print(my_heap.heap) print('______') my_heap.insert('6') print(my_heap.heap) print('______') my_heap.insert('5') print(my_heap.heap) print('______') my_heap.insert('4') print(my_heap.heap) print('______') my_heap.insert('3') print(my_heap.heap) my_heap.extract() print(my_heap.heap) my_heap.extract() print(my_heap.heap)
70f438ce30d9445b69fe0ce65638ec016bb4a284
olivigora/tokyo-3
/fibonacco numbers.py
157
4.125
4
def fibonacci(x): a = [1] for x in range(x): a.append(a[x]+a[x-1]) print(a) x = int(input("How many Fibonacci numbers do you want?: ")) fibonacci(x)
a041e414b78ccd1acd3fb0c83f651f0f63ee784a
BorjaSuarezMoron/trabajo
/venv/diccionario2.py
465
3.953125
4
# -*- coding: utf-8 -*- string_input = raw_input("Escriba ") def prueba(string_input): input_list = string_input.split() # splits the input string on spaces # process string elements in the list and make them integers print input_list diccionario={} for i in range(len(input_list)): valor=input_list[i] contador= input_list.count(valor) diccionario[input_list[i]]=contador print diccionario prueba(string_input)
140a585fe0be022403bfd60b71b687699f62f708
RainMoun/nowcoder_program
/剑指offer/快速排序.py
566
3.828125
4
def quick_sort(num_lst, left, right): if left >= right: return low = left high = right key = num_lst[low] while left < right: while left < right and num_lst[right] >= key: right -= 1 num_lst[left] = num_lst[right] while left < right and num_lst[left] <= key: left += 1 num_lst[right] = num_lst[left] num_lst[right] = key quick_sort(num_lst, low, left - 1) quick_sort(num_lst, left + 1, high) lst = [7, 5, 3, 9, 10, 1, 4, 15] quick_sort(lst, 0, len(lst) - 1) print(lst)
ab8f7eb116d786a06622703b548396a069a1720c
karan2808/Python-Data-Structures-and-Algorithms
/Stack/BinaryTreeInOrderTraversal.py
1,047
3.953125
4
class Solution: def inorderTraversal(self, root): result = [] stack = [] current = root # while current is not none or stack is not empty while current != None or len(stack) > 0: # push all the left nodes onto stack while current: stack.append(current) current = current.left # get the stack top, visit root node current = stack.pop() result.append(current.val) # go to the right node and repeat current = current.right return result class TreeNode: def __init__(self, val = 0, left = None, right = None): self.val = val self.left = left self.right = right def main(): mySol = Solution() root = TreeNode(1, None, TreeNode(2)) root.right.left = TreeNode(1) root.right.right = TreeNode(3) print("The inorder traversal of the BT is ") print(mySol.inorderTraversal(root)) if __name__ == "__main__": main()
20e53c74fa106387e9f986261cf15ebcc88fdd13
JDavid121/Script-Curso-Cisco-Python
/145 tuple application.py
213
3.71875
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 25 22:42:13 2020 TUPLE APPLICATION @author: David """ var = 123 t1 = (1,) t2 = (2,) t3 = (3,var) t1,t2,t3 = t2,t3,t1 print(t1,t2,t3) print(type(t1))
65920ef8856c5040e1098ea1f2bd6cc9dafa98d7
RomanAleksejevGH/Python
/groupwork/booksmenu.py
1,674
3.78125
4
import books newLib=books.library() #newLib.info("Математика для тех, кто не открывал учебник") def book_search(): get_book=input('\nВведите название книги:\n') newLib.infoBook(get_book) def author_search(): get_author = input('\nВведите имя автора:\n') newLib.infoAuthor(get_author) def book_by_letter(): get_book = input('\nВведите название книги:\n') newLib.book_by_letter(get_book) def author_by_letter(): get_author = input('\nВведите имя автора:\n') newLib.author_by_letter(get_author) def menu(): while True: flag = input('\n' 'Поиск книги[п] Поиск по букве книги[1] Добавление книги[н]\n' 'Поиск по автору[а] Поиск по букве автора[2] Выход[в]\n') if flag == 'п': print('\nПоиск книги') book_search() elif flag == '1': print('\nПоиск по букве книги') book_by_letter() elif flag== 'н': print('\nДобавление книги') newLib.add_book() elif flag == 'а': print('\nПоиск по автору') author_search() elif flag == '2': print('\nПоиск по букве автора') author_by_letter() elif flag == 'в': print('\nВыход') break else: break print('Добро пожаловать в бибилиотеку.\n') menu()
55c83c1c2c1bbe4352cbfb8d98e569e84f8b5b4a
iainfraser188/funtions-lab-2
/start_code/task_list.py
2,188
4.0625
4
# As a user, to manage my task list I would like a program that allows me to: # 1. Print a list of uncompleted tasks # 2. Print a list of completed tasks # 3. Print a list of all task descriptions # 4. Print a list of tasks where time_taken is at least a given time # 5. Print any task with a given description ### Extension # 6. Given a description update that task to mark it as complete. # 7. Add a task to the list tasks = [ { "description": "Wash Dishes", "completed": False, "time_taken": 10 }, { "description": "Clean Windows", "completed": False, "time_taken": 15 }, { "description": "Make Dinner", "completed": True, "time_taken": 30 }, { "description": "Feed Cat", "completed": False, "time_taken": 5 }, { "description": "Walk Dog", "completed": True, "time_taken": 60 }, ] def print_uncompleted_tasks(): incomplete = [] for task in tasks: if task["completed"] == False: incomplete.append(task) print(incomplete) print_uncompleted_tasks() def print_completed_tasks(): complete = [] for task in tasks: if task["completed"] == True: complete.append(task) print(complete) print_completed_tasks() def print_task_descriptions(): descriptions = [] for task in tasks: descriptions.append(task["description"]) print(descriptions) print_task_descriptions() def print_minimum_time_tasks(time): longer_tasks = [] for task in tasks: if task["time_taken"] > time: longer_tasks.append(task) print(longer_tasks) print_minimum_time_tasks(30) def print_described_task(description): described_task = [] for task in tasks: if task["description"] == description: described_task.append(task) print(described_task) print_described_task("Walk Dog") def Mark_complete(description): for task in tasks: if task["description"] == description: task["completed"] = True Mark_complete("Feed Cat") print(tasks) def add_task(description, completed, time): tasks.append({"description": description, "completed": completed, "time_taken": time}) add_task("Shower", True, 10) print(tasks)
36910b80d5248e8e4e30861f8677fdb30d77da2f
Tom-Harkness/projecteuler
/Python/utilityfunctions.py
2,770
3.90625
4
def isPrime(n): if n == 1: return False if n == 2: return True if n % 2 == 0: return False i = 3 while (i*i<=n): if n % i == 0: return False i += 2 return True def isPentagonal(n): return (24*n+1)**0.5 % 6 == 5 def isHexagonal(n): return (8*n+1)**0.5 % 4 == 3 def primeFactors(n): """returns a list of prime factors of n, repeats allowed""" pfactors = [] if n == 1: return [1] if n == 2: return [2] if n % 2 == 0: while n % 2 == 0: n //= 2 pfactors.append(2) i = 3 while (i*i<=n): if n % i == 0: while n % i == 0: n /= i pfactors.append(i) i += 2 if n != 1: pfactors.append(int(n)) return pfactors def distinctPrimeFactors(n): """returns a list of distinct prime factors of n""" pfactors = [] if n == 1: return [] if n == 2: return [2] if n % 2 == 0: pfactors.append(2) while n % 2 == 0: n /= 2 i = 3 while (i*i<=n): if n % i == 0: pfactors.append(i) while n % i == 0: n /= i i += 2 if n != 1: pfactors.append(int(n)) return pfactors def sieve_of_eratosthenes(limit): """returns a list of the primes under `limit`""" numbers = [False]*2 + (limit-1)*[True] n = 2 while n*n <= limit: if numbers[n]: m = n*n while m <= limit: numbers[m] = False m += n n += 1 return sorted([_ for _ in range(len(numbers)) if numbers[_]]) def phi(n): pfactors = primeFactors(n) result = 1 for p in set(pfactors): exp = pfactors.count(p) result *= p**(exp-1)*(p-1) return result def getProperDivisors(n): if n == 1: return [1] divisors = [1] for i in range(2, n//2+1): if n % i == 0: divisors.append(i) return sorted(divisors) def numberOfDivisors(n): pFactors = primeFactors(n) factor_exponent_pairs = [] for unique_prime in set(pFactors): factor_exponent_pairs.append((unique_prime, pFactors.count(unique_prime))) divisors = 1 for pair in factor_exponent_pairs: divisors *= pair[1]+1 return divisors def properDivisorSum(n): if n == 1: return 1 divisor_sum = 1 for i in range(2, n//2+1): if n % i == 0: divisor_sum += i return divisor_sum def fib(n): a, b = 0, 1 for _ in range(n): a, b = b, a+b return a def digit_sum(n): dsum = 0 while n != 0: dsum += n % 10 n //= 10 return dsum
0b03c2f019a2f7d924107aae2a08d484db611155
alexandermedv/Prof_python2
/main.py
2,146
3.5
4
import csv import re import pandas as pd import numpy as np def lastname(contacts_list): """Обработка фамилии""" result = [] for record in contacts_list: pattern = "[\w]+" words = re.findall(pattern, record[0]) if len(words) == 3: record[0] = words[0] record[1] = words[1] record[2] = words[2] elif len(words) == 2: record[0] = words[0] record[1] = words[1] result.append(record) return result def firstname(contacts_list): """Обработка имени""" result = [] for record in contacts_list: pattern = "[\w]+" words = re.findall(pattern, record[1]) if len(words) == 2: record[1] = words[0] record[2] = words[1] result.append(record) return result def phone(contacts_list): """Обработка номера телефона""" pattern = "[\d]" result = [] for record in contacts_list: phone_list = re.findall(pattern, record[5]) if phone_list: if phone_list[0] == '8': phone_list[0] = '7' if len(phone_list) > 11 and re.findall('доб.', record[5]): record[5] = '+' + phone_list[0] + '(' + ''.join(phone_list[1:4]) + ')' + ''.join(phone_list[4:7]) + '-' + ''.join(phone_list[7:9]) + '-' + ''.join(phone_list[9:11]) + ' доб.' + ''.join(phone_list[11:]) else: record[5] = '+' + phone_list[0] + '(' + ''.join(phone_list[1:4]) + ')' + ''.join(phone_list[4:7]) + '-' + ''.join(phone_list[7:9]) + '-' + ''.join(phone_list[9:11]) result.append(record) return result if __name__ == "__main__": with open("phonebook_raw.csv") as f: rows = csv.reader(f, delimiter=",") contacts_list = list(rows) contacts_list = lastname(contacts_list) contacts_list = firstname(contacts_list) contacts_list = phone(contacts_list) contacts_list = pd.DataFrame(contacts_list).replace('', np.NaN).groupby([0, 1]).first() contacts_list.to_csv("phonebook.csv", header=False)
7e16019f837e72d25cee3c1f60f3017f5c4be478
QuratulainZahid93/unit3
/unit3_6.py
2,076
4.3125
4
# Invite some people to dinner. guests = ['sherry', 'aney', 'maha'] name = guests[0].title() print(name + ", please come to dinner.") name = guests[1].title() print(name + ", please come to dinner.") name = guests[2].title() print(name + ", please come to dinner.") name = guests[1].title() print("\nSorry, " + name + " can't make it to dinner.") # Jack can't make it! Let's invite Gary instead. del(guests[1]) guests.insert(1, 'zain') # Print the invitations again. name = guests[0].title() print("\n" + name + ", please come to dinner.") name = guests[1].title() print(name + ", please come to dinner.") name = guests[2].title() print(name + ", please come to dinner.") # We got a bigger table, so let's add some more people to the list. print("\nWe got a bigger table!") guests.insert(0, 'humza') guests.insert(2, 'Taha') guests.append('daniyal') name = guests[0].title() print(name + ", please come to dinner.") name = guests[1].title() print(name + ", please come to dinner.") name = guests[2].title() print(name + ", please come to dinner.") name = guests[3].title() print(name + ", please come to dinner.") name = guests[4].title() print(name + ", please come to dinner.") name = guests[5].title() print(name + ", please come to dinner.") # Oh no, the table won't arrive on time! print("\nSorry, we can only invite two people to dinner.") name = guests.pop() print("Sorry, " + name.title() + " there's no room at the table.") name = guests.pop() print("Sorry, " + name.title() + " there's no room at the table.") name = guests.pop() print("Sorry, " + name.title() + " there's no room at the table.") name = guests.pop() print("Sorry, " + name.title() + " there's no room at the table.") # There should be two people left. Let's invite them. name = guests[0].title() print(name + ", please come to dinner.") name = guests[1].title() print(name + ", please come to dinner.") # Empty out the list. del(guests[0]) del(guests[0]) # Prove the list is empty. print(guests)
7ccf45bad51f087f12dca35c502ceec801eb4799
dalismo/python-challenge
/PyBank/main.py
2,213
3.65625
4
# modules to bring in import os import csv # filepath budget_csv = os.path.join('.','Resources','budget_data.csv') # variables to store for counts, calcs and loop total_months = [] total_net_gainloss = 0 total_gainloss = 0 prior_gainloss = 0 amount_gainloss = 0 amt_gainloss = [] difference = 0 difference_list = [] max_month = 0 min_month = 0 # # check # print(total_months) # Open and read the file using module with open(budget_csv) as csvfile: csvreader = csv.reader(csvfile, delimiter = ',') csv_header = next(csvreader) # variable to store rows # firstrow = next(csvreader) # take the prior value from the firstrow,[] is the index position # check # print(prior_gainloss) # start of the loop through the data for row in csvreader: total_months.append(row[0]) total_gainloss = total_gainloss + int(row[1]) amount_gainloss = int(row[1]) difference = amount_gainloss - prior_gainloss if prior_gainloss == 0: difference = 0 difference_list.append(difference) prior_gainloss = amount_gainloss theaverage= sum(difference_list)/(len(total_months)-1) new_month = (len(total_months)) highest = max(difference_list) lowest = min(difference_list) newaverage = "{:.2f}".format(theaverage) new_month = str(new_month) total_gainloss = str(total_gainloss) newaverage = str(newaverage) highest = str(highest) lowest = str(lowest) # # time to print results to match view needed print("Financial Analysis") print("--------------------------------------------") print("Total Months: "+ new_month) print("Total: $"+total_gainloss) print("Average Change: $"+ newaverage) print("Greatest Increase in Profits: $"+ highest) print("Greatest Decrease in Profits: $"+ lowest) # export of the file output = open("results.txt","w+") output.write("Financial Analysis ") output.write("\n -------------------------------------------- ") output.write("\nTotal Months: "+ new_month) output.write("\nTotal: $"+ total_gainloss) output.write("\nAverage Change: $"+ newaverage) output.write("\nGreatest Increase in Profits: $"+ highest) output.write("\nGreatest Decrease in Profits: $"+ lowest)
1286bf30879c0f24a8272c92d259c83023fc4427
soyoonjeong/python_crawling
/2_currencycode_scrap.py
865
3.5
4
import os import requests from bs4 import BeautifulSoup os.system("cls") url = "https://www.iban.com/currency-codes" print("Hello! Please choose select a country by number:") result = requests.get(url) soup = BeautifulSoup(result.text, "html.parser") tds = soup.find_all("td") names = [] codes = [] for index, td in enumerate(tds): if index % 4 == 0: names.append(td.string) elif index % 4 == 2: codes.append(td.string) for index, name in enumerate(names): print(f"# {index} {name}") while True: try: select = int(input("#: ")) if select < 0 or select >= len(names): print("Choose a number from the list.") else: print(f"You chose a {names[select]}.") print(f"The currency code is {codes[select]}.") break except: print("That wasn't a number.")
8a13e4e6a312514c9a8ddb7b343bf705bb5bb037
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/bxxbub001/question4.py
803
3.765625
4
#marks #B.Booi #24 April def marks(): fail = 0 thirds = 0 lower2 = 0 upper2 = 0 first = 0 numbers = input("Enter a space-separated list of marks:\n") numb_list=numbers.split(" ") #print(numb_list) listlen = len(numb_list) #print("length",listlen) for x in range(listlen): num = eval(numb_list[x]) if num < 50: fail +=1 elif num <60: thirds +=1 elif num <70: lower2 +=1 elif num <75: upper2 +=1 elif num<= 100: first +=1 print("1 |","X"*first,sep="") print("2+|","X"*upper2,sep="") print("2-|","X"*lower2,sep="") print("3 |","X"*thirds,sep="") print("F |","X"*fail,sep="") marks()
ed3acfad76d2291a97a8d0bc5524f52da4f36627
tswsxk/CodeBook
/Leetcode/SearchInsertPosition.py
584
3.953125
4
class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ head = 0 tail = len(nums) - 1 while head < tail - 1: mid = (head + tail + 1) // 2 if nums[mid] == target: return mid elif nums[mid] < target: head = mid else: tail = mid if nums[head] >= target: return head elif nums[tail] < target: return tail + 1 else: return tail if __name__ == "__main__": sol =Solution() print sol.searchInsert([1, 2], 0)
790cb075ab683b4ad0c6be81acd1309f109d5545
buptwxd2/leetcode
/Round_1/496. Next Greater Element I/solution_1.py
679
3.640625
4
class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: my_stack = [] my_dict = {} for num in nums2: while my_stack and my_stack[-1] < num: top_num = my_stack.pop(-1) my_dict[top_num] = num my_stack.append(num) for num in my_stack: my_dict[num] = -1 my_list = [my_dict[num] for num in nums1] return my_list """ Results: Runtime: 48 ms, faster than 65.35% of Python3 online submissions for Next Greater Element I. Memory Usage: 13.2 MB, less than 77.78% of Python3 online submissions for Next Greater Element I. """
fed9f9bd907c7e1bd3e70288915c20883e7f68f4
rkarna/DSC510Summer2020
/Jena_Binay_DSC510/week2_print_receipt.py
1,099
4.09375
4
#DSC 510 #Week 2 Programming Assignment 1.2 #Programming Assignment Week 2 #Author: Binay P Jena #06/12/2020 from datetime import datetime execution_date = datetime.now().strftime("%Y-%m-%d") def _total_charges (length): print("Transaction Details - ") install_cost = length * 0.87 print("Installation Length : " + str(length) + " feet") print("Installation Charge : $ " + str(install_cost)) misc_cost = 0 #not relevant for Week 2 assignment scope addnl_tax = 0 #not relevant for Week 2 assignment scope total_charges = install_cost + misc_cost + addnl_tax print("Total Charges : $ " + str(total_charges)) print("Greetings ! Have a nice day !!") company = input("Please provide company name: ") length_ip = input("Provide installation length in feet (enter digits only w decimals): ") length = float(length_ip) print("Hello, We're pleased to serve " + company + ", today " + execution_date + " ... ") print("Receipt : ") print("Date : " + execution_date) _total_charges(length=length) print("We look forward to doing business with you again... ") print("Thank You !!")
5ba1efe224bdcd173eee72d3369ecb283e69d3ab
ScatterBrain-I/MCLAPython
/LectureWork/1d.Comments.py
164
3.625
4
import math # Peter E Niemeyer # 7/7/17 # # this is to figure the volume of a cone radius = 10 height = 44 volume = math.pi * (radius * radius) * (height/3) print volume
42f4524ed8bfef1538b79246b27bf27f4f4be194
dworakp/guessing-game
/guessing.py
1,376
4.125
4
import random number=random.randint(1,100) guesses = [0] print("I've picked a random number from 1 to 100. Guess the number!") print("If your guess is more than 10 away from my number, I'll tell you you're COLD") print("If your guess is within 10 of my number, I'll tell you you're WARM") print("If your guess is farther than your most recent guess, I'll say you're getting COLDER") print("If your guess is closer than your most recent guess, I'll say you're getting WARMER") while True: print("I've picked a random number from 1 to 100. Guess the number!") guess=int(input("Your guess? ")) if guess > 100 or guess < 1: print("OUT OF BONDS!") continue if guess==number: print(f"YOU WON! NUMBER OF GUESSES {len(guesses)}") #len() counts our placeholder, so we count the number of break # guesses before appending new one guesses.append(guess) # when testing the first guess, guesses[-2]==0, which evaluates to False # and brings us down to the second section if guesses[-2]: if abs(number-guess)<abs(number-guesses[-2]): print("WARMER!") else: print("COLDER!") else: if abs(number-guess)>10: print("COLD!") else: print("WARM!")
7ea611bce359960fd2f2ad160fd0bf62a0194ccb
Sanlador/School
/CS531/sudoku.py
13,225
3.59375
4
import numpy as np import math #reads file of sudoku puzzles and places them in arrays arranged by difficulty (file is specifically formatted prior to input) def readPuzzleFile(file): easy = [] medium = [] hard = [] evil = [] difficulty = { "Easy": 1, "Medium": 2, "Hard": 3, "Evil": 4 } #for each configuration in the text file: f = open(file, "r") file = f.read().splitlines() board = np.zeros((9,9)) control = False i = 0 for line in file: #determine which difficulty the puzzle is if len(line.split()) > 1: #place the board into the correct array if control == True: if difficulty[d] == 1: easy.append(board) elif difficulty[d] == 2: medium.append(board) elif difficulty[d] == 3: hard.append(board) elif difficulty[d] == 4: evil.append(board) control = True #throw out first string and read the second i = 0 d = line.split()[1] board = np.zeros((9,9)) #read the following nine lines in as a 9x9 array of ints (the sudoku board) else: for j in range(9): board[i][j] = int(line[j]) i += 1 if i == 9: i = 0 return easy, medium, hard, evil def alldiff(board, row, col): if board[row][col] != 0: return [board[row][col]] if row < 3: squareRow = 0 elif row < 6: squareRow = 3 else: squareRow = 6 if col < 3: squareCol = 0 elif col < 6: squareCol = 3 else: squareCol = 6 domain = [1,2,3,4,5,6,7,8,9] for i in range(9): if board[row][i] in domain and board[row][i] != 0 and i != col: domain.remove(board[row][i]) if board[i][col] in domain and board[i][col] != 0 and i != row: domain.remove(board[i][col]) for i in range(3): for j in range(3): if board[squareRow + i][squareCol + j] in domain and board[squareRow + i][squareCol + j] != 0: domain.remove(board[squareRow + i][squareCol + j]) return domain def success(assign): #check that board is filled for i in range(9): for j in range(9): if assign.board[i][j] == 0: return False for i in range(9): for j in range(9): if assign.domain[i][j] != [0]: return False return True class assignment: domain = [] board = [] def __init__(self, board): self.board = board for i in range(9): self.domain.append([[],[],[],[],[],[],[],[],[]]) for j in range(9): self.domain[i][j] = alldiff(board, i, j) if self.domain[i][j] == [0]: print("Test") def makeAssignment(self, row, col, assignment): self.board[row][col] = assignment self.domain[row][col] = [0] def assignmentComplete(self): for i in range(9): for j in range(9): if (self.domain[i][j]) != [0]: return False return True def nakedSingle(self): control = False for i in range(9): for j in range(9): if len(self.domain[i][j]) == 1 and self.domain[i][j][0] != 0: self.makeAssignment(i,j, self.domain[i][j][0]) control = True return control def hiddenSingle(self): hidden = False for i in range(9): for j in range(9): #determine square if i < 3: squareRow = 0 elif i < 6: squareRow = 3 else: squareRow = 6 if j < 3: squareCol = 0 elif j < 6: squareCol = 3 else: squareCol = 6 control = False for d in self.domain[i][j]: controlRow = True controlCol = True controlBox = True for x in range(9): if control == False: if d in self.domain[i][x] and x != j: controlRow = False if d in self.domain[x][j] and x != i: controlCol = False for x in range(3): for y in range(3): if d in self.domain[squareCol + x][squareRow + y]: controlBox = False if controlRow and controlCol and controlBox: self.makeAssignment(i,j, d) hidden = True return hidden def pairs(self): b = False hidden = False for i in range(9): for j in range(9): #determine square if i < 3: squareRow = 0 elif i < 6: squareRow = 3 else: squareRow = 6 if j < 3: squareCol = 0 elif j < 6: squareCol = 3 else: squareCol = 6 for d in range(0, len(self.domain[i][j]) - 1): control = False for z in range(d + 1, len(self.domain[i][j])): common = [] count = 0 if control == False: for x in range(j - 1,9): if self.domain[i][j][d] in self.domain[i][x] and self.domain[i][j][z] in self.domain[i][x] and x != j: count += 1 if self.domain[i][j][d] in self.domain[x][j] and self.domain[i][j][z] in self.domain[x][j] and x != i: count += 1 for x in range(3): for y in range(3): if len(self.domain) > 2 and self.domain[i][j][d] in self.domain[x + squareRow][y + squareCol] and self.domain[i][j][z] in self.domain[x + squareRow][y + squareCol] and (x != i and y != j): count += 1 if count < 2: common.append([i, x, self.domain[i][j][d], self.domain[i][j][z]]) else: common = [] control = False if count == 1: control = True count = 0 if control: if len(self.domain[i][j]) > 2 or len(self.domain[common[0][0]][common[0][1]]) > 2: hidden = True self.domain[i][j] = [self.domain[i][j][d], self.domain[i][j][z]] if self.domain[common[0][0]][common[0][1]] != [0]: self.domain[common[0][0]][common[0][1]] = [self.domain[i][j][0], self.domain[i][j][1]] common = [] return hidden def triples(self): hidden = False for i in range(9): for j in range(9): #determine square if i < 3: squareRow = 0 elif i < 6: squareRow = 3 else: squareRow = 6 if j < 3: squareCol = 0 elif j < 6: squareCol = 3 else: squareCol = 6 for d in range(0, len(self.domain[i][j]) - 2): control = False for z in range(d + 1, len(self.domain[i][j]) - 1): for w in range(z + 1, len(self.domain[i][j])): common = [] count = 0 if control == False: for x in range(9): if self.domain[i][j][d] in self.domain[i][x] and self.domain[i][j][z] in self.domain[i][x] and self.domain[i][j][w] in self.domain[i][x] and x != j: count += 1 if self.domain[i][j][d] in self.domain[x][j] and self.domain[i][j][z] in self.domain[x][j] and self.domain[i][j][w] in self.domain[x][j] and x != i: count += 1 for x in range(3): for y in range(3): if len(self.domain) > 3 and self.domain[i][j][d] in self.domain[x + squareRow][y + squareCol] and self.domain[i][j][z] in self.domain[x + squareRow][y + squareCol] and self.domain[i][j][w] in self.domain[x + squareRow][y + squareCol] and (x != i and y != j): count += 1 if count < 3: common.append([i, x, self.domain[i][j][d], self.domain[i][j][z], self.domain[i][j][w]]) else: common = [] control = False if count == 2: control = True count = 0 if control: if len(self.domain[i][j]) > 3 or len(self.domain[common[0][0]][common[0][1]]) > 3: hidden = True self.domain[i][j] = [self.domain[i][j][d], self.domain[i][j][z], self.domain[i][j][w]] self.domain[common[0][0]][common[0][1]] = [self.domain[i][j][0], self.domain[i][j][1], self.domain[i][j][2]] common = [] return hidden def inference(self, level): control = False while control == False: nakedS = self.nakedSingle() hiddenS = self.hiddenSingle() if hiddenS == False: if level > 1: pair = self.pairs() else: pair = False if pair == False: if level > 2: tri = self.triples() else: tri = False if tri == False: control = True def backtrackSearch(assign, inferenceLvl, bound, backtrack, depth, MCV = False): if success(assign) or depth == bound: return assign, backtrack, depth + 1 for i in range(9): for j in range(9): alldiff(assign.board, i, j) if len(assign.domain[i][j]) == 0: return assignment(np.zeros((9,9))), backtrack + 1, depth if inferenceLvl > 0: assign.inference(inferenceLvl) for i in range(9): for j in range(9): if len(assign.domain[i][j]) == 1 and assign.domain[i][j][0] != 0: assign.makeAssignment(i,j,assign.domain[i][j][0]) varRow = 0 varCol = 0 if MCV: minRow = 0 minCol = 0 minDomain = math.inf for i in range(9): for j in range(9): if len(assign.domain[i][j]) < minDomain and assign.domain[i][j] != 0: minDomain = len(assign.domain[i][j]) minRow = i minCol = j varRow = minRow varCol = minCol else: control = False while control == False: if assign.domain[varRow][varCol] != [] and assign.domain[varRow][varCol][0] != 0: control = True else: varCol += 1 if varCol >= 9: varRow += 1 varCol = 0 if varRow == 9: return assignment(np.zeros((9,9))), backtrack + 1, depth for i in assign.domain[varRow][varCol]: tempAssign = assign tempAssign.makeAssignment(varRow,varCol, i) assign, backtrack, depth = backtrackSearch(tempAssign, inferenceLvl, bound, backtrack + 1, depth + 1, MCV) if assign != []: return tempAssign, backtrack, depth return assignment(np.zeros((9,9))), backtrack + 1, depth f = open("zeros.csv", "w") easy, medium, hard, evil = readPuzzleFile("sudoku-problems.txt") f.write("Easy\n") for i in easy: count = 0 for j in i: for k in j: if k == [0]: count += 1 f.write(str(count) + "\n") f.write("medium\n") for i in medium: count = 0 for j in i: for k in j: if k == [0]: count += 1 f.write(str(count) + "\n") f.write("hard\n") for i in hard: count = 0 for j in i: for k in j: if k == [0]: count += 1 f.write(str(count) + "\n") f.write("evil\n") for i in evil: count = 0 for j in i: for k in j: if k == [0]: count += 1 f.write(str(count) + "\n") f.close() ''' assign = assignment(easy[0]) s, backtracks, depth = backtrackSearch(assign, 3, 950, 0, 0) for j in range(3): f.write("Easy, Constant Search\nLevel of inference, # of backtracks, depth, # of empty spaces\n") for i in easy: assign = assignment(i) s, backtracks, depth = backtrackSearch(assign, j, 950, 0, 0) count = 0 for x in i: for y in x: if y == 0: count += 1 f.write(str(j) + "," + str(backtracks) + "," + str(depth) + str(count) + "\n") f.write("Easy, MCV\nLevel of inference, # of backtracks, depth, # of empty spaces\n") for i in easy: assign = assignment(i) s, backtracks, depth = backtrackSearch(assign, j, 950, 0, 0, True) count = 0 for x in i: for y in x: count += 1 f.write(str(j) + "," + str(backtracks) + "," + str(depth) + str(count) + "\n") f.write("Medium, Constant Search\nLevel of inference, # of backtracks, depth, # of empty spaces\n") for i in medium: assign = assignment(i) s, backtracks, depth = backtrackSearch(assign, j, 950, 0, 0) count = 0 for x in i: for y in x: count += 1 f.write(str(j) + "," + str(backtracks) + "," + str(depth) + str(count) + "\n") f.write("Medium, MCV\nLevel of inference, # of backtracks, depth, # of empty spaces\n") for i in medium: assign = assignment(i) s, backtracks, depth = backtrackSearch(assign, j, 950, 0, 0, True) count = 0 for x in i: for y in x: count += 1 f.write(str(j) + "," + str(backtracks) + "," + str(depth) + str(count) + "\n") f.write("Hard, Constant Search\nLevel of inference, # of backtracks, depth, # of empty spaces\n") for i in hard: assign = assignment(i) s, backtracks, depth = backtrackSearch(assign, j, 950, 0, 0) count = 0 for x in i: for y in x: count += 1 f.write(str(j) + "," + str(backtracks) + "," + str(depth) + str(count) + "\n") f.write("Hard, MCV\nLevel of inference, # of backtracks, depth, # of empty spaces\n") for i in hard: assign = assignment(i) s, backtracks, depth = backtrackSearch(assign, j, 950, 0, 0, True) count = 0 for x in i: for y in x: count += 1 f.write(str(j) + "," + str(backtracks) + "," + str(depth) + str(count) + "\n") f.write("Evil, Constant Search\nLevel of inference, # of backtracks, depth, # of empty spaces\n") for i in evil: assign = assignment(i) s, backtracks, depth = backtrackSearch(assign, j, 950, 0, 0) count = 0 for x in i: for y in x: count += 1 f.write(str(j) + "," + str(backtracks) + "," + str(depth) + str(count) + "\n") f.write("Evil, MCV\nLevel of inference, # of backtracks, depth, # of empty spaces\n") for i in evil: assign = assignment(i) s, backtracks, depth = backtrackSearch(assign, j, 950, 0, 0, True) count = 0 for x in i: for y in x: count += 1 f.write(str(j) + "," + str(backtracks) + "," + str(depth) + str(count) + "\n") f.close()'''
d750a6b9e5d3f75dff0f0bfba73b76d70002901c
dsspasov/HackBulgaria
/week0/2-Python-harder-problems-set/problem30_test.py
454
3.578125
4
#problem30_test.py import unittest from problem30 import groupby class TestGroupBy(unittest.TestCase): def test_empty_list(self): self.assertEqual({'odd':0, 'even':0}, groupby(lambda x: 'odd' if x % 2 else 'even', [])) def test_not_empty_list(self): self.assertEqual({'odd':[1,3,5,9] , 'even':[2,8,10,12]}, groupby(lambda x: 'odd' if x % 2 else 'even', [1, 2, 3, 5, 8, 9, 10, 12])) if __name__ == '__main__': unittest.main()
4c13ba803a0fc414c94a3860e0d33fdfe813f0fe
DeanHe/Practice
/LeetCodePython/SmallestValueAfterReplacingWithSumOfPrimeFactors.py
1,241
4.0625
4
""" You are given a positive integer n. Continuously replace n with the sum of its prime factors. Note that if a prime factor divides n multiple times, it should be included in the sum as many times as it divides n. Return the smallest value n will take on. Example 1: Input: n = 15 Output: 5 Explanation: Initially, n = 15. 15 = 3 * 5, so replace n with 3 + 5 = 8. 8 = 2 * 2 * 2, so replace n with 2 + 2 + 2 = 6. 6 = 2 * 3, so replace n with 2 + 3 = 5. 5 is the smallest value n will take on. Example 2: Input: n = 3 Output: 3 Explanation: Initially, n = 3. 3 is the smallest value n will take on. Constraints: 2 <= n <= 10^5 """ from functools import lru_cache class SmallestValueAfterReplacingWithSumOfPrimeFactors: def smallestValue(self, n: int) -> int: visited = {} def prime_sum(num): if num in visited: return visited[num] tmp, res = num, 0 for i in range(2, num + 1): while tmp % i == 0: res += i tmp //= i if tmp == 1: break visited[num] = res return res while n not in visited: n = prime_sum(n) return n
96145aafa29063359becd3fc98fc932e78712204
franceshoho/Aliens_Invasion
/ship.py
1,500
3.890625
4
import pygame class Ship: """A class to manage the ship""" def __init__(self, ai_game): """Initialize the ship and set its starting position""" # get screen from ai_game self.screen = ai_game.screen # get settings from ai_game self.settings = ai_game.settings # get rect attr from ai_game screen self.screen_rect = ai_game.screen.get_rect() # Load ship image and get its rect self.image = pygame.image.load('images/ship.bmp') # get ship position (x,y) self.rect = self.image.get_rect() # start each new ship at the bottom center of screen self.center_ship() # set initial key stroke state self.moving_right = False self.moving_left = False self.moving_up = False def update(self): """update ship position based on movement flag""" # before each move, check if ship is inside screen if self.moving_right and self.rect.right < self.screen_rect.right: self.x += self.settings.ship_speed if self.moving_left and self.rect.left > 0: self.x -= self.settings.ship_speed # update ship position self.rect.x = self.x def blitme(self): """draw ship onto screen by copying pixel from image to position""" self.screen.blit(self.image, self.rect) def center_ship(self): self.rect.midbottom = self.screen_rect.midbottom self.x = float(self.rect.x)
0c240dc233f789d84b520990af063cb5b991a11b
Jill1627/lc-notes
/countAndSay.py
1,173
3.671875
4
""" 问题:输出第n位count and say sequence - 注意count and say sequence的生成方式 思路:递归,算法设计如何从n-1到n 1. 考虑n=0,1的特殊情况 2. 初始:res, count = 1, prev = self.countAndSay(n - 1),还有prevNum 3. 在loop中,考察当前i(curNum)与prevNum的关系,更新count 4. 如果当前位与前一位相等,只需要count++ 5. 如果当前位与前一位不等,更新答案,同时:reset count = 1,preNum = curNum 6. 最后一步,还要将prevNum加入答案 完成 """ class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ # base case if n is None or n == 0: return "0" if n == 1: return "1" # recursion prev = self.countAndSay(n - 1) prevNum = prev[0] count = 1 res = "" for i in xrange(1, len(prev)): if prev[i] == prevNum: count += 1 else: res = res + str(count) + prevNum prevNum = prev[i] count = 1 res = res + str(count) + prevNum return res
8acddf851481fec34d87ae05bddd319ddcc60fc6
Zorro30/Udemy-Complete_Python_Masterclass
/Regular_expression/star_character.py
147
3.96875
4
import re pattern = r"eggs(bacon)*" if re.match(pattern, "eggsbaconbacon"): print ("Match found!") else: print("Does not match!")
c3be5862c916bf4bfb702841f79e77e3e4275560
zx000ppze000/Pathon
/w1_lect_p2.py
376
3.625
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 17 23:42:57 2018 @author: zhangx """ """a = 0 while a<5: print(a) a += 1 """ """for n in range(5): print(n) """ """for n in range(0,10,2): print(n) """ """mysum = 0 for i in range(7, 10): mysum += i print(mysum) """ mysum = 0 for i in range(5, 11, 2): mysum+=1 if mysum ==5: break mysum += 1 print(mysum)
72a2b890d37e93beaf2b69f37a21cc79be259e4e
bsiranosian/brown-compbio
/CSCI1820/hw3/src/alignment_with_inversions.py
7,902
3.609375
4
#parameters import argparse parser = argparse.ArgumentParser(description="Script compute the optimal local alignment with inversions of two sequences. Takes input from two fasta sequences.") parser.add_argument("fasta1", action="store", metavar="fasta1", help="The file name of the first fasta sequence") parser.add_argument("fasta2", action="store", metavar="fasta2", help="The file name of the second fasta sequence") parser.add_argument("--match", action="store", metavar="match", default="1", help="score for a match") parser.add_argument("--mismatch", action="store", metavar="mismatch", default="-1", help="score for a mismatch") parser.add_argument("--gap", action="store", metavar="gap", default="-1", help="score for a gap") parser.add_argument("--invert", action="store", metavar="invert", default="-1", help="score for a invert") args=parser.parse_args() #parameters and paths specified in section above fasta1=args.fasta1 fasta2=args.fasta2 match=int(args.match) mismatch=int(args.mismatch) gap=int(args.gap) invert=int(args.invert) #global_alignment(seq1, seq2, match_score, mismatch_score, gap_penalty, return_score): Helper function for local alignment with inversions. # returns the optimal global alignment of two sequences by using the given parameters. # uses the needleman-wunsch algorithm for alignment. Depends on helper function single_score. # if return_score is true, simply return the highest score for the alignment. otherwise, return a list of the two aligned strings. def global_alignment(seq1, seq2, match_score, mismatch_score, gap_penalty, return_score): n = len(seq1) m = len(seq2) score_matrix=[[0 for i in range(m+1)] for j in range(n+1)] trace_matrix = [[0 for i in range(m+1)] for j in range(n+1)] for i in range(1, n+1): for j in range(1, m+1): #arguments to maximization args=[(score_matrix[i-1][j-1] + single_score(seq1[i-1], seq2[j-1], match_score, mismatch_score)), (score_matrix[i-1][j] + gap_penalty), (score_matrix[i][j-1] + gap_penalty)] #pick max score_matrix[i][j] = max(args) #argmax for traceback trace_matrix[i][j] = args.index(max(args)) # For GLOBAL alignment we want to start at the LAST score in the matrix. # Traceback al1 = '' al2 = '' cur_i = n cur_j = m #this code is for traceback, but not important for finding the score while (cur_i!=0) or (cur_j!=0): # if at one end of the matrix if cur_i ==0: al1 += "-" al2 += seq2[cur_j-1] cur_j+=-1 # if at one end of the matrix elif cur_j ==0: al2 += "-" al1 += seq1[cur_i-1] cur_i+=-1 #if match or mismatch elif trace_matrix[cur_i][cur_j] == 0: al1 += seq1[cur_i-1] al2 += seq2[cur_j-1] cur_i += -1 cur_j += -1 #if gap in i elif trace_matrix[cur_i][cur_j] == 1: al1 += seq1[cur_i-1] al2 += "-" cur_i += -1 #if gap in j elif trace_matrix[cur_i][cur_j] == 2: al1 += "-" al2 += seq2[cur_j-1] cur_j += -1 #only return score of global alignment if return_score: return score_matrix[n][m] else: #return the actual alignment return[al1[::-1],al2[::-1]] #single_score(char1, char2): defines the match and mismatch scores for a single base def single_score(char1, char2, match_score, mismatch_score): if char1==char2: return match_score else: return mismatch_score # reverse_complement(pattern): returns the reverse complement of DNA string pattern. Equivalent to an inversion. def reverse_complement(pattern): chars = list(pattern) complement = '' lookup = dict({("A","T"),("T","A"),("C","G"),("G","C")}) for base in chars: complement += lookup[base] rev_complement = complement[::-1] return rev_complement #local_alignment_inversions(seq1,seq2,match_score, mismatch_score, gap_penalty,inversion_penalty): performs local alignment with inversions # uses the algorithm from the waterman paper. # prints the alignment with "*" highlighting the region to be reverse complemented. def local_alignment_inversions(seq1,seq2,match_score, mismatch_score, gap_penalty,inversion_penalty): n = len(seq1) m = len(seq2) #Initialize matricies for scoring, traceback, and Z score_matrix=[[0 for i in range(m+1)] for j in range(n+1)] trace_matrix = [[[-1,0] for i in range(m+1)] for j in range(n+1)] Z = [[[[inversion_penalty for j in range(m+1)] for i in range(n+1)] for h in range (m+1)] for g in range (n+1)] max_score = -999999999 max_pos=[0,0] for i in range(1, n+1): for j in range(1, m+1): for g in range(i, 0,-1): for h in range(j, 0, -1): #really only need to do inversions when sequences are the same length if (i-g == j-h): #Calculate Zscore by doing global alignment of the sequence and the reverse complement Z[g-1][h-1][i-1][j-1] = global_alignment(seq1[g-1:i],reverse_complement(seq2[h-1:j]),match_score,mismatch_score,gap_penalty,True) + inversion_penalty #get Z values for i and j. keep length of inversion zvals = [] lengths = [] for g in range(1, i+1): for h in range(1, j+1): zvals.append(score_matrix[g-2][h-2] + Z[g-1][h-1][i-1][j-1]) lengths.append(i-g+1) #store values for argmax implementation args = [ max(zvals), (score_matrix[i-1][j-1] + single_score(seq1[i-1],seq2[j-1],match_score,mismatch_score)), (score_matrix[i-1][j] + gap_penalty), (score_matrix[i][j-1] + gap_penalty), 0] #pick max score_matrix[i][j] = max(args) #argmax for traceback if args.index(max(args)) ==0: #if inversion, store the length trace_matrix[i][j] = [0,lengths[zvals.index(max(zvals))]] else: trace_matrix[i][j] = [args.index(max(args)),0] #keep track of max score and max position so we don't have to find it later if max(args) >= max_score: max_score=max(args) max_pos=[i,j] #TRACEBACK #sequences al1 = '' al2 = '' #current positions current_score= max_score cur_i =max_pos[0] cur_j =max_pos[1] #testing prints..... for row in score_matrix: print row print " --- " for row in trace_matrix: print row print " ****** " while current_score > 0: # if we're in an inversion if trace_matrix[cur_i][cur_j][0] == 0: # get length of inversion. Append sequence of inversion with markers around what to reverse complement invlength = trace_matrix[cur_i][cur_j][1] s1 = seq1[cur_i-invlength:cur_j] al1 += " " + s1[::-1] + " " s2 = seq2[cur_j-invlength:cur_j] al2 += "*" + s2[::-1] + "*" cur_i += -invlength cur_j += -invlength current_score=score_matrix[cur_i][cur_j] #if match or mismatch if trace_matrix[cur_i][cur_j][0] == 1: al1 += seq1[cur_i-1] al2 += seq2[cur_j-1] cur_i += -1 cur_j += -1 current_score=score_matrix[cur_i][cur_j] #if gap in i elif trace_matrix[cur_i][cur_j][0] == 2: al1 += seq1[cur_i-1] al2 += "-" cur_i += -1 current_score=score_matrix[cur_i][cur_j] #if gap in j elif trace_matrix[cur_i][cur_j][0] == 3: al1 += "-" al2 += seq2[cur_j-1] cur_j += -1 current_score=score_matrix[cur_i][cur_j] #if alignment is discontinued elif trace_matrix[cur_i][cur_j][0] == 4: current_score=0 print al1[::-1] print al2[::-1] #don't really need to return anything #return[al1[::-1],al2[::-1]] #helper function to read fastas and call alignment with inversions def do_alignment(fasta1, fasta2,match_score, mismatch_score, gap_penalty,inversion_penalty): f1=open(fasta1, 'r') f2=open(fasta2, 'r') seq1 = '' seq2 = '' #Read fasta files into a sequence lines1 = f1.read().split('\n') for line in lines1: if (len(line) > 0): if (line[0] != ">"): seq1=seq1+line lines2 = f2.read().split('\n') for line in lines2: if (len(line) > 0): if (line[0] != ">"): seq2=seq2+line local_alignment_inversions(seq1,seq2,match_score, mismatch_score, gap_penalty,inversion_penalty) #FUNCTION CALL def main(): do_alignment(fasta1,fasta2,match,mismatch,gap,invert) if __name__ =='__main__':main()
d25d2a8a56754ad1a2fd8f056a628f5249f659bc
AlexKolchin/geekbrains
/Modules/math_ex.py
545
3.921875
4
import math #1. Найти длину окружности с определенным радиусом r = 100 print(2*r*math.pi) #2. Найти площадь окружности с определённым радиусом print((r**2)*math.pi) print(math.pow(r, 2)*math.pi) #3. По координатам 2-х точек определить расстояние между ними x1 = 10 y1 = 10 x2 = 50 y2 = 100 l = math.sqrt((x1-x2)**2 + (y1-y2)**2) print(l) #4. Найти факториал числа 9 print(math.factorial(9))
40db83c1e54636bc9b238468820fe26e4c124345
lovroselic/Coursera
/String Algorithms/suffix_tree/suffix_tree V2.py
2,993
3.71875
4
# python3 #https://www.geeksforgeeks.org/generalized-suffix-tree-1/ import sys NA = -1 #DEBUG = False DEBUG = True if DEBUG: test = open("sample_tests\\sample3", "r") class Node: __num__ = -1 def __init__(self, parentkey, pos = -1, substr = "", suffixlink = None): self.parent = parentkey self.children = {} self.suffixlink = suffixlink self.position = pos Node.__num__ += 1 self.id = Node.__num__ self.length = 1 self.substring = substr def isLeaf(self): return len(self.children) == 0 def isSingle(self): return len(self.children) == 1 def suffix_trie(text): root = Node(None) for t in range(len(text)): pat = text[t:] #if DEBUG: print(pat, t) node = root for ci in range(len(pat)): c = pat[ci] pos = t + ci #if DEBUG: print(c, "pos:", pos) if c in node.children: node = node.children[c] else: actNode = Node(node.id, pos, c) node.children[c] = actNode node = actNode return root def printST(node): for c in node.children: print(node.children[c].substring) printST(node.children[c]) return def walkDFS(node): print(".......") print("node:", node.id, "single", node.isSingle(), "leaf", node.isLeaf()) if node.isSingle(): child = next(iter(node.children.values())) print("..parent", node.parent, "child", child.id) #concat while child.isSingle() or child.isLeaf(): print("** CONCAT ** ", node.id, "with", child.id) #add child to node node.length +=1 node.substring += child.substring print("==", node.substring) #point to next child if child.isLeaf(): node.children = {} return else: child = next(iter(child.children.values())) node.children = {} return #really? print ("******") for c in node.children: print(c, " -> ", node.children[c].id) walkDFS(node.children[c]) return def build_suffix_tree(text): """ Build a suffix tree of the string text and return a list with all of the labels of its edges (the corresponding substrings of the text) in any order. """ global trie trie = suffix_trie(text) walkDFS(trie) print("===============================") printST(trie) #result = [] # Implement this function yourself #return result return if __name__ == '__main__': global text if DEBUG: text = test.readline ().strip () else: text = sys.stdin.readline ().strip () #text = sys.stdin.readline().strip() build_suffix_tree(text) #if DEBUG: print(text) #print("\n".join(result))
79e4ffa5d4cccf44de87b3d02d11dc8750fc867c
Gagan-453/Python-Practicals
/timedelta and programs.py
2,505
4.28125
4
#timedelta class of datetime module is useful to find durations like difference between two dates or finding the date after adding a period to an existing date #Program to find future date and time from an existing date and time from datetime import * d1 = datetime(2016, 4, 29, 16, 45, 0) #Store the date and time in datetime object: d1 period1 = timedelta(days = 10, seconds = 10, minutes = 20, hours = 12) #Define the duration using timedelta object: period1 #Add the duration to d1 and display print('The new date and time is', d1+period1) print('-------------------------------------------------------------') #Program to display the next 10 dates continuously from datetime import * d = date.today() print(d) for x in range(1, 10): nextdate = d+timedelta(days = x) print(nextdate) print('------------------------') #Program to accept date of births of two persons and determining the older person #Enter date of births and store it into date class objects d1, m1, y1 = [int(x) for x in input('Enter first person\'s date of birth (DD/MM/YYYY): ').split('/')] b1 = date(y1, m1, d1) d2, m2, y2 = [int(x) for x in input('Enter second person\'s date of birth (DD/MM/YYYY): ').split('/')] b2 = date(y2, m2, d2) #Compare the birth dates if b1==b2: print('Both persons are of equal age') elif b1 > b2: print('The second person is older') else: print('The first person is older') print('------------------------------------------------------') #Sorting dates from datetime import * group = [] #take an empty list group.append(date.today()) #Add today's date to list #Create some more dates d = date(2019, 6, 29) group.append(d) d = date(2017, 7, 15) group.append(d) group.append(d+timedelta(days=25)) #Add 25 days to the date and add to list group.sort() #Sort the list for d in group: print(d) print('--------------------') #Stopping Execution temporarily import time, random #Generate 10 random numbers for i in range(10): num = random.randrange(100, 200, 5) #Generate in the range 100 to 200 print(num) time.sleep(3.5)#Suspend execution for 3.5 seconds print('-----') #Knowing the time taken by a program from time import * t1 = perf_counter#Note the starting time of the program #Do some processing sum = 1+27829 #Make the processor or PVM sleep for 3 seconds sleep(3) #This is also measured by perf_counter() but this is not measured if we use perf_time() function t2 = perf_counter() #Note the ending time of the program print('Execution time = %f seconds' %t2)
8e699ea99af07d3c2c1dd445a0e62ce45b653526
azharul/misc_problems
/iterator.py
674
4.28125
4
#!/usr/bin/python #Write Interleaving Iterator class which takes a list of Iterators as input and iterates one element at a time from each iterator until they are all empty # interleaving iterators are also called Round Robin iterator from itertools import islice, cycle def roundrobin(*iterables): "roundrobin('ABC', 'D', 'EF') --> A D E B F C" pending = len(iterables) nexts = cycle(iter(it).next for it in iterables) while pending: try: for next in nexts: yield next() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending)) print list(roundrobin(range(5),"hello")
3cc5925d3e66a1ef7bb5236e675589544dddaf9a
ajing/clusterVis
/TreeRebuilder.py
4,417
3.5
4
""" Rewrite file to make the node name simple, so graphviz can understand Assumption: 1. node names are started with CHEMBL or ASD 2. only two kinds of statements contain node name: (1) node declaration (2) edge between nodes. """ import sys def NodeNameExist(line): if "CHEMBL" in line or "ASD" in line or "Chk1" in line: return True else: return False def IsEdge(line): if "--" in line: return True else: return False def NameAndAttribute(line): split_index = line.index("[") name = line[:split_index] attr = line[split_index:] return name, attr def ProcessName(name, isedge): if isedge: firstnode, secondnode = name.split("--") firstnode = firstnode.strip() secondnode = secondnode.strip() return firstnode, secondnode else: return name.strip() def static_var(varname,value): def decorate(func): setattr(func, varname, value) return func return decorate @static_var("counter", 0) @static_var("hashtable", dict()) def HashANode(nodename): if nodename in HashANode.hashtable: return "N" + str(HashANode.hashtable[nodename]) else: HashANode.hashtable[nodename] = HashANode.counter HashANode.counter += 1 return "N" + str(HashANode.hashtable[nodename]) def CleanAttribute(attr): new_attr = attr.replace(",", "") return new_attr def AddAttributeLabel(attr, label): if "label" not in attr: return attr idx = attr.index("\"") return attr[:(idx + 1)] + label + attr[(idx + 1):] def AddMoreAttribute(attr, labelname, labelvalue): right = attr.index("]") new_attr = attr[:right] + " " + str(labelname) + "=" + str(labelvalue) + "]\n" return new_attr def GetAttributeValue(attrname, attr): left = attr.index("[") + 1 right = attr.index("]") attr = attr[left:right] attrlist = attr.split() for each in attrlist: if attrname in each: value = each.split("=")[1] if value.endswith("!"): return value[:-1] else: return value def GetSize(width): return 100 ** (width/0.3) def SimplifyName(aname): if "CHEMBL" in aname: return aname.replace("CHEMBL", "C") if "ASD" in aname: return aname.replace("ASD", "A") @static_var("counter", 0) @static_var("hashtable", dict()) def HashAName(nodename): if nodename in HashAName.hashtable: return str(HashAName.hashtable[nodename]) else: HashAName.hashtable[nodename] = HashAName.counter HashAName.counter += 1 return str(HashAName.hashtable[nodename]) def PrintHash(hashtable): newdict = dict((y,x) for x,y in hashtable.iteritems()) for each in newdict: print each, ":", newdict[each] def RewriteDot(infile): nodename = dict() newfilename = infile + "_simple" newfileobj = open(newfilename, "w") for eachline in open(infile): if NodeNameExist(eachline): name, attr = NameAndAttribute(eachline) attr = CleanAttribute(attr) if IsEdge(eachline): fnode, snode = ProcessName(name, True) fnode_new = HashANode(fnode) snode_new = HashANode(snode) new_line = "--".join([fnode_new, snode_new]) + attr else: node = ProcessName(name, False) node_new = HashANode(node) #if not "_" in node and float(GetAttributeValue("width", attr)) > 0.15: ##for display large node # new_name = HashAName(node) # attr = AddAttributeLabel(attr, new_name) # attr = AddMoreAttribute(attr, "fixedsize", "true") new_line = node_new + attr newfileobj.write(new_line) else: newfileobj.write(eachline) newfileobj.close() PrintHash(HashAName.hashtable) def GetMaxWidth(infile): widthlist = [] for eachline in open(infile): if NodeNameExist(eachline): name, attr = NameAndAttribute(eachline) if not IsEdge(eachline): widthlist.append(float(GetAttributeValue("width", attr))) print max(widthlist) if __name__ == "__main__": infile = sys.argv[1] print infile RewriteDot(infile) #GetMaxWidth(infile)
606877c697359e4294811eb327f97ffcb8e89511
castorfou/scikit-learn-mooc
/notebooks/cross_validation_ex_05.py
3,664
4.03125
4
#!/usr/bin/env python # coding: utf-8 # # 📝 Introductory exercise for non i.i.d. data # # <div class="admonition note alert alert-info"> # <p class="first admonition-title" style="font-weight: bold;">Note</p> # <p class="last">i.i.d is the acronym of "independent and identically distributed" # (as in "independent and identically distributed random variables").</p> # </div> # # This exercise aims at showing some aspects to consider when dealing with non # i.i.d data, typically time series. # # For this purpose, we will create a synthetic dataset simulating stock values. # We will formulate the following data science problem: predict the value of a # specific stock given other stock. # # To make this problem interesting, we want to ensure that any predictive model # should **not** work. In this regard, the stocks will be generated completely # randomly without any link between them. We will only add a constraint: the # value of a stock at a given time `t` will depend on the value of the stock # from the past. # # We will create a function to generate such data. # In[1]: import numpy as np import pandas as pd def generate_random_stock_market(n_stock=3, seed=0): rng = np.random.RandomState(seed) date_range = pd.date_range(start="01/01/2010", end="31/12/2020") stocks = np.array([ rng.randint(low=100, high=200) + np.cumsum(rng.normal(size=(len(date_range),))) for _ in range(n_stock) ]).T return pd.DataFrame( stocks, columns=[f"Stock {i}" for i in range(n_stock)], index=date_range, ) # Now that we have our data generator, let's create three quotes, corresponding # to the quotes of three different companies for instance. We will plot # the stock values # In[2]: stocks = generate_random_stock_market() stocks.head() # In[3]: import matplotlib.pyplot as plt stocks.plot() plt.ylabel("Stock value") plt.legend(bbox_to_anchor=(1.05, 0.8), loc="upper left") _ = plt.title("Stock values over time") # Because the stocks are generated randomly, it is not possible for a # predictive model to be able to predict the value of a stock depending on the # other stocks. By using the cross-validation framework from the previous # exercise, we will check that we get such expected results. # # First, let's organise our data into a matrix `data` and a vector `target`. # Split the data such that the `Stock 0` is the stock that we want to predict # and the `Stock 1` and `Stock 2` are stocks used to build our model. # In[11]: # Write your code here. data = stocks[['Stock 1', 'Stock 2']].reset_index(drop=True) target = stocks[['Stock 0']].reset_index(drop=True) # Let's create a machine learning model. We can use a # `GradientBoostingRegressor`. # In[13]: # Write your code here. from sklearn.ensemble import GradientBoostingRegressor gbr = GradientBoostingRegressor() # Now, we have to define a cross-validation strategy to evaluate our model. # Use a `ShuffleSplit` cross-validation. # In[15]: # Write your code here. from sklearn.model_selection import ShuffleSplit cv = ShuffleSplit(n_splits=30, test_size=0.2) # We should be set to make our evaluation. Call the function `cross_val_score` # to compute the $R^2$ score for the different split and report the mean # and standard deviation of the model. # In[17]: # Write your code here. from sklearn.model_selection import cross_val_score scores = cross_val_score(gbr, data, target, cv=cv, scoring="r2") print(f'{scores.mean()} +/- {scores.std()}') # Your model is not giving random predictions. Could you ellaborate on what # are the reasons of such a success on random data.
434e11bf4a5f81fd9e2530f48082e0eb4ebf2d42
Gustovus/PFB_problemsets
/Python_Problemsets/problemset4_factcount.py
165
3.640625
4
#!/usr/bin/env import sys findfact = sys.argv[1] findfact = int(findfact) count = 1 fact = 1 while count <(findfact+1): fact *= count count += 1 print(fact)
c1aa83cfc9e30f737dd1d88a74e36d89acf280fa
WillianComenalli/ImageSplicingDetection
/source/distanceMetrics.py
485
3.5625
4
''' Created on 05 ott 2016 @author: lorenzocioni Different matrics for evaluating distances bewteen eigenvalues ''' import math def linearDistance(a, b): return abs(a - b) def quadraticDistance(a, b): return pow((a - b), 2) def logarithmicDistance(a, b): if abs(a - b) > 0: return math.log(abs(a - b)) else: return 1000 def squareRootDistance(a, b): return math.sqrt(abs(a - b)) def cubicRootDistance(a, b): return pow((a - b), 1/3)
e1faa3f2477a24537a5d7036514172a2c8580e55
K7evin/Hello
/Hello.py
136
3.875
4
username = input("Hi, whats your name? ") # Respond to the user: nice to meet you “username” print("Nice to meet you, " + username)
0169cd5a80122e36468d2a439803a69b8e9d50dc
Yalfoosh/pizza
/src/yeast_prediction/preprocessing/dataset.py
1,530
3.515625
4
import csv from pathlib import Path from typing import List, Union from .utils import fahrenheit_to_kelvin def preprocess_raw_yeast_dataset( source_path: Union[Path, str], delimiter: str = "\t", ) -> List[List[Union[float, int]]]: """ Preprocesses a dataset in the form of a CSV file. Args: source_path (Union[Path, str]): A Path or a str representing the file path of the dataset you wish to preprocess. delimiter (str, optional): The delimiter of the CSV file. Defaults to "\t". Returns: List[List[Union[float, int]]]: A list of rows that contained the preprocessed data. """ new_rows = list() new_rows.append( ["temperature_kelvin", "cake_yeast_percentage", "fermentation_hours"] ) with open(source_path) as file: iterator = csv.reader(file, delimiter=delimiter) try: next(iterator) except StopIteration: return new_rows for row in iterator: if row is None or len(row) != 5: continue ( temperature_fahrenheit, _, _, cake_yeast_percentage, fermentation_hours, ) = row new_rows.append( [ fahrenheit_to_kelvin(int(temperature_fahrenheit)), float(cake_yeast_percentage), int(fermentation_hours), ] ) return new_rows
e749cecbf7d6c6ded05510be93b75d4df5195615
dixit5sharma/Individual-Automations
/Sudoku_Easy.py
895
3.671875
4
print("Input Sudoku - ") with open("Files/SudokuFileEasy.txt","r") as f: a=[] for line in f: print(line,end="") a.append(list(map(int,line.split()))) loopContinue=True while(loopContinue): for i in range(9): for j in range(9): if a[i][j]==0: s={1,2,3,4,5,6,7,8,9} # Set for k in range(9): s.discard(a[i][k]) s.discard(a[k][j]) if len(s)==1: a[i][j]=int(s.pop()) # print("Updated - ",a[i][j],"at",i+1,j+1) loopContinue=False for i in range(9): for j in range(9): if a[i][j]==0: loopContinue=True print("\n") print("Solved Sudoku - ") for i in range(9): for j in range(9): print(a[i][j],end=" ") print()
0b11a9816b1a01cefa52012d6dce688dd997f361
ashrielbrian/coursera-algorithms-specialization
/01 Algorithmic Toolbox/03 Week 3/covering-segments-revised.py
1,140
3.9375
4
# Uses python3 import sys from collections import namedtuple Segment = namedtuple('Segment', 'start end') def optimal_points(segments): points = [] # Sort according to the end points of each segment in ascending order sortedSegments = sorted(segments, key=lambda segment: segment.end) requiredPoint = sortedSegments[0].end points.append(requiredPoint) # Iterate through each segment in list for i in range(len(sortedSegments)): currentSegment = sortedSegments[i] # If the segment in question is outside the range of the selected coordinate, we choose this new segment end coordinate as the next required point if (requiredPoint < currentSegment.start or requiredPoint > currentSegment.end): requiredPoint = currentSegment.end points.append(requiredPoint) return points if __name__ == '__main__': input = sys.stdin.read() n, *data = map(int, input.split()) segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2]))) points = optimal_points(segments) print(len(points)) for p in points: print(p, end=' ')
45f108190fc597c625059e02ab6e44a784d3aa41
jhonatanmaia/python
/study/curso-em-video/exercises/029.py
132
3.671875
4
a=int(input('Enter the velocity: ')) if a>80: b=(a-80)*7.0 print('You received a traffic ticket! Value $ {:.2f}'.format(b))
642e36b167d30ccdd0426370b18f8bcf80e86300
James-Do9/Python-Mastering-Exercises
/exercises/11-Swap_digits/app.py
292
4.1875
4
#Complete the fuction to return the swapped digits of a given two-digit-interger. def swap_digits(num): left_num = str(num // 10) right_num = str(num % 10) return (right_num) + (left_num) #Invoke the function with any two digit interger as its argument print(swap_digits(13))
6d788d93336c264037107711ff97efaecaf37d90
daniel-reich/ubiquitous-fiesta
/rMwssAueJjn9FmjZC_10.py
253
3.578125
4
def number_pairs(txt): txt = txt.split(' ') numLis = txt[1:] pair = 0 while len(numLis): count = numLis.count(numLis[0]) pair += count//2 numLis = list(filter(lambda n: n !=numLis[0], numLis)) return pair
87fc7bbba277f7d2f4dea919746156af6d54aab4
AdamZhouSE/pythonHomework
/Code/CodeRecords/2618/60760/320294.py
214
3.546875
4
tests=int(input()) #找规律 lists=[] all=[] all.append(tests) for i in range(tests): a=int(input()) all.append(a) lists.append(list(map(int,input().split(' ')))) all+=lists res=sum(all) print(res)
0e2a43ed96efc6516f72956dc2c1d3cc3d5ffc59
henrique17h/Aprendizado_Python
/desafio91.py
1,544
3.65625
4
from time import sleep time = list() dados = dict() partidas = list() while True: dados.clear() dados['Nome'] = str(input('Nome do jogador: ')) total = int(input(f'Quantos partidas {dados["Nome"]} jogou: ')) partidas.clear() totGols = 0 for c in range(1, total+1): partidas.append(int(input(f'Quantos gols na partida {c}: '))) dados['Gols'] = partidas[:] dados['Total'] = sum(partidas) time.append(dados.copy()) while True: resp = str(input('Quer continuar: (S/N)')).upper()[0] if resp in 'SN': break print('Por favor digite apenas "S/N" para continuar ou parar o programa') if resp == 'N': break sleep(1) print('-=' * 30) print('Cod', end='') for i in dados.keys(): print(f'{i:<15}', end='') print() print('-=' * 40) for k, v in enumerate(time): print(f'{k:>3} ', end='') for d in v.values(): print(f'{str(d):<15}', end='') print() print('-=' * 40) while True: busca = int(input('Deseja ver os dados de qual jogador: (999 para interromper)')) if busca == 999: break if busca >= len(time): print(f'Erro! Não existe jogador com o código: {busca}!') sleep(1) else: print(f' ----- Levantamento do Jogador {time[busca]["Nome"]}:') for i, g in enumerate(time[busca]['Gols']): print(f' No jogo {i+1} fez {g} gols.') print('-=' * 40) sleep(2) print('<<<< VOLTE SEMPE!!! >>>>')
e21f6f0c0f7014a0d9ecb10370662a4ab7bd9714
Shelkopryad/python_common
/counter.py
283
3.546875
4
words = input("Write:\n") def replace(s): return s.replace(".", "").replace(",", "").replace("!", "") tmp = [x.lower() for x in replace(words).split()] result = {} for x in tmp: if x not in result: result[x] = 1 else: result[x] += 1 print("\n", result)
b8557b82dccf452688c8d4beabb48a4171f6d6d5
likhitha5101/DAA
/Assignment-5/bruteforce.py
326
3.859375
4
def matchnuts(nuts,bolts): n=len(nuts) for i in range(0,n): for j in range(0,n): if(nuts[j]==bolts[i]): nuts[i],nuts[j]=nuts[j],nuts[i] print("Arranged order of nuts: ",nuts) bolts=[5,2,1,4,9,8,6] nuts=[1,4,6,8,9,5,2] print("Order of Bolts: ",bolts) print("Initial order of nuts: ",nuts) matchnuts(nuts,bolts)