blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8f554b1dfaf1b15ad136b029ed866bba590a2243
sungminoh/algorithms
/leetcode/solved/239_Sliding_Window_Maximum/solution.py
3,811
3.8125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 sungminoh <smoh2044@gmail.com> # # Distributed under terms of the MIT license. """ Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. Follow up: Could you solve it in linear time? Example: Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3 Output: [3,3,5,5,6,7] Explanation: Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Constraints: 1. 1 <= nums.length <= 10^5 2. -10^4 <= nums[i] <= 10^4 3. 1 <= k <= nums.length """ from collections import deque import sys from typing import List import pytest def print_tree(root): from itertools import zip_longest def build_lines(root): if not root: return [''], 0 left, lw = build_lines(root.left) lp = ' '*lw right, rw = build_lines(root.right) rp = ' '*rw s = str(root) subs = [(l if l else lp) + ' '*len(s) + (r if r else rp) for l, r in zip_longest(left, right)] first_line = lp + s + rp return [first_line] + subs, len(first_line) lines, _ = build_lines(root) print('\n'.join(lines)) class Node: def __init__(self, val): self.val = val self.left = None self.right = None def __repr__(self): return '(%r)' % self.val def insert(root, node): if node.val < root.val: if root.left is None: root.left = node else: insert(root.left, node) else: if root.right is None: root.right = node else: insert(root.right, node) def max_val(root): if root.right is None: return root.val else: return max_val(root.right) def remove(root, val): if not root: return None elif root.val == val: if root.right is None: return root.left else: n = root.right while n.left: n = n.left root.val, n.val = n.val, root.val root.right = remove(root.right, n.val) elif val < root.val: root.left = remove(root.left, val) else: root.right = remove(root.right, val) return root class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: i = 0 queue = deque() ret = [] for i, n in enumerate(nums): if queue and queue[0] <= i - k: queue.popleft() while queue and nums[queue[-1]] < n: queue.pop() queue.append(i) if i >= k-1: ret.append(nums[queue[0]]) return ret def _maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: if not nums: return [] root = Node(nums[0]) for i in range(1, min(k, len(nums))): insert(root, Node(nums[i])) ret = [max_val(root)] for i in range(len(nums) - k): j = i + k insert(root, Node(nums[j])) root = remove(root, nums[i]) ret.append(max_val(root)) return ret @pytest.mark.parametrize('nums, k, expected', [ ([1,3,-1,-3,5,3,6,7], 3, [3,3,5,5,6,7]), ([1,-1], 1, [1, -1]) ]) def test(nums, k, expected): assert expected == Solution().maxSlidingWindow(nums, k) if __name__ == '__main__': sys.exit(pytest.main(["-s", "-v"] + sys.argv))
84b35e76c7fd1c9206f27f3f19879bf3785ab8e0
ricardostange/classes
/new_base.py
507
3.96875
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 27 23:57:14 2017 @author: Ricardo """ def new_base(number, base): nNumber = [] #number will be represented as a list of numbers assert ((number > 1) and (number%1) == 0) while number > 0: c = number % base number -= c number /= base nNumber.insert(0,int(c)) return nNumber number = 42 base = 5 print(new_base(number, base)) number = 23 base = 7 print(new_base(number, base))
aa90bf9ad2759bc245e8408e1a3a61e68dd84449
matheusmrf/Linguagem-de-Programacao
/main.py
4,515
4.03125
4
# Nome: Bruno Pena Baeta e Matheus Rangel de Figueiredo # Professor: Hugo Bastos de Paula # Matéria: Linguagens de Programação from lib.interface import * from lib.arquivo import * from time import sleep ########################################### Funcao 1 ###################################################### def func1(): # Formulário do produto global preco, qtde, menor nome = input('Digite o nome do produto (string): ') t = True while t: try: qtde = input('Digite a quantiadade desse produto no estoque (int): ') int(qtde) t = False except: print(f"'{qtde}' não é do tipo int") t = True while t: try: preco = input('Digite o preço desse produto (float): ') float(preco) t = False except: print(f"'{preco}' não é do tipo float") t = True while t: try: menor = input('Esse produto pode ser consumido por menores de idade? (boolean): ') bool(menor) t = False except: print(f"'{menor}' não é do tipo boolean") # Criando dicionário do produto produto = { "nome": nome, "qtde": qtde, "preco": preco, "menor": menor } # Apresentando valores criados print(f"""Produto criado: Nome: {produto["nome"]} Quantidade no estoque: {produto["qtde"]} Preço: R${produto["preco"]} Pode ser consumido por menores de idade? {produto["menor"]} """) ########################################### Funçao 2 ###################################################### # Declarando o vetor de Fibonacci sequencia = [] # Função recursiva que é chamada pela Função 2 e imprime a sequência de Fibonacci def fibonacci(contador, n1, n2): if contador < 1: return 0 else: sequencia.append(n1 + n2) return fibonacci(contador - 1, n2, n1 + n2) # FUNÇÃO 2: Função que apresenta a sequencia de Fibonacci usando recursividade e vetores def func2(): q = int(input('Digite a quantidade de termos que deverão aparecer na sequência: ')) if q < 1: print("Digite um número válido.") elif q < 2: sequencia.append(1) elif q < 3: sequencia.append(1) sequencia.append(1) else: sequencia.append(1) sequencia.append(1) fibonacci(q - 2, 1, 1) print(sequencia) ########################################### Funçao 3 ###################################################### def func3(): arq = 'cadastros.txt' if not arquivoExiste(arq): criarArquivo(arq) while True: resposta = menu(['Cadastrar Pessoas', 'Listar Pessoas Cadastradas', 'Voltar para o menu principal']) if resposta == 1: # Opcao de cadastrar cabecalho('Novo Cadastro') nome = str(input('Digite seu nome: ')) idade = leiaInt('Digite sua idade: ') sexo = input('Digite seu sexo (m/f): ') email = input("Digite seu email: ") cadastrar(arq, nome, idade, sexo, email) elif resposta == 2: lerArquivo(arq) elif resposta == 3: cabecalho('Voltando para o menu principal... ') break else: print('\033[31mErro! Digite uma opcao válida.\033[m') sleep(2) ########################################### MENU PRINCIPAL ###################################################### while True: resposta = menu(['Funcao de criar produto (tipos de dados e dicionários)', 'Função recursiva que apresenta a ' 'sequencia de Fibonacci (recursividade ' 'e vetores)', 'Função para cadastrar ' 'clientes em um arquivo ' 'externo (manipulação de ' 'arquivos)', 'Sair do Sistema']) if resposta == 1: func1() elif resposta == 2: func2() elif resposta == 3: func3() elif resposta == 4: cabecalho('Encerrando o programa. ') break else: print('\033[31mErro! Digite uma opcao válida.\033[m') sleep(2)
85a64671094472f946234a26fa55e7cd9868c22a
shadydealer/Python-101
/Solutions/week10/VehicleManager/src/queries/fetcher.py
665
3.96875
4
import sqlite3 from queries.sqlite3_handler import execute_and_fetch """ A class that is used to select/fetch from given database. """ class Fetcher: def __init__(self, *, dbName): self.dbName = dbName """ Fetches a row from the database by given columns. @return value: Tuple containg the row data from the table. """ def fetch_row(self, *, tableName, columnsAndValues): GET_ROW_SQL = f''' SELECT * FROM {tableName} WHERE {'OR '.join([f'{k} LIKE "%{v}%"' for k,v in columnsAndValues.items()])}; ''' return execute_and_fetch(dbName=self.dbName, query=GET_ROW_SQL)
09e97ca7073eeca611919fd59aaeda5a870c6105
t9niro00/Python
/ExForReview/ex3.py
1,011
4.03125
4
import threading import time val = 0 lock = threading.Lock() class Thread(threading.Thread): def __init__(self, t, *args): threading.Thread.__init__(self, target = t, args = args) self.start() #start the thread def increment(): global val print(threading.currentThread()) #print the current thread try: lock.acquire() #acquire the lock print('lock acquired') val += 1 #add 1 to increment print('Hello world: {}'.format(val)) #print the current increment time.sleep(0.4) #sleep for a little so that the threading is easier to read finally: lock.release() #release the lock print('lock released') def hello_world(): while val < 7: increment() #run the increment function while val is smaller than 7 #main function that starts the two threads run the same function def main(): for i in range(2): thread = Thread(hello_world) if __name__ == '__main__': main() #run the main function
431e5978c7ea9d0f557443e0def0f9341a1180fc
Grande-zhu/CSCI1100
/LAB/LAB3/lab03_check3.py
980
3.53125
4
def find_next(bpop,fpop): bpop_next = max((10*bpop)/(1+0.1*bpop)-0.05*bpop*fpop,0) fpop_next=max(0.4*fpop+0.02*fpop*bpop,0) return(bpop_next,fpop_next) bpop=input("Numbers of bunnies==>") print(bpop) fpop=input("Numbers of foxes==>") print(fpop) bpop=int(bpop) fpop=int(fpop) print("Year 1: {} {}".format(bpop,fpop)) bpop_next=find_next(bpop,fpop)[0] fpop_next=find_next(bpop,fpop)[1] bpop=int(bpop_next) fpop=int(fpop_next) print("Year 2: {} {}".format(bpop,fpop)) bpop_next=find_next(bpop,fpop)[0] fpop_next=find_next(bpop,fpop)[1] bpop=int(bpop_next) fpop=int(fpop_next) print("Year 3: {} {}".format(bpop,fpop)) bpop_next=find_next(bpop,fpop)[0] fpop_next=find_next(bpop,fpop)[1] bpop=int(bpop_next) fpop=int(fpop_next) print("Year 4: {} {}".format(bpop,fpop)) bpop_next=find_next(bpop,fpop)[0] fpop_next=find_next(bpop,fpop)[1] bpop=int(bpop_next) fpop=int(fpop_next) print("Year 5: {} {}".format(bpop,fpop))
ace78408e561f77f81e1bf706ed8b266b30992a5
simonesilvetti/teaching_2017_units_dmg_python
/Lez10/files/Expolish.py
779
4.125
4
def isAnOperator( x ): """Return True if x is '+','-','*','/'""" return (x=='+') or (x=='-') or (x=='*') or (x=='/') def compute( op , x , y ): """Compute the value of expression 'x op y', where -x and y are two integers and op is an operator in '+','-','*','/'""" if (op=='+'): return x+y elif op=='-': return x-y elif op=='*': return x*y elif op=='/': return x/y else: return 0 def evalPolishExpression( e ): """Evaluate expression e in polish notation""" stack = [] for v in [ e[len(e)-i] for i in range(1,len(e)+1) ]: if isAnOperator( v ): stack.append( compute( v , stack.pop() , stack.pop() ) ) else: stack.append( v ) return stack.pop()
4f79ecc3467a8ce226e40a3fb24901003fd9834b
nana-agyeman1/Global-code-py-2k19
/fibonacci.py
195
3.953125
4
fibnum = int(input("Enter the number here: ")) def fib(n): if n == 0 or n == 1: return n return fib(n-1) + fib(n-2) print (list(map(fib, range(1,fibnum+1)))) print(fib(fibnum+1))
bf46193677af2e1abcedd29de35463f0961a9999
umerfarooq01/OOP-in-Python
/class_fun.py
349
3.84375
4
# Here we learn how to create Python Class Functions class course: def __init__(self, name): self.name="Python" self.students=[] def add_students(self,student): self.students.append(student) # c1=course("Python") # c1.add_students("Umer") # c1.add_students("Farooq") # print(c1.students) # print(len(c1.students))
a1d3cd4ff558ec993afbb09351eab9c14514053c
LisaLen/code-challenge
/interview_cake_chals/find_repeat_space_edition.py
1,559
4.125
4
'''Find a duplicate, Space Edition™. We have a list of integers, where: The integers are in the range 1..n1..n The list has a length of n+1n+1 It follows that our list has at least one integer which appears at least twice. But it may have several duplicates, and each duplicate may appear more than twice. Write a function which finds an integer that appears more than once in our list. (If there are multiple duplicates, you only need to find one of them.) We're going to run this function on our new, super-hip MacBook Pro With Retina Display™. Thing is, the damn thing came with the RAM soldered right to the motherboard, so we can't upgrade our RAM. So we need to optimize for space! >>> find_duplicate([1, 2, 1, 3, 4, 6, 5]) 1 >>> find_duplicate([1,1]) 1 ''' def find_duplicate(lst): floor = 1 ceiling = len(lst) - 1 while floor < ceiling: mid = floor + (ceiling - floor) // 2 # found to ranges of numbers floor... mid, mid+1 ... ceiling numbers_in_lower_range = 0 lower_floor = floor lower_ceiling = mid for item in lst: if item >= lower_floor and item <= lower_ceiling: numbers_in_lower_range += 1 lower_range_len = lower_ceiling - lower_floor + 1 if numbers_in_lower_range > lower_range_len: ceiling = lower_ceiling else: floor = lower_floor return ceiling if __name__ =='__main__': import doctest if doctest.testmod().failed == 0: print('\n***PASSED***\n')
3c372d5795cd918bd30cc6138313d85fc99430d1
GamaCatalin/Facultate
/An1_sem1/Python/Seminar/Seminar 8/Client.py
943
3.578125
4
class Client: def __init__(self, clientId, name, age): self._clientId = clientId self.Name = name self.Age = age @property def Id(self): return self._clientId @property def Name(self): return self._name @Name.setter def Name(self, value): if value == None or len(value) < 3: raise ValueError("Client name too short") self._name = value @property def Age(self): return self._age @Age.setter def Age(self, value): if value == None or value < 18: raise ValueError("Client must be 18!") self._age = value def __eq__(self, z): if isinstance(z, Client) == False: return False return self.Id == z.Id def __str__(self): return "Id=" + str(self.Id) + ", Name=" + str(self.Name) + ", Age="+str(self.Age) def __repr__(self): return str(self)
6a0dc338b01871fa14dd54353870eb2114094c22
taniamichelle/Sprint-Challenge--Intro-Python
/src/oop/oop2.py
1,296
4.0625
4
# GroundVehicle class class GroundVehicle(): # change it so the num_wheels defaults to 4 if not specified def __init__(self, name = 'Bob', num_wheels = 4): self.name = name self.num_wheels = num_wheels # add method drive() that returns "vroooom". def drive(self): return ("vroooom") # instantiate instance of GroundVehicle to test g = GroundVehicle("Fred") print(g.name) print(g.num_wheels) print(g.drive()) # Subclass Motorcycle from GroundVehicle. class Motorcycle(GroundVehicle): # when you instantiate a Motorcycle, it should automatically set # num_wheels to 2 by passing it to the constructor of its superclass. def __init__(self, name = 'Rosie', num_wheels = 2): super().__init__(name, num_wheels) self.num_wheels = num_wheels # Override the drive() method in Motorcycle so that it returns "BRAAAP!!" def drive(self): return ("BRAAAP!!") # instantiate instance of Motorcycle to test m = Motorcycle("Jillian") print(m.name) print(m.num_wheels) print(m.drive()) vehicles = [ GroundVehicle(), GroundVehicle(), Motorcycle(), GroundVehicle(), Motorcycle(), ] # Go through the vehicles list and print the result of calling drive() on each. for v in vehicles: print(v.drive())
099f76cf84cef7876162dea49aff47b44c10ee44
guiconti/workout
/leetcode/148.sort-list/148.sort-list.py
1,752
3.9375
4
# 148. Sort List # Medium # 2038 # 102 # Add to List # Share # Sort a linked list in O(n log n) time using constant space complexity. # Example 1: # Input: 4->2->1->3 # Output: 1->2->3->4 # Example 2: # Input: -1->5->3->4->0 # Output: -1->0->3->4->5 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def sortedMerge(self, a, b): result = None # Base cases if not a: return b if not b: return a # pick either a or b and recur.. if a.val <= b.val: result = a result.next = self.sortedMerge(a.next, b) else: result = b result.next = self.sortedMerge(a, b.next) return result def mergeSort(self, head): # Base case if head is None if not head or not head.next: return head # get the middle of the list middle = self.getMiddle(head) nextToMiddle = middle.next # set the next of middle node to None middle.next = None # Apply mergeSort on left list left = self.mergeSort(head) # Apply mergeSort on right list right = self.mergeSort(nextToMiddle) # Merge the left and right lists sortedList = self.sortedMerge(left, right) return sortedList # Utility function to get the middle # of the linked list def getMiddle(self, head): if not head: return head slow = head fast = head while fast.next and fast.next.next: slow = slow.next fast = fast.next.next return slow def sortList(self, head: ListNode) -> ListNode: head = self.mergeSort(head) return head
15eb83fef03b64c1a0170c5d768d28cdda155222
jyt0532/Trie
/trie.py
2,143
3.640625
4
class TrieNode: def __init__(self, count, depth): self.count = count self.depth = depth self.children = Trie() def add_count(self, count): self.count = self.count+count class Trie: def __init__(self): self.tree = {} def add_words(self, words, count, depth): if words[0] not in self.tree: self.tree[words[0]] = TrieNode(0, depth+1) if len(words) == 1: self.tree[words[0]].add_count(count) else: self.tree[words[0]].children.add_words(words[1:], count, depth+1) def print_trie(self): for key, value in self.tree.iteritems(): tabs = "" for i in range(0, value.depth-1): tabs = tabs + "\t" print tabs + key + ":" + str(value.count) if bool(value.children): value.children.print_trie() def get_string_count(self, words): if words[0] not in self.tree: return 0 else: if len(words) == 1: if self.tree[words[0]].count != 0: return self.tree[words[0]].count else: return 0 else: return self.tree[words[0]].children.get_ngram_count(words[1:]) if __name__=="__main__": simple_trie = Trie() sentence1 = "apple ipad mini" sentence2 = "apple ipad" sentence3 = "apple" sentence4 = "apple ipad price" sentence5 = "banana" sentence6 = "banana ha ya" words1 = sentence1.split(" ") words2 = sentence2.split(" ") words3 = sentence3.split(" ") words4 = sentence4.split(" ") words5 = sentence5.split(" ") words6 = sentence6.split(" ") simple_trie.add_words(words1, 5, 0) simple_trie.add_words(words2, 4, 0) simple_trie.add_words(words3, 3, 0) simple_trie.add_words(words4, 2, 0) simple_trie.add_words(words5, 1, 0) simple_trie.add_words(words6, 6, 0) simple_trie.add_words(words4, 100, 0) simple_trie.print_trie() print simple_trie.get_ngram_count(["apple", "ipad", "bye"]) print simple_trie.get_ngram_count(words4)
7221bdcb89acd281939e4b41da274489a664fbe0
lvah/201901python
/day25/16_字符串的替换与分离.py
623
3.78125
4
""" 文件名: $NAME.py 日期: 25 作者: lvah 联系: xc_guofan@qq.com 代码描述: """ import re s = 'westos is a company' print(s.replace('westos', 'fentiao')) # 将westos和company都替换位cat print(re.sub(r'(westos|company)', 'cat', s)) # 将所有的数字替换位0; s1 = "本次转发数位100, 点赞数为80;" print(re.sub(r'\d+', '0', s1)) def addNum(Obj): # num是一个字符串 num = Obj.group() # newNum是一个整形数 newNum = int(num) + 1 return str(newNum) # .*? # 对于所有的数字加1; print(re.sub(r'\d+', addNum, s1)) s2 = '1+2=3' print(re.split(r'[+=]', s2))
d79e045bb012beb7d942ed0a6259f6e5a6408cf1
Joz1203/COM404
/1-basics/4-repetition/2-for-loop/3-range/bot.py
367
3.921875
4
#user input brightness level print("What level of brightness is required?") brightness = int(input("")) print() print("Adjusting brightness...") print() #brightness increasing for number in range(2, brightness + 1, 2): print("Beep's brightness level:", number * "*") print("Bop's brightness level:", number * "*") print() print("Adjustments complete!")
2653880ea9174d601ea8347dcc3e6cfc0a5bcc3c
Telmo465/AI-B
/aplic8.py
241
3.578125
4
import random s=1 n = int(input("Número de elementos")) a = [0 for i in range (n)] for i in range(n): a[i]=random.randint(0,1000) if i%2 == 0: s*= a[i] print(a) if s != 1: print("Produto dos números de indice par:", s)
d08084271f5394620541adc010f196144fe312a8
joymaxnascimento/python
/hackerrank/python-mutations.py
286
3.6875
4
""" https://www.hackerrank.com/contests/linguagens-de-programacao-para-ciencia-de-dados/challenges/python-mutations """ def mutate_string(string, position, character): string = list(string) string[position] = character string = ''.join(string) return string
036f0cf31b5bd9dc0ab0a7d4e2750d0f43982651
Deanwinger/python_project
/python_fundemental/148_Diameter_of_Binary_Tree.py
886
3.953125
4
# leetcode 543. Diameter of Binary Tree # 程序员代码面试指南 P169 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 这一题有点tricky的就是, 有三种情况, 最长直径在左树, 或者是右树, 还可能是跨越左右树 class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: if not root: return 0 left = self.get_length(root.left) right = self.get_length(root.right) o = left+right t = self.diameterOfBinaryTree(root.left) s = self.diameterOfBinaryTree(root.right) return max((t,s,o)) def get_length(self, root): if not root: return 0 return max(self.get_length(root.left), self.get_length(root.right))+1
d7e383992ce3ece3a756c9598ad595075c715efa
NWChen/tshirt-shooting-robot
/Code/sim/Wheel.py
1,168
4.28125
4
import math from Point import Point """ Implements an independent swerve module as a wheel. """ class Wheel(object): """ Creates a Wheel object. @type center: Point @param center: The center of mass of the rectangle representing the wheel's shape @type speed: number @param speed: The speed with which the wheel moves """ def __init__(self, center=Point(0,0), speed=0.0): self.angle = 0.0 # angle to the axis perpendicular to the forward-facing edge of the chassis self.angle_to_field = 0.0 # angle to the axis perpendicular to the top edge of the field self.center = center self.speed = speed """ Sets the speed of the wheel from a range of -1.0 to 1.0. @type speed: number @param speed: The speed of the wheel """ def set_speed(self, speed): if speed < -1.0: self.speed = -1.0 elif speed > 1.0: self.speed = 1.0 else: self.speed = speed """ Sets the angle of the wheel relative to the chassis of the robot. """ def set_angle(self, angle): self.angle = angle % 360 """ Sets the angle of the wheel relative to the field. """ def set_angle_to_field(self, angle_to_field): self.angle_to_field = angle_to_field % 360
77930e259dcee9191ac3608d5dd41cf0c41d84d1
muskansaini017/Calculator-GUI-Tkinter
/main.py
5,701
3.53125
4
import tkinter as tk from tkinter import * from tkinter import messagebox value='' int_value=0 operator='' # functions def btn1_clicked(): global value value=value + "1" data.set(value) def btn2_clicked(): global value value= value+"2" data.set(value) def btn3_clicked(): global value value= value+"3" data.set(value) def btn4_clicked(): global value value= value+"4" data.set(value) def btn5_clicked(): global value value= value+"5" data.set(value) def btn6_clicked(): global value value= value+"6" data.set(value) def btn7_clicked(): global value value= value+"7" data.set(value) def btn8_clicked(): global value value= value+"8" data.set(value) def btn9_clicked(): global value value= value+"9" data.set(value) def btn0_clicked(): global value value= value+"0" data.set(value) def btnadd_clicked(): global int_value global operator global value int_value=int(value) operator='+' value=value +"+" data.set(value) def btnsub_clicked(): global int_value global operator global value int_value = int(value) operator = '-' value = value + "-" data.set(value) def btnmul_clicked(): global int_value global operator global value int_value = int(value) operator = 'x' value = value + "x" data.set(value) def btndiv_clicked(): global int_value global operator global value int_value = int(value) operator = '/' value = value + "/" data.set(value) def btnclear_clicked(): global int_value global operator global value value='' int_value=0 operator='' data.set(value) def btnequal_clicked(): global int_value global operator global value value2=value if operator=='+': x= (int(value2.split("+")[1])) c= int_value+x data.set(c) value=str(c) elif operator=='-': x= (int(value2.split("-")[1])) c= int_value-x data.set(c) value=str(c) elif operator=='x': x= (int(value2.split("x")[1])) c= int_value * x data.set(c) value=str(c) elif operator == '/': x = (int(value2.split("/")[1])) if x==0: messagebox.showerror("Error","Division by Zero") int_value=0 value='' data.set(value) else: c = int(int_value / x) data.set(c) value = str(c) # initializing window window=tk.Tk() window.title("Calculator Project") #window.configure(background='Green') window.geometry('300x400+300+90') window.resizable(0,0) # creating label data= StringVar() label1=Label( window,text="Label",anchor=SE,font=("Verdana",20), textvariable=data,background='White',fg='Black' ) # SE=South-east label1.pack(expand=True, fill= "both") # creating frames frame1= Frame(window,bg='Black') # you can use --> bg="#000000" for black frame1.pack(expand=True, fill= "both") frame2= Frame(window) frame2.pack(expand=True, fill= "both") frame3= Frame(window) frame3.pack(expand=True, fill= "both") frame4= Frame(window) frame4.pack(expand=True, fill= "both") # creating buttons for frame1 btn1=Button(frame1,text="1", font=("Verdana",22),relief=GROOVE,border=0,command=btn1_clicked) btn1.pack(side=LEFT,expand=True,fill='both') btn2=Button(frame1,text="2", font=("Verdana",22),relief=GROOVE,border=0,command=btn2_clicked) btn2.pack(side=LEFT,expand=True,fill='both') btn3=Button(frame1,text="3", font=("Verdana",22),relief=GROOVE,border=0,command=btn3_clicked) btn3.pack(side=LEFT,expand=True,fill='both') btnadd=Button(frame1,text="+", font=("Verdana",22),relief=GROOVE,border=0,command=btnadd_clicked) btnadd.pack(side=LEFT,expand=True,fill='both') # creating buttons for frame2 btn4=Button(frame2,text="4", font=("Verdana",22),relief=GROOVE,border=0,command=btn4_clicked) btn4.pack(side=LEFT,expand=True,fill='both') btn5=Button(frame2,text="5", font=("Verdana",22),relief=GROOVE,border=0,command=btn5_clicked) btn5.pack(side=LEFT,expand=True,fill='both') btn6=Button(frame2,text="6", font=("Verdana",22),relief=GROOVE,border=0,command=btn6_clicked) btn6.pack(side=LEFT,expand=True,fill='both') btnsub=Button(frame2,text="-", font=("Verdana",22),relief=GROOVE,border=0,command=btnsub_clicked) btnsub.pack(side=LEFT,expand=True,fill='both') # creating buttons for frame3 btn7=Button(frame3,text="7", font=("Verdana",22),relief=GROOVE,border=0,command=btn7_clicked) btn7.pack(side=LEFT,expand=True,fill='both') btn8=Button(frame3,text="8", font=("Verdana",22),relief=GROOVE,border=0,command=btn8_clicked) btn8.pack(side=LEFT,expand=True,fill='both') btn9=Button(frame3,text="9", font=("Verdana",22),relief=GROOVE,border=0,command=btn9_clicked) btn9.pack(side=LEFT,expand=True,fill='both') btnmul=Button(frame3,text="x", font=("Verdana",22),relief=GROOVE,border=0,command=btnmul_clicked) btnmul.pack(side=LEFT,expand=True,fill='both') # creating buttons for frame4 btnclear=Button(frame4,text="C", font=("Verdana",22),relief=GROOVE,border=0,command=btnclear_clicked) btnclear.pack(side=LEFT,expand=True,fill='both') btn0=Button(frame4,text="0", font=("Verdana",22),relief=GROOVE,border=0,command=btn0_clicked) btn0.pack(side=LEFT,expand=True,fill='both') btnequal=Button(frame4,text="=", font=("Verdana",22),relief=GROOVE,border=0,command=btnequal_clicked) btnequal.pack(side=LEFT,expand=True,fill='both') btndiv=Button(frame4,text="/", font=("Verdana",22),relief=GROOVE,border=0,command=btndiv_clicked) btndiv.pack(side=LEFT,expand=True,fill='both') window.mainloop()
21ac9ce105bc80c334246e34b568587283443c2d
Qiumy/leetcode
/Python/349. Intersection of Two Arrays.py
842
4.09375
4
# Given two arrays, write a function to compute their intersection. # # Example: # Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. # # Note: # Each element in the result must be unique. # The result can be in any order. class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ res = [] for num in nums1: if num in nums2 and not num in res: res.append(num) return res class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ nums1, nums2 = set(nums1), set(nums2) return list(nums1 & nums2)
15191d3fe67a6833d147bec33dac3bfcabda6440
AyushSingh445132/What-I-have-learnt-so-far-in-Python
/11.2.Python Exercise 3 - Guess the number.py
1,078
4.375
4
# Create a Program to guess a given number # Rerun the program to a specific number of turns # After every turn print whether the typed number is "greater" or "lesser" than the number to be found # If the user cannot guess the number after all turns are finished print "Game Over" # If the user won print the number of guesses user took to finish it. # guess number n = 26 # nog = number_of_guesses nog = 1 print("You will get 5 chances to guess the correct number") while (nog<=5): # gn = guess_number gn = int(input("Enter Number:\n")) if gn<n: print("Sorry!! wrong number.Guess a number greater than this\n") elif gn>n: print("Sorry!! wrong number.Guess a number smaller than this\n") else : print("Congratulation you won the Game") print("You have guessed the correct number") print("You took" , nog , "guess to finish the game") break print(5-nog, "guesses left") nog = nog + 1 if (nog>5): print("Game Over\n") print("You could not guess the number")
85f479e8f3248fd718125af703bcbb3cfb440079
anniemaa/OOP-Python
/20-valid-parentheses.py
840
3.703125
4
class Solution: def isValid(self, s: str) -> bool: pastParens = [] for i in s: if self.isOpenParens(i): pastParens.append(i) elif len(pastParens) == 0: return False else: op = pastParens.pop() cl = i if not self.parenIsSameType(op, cl): return False return len(pastParens) == 0 def isOpenParens(self, p): if p == '(' or p == '[' or p == '{': return True else: return False def parenIsSameType(self, op, cl): if op == '(' and cl == ')': return True if op == '[' and cl == ']': return True if op == '{' and cl == '}': return True else: return False
7ee6fa12cc6b26d97c2c53228871c4509baaee8a
Anitha710/265441_Daily_Commits
/dictionaries.py
679
4.0625
4
# dictionaries ages = {"Dave": 24, "Mary":42, "Jhon": 58} print(ages["Dave"]) print(ages["Mary"]) # use of get pairs = { 1: "apple", "orange": [2, 3, 4], True: False, None: "True", } print(pairs.get("orange")) print(pairs.get(7)) print(pairs.get(12345, "not in dictionary"))\ #example fib = {1: 1, 2: 1, 3: 2, 4: 3} print(fib.get(7, 5) + fib.get(4, 0)) # tuple words = ("spam", "eggs", "sausages",) print(words[0]) # list slices squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(squares[2:6]) print(squares[3:8]) print(squares[:6]) print(squares[::6]) print(squares[2:6:3]) # example sqs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(sqs[7:5:-1])
5328876f4bca08519a70ee63158fe2e0c6fa04ef
emotrix/Emotrix
/emotrix/TimeBuffer.py
1,169
3.5625
4
# -*- coding: utf-8 -*- import time class TimeBuffer: dataBuffer = None timestamps = None seconds_back = 0 def __init__(self, seconds_back): self.dataBuffer = [] self.timestamps = [] self.seconds_back = seconds_back def insert(self, value): """ Insert an element into buffer. """ current_timestamp = time.time() self.timestamps.append(current_timestamp) self.dataBuffer.append(value) if (self.timestamps[0] < (current_timestamp - self.seconds_back)): self.dataBuffer.pop(0) self.timestamps.pop(0) def getAll(self): """ Retrieve all data from buffer. """ return self.dataBuffer def getLast(self): """ Retrieve last element from buffer. """ return self.dataBuffer[len(self.dataBuffer) - 1] def getLength(self): return len(self.dataBuffer) def getAllAndClearBuffer(self): """ Retrieve all data and clear buffer. """ data = self.dataBuffer self.dataBuffer = [] self.timestamps = [] return data
122a11eac175b7b8764c8d7410a4702ecd0d0c7e
wtyqqq/lzu_ds_review_2020
/CS171/lab11/ex5.py
758
3.71875
4
def printSubStr(str, low, high): for i in range(low, high + 1): print(str[i], end="") print(' ') def longestPalSubstr(str): n = len(str) maxLength = 1 start = 0 for i in range(n): for j in range(i, n): flag = 1 for k in range(0, ((j - i) // 2) + 1): if (str[i + k] != str[j - k]): flag = 0 if (flag != 0 and (j - i + 1) > maxLength): start = i maxLength = j - i + 1 printSubStr(str, start, start + maxLength - 1) return maxLength if __name__ == '__main__': longestPalSubstr('babab') longestPalSubstr('bab') longestPalSubstr('cbbd') longestPalSubstr('a') longestPalSubstr('acc')
3c9f1841ed07919237ad8eea4b2ab1a603b71a58
ivnxyz/practicas-programacion-inviertete
/CAROLA/trabajo de CAROLA.py
537
3.84375
4
r=1.1 pi=3.1416 area= pi*(r*r) print(area) #DEVUELVE EL VALOR ABSOLUTO n=1 d=21 diferencia= n-d print (diferencia) #propinas total=44.50 propina=10 t= total/10 prpo= t+total print(prpo) #calcula tu peso en otro planeta p= 70 gt= 9.78 gm= 3.72 total = p*gm print(total) # strings m="hola" m*100 #mensaje con vareables nombre="carola" abjetivo="chida" verbo="jugar" #letra indice var="abcdefghijk" lent=[10] #tranformar a mayuscuula enunciado="hola mundo" enunciado.upper() #tranforma a minusculas var="HOLA MUNDO" var.lower()
c5231793ee131cbaa7bed37fb3b4f19ee4c9234f
singhdharm17/Python_Edureka
/Question_6.py
312
3.84375
4
# 6. Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 # and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. lst = [i for i in range(2000, 3000) if i % 7 == 0 if i % 5 != 0] print(lst)
4544c39b2de51f2fd3e0361618a1164b3e682475
MakrisHuang/LeetCode
/python/300_longest_increasing_subsequence.py
1,443
3.75
4
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: # in brute force it gives us O(n^2) time complexity # here we will maintain a global array that store the longest chain # To maintain this, every time we iterate the element, we insert the # elements with binary search. This will give us O(NlogN) time complexity def binary_search_get_index(nums, target) -> int: left, right = 0, len(nums) - 1 while left < right: mid = left + (right - left) // 2 if nums[mid] == target: return mid elif nums[mid] < target: left = mid + 1 else: right = mid return left sub = [nums[0]] for num in nums[1:]: if num > sub[-1]: sub.append(num) else: i = binary_search_get_index(sub, num) sub[i] = num return len(sub) def lengthOfLIS_python_binary_search(self, nums: List[int]) -> int: sub = [] for num in nums: i = bisect_left(sub, num) # If num is greater than any element in sub if i == len(sub): sub.append(num) # Otherwise, replace the first element in sub greater than or equal to num else: sub[i] = num return len(sub)
eeb1fdca8c77326defe6728765df1d6f70282ead
deequez/Exercise03
/calculator.py
1,106
4.03125
4
from arithmetic import * while True: user_input = raw_input("> ") tokens = user_input.split(" ") if len(tokens) == 2 or len(tokens) == 3: tokens[1] = int(tokens[1]) if len(tokens) == 3: tokens[2] = int(tokens[2]) if tokens[0] == 'q': break elif tokens[0] == '+': addition = add(tokens[1], tokens[2]) print addition elif tokens[0] == '-': subtraction = subtract(tokens[1], tokens[2]) print subtraction elif tokens[0] == '*': multiplication = multiply(tokens[1], tokens[2]) print multiplication elif tokens[0] == '/': division = divide(tokens[1], tokens[2]) print division elif tokens[0] == 'square': square_it = square(tokens[1]) print square_it elif tokens[0] == 'cube': cube_it = cube(tokens[1]) print cube_it elif tokens[0] == 'pow': power_it = power(tokens[1], tokens[2]) print power_it elif tokens[0] == 'mod': mod_it = mod(tokens[1], tokens[2]) print mod_it
760774bf6f254646c5283eb11a1cdb7b0edc6e2b
Kaichloe/algo_expert
/Easy/valid_seq.py
163
3.515625
4
def isValidSubsequence(array, sequence): counter = 0 for num in array: if num == sequence[counter]: counter += 1 return counter == len(sequence)
1c664719abb52c8fafb1d05814ab96581b00550e
phroiland/forex_algos
/forex/src/pricing/currency.py
3,020
4.21875
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed May 31 07:17:05 2017 @author: jonfroiland """ """ Be sure to include docstrings at the module, class, and method levels. """ """ The advantage of class definitions in general is to achieve code reuse via inheritance. """ class Currency: def __init__(self, date_time, price): self.date_time = date_time, self.price = self.price() class Euro(Currency): def price(self): return Decimal(self.price) class Cable(Currency): def price(self): return Decimal(self.price) class Loonie(Currency): def price(self): return Decimal(self.price) class Swiss(Currency): def price(self): return Decimal(self.price) class Kiwi(Currency): def price(self): return Decimal(self.price) class Aussie(Currency): def price(self): return Decimal(self.price) """ The following is a class that will be used to build four positions. - Long - Stop Loss for Long - Short - Stop Loss for Short """ class Position: def __init__(self,name, symbol): self.name = name, self.symbol = symbol Long, stopLong, Short, stopShort = Position('Long','L'), Position('stopLong','SL'), Position('Short','S'), Position('stopShort','SS') positions = [Euro('EURUSD',Long),Cable('GPBUSD',Long),Loonie('USDCAD',Long), Swiss('USDCHF',Long),Kiwi('NZD/USD',Long),Aussie('AUDUSD',Long)] class Economics(): """ Economic Releases Eurozone: monthly economic data is generally released at 2 a.m. Eastern Time (ET) in the United States. The time segment from 30 to 60 minutes prior to these releases and one to three hours after- wards highlights an enormously popular period to trade EUR pairs because the news will impact at least three of the five most popular crosses. It also overlaps the run-up into the U.S. trading day, drawing in significant volume from both sides of the Atlantic. USzone: U.S. economic releases tend to be released between 8:30 a.m. and 10 a.m. ET and generate extraordinary EUR trading volume as well, with high odds for strongly trending price movement in the most popular pairs. Japanese data releases get less attention because they tend to come out at 4:30 p.m. and 10 p.m. ET, when the eurozone is in the middle of their sleep cycle. Even so, trading volume with the EUR/JPY and EUR/USD pairs can spike sharply around these time zones. """ def __init__(self, zone, hours): self.zone = zone self.hours = hours def eurozone(self, instrument, hours): def uszone(self, instrument, hours):
15130f2b5d21d2da894a83d546905c8e602cdabf
cloudoutloud/learn-python
/entry-level/bio.py
439
4.21875
4
# This script pulls user data and prints as a string name = input("What is your name? ") color = input("What is your favorite colour? ") age = int(input("How old are you today? ")) # Use end=" " to place print all on same line # print(name, end=" ") # print("is " + str(age) + " years old", end=" ") # print("and loves the color " + color + ".", end=" ") print(name, 'is', age, 'years old and loves the color', color + '.', sep=", ")
d5bfc5be15cc515cc8d5b239ad0e296e4f2466e4
amj4379/cti110
/P2HW2 - Tip Tax Total.py
415
3.765625
4
# CTI-110 # P2HW2 - Tip Tax Total # Anthony Jackson # 2/20/18 BillTotal =float(input("Enter Bill Total $ ")) tip = 0.18 * BillTotal salesTax = .07 * BillTotal total = BillTotal + tip + salesTax print ("Bill Total $" + format(BillTotal, ",.2f")) print ("tip $" + format(tip, ",.2f")) print ("salesTax $" + format(salesTax, ",.2f")) print ("total $" + format(total, ",.2f"))
0fef8977a674085aa2e06732c6357be85a90baea
hianp/Exercicios_Curso_em_video_Py
/Ex036.py
381
3.71875
4
v = float(input('Qual o valor da casa: R$')) s = float(input('Qual seu sálario: R$')) a = int(input('Vai pagar em quantos anos? ')) m = a * 12 prest = v / m porc = (s * 30)/100 print(f'Para pagar uma casa de R${v:.2f} em {a} anos a prestação será de R${prest:.2f}') if prest > porc: print('Empréstimo negado') else: print('Emprestimo pode ser CONCEDIDO')
fe66bcfada0493272468203cb0d496899da93bda
RomyRobi/Homework3-Python
/PyPoll/main.py
2,020
3.53125
4
# Import Dependencies import os import csv # Create file path csv_path = os.path.join("Resources", "election_data.csv") # Open file as cvs file and skip headers with open(csv_path, newline='') as csv_file: csv_reader = csv.reader(csv_file, delimiter = ',') next(csv_reader) # Create counter/dictionary for total number of votes, candidates' votes, etc. count_votes = 0 candidates_votes = {} winner = 0 # Loop through each row of data for row in csv_reader: # If statement to add candidate and first vote to dictionary or tally votes if row[2] not in candidates_votes.keys(): candidates_votes[row[2]] = 1 else: candidates_votes[row[2]] += 1 # Increase vote count for each row of data count_votes += 1 # Open/create .txt file to write results to txt_file = open("PypollResults.txt", "w") # Print results to terminal and .txt file print("Election Results") print("---------------------------------") print(f'Total Votes: {count_votes}') print("---------------------------------") print("Election Results", file=txt_file) print("---------------------------------", file=txt_file) print(f'Total Votes: {count_votes}', file=txt_file) print("---------------------------------", file=txt_file) # Loop through dictionary to extract candidates and their votes and print for key, value in candidates_votes.items(): if value > winner: winner = value winner_name = key percent_total = round((value/count_votes)*100, 3) print(f'{key}: {percent_total}% ({value})') print(f'{key}: {percent_total}% ({value})', file=txt_file) print("---------------------------------") print("---------------------------------", file=txt_file) print(f'Winner: {winner_name}') print(f'Winner: {winner_name}', file=txt_file) print("---------------------------------") print("---------------------------------", file=txt_file)
d517544485061403429d5c51aefd791e3af308fd
daniel-reich/ubiquitous-fiesta
/hmt2HMc4XNYrwPkDh_19.py
96
3.875
4
def invert(s): if s == "": return "" return s[len(s)-1].swapcase() + invert(s[:len(s)-1])
563694cf32aed11ad54be215c46d732fd25b3b7c
RMolleda/Python__init__
/exercises/practice.py
105
4.0625
4
x = " | " y = "___" for num in range(8): print(y * 8, sep="") print(x * 8, sep="") print(y *8)
1331a65410c8cf1b61dda59afebaa048904097de
ivklisurova/SoftUni_Python_Advanced
/Functions_advanced/operate.py
534
4.03125
4
def operate(fargs, *args): result = 0 for i in range(len(args)): if i == 0: result = args[i] else: if fargs == '+': result += args[i] # elif fargs == '-': # result -= args[i] elif fargs == '*': result *= args[i] # elif fargs == '/': # result /= args[i] return result print(operate("+", 1, 2, 3)) print(operate("*", 3, 4)) # print(operate('/', 15, 3)) # print(operate('-', 12, 2))
1588126651e2370e9d44ae8e72c72bde52634471
lucaGazzola/sudoku-solver
/sudoku.py
829
3.609375
4
import numpy as np def is_possible(sudoku,i,j,n): return n not in sudoku[i] and n not in sudoku[:,j] and n not in sudoku[(i//3)*3:(i//3)*3+3, (j//3)*3:(j//3)*3+3] def fill(sudoku): global counter for k in range(0,len(sudoku)): for j in range (0,len(sudoku[k])): if sudoku[k][j] == 0: for i in range(1,10): if is_possible(sudoku,k,j,i): sudoku[k][j] = i fill(sudoku) counter += 1 sudoku[k][j] = 0 return print(sudoku) if __name__ == '__main__': global counter sudoku = np.genfromtxt('sudoku_hard.csv', delimiter=',') print(sudoku) counter = 0 fill(sudoku) print('filling procedure rolled back {} times'.format(counter))
91695f7be1e9ceba3818ef808d9dee0d61a82c6c
brittani-ericksen/dec2020-dir
/week_01/python2/list.py
914
3.984375
4
# appending to list power_rangers = [] power_rangers.append("Jason") power_rangers.append("Trini") power_rangers.append("Billy") power_rangers.append("Zack") power_rangers.append("Kim") print(power_rangers) ############################## # while loop power_rangers = [] power_rangers.append("Jason") power_rangers.append("Trini") power_rangers.append("Billy") power_rangers.append("Zack") power_rangers.append("Kim") index = 0 while index < len(power_rangers): print(power_rangers[index]) index += 1 ############################## # for loop power_rangers = ['Jason', 'Trini', 'Billy', 'Zack', 'Kim'] for ranger in power_rangers: print(ranger) ############################## power_rangers = ['Jason', 'Trini', 'Billy', 'Zack', 'Kim'] print(power_rangers) # add tommy power_rangers.append("Tommy") print(power_rangers) # remove tommy power_rangers.remove("Tommy") print(power_rangers)
bb843863c940ce7ff71124ed78b86af6c38867ea
Chloe5/event-driven-gainiangu
/1_weibo_hot_events_detection/Crawler/DynamicCrawler/DynamicCrawler/Utility.py
658
3.515625
4
def loop_increase(integer, base): """ increase integer by 1 if it exceeds base then reset integer :param integer: :param base: :return: """ return (integer + 1) % base def reset_dict(dict): for key in dict: dict[key] = '' def test_exception(func): """ Try to test exception on one certain function :param func: :return: """ def _test_eception(*args, **keyargs): try: return func(*args, **keyargs) except Exception as e: print e print 'Error execute: %s' % func.__name__ return _test_eception
f0d0dfbf3d13aec99ffb9b92e5f050a107d48104
edneipdemelo/1stWeek
/014.py
210
4.125
4
# Leia um ângulo em graus e apresente-o convertido em radianos. print('Digite o ângulo em graus:') degree = float(input()) radian = degree * 3.14 / 180 print(f'O ângulo convertido em radianos é: {radian}')
e8734ddaf8f0081b397f647b27da5245c87e0061
Elida2000/Tarea2
/exercise02-result/main_app.py
1,721
3.765625
4
from proyecto_finanzas import ProyectoFinanzas, Ingresos, Egresos print("Inicio ProyectoFinanzas: \n") proyectoFinanzasObj = ProyectoFinanzas() while True: print("Menu: \n") print("(0) salir") print("(1) registrar ingreso") print("(2) registrar egreso") print("(3) ver reporte de ingresos") print("(4) ver reporte de egresos") print("(5) ver reporte de todas las transacciones") print("(6) ver reporte total de la cuenta \n") option = int(input("opcion: ")) print() if option == 0: print("Termino ProyectoFinanzas\n") break elif option == 1: NewEntries = float(input("Puede agregar el monto a ingresar: ")) proyectoFinanzasObj.addEntries(Ingresos(NewEntries)) print() elif option == 2: NewExpenses = float(input("Puede registrar su egreso: ")) proyectoFinanzasObj.addExpenses(Egresos(NewExpenses)) print() elif option == 3: print("Su reporte de ingresos es: ") proyectoFinanzasObj.getEntries() print() elif option == 4: print("Su reporte de egresos es: ") proyectoFinanzasObj.getExpenses() print() elif option == 5: print("Su reporte de todas las transacciones realizadas es: ") proyectoFinanzasObj.getAllFinances() print() elif option == 6: proyectoFinanzasObj.totalAccount() print() elif ( option != 0 or option != 1 or option != 2 or option != 3 or option != 4 or option != 5 or option != 6 ): print("Error. La opcion que desea ingresar no existe\n") break
8a325206ebc3ce89fe8de904ffc4c53d37bec287
lxconfig/BlockChainDemo
/Python_Workspace/final/Person.py
1,050
3.796875
4
class Person: def __init__(self, name, dob, sex, zipcode, illness): self.name = name self.dob = dob self.sex = sex self.zipcode = zipcode self.illness = illness def __repr__(self): return "{0}, {1}, {2}, {3}, {4}\n".format(self.name, self.print_dob(), self.print_sex(), self.print_zipcode(), self.illness) def __str__(self): return "{0}, {1}, {2}, {3}, {4}".format(self.name, self.print_dob(), self.print_sex(), self.print_zipcode(), self.illness) def print_dob(self): filled_dob = self.dob to_fill = 8 - len(self.dob) for i in range(to_fill): filled_dob = filled_dob + '*' return filled_dob def print_sex(self): if self.sex == '': return '*' else: return self.sex def print_zipcode(self): filled_zipcode = self.zipcode to_fill = 5 - len(self.zipcode) for i in range(to_fill): filled_zipcode = filled_zipcode + '*' return filled_zipcode
0e34d5081c469ab4205da4cbd85b401d58d57255
addyp1911/Python-week-1-2-3
/python/Algorithms/Anagrams/AnagramsBL.py
429
4.0625
4
# ----------------------------------anagrams prg----------------------------------------------- # Anagrams.py # date : 26/08/2019 # method to check if two user entered strings are anagrams of each other def checkAnagrams(str1,str2): string1=sorted(str1) string2=sorted(str2) if(string1==string2): #to check if all the characters in both the strings are equal to each other return True return False
9e8eca45d64d46395b9cf4ee1c1022dede0bfa94
Hemanthtm2/python-magic
/fileops.py
434
3.984375
4
#!/usr/bin/python ##instaed of f.close() function we can use with statement ## with open('my_new_file.txt',mode='r') as f: print(f.read()) with open('my_new_file.txt',mode='a') as f: f.write("This is thrid line") with open('my_new_file.txt',mode='r') as f: print(f.read()) with open('mypython.txt',mode='w') as f: f.write('I created this file') with open('mypython.txt',mode='r') as f: print(f.read())
c8331e6471d6b846fb3ec0b1fd21a3081c42def6
koiic/python_mastery
/AUB/ass9/segment.py
618
3.734375
4
import math class Segment2D: """ """ def __init__(self, arg1, arg2): self.first_tuple = arg1 self.second_tuple = arg2 def length(self): x1, y1, = self.first_tuple x2, y2 = self.second_tuple line = math.sqrt( pow(2, (x2 - x1)) + pow(2, (y2 - y1)) ) return line def slope(self): x1, y1, = self.first_tuple x2, y2 = self.second_tuple slope = (y2 - y1) / (x2 - x1) return slope if __name__ == '__main__': new1 = Segment2D((5, 4), (10, 7)) print(new1.length()) print(new1.slope())
9d9820141542e81b8e481453aa765ad0613f2fc8
Voulzy/blockc
/Iota/cleardb.py
212
3.78125
4
import sqlite3 conn = sqlite3.connect("car.db") c = conn.cursor() sql = 'DELETE FROM car' cur = conn.cursor() cur.execute(sql) conn.commit() for row in c.execute("SELECT * FROM car"): print(row) conn.close()
ee86e83fcc9319df5e3476fa946a67f52aff1bf0
nanigasi-san/nanigasi
/AtCoder/ABC/008-B.py
218
3.578125
4
N = int(input()) list = [] maxname = "" maxtime = 0 for n in range(N): list.append(input()) for _ in list: cou = list.count(_) if cou > maxtime: maxtime = cou maxname = _ print(maxname) #ac
730524a46e77d4b54642cb6dfd9497a030e3f146
thasleem-banu/python
/Aasetpro69.py
314
3.734375
4
bh,sbt=map(str,input().split("|")) cct=input() if len(bh)>len(sbt): if len(bh)==len(sbt)+len(cct): print(bh+"|"+sbt+cct) elif len(bh)<len(sbt): if len(sbt)==len(bh)+len(cct): print(bh+cct+"|"+sbt) elif len(bh)==len(sbt) and len(cct)>1 or (len(sbt) or len(bh)): print("impossible")
4066e1f032374e5a30b71df868c7c061387e2ecb
GauravPadawe/Universities-Students-and-Fees
/Enrollments and Fees.py
1,692
4.0625
4
usa_univs = [ ['California Institute of Technology',2175,37704], ['Harvard',19627,39849], ['Massachusetts Institute of Technology',10566,40732], ['Princeton',7802,37000], ['Rice',5879,35551], ['Stanford',19535,40569], ['Yale',11701,40500] ] def total_enrollment(a): # Defining a procedure i = [] # Defining variable having empty list for storing total number of students j = [ # Defining variable having empty list for storing total number of fees (fees of individual university * number of students enrolled) final = [] # Defining variable having empty list which will store final value (["total number of srudents", "total fees"]) for x in a: # For x (individual value of a) #print (x[1]) # you can un-comment print to see what's happening in the block i.append(x[1]) # Appending i[] with every x[1] value ,i.e, [2175, 19627, 10566, ...., ] for y in a: # For y (individual value of a) y = y[1] * y[2] # As given, total number of fees (fees of individual university * number of students enrolled) so y = y[1] * y[2] #print (y) # you can un-comment print to see what's happening in the block j.append(y) # Appending j[] with every y value sum_i = sum(i) # sum_i will sum the values in i sum_j = sum(j) # sum_j will sum the values in j final.append(sum_i) # Appending sum_i and sum_j to final[] final.append(sum_j) return final # Returning final print (total_enrollment(usa_univs)) # CODED BY - GAURAV PADAWE
af27c954e8167e57c3881c549be3d7d366a16e2c
akki8087/HackerRank
/Staircase.py
327
4.1875
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 16 22:39:53 2018 @author: NP """ #!/bin/python3 import math import os import random import re import sys def staircase(n): for i in range(1,n+1): print(('#'*i).rjust(n,' ')) if __name__ == '__main__': n = int(input()) staircase(n)
5d51673f4e28988f5d0ad19171e13a14e2433da5
depchen/arithmetic
/剑指/03.py
901
3.703125
4
# 题目描述 # 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。 # -*- coding:utf-8 -*- class ListNode: def __init__(self,x): self.val = x self.next = None class Solution: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead(listNode): # write code here a=[] while listNode: a.append(listNode.val) listNode = listNode.next return a[: :-1] if __name__ == '__main__': # a=[1,2,3,4,5] # print(a[-2:-4:-1]) c:顺序为1 逆序为-1 a:从指定顺序开始的第几个开始 b:顺序为len 逆序为-(len+1) list1=ListNode(1) list2=ListNode(2) list1.next=list2 list3=ListNode(3) list2.next = list3 list4=ListNode(4) list3.next=list4 list4.next=None a=Solution.printListFromTailToHead(list1) print(a)
b5e2d7dd4053cc95c0a06a032b0b697adcc493ea
swordsx/leetcode
/Implement strStr().py
317
3.5
4
class Solution: # @param {string} haystack # @param {string} needle # @return {integer} def strStr(self, haystack, needle): lenH, lenN = len(haystack), len(needle) for i in range(lenH - lenN + 1): if haystack[i:i+lenN] == needle: return i return -1
2698848b8a1d10822631f2315ed32463995e8dd5
marcoslimafpv/Desafio-Capgemini
/cadastroanuncio.py
1,116
3.84375
4
cadastro = '====Dados do anúncio====' print(cadastro) visu1 = 30 investimentoDia = int(input('Valor do investimento por dia: ')) cadastro = 'Cadastro de anúncio, preencha os dados.' nome = str(input('Digite o nome do anúncio: ')) cliente = str(input('Digite o nome do Cliente: ')) dataInicio = int(input('Data Início: ')) dataTermino = int(input('Data Término: ')) qtdDias = dataTermino - dataInicio valorInvestido = int (investimentoDia * qtdDias) qtdVOriginal = int (visu1 * valorInvestido) qtdVCompart = int (qtdVOriginal / 100*12) qtdCompart2 = int (qtdVCompart / 3 *40) visuTotal = int (qtdCompart2 * 4 + qtdVOriginal) valorTotalInvestido = int (dataTermino - dataInicio) * investimentoDia print('O valor total investido é : ', valorTotalInvestido) qtdMaxVisu = int (qtdCompart2 + qtdVCompart) print('A quantidade de máxima de visualizações é: ', qtdMaxVisu) qtdMaxCliques = int (qtdMaxVisu / 100) * 12 print('A quantidade máxima de cliques é: ', qtdMaxCliques) qtdMaxCompart = int (qtdMaxCliques / 20) * 3 print('A quantidade máxima de compartilhamentos é: ', qtdMaxCompart)
dc6282fd2889d2c462148ac8f202cefc53c540cd
ambrocio-gv/PythonConsoleApps
/3a.py
1,170
4.0625
4
#In #The first line of input consists of an integer N, representing the number of test cases. #Each test case is composed of two lines, each containing a positive integer. These two #integers represent Hashmat and is compared to his opponent by using a function named #difference(a, b), which returns the difference between a and b, by sybtracting the smaller #number from the larger number #Out #For each test case, output the difference in strength between Hasmat and his opponent #on a separate line. N = int(input("N:")) i = 1 def difference( a, b ): if a >= b: diff = a - b elif b > a: diff = b - a return diff def check (x): while True: try: x = int(x) if x >= 0: return(x) else: x = input("input again:") except ValueError: x = input("input again:") while True: while (i <= N): a = (input("a:")) a = check(a) b = (input("b:")) b = check(b) diff = difference(a , b) print (diff) i = i + 1 break
f2c525b3eb33e328cc90eb8e8703a0ff8aec929f
mumat0103/etc
/removeFile.py
439
4.0625
4
import os def removeExtensionFile(filePath, fileExtention) : if os.path.exists(filePath): for file in os.scandir(filePath): if file.name.endswith(fileExtention): os.remove(file.path) return 'Remove FIle : ' + fileExtention else : return "Directory Not Fonud" path = input("Enter File Path : ") file = input("Enter File Extension : ") removeExtensionFile(path,file)
c182b361b97bc512b60fe1af29802b24111cc89e
chenshanghao/Interview_preparation
/Company/Amazon/Leetcode_98/my_solution.py
775
4.09375
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: True if the binary tree is BST, or false """ def isValidBST(self, root): # write your code here if not root: return True return self.checkisValidBST(root, float('-inf'), float('inf')) def checkisValidBST(self, node, left, right): if not node: return True elif left < node.val < right: return self.checkisValidBST(node.left, left, node.val) and self.checkisValidBST(node.right, node.val, right) else: return False
60eddb21aef02bfdff50cefff5c2841eddf0e7dc
quantum109678/IT_3
/dsa/lab1/p6.py
120
3.921875
4
s1=input("Enter String1") s2=input("Enter String2") s3=input("Enter String3") a=s1[:] b=s2[:] d=a.replace(b,s3) print(d)
b83fb3d2882e49de46d35ee8394781a97e005476
Bharath-Gopal/python
/rps.py
1,674
4.09375
4
#Rock, Paper, Scissors import random print("\n") print("-"*50) print("Rock, Paper, Scissors") print("-"*50) print("\n") while True: print("Pick your choice : ") print("1. Rock\n2. Paper\n3. Scissors\n") choice = int(input()) if choice==1: cn="Rock" elif choice==2: cn="Paper" elif choice==3: cn="Scissors" else : print("INVALID CHOICE") break print("User's Choice : ",cn) c_choice = random.randint(1,3) if c_choice==1: ccn="Rock" elif c_choice==2: ccn="Paper" else: ccn="Scissors" print("Computer's Choice : ",ccn) if ((choice==1 and c_choice==3) or (choice==3 and c_choice==1)): print("Rock Wins!") result = "Rock" elif ((choice==1 and c_choice==2) or (choice==2 and c_choice==1)): print("Paper Wins!") result = "Paper" elif ((choice==1 and c_choice==1) or (choice==1 and c_choice==1)): print("Draw!") result = "Rock" elif ((choice==2 and c_choice==3) or (choice==3 and c_choice==2)): print("Scissors Wins!") result = "Scissors" elif ((choice==2 and c_choice==2) or (choice==2 and c_choice==2)): print("Draw!") result = "Paper" else: print("Draw!") result = "Scissors" if(result == cn): print("USER WINS!!!") elif(result == ccn): print("COMPUTER WINS!!!") else: print("DRAW") print("Do you want to play again? (Y/N)") ans = input() if(ans == 'n' or ans == 'N'): break print("\nThanks for Playing\n")
baeea8a24eb6e66b86229e720b287c0ea2d8b455
A432-git/Leetcode_in_python3
/56.py
700
3.859375
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 14 20:27:10 2020 @author: leiya """ class Solution: def merge(self, intervals): intervals.sort(key=lambda x: x[0]) merged = [] for interval in intervals: # if the list of merged intervals is empty or if the current # interval does not overlap with the previous, simply append it. if merged == [] or merged[-1][1] < interval[0]: merged.append(interval) else: # otherwise, there is overlap, so we merge the current and previous # intervals. merged[-1][1] = max(merged[-1][1], interval[1]) return merged
9f1010fcacce4c17f51eb4b8cd1ac9c21f9c35ea
pushsing/Python
/assignments/ProgramsonFunctions/Sum&Multiply.py
221
3.6875
4
def sum(o): s=0 for i in o: s=s+i return s def multiply(o): s=1 for i in o: s=s*i return s l=[1,3,4] tt=sum(l) print("Sum:",tt) rr= multiply(l) print("Multiply:", rr )
2650b919085aedd35d5e28061d5448aa2f11032c
reporter-law/book_code
/二级/turtle画图.py
703
3.609375
4
"""程序说明""" # -*- coding: utf-8 -*- # Author: cao wang # Datetime : 2020 # software: PyCharm # 收获: import turtle,time for i in range(4): turtle.fd(80) time.sleep(2) turtle.right(90) #turtle.done() def draw_snake(): turtle.setup(1300,800,0,0)#画布 turtle.pensize(30)#画笔宽度 turtle.pencolor("blue")#画笔颜色 turtle.seth(-40)#画笔角度逆时针 for i in range(4): turtle.circle(40,80)#圆形轨迹爬行,rad半径,angle是弧度值 time.sleep(2) turtle.circle(-40,80) turtle.circle(40,40) time.sleep(2) turtle.fd(40)#z直线爬行 time.sleep(2) turtle.circle(16,180) turtle.fd(80/3) #draw_snake()
6e3b8a82310a421a10e180b7166f3eb5d4979fb5
FelicianoSachilombo/psr_21-22
/Parte03/T/ExDicts/main.py
451
3.53125
4
#!/usr/bin/python3 import colorama from collections import namedtuple Complex = namedtuple('Complex', ['r', 'i']) def addComplex(x, y): a = x['r'] b = x['i'] c = y['r'] d = y['i'] return {'r': a + c, 'i': b + d} def main(): cs = {'c1': {'r': 4, 'i': 8}, 'c2': {'r': 8, 'i': -4}} print(cs['c1']) print(cs['c2']) cs['c3'] = addComplex(cs['c1'], cs['c2']) print(cs) if __name__ == '__main__': main()
fb1ad3ffdca95cd0818a54d8aa7d757c0a9ce7e2
olivares10/proyectoPython
/duplas/ejercicio2.py
91
3.65625
4
lista = [] for i in range(5): tmp = int(input("Digite Nùmero:")) lista.append(tmp)
8e5520df95a7c3d2a143570dbfe6ab456db25b51
bcc/adventofcode2020
/03/03.py
641
3.734375
4
#!/usr/bin/python3 import sys x_move1 = 3 y_move1 = 1 p2_move = [ [1,1], [3,1], [5,1], [7,1], [1,2] ] lines = [] for line in sys.stdin: lines.append(line.rstrip()) def check_slope(lines, x_move, y_move): count = 0 x = 0 y = 0 while y < len(lines)-1: for i in range(0, x_move): x = (x + 1) % (len(lines[y])) for i in range(0,y_move): y = y + 1 if lines[y][x] == '#': count = count + 1 return count print(check_slope(lines, x_move1, y_move1)) result = 1 for p2 in p2_move: result = result * check_slope(lines, p2[0], p2[1]) print(result)
05cf025ce775e6e9ae90e2a57a45b993f754d770
detcitty/100DaysOfCode
/python/unfinshed/koka.py
469
3.546875
4
# https://www.codewars.com/kata/58e8cad9fd89ea0c6c000258/train/python import re def kooka_counter(laughing): #your code here male_regex = r'HaHaHa' female_regex = r'hahaha' males = re.findall(male_regex, laughing) females = re.findall(female_regex, laughing) size_males = len(males) size_females = len(females) #print(size_males, size_females) return(sum([size_females, size_males])) test1 = kooka_counter("hahaha") print(test1)
7b2df4d802d9cf7436b1f32a9b22cc9960f2c370
Monikabandal/My-Python-codes
/Finding Numbers in a Haystack.py
190
3.625
4
import re fname = raw_input("Enter file name: ") fh = open(fname) count=0 for line in fh: x=re.findall('[0-9]+',line) for i in x: count = count+int(i) print count
b124c3df74c4c4f2b16b0db63ac7d3c72dcb2fb9
BensyBenny/Bensybenny-rmca-s1A
/lengthp8.py
290
4.15625
4
def longestword(wlist): word_len = [] for n in wlist: word_len.append((len(n), n)) word_len.sort() return word_len[-1][0], word_len[-1][1] result =longestword(["Apple", "Mango", "Banana"]) print("\nLongest word: ",result[1]) print("Length of the longest word: ",result[0])
c0ed05e15dd1912dce1f153fa759cb2a4f4edd54
Get-out/getout
/atlas_api/species_list.py
933
3.53125
4
from atlas_api.location import Location class SpeciesList(object): """Knows how to get species for a location given a particular distribution of weightings""" def __init__(self, location, species_weights): self.location = location self.species_weights = species_weights def retreive(self, amount): """Retrieve a number of species""" species_weight = {x : int(self.species_weights.get(x, 5)) for x in ("bird", "plant", "tree")} # Don't include fish unless the user really wants it # More likely that user is looking at an area not around water # We should probably do geo-magic to work that out species_weight['fish'] = int(self.species_weights.get('fish', 0)) # Land_animal maps to other species_weight['other'] = int(self.species_weights.get('land_animal', 5)) return Location(self.location).ranked_species(10, species_weight)
4ffd7ec53dbb49de34d74f8737999c583d6dd581
asralabs/cseu
/CSEUUtil.py
1,203
3.6875
4
#askuser_sel: get selection from a user, sanitize input #str title,str query,list opt {str}, str default #return str def askuser_sel(title,query,options,default): while (1==1): print "\n"+title for i in options: print i sel=raw_input(query+"["+default+"]:") if sel=="": sel=default for i in options: if sel==i: return sel print sel+" was invalid. Please type one of the options." #askuser_num: get number from a user, sanitize input #str title, str query, int default,int numMin,int numMax #numMax/numMin can also = "", for no max or nomin #return int def askuser_int(title,query,default,numMin,numMax): #make sure numMin/numMax is int while (1==1): print "\n"+title sel=raw_input(query+"["+str(default)+"]:") try: sel=int(sel) if numMin=="": #no min if numMax=="": #no max return sel else: #max if sel<=int(noMax): return sel else: #min if sel>=int(numMin): if numMax=="": #no max return sel elif sel<=int(numMax): #sel less then max return sel except ValueError,e: #print "ValueError Exception:"+str(e) pass print str(sel)+" was invalid. min="+str(numMin)+", max="+str(numMax)
3095884f4c33f422358830674588cbb3a97aae39
LilMarc0/SnakeAI
/Snake.py
2,299
3.703125
4
class Snake: ''' length - snake's body length in pixels x & y - head coordinates ''' def __init__(self, length, x, y, boundX, boundY): self.length = length self.x = x self.y = y self.body = [[self.x, self.y-i] for i in range(self.length)] self.direction = 2 self.boundX = boundX self.boundY = boundY self.head = self.body[0] self.wrongDirection = False assert(self.length == len(self.body)) @property def snakeBody(self): return self.body ''' Direction changes ''' def moveRight(self): if self.direction == 0: self.wrongDirection = True return self.direction = 2 def moveLeft(self): if self.direction == 2: self.wrongDirection = True return self.direction = 0 def moveUp(self): if self.direction == 3: self.wrongDirection = True return self.direction = 1 def moveDown(self): if self.direction == 1: self.wrongDirection = True return self.direction = 3 ''' Returns 'HIT' if snake hits wall or himself 'FOOD' if snake eats '' otherwise ''' def update(self, food): new_head = self.body[0].copy() if self.direction == 0: # left new_head[1] -= 1 elif self.direction == 1: # up new_head[0] -= 1 elif self.direction == 2: # right new_head[1] += 1 elif self.direction == 3: # down new_head[0] += 1 if new_head[0] > self.boundX-1 or new_head[1] > self.boundY-1 or new_head[0] < 0 or new_head[1] < 0\ or new_head in self.snakeBody: return 'HIT' if new_head == food: self.body.insert(0, new_head) self.length += 1 self.head = new_head.copy() return 'FOOD' self.head = new_head.copy() self.body.insert(0, new_head) self.body.pop() if self.wrongDirection: self.wrongDirection = False return 'WRONG' else: return 'MOVED'
b11536247a52194fd72aa002ce1d680d107ddd0b
VataX/isn
/TP7/ex2.py
224
3.875
4
# -*- coding: utf-8 -*- def compteMots(s): count=1 for espace in s: if(espace==" "): count=count+1 return count s=str(input("Saisissez une phrase :")) a=compteMots(s) print(a)
2e6425a76c19959f479342c6a057c68bc1d3e511
srk112006/quiz
/imyth.py
1,544
4.03125
4
print ("This is the Indian Mythology Quiz!! Get ready!") print ("Type your answers as 'A','B','C' or 'D'") print ("Who poisoned Bhima during their younger years? ") ans = input("Your options are A-Dushasana, B-Shakuni,C-Vikarna,D- Duryodhana ") if ans == "D": print ("Good job! The questions will get harder!") else: print ("Sorry! This answer is wrong! The right answer was D-Duryodhana") print ("How many childeren did Sita give birth to? ") ans = input("Your options are A-1, B-2,C-3,D- None ") if ans == "A": print ("Good job! The questions will get harder!") else: print ("Sorry! This answer is wrong! The right answer was A-1") print ("Who is Chandra's favorite wife? ") ans = input("Your options are A-Krittika, B-Rohini,C-Ashvini,D- Swati ") if ans == "B": print ("Good job! The questions will get harder!") else: print ("Sorry! This answer is wrong! The right answer was B-Rohini") print ("Who was the stone woman in the ramayana? ") ans = input("Your options are A-Ahalya, B-Vimala,C-Asha,D- Dushalla ") if ans == "A": print ("Good job! The questions will get harder!") else: print ("Sorry! This answer is wrong! The right answer was A-Ahalya") print ("Who was the grandson of Krishna? ") ans = input("Your options are A-Paurava, B-Yadu,C-Aniruddha,D- Vasudeva ") if ans == "C": print ("Good job! The quiz is over!") else: print ("Sorry! This answer is wrong! The right answer was C-Aniruddha. The quiz is over!")
c78e2c1202088b43cc939db5e9ff42bec1e9f96e
sakthi5006/epi-python
/Strings/stringsbootcamp.py
605
4.03125
4
# Strings are a special kind of array made out of characters. # Comparison, joining, splitting, searching for substrings, # replacing one string by another, and parsing are all operations # commonly applied to strings that are not sensible for general arrays, # so the book has a separate category for them. # Book example for checking whether a string is palindromic: def is_palindromic(s): return all(s[i] == s[~i] for i in range(len(s) // 2)) # s[~i] is s[-[i + 1]] print(is_palindromic("sollos")) # time complexity of O(n) and space complexity of O(1) # where n is the length of the string.
1d3cdb735a56414d1c2b35796102f41416be64f4
CodecoolMSC2016/python-pair-programming-exercises-2nd-tw-pklaudia_kzoli
/listoverlap/listoverlap_module.py
337
3.890625
4
def listoverlap(list1, list2): c = [] for a in list1: if a in list2: c.append(a) c = set(c) c = list(c) return c def main(): x = listoverlap([1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) print(x) return if __name__ == '__main__': main()
ff3469075830650a01b403886bbba24dbfd0568e
ArexChu/python
/basic/dice.py
269
3.75
4
#coding: utf-8 from random import randint class Dice(): sides = 6 def __init__(self,sides): self.sides = sides def roll_dice(self): x = randint(1,self.sides) print(x, end=' ') dice = Dice(6) for i in range(10): dice.roll_dice()
c9f8eeef25afa2724cbcd1a8257f033c2dc4c139
pra-kri/MP006-Random-Stuff
/python_practice.py
9,905
3.5625
4
""" To cover today: --------------+ [/] - Enumerate [/] - Lambdas [/] - args/kwargs [/] - testing membership within different data structures [X] - debugging [/] - generators [/] - Functional programming concepts [/] - map [/] - filter [/] - reduce [/] - Ternary operators/ conditional expressions [X] - optimising python code.. (especially loops, using vectorisation and FP...) [/] - exception handling [/] - how to make Python modules ... just put an empty __init__.py file in the directory... --> Didnt cover debugging or optimisation today. Do that another day.... References: ----------+ Intermediate Python book: http://book.pythontips.com/en/latest/index.html Python Performance Tips: https://nyu-cds.github.io/python-performance-tips/08-loops/ Also, should check out these pages later. Looks pretty useful...: ----------+ essay on optimising loops: https://www.python.org/doc/essays/list2str/ wiki on performance tips: https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Loops pandas optimising tips: https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6 Python for Finance txtbook: Ch 4, 8 """ #=============================================# #============== ENUMERATE ==============# #=============================================# list1 = ['a', 'b', 'c', 'd', 'eeee', 'f', 'g', 'h', 'z'] # the optional 2nd argument in enumerate is the number you start enumerating from... aaa = enumerate(list1, 3) for i in aaa: print(i) print("----------------------------") bbb = list(enumerate(list1, 4)) print(bbb) #=============================================# #=============== LAMBDAS ===================# #=============================================# print("----------------------------") # lambda = temporary 1-line function, pretty much... # Behave exactly like normal functions.# # Possible use cases: - you may only want to use a quick function once or twice, in which case it will be too much effort to def a new function. So could just use a lambda instead. This would probably be very useful for simple mathematical functions that dont require too much thinking to understand... :) test1 = lambda x, y: x**y print(test1(3,4)) print(test1(2,10)) #=============================================# #============= *args, **kwargs =============# #=============================================# # *args def test_var_woah(intentional_arg, *args): print("this is intentional: " + intentional_arg) for i in args: print("extra from *args : " + i) test_var_woah('1','2','3','a','b','c','d','e') print("================================") # *kwargs def test_var_twooo(intentional_kwarg, **kwargs): print("This is your first kwarg:" + intentional_kwarg) for i in kwargs: print("These are your extra kwargs: " + i) print type(i) print(kwargs) test_var_twooo(intentional_kwarg = "onetwothree", kwarg1 = "ok lets see if this works", kwarg2 = "hmmmmmmmmm", kwarg3 = "string 1223", kwarg4 = 12345, kwarg5 = True) # ok, so the kwargs that are added to the function are stored as dictionaries, where the keyword is the key in the dictionary. #=============================================# #=========== Membership Testing ============# #=============================================# """ # Commenting this entire section out, since it takes quite a bit of time... # Reference: https://nyu-cds.github.io/python-performance-tips/05-membership/ # Which data structure is best to use when testing if an element is part of a collection of elements? # Dictionaries {} and sets () will be the best, because they are both implemented using a hash table. Lists will be quite bad, because you'd have to check each element of a list (unless you have a sorted list and use binary search or something...) import time letters = 'abcdefghijklmnopqrstuvwxyz' letters_list = [x+y+z+k+l for x in letters for y in letters for z in letters for k in letters for l in letters] time0 = time.time() print('aaaaa' in letters_list) time1 = time.time() print("Time taken to find 'aaaaa' in letters_list = " + str(time1-time0)) # turns out to be 0.0 sec. time2 = time.time() print('zzzzz' in letters_list) time3 = time.time() print("Time taken to find 'zzzzz' in letters_list = " + str(time3-time2)) # turns out to be 0.20 sec # Finding zzzzz takes much longer than finding aaaaa, presumably because you have to do a linear search through a list. letters_dict = dict([(x,x) for x in letters_list]) time4 = time.time() print('aaaaa' in letters_dict) time5 = time.time() print("Time taken to find 'aaaaa' in letters_dict = " + str(time5-time4)) # turns out to be 0.0 sec time6 = time.time() print('zzzzz' in letters_dict) time7 = time.time() print("Time taken to find 'zzzzz' in letters_dict = " + str(time7-time6)) # turns out to be 0.0 sec # For the dictionary, times taken to find zzzzz and aaaaa are the same, since there is no linear search. # Instead the dictionary uses a hashing function on the key. """ #=============================================# #=============== Generators ================# #=============================================# """ Quick overview of definitions... -> Iterable: Any object which can provide us with an ITERATOR. The object will have an __iter__ or a __getitem__ method. These methods will return an iterator. -> Iterator: Any object which has a __next__ method defined. That's all. -> Iteration: the process of taking an item from something... -> Generators: Generators are basically just iterators that you can only iterate over once. Why? Because they do NOT store all the values in memory. They GENERATE values as needed, when being iterated over. You mostly implement a GENERATOR as a function. Instead of using 'return', use 'yield'. Since generators dont store all values in memory, they are resource-efficient. """ def generator_1(N): for i in range(N): yield i def not_generator_1(N): for i in range(N): return i print(generator_1(10)) gen_test = generator_1(10) print(next(gen_test)) print(next(gen_test)) print(next(gen_test)) print(next(gen_test)) print(next(gen_test)) not_gen_test = not_generator_1(10) print(not_gen_test) #print(next(not_gen_test)) # this doesnt have a __next__ method, so wont work. #=============================================# #================== Map ====================# #=============================================# # map(function_to_apply, inputs_list) # And instead of using a defined function, can also easily use a lambda function. def square_number(x): return x**2 test_list_1 = [0,1,2,3,4,5,6,7,8,9,10] test_map = map(square_number, test_list_1) print(test_map) # do another method, this time using lambdas, and a different function... test_map2 = map(lambda x: x**x,test_list_1) print(test_map2) #=============================================# #================= Filter ==================# #=============================================# # filter(function_to_apply_that_should_return_TRUE, inputs_list) # If even, should % 2 to equal 0. even_number_list = filter(lambda x: x % 2 == 0, test_list_1) print(even_number_list) #=============================================# #================= Reduce ==================# #=============================================# # allows you to apply a rolling computation to sequential pairs of values in a list. # reduce(function_to_apply_on_pairs, inputs_list) total_product = reduce(lambda x, y: x, test_list_1) print(total_product) """ Its kind of like...: -> Funciton is applied to the first two elements of the list. -> Output of the function replaces the first two elements. (Now the first element of the list is the output of the last calculation.) -> Now just do the same thing again: apply the funciton to the new first two elements of the list. ->>> and so on.... """ #===============================================# #= Ternary Operators/ Conditional Expressions =# #===============================================# test_state = True state = "okkkkk" if test_state is True else "nope not Trueeee" print(state) # Also, note that True = 1, and False = 0 # so you can refer to element 1 of a list by using: list_to_check[True] # And you can replace the 'True' with something you want to test. #===============================================# #=========== Exception Handling ===============# #===============================================# # basic code: try/except try: file = open('test_file12323323.txt', 'rb') except IOError as e: print(e) # more advanced: handling multiple specific exceptions... try: file = open('test_file12323323.py', 'rb') except EOFError as e: print(e) #raise e except IOError as f: print(f) # or, if you want to handle ALL exceptions, regardless of type... try: file = open('test_file12323323', 'rb') except Exception as e: # whatever you want to happen in here print(e) #raise(e) # and then there's also the 'finally' clause, which will run whether or not an exception is raised. try: file = open('test_file12323323.txt', 'rb') except IOError as e: #raise e print(e) finally: print('This will be printed regardless of what happens') # and there's also the else clause: try: file = open('test_file12323323.txt', 'rb') except IOError as e: #raise e print(e) else: #file = open('test_file12323323.eeee', 'rb') print('else part worked!!!!!!!!!!') # this part will run if there are NO exceptions raised in the try. # but any exceptions that occur here will not be caught... finally: print('This will be printed regardless of what happens aaaaa')
2523cf35647985f763d6a2518ca3c361d9a2bd63
alparty/labs
/techlead/sort_colors.py
1,056
4.28125
4
""" Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. Can you do this in a single pass? Example: Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2] """ class Solution: def sortColors(self, nums): vals = [0,0,0] for i in range(len(nums)): vals[nums[i]] += 1 numsort = ([0]*vals[0]) + ([1]*vals[1]) + ([2]*vals[2]) return numsort nums = [0, 1, 2, 2, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1] #[0, 1, 2, 2, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1] numsort = Solution().sortColors(nums) # print(numsort) print(numsort == [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2]) print(Solution().sortColors([2,0,2,1,1,0]) == [0,0,1,1,2,2]) print(Solution().sortColors([0]) == [0]) print(Solution().sortColors([1]) == [1]) print(Solution().sortColors([]) == [])
ef1e19c29017acd11daeba861e883cb1119ab4ec
DaHuO/Supergraph
/codes/BuildLinks1.10/test_input/CJ_16_2/16_2_3_ana_valeije_C.py
2,131
3.59375
4
def add_dict(d, key): if key not in d: d[key] = 1 else: d[key] += 1 def find_doubles(firsts, seconds, topics): doubles = [] for topic in topics: if topic[0] in firsts and topic[1] in seconds: doubles.append(topic) return doubles def choose_doubles(doubles): f = {} s = {} for topic in doubles: add_dict(f, topic[0]) add_dict(s, topic[1]) chosen = None smallest = None for topic in doubles: if smallest == None: chosen = topic smallest = min(f[topic[0]], s[topic[1]]) else: if min(f[topic[0]], s[topic[1]]) < smallest: chosen = topic smallest = min(f[topic[0]], s[topic[1]]) return chosen def solveCase(case, f, fout): N = int(f.readline().strip()) topics = [] firsts = {} seconds = {} for _ in xrange(N): topic = f.readline().strip() first, second = topic.split(' ') topics.append((first, second)) add_dict(firsts, first) add_dict(seconds, second) real_topics = [] for topic in topics: if firsts[topic[0]] == 1 or seconds[topic[1]] == 1: real_topics.append(topic) for topic in real_topics: topics.remove(topic) if topic[0] in firsts: firsts.pop(topic[0]) if topic[1] in seconds: seconds.pop(topic[1]) while firsts or seconds: doubles = find_doubles(firsts, seconds, topics) if doubles: double_topic = choose_doubles(doubles) topics.remove(double_topic) firsts.pop(double_topic[0]) seconds.pop(double_topic[1]) else: remove_topic = None for topic in topics: if topic[0] in firsts: firsts.pop(topic[0]) remove_topic = topic break if topic[1] in seconds: seconds.pop(topic[1]) remove_topic = topic break topics.remove(remove_topic) n_fake = len(topics) writeLine(fout, case, str(n_fake)) def writeLine(fout, n, result): print("Case #%d: %s\n" %(n, result)) fout.write("Case #%d: %s\n" %(n, result)) if __name__ == '__main__': inputFileName = 'C-small-attempt1.in' f = file(inputFileName) fout = file("%s.out" %(inputFileName.split(".")[0]), "w") T = eval(f.readline()) for case in xrange(T): solveCase(case + 1, f, fout) f.close() fout.close()
1a0e0a5267eac3d753cdcc857cdddb45f9f1b14d
vineel96/PythonTrack-Exercism
/clock/clock.py
781
3.78125
4
class Clock(object): out_hour=0 out_minute=0 def __init__(self, hour, minute): self.hour=hour self.minute=minute self.total_minutes=hour*60+minute self.update() def __repr__(self): return '%02d:%02d' % (self.out_hour,self.out_minute) def __eq__(self, other): return (self.out_hour==other.out_hour) and (self.out_minute==other.out_minute) def __add__(self, minutes): self.total_minutes+=minutes self.update() return self def __sub__(self, minutes): self.total_minutes-=minutes self.update() return self def update(self): htemp = self.total_minutes // 60 self.out_hour = htemp % 24 self.out_minute = self.total_minutes % 60
6e95a70e8cd1e21b528f4f4a39eb32b4b1044163
Chiva-Zhao/pproject
/cookbook/multithread/thread_lock.py
5,406
4.09375
4
# 给关键部分加锁 # 需要对多线程程序中的临界区加锁以避免竞争条件 # 在多线程程序中安全使用可变对象,需要使用 threading 库中的 Lock 对象 import threading class ShareCounter: ''' A counter object that can be shared by multiple threads. ''' def __init__(self, init_value=0): self._value = init_value self._value_lock = threading.Lock() def incr(self, delta=1): ''' Increment the counter with locking ''' with self._value_lock: self._value += delta def decr(self, delta=1): ''' Decrement the counter with locking ''' with self._value_lock: self._value -= delta # Lock 对象和 with 语句块一起使用可以保证互斥执行,就是每次只有一个线程可以 # 执行 with 语句包含的代码块。 with 语句会在这个代码块执行前自动获取锁,在执行结 # 束后自动释放锁。 # 线程调度本质上是不确定的,因此,在多线程程序中错误地使用锁机制可能会导致 # 随机数据损坏或者其他的异常行为,我们称之为竞争条件。为了避免竞争条件,最好 # 只在临界区(对临界资源进行操作的那部分代码)使用锁。在一些“老的” Python 代 # 码中,显式获取和释放锁是很常见的。下边是一个上一个例子的变种: import threading class SharedCounter: ''' A counter object that can be shared by multiple threads. ''' def __init__(self, initial_value=0): self._value = initial_value self._value_lock = threading.Lock() def incr(self, delta=1): ''' Increment the counter with locking ''' self._value_lock.acquire() self._value += delta self._value_lock.release() def decr(self, delta=1): ''' Decrement the counter with locking ''' self._value_lock.acquire() self._value -= delta self._value_lock.release() # 相比于这种显式调用的方法, with 语句更加优雅,也更不容易出错,特别是程序员 # 可能会忘记调用 release() 方法或者程序在获得锁之后产生异常这两种情况(使用 with # 语句可以保证在这两种情况下仍能正确释放锁)。为了避免出现死锁的情况,使用锁机 # 制的程序应该设定为每个线程一次只允许获取一个锁。如果不能这样做的话,你就需 # 要更高级的死锁避免机制,我们将在 12.5 节介绍。在 threading 库中还提供了其他的 # 同步原语,比如 RLock 和 Semaphore 对象。但是根据以往经验,这些原语是用于一些 # 特殊的情况,如果你只是需要简单地对可变对象进行锁定,那就不应该使用它们。一 # 个 RLock (可重入锁)可以被同一个线程多次获取,主要用来实现基于监测对象模式 # 的锁定和同步。在使用这种锁的情况下,当锁被持有时,只有一个线程可以使用完整 # 的函数或者类中的方法。比如,你可以实现一个这样的 SharedCounter 类: import threading class SharedCounter: ''' A counter object that can be shared by multiple threads. ''' _lock = threading.RLock() def __init__(self, initial_value=0): self._value = initial_value def incr(self, delta=1): ''' Increment the counter with locking ''' with SharedCounter._lock: self._value += delta def decr(self, delta=1): ''' Decrement the counter with locking ''' with SharedCounter._lock: self.incr(-delta) # 在上边这个例子中,没有对每一个实例中的可变对象加锁,取而代之的是一个被所 # 有实例共享的类级锁。这个锁用来同步类方法,具体来说就是,这个锁可以保证一次 # 只有一个线程可以调用这个类方法。不过,与一个标准的锁不同的是,已经持有这个 # 锁的方法在调用同样使用这个锁的方法时,无需再次获取锁。比如 decr 方法。这种实 # 现方式的一个特点是,无论这个类有多少个实例都只用一个锁。因此在需要大量使用 # 计数器的情况下内存效率更高。不过这样做也有缺点,就是在程序中使用大量线程并 # 频繁更新计数器时会有争用锁的问题。信号量对象是一个建立在共享计数器基础上的 # 同步原语。如果计数器不为 0, with 语句将计数器减 1,线程被允许执行。 with 语句 # 执行结束后,计数器加1。如果计数器为 0,线程将被阻塞,直到其他线程结束将计数 # 器加 1。尽管你可以在程序中像标准锁一样使用信号量来做线程同步,但是这种方式并 # 不被推荐,因为使用信号量为程序增加的复杂性会影响程序性能。相对于简单地作为 # 锁使用,信号量更适用于那些需要在线程之间引入信号或者限制的程序。比如,你需 # 要限制一段代码的并发访问量,你就可以像下面这样使用信号量完成: from threading import Semaphore import urllib.request # At most, five threads allowed to run at once _fetch_url_sema = Semaphore(5) def fetch_url(url): with _fetch_url_sema: return urllib.request.urlopen(url)
19932da3cd64679a5f908f5212ab995fa216feb9
Kalliojumala/School-Work
/Week 13/13.3.py
304
3.8125
4
#13.3 #Combine two tuples t1 = (5,4,3) t2= (9,2, 12) T = t1 + t2 #print("T =",T) #13.3.1 #checks if user input in tuple T = (23, 45, 93, 59, 35, 58, 19, 3) try: print(int(input("Anna luku: ")) in T) except ValueError: pass #13.3.2 #average of T print(f"T:n keskiarvo: {sum(T)/len(T)}")
3f8880b102a07287db695ab2e4e562a978ce4500
naxolorca/MCOC-Nivelacion
/20082019/001452.py
138
3.71875
4
def convert(miles): # funcion para convetir miles a km km = 1.6 * miles print str(miles) + " millas son " + str(km) + " km" convert(20)
d5a06d38a17a537dfe79d742901670525a558a65
RayMJK/sparta_algorithm
/week_1/homework/01_find_prime_list_under_number.py
749
3.796875
4
input = 20 list = [] # 소수는 자기 자신과 1 외에는 아무것도 나눌 수 없다. # 주어진 자연수 N이 소수이기 위한 필요 충분 조건은 # N이 N 제곱근보다 크지 않은 어떤 소수로도 나눠지지 않는다. # 수가 수를 나누면 몫이 발생하는데, 몫과 나누는 수 둘중 하나는 반드시 N의 제곱근 이하 def find_prime_list_under_number(number): # 이 부분을 채워보세요! for i in range(2, number+1): check = 0 for j in range(2, i): if i % j == 0: check = 1 break if check == 0: list.append(i) check = 0 return list result = find_prime_list_under_number(input) print(result)
02a61de6dcbced112520079e9c3f15073cde48f4
peterzhang45/Python_Exercises_01
/01. Character_Input/character_input.py
370
4.03125
4
import datetime now = datetime.datetime.now() name = input("Please enter your name: ") age = input("Please enter you age: ") time = int(now.year)+ (100 - int(age)) string = ("Hi "+ name + ", in " + str(time) + ", you will turn 100 years old!\n") print(string) times = input("How many time you want to print out the previous message: ") print(int(times) * string)
b65ef5fea6a0f4feebe13535d419e88fb2a9fc3d
skybrim/practice_leetcode_python
/top_interview_questions_in_2018/classic/super_egg_drop.py
1,289
3.640625
4
#!/usr/bin/env pytho # -*- coding: utf-8 -*- def super_egg_drop(K, N): T = 1 while helper(K, T) < N+1: T += 1 return T def helper(K, T): if K == 1: return T if T == 1: return 2 return helper(K-1, T-1) + helper(K, T-1) def superEggDrop(self, K: int, N: int) -> int: """ @param K: int @return: int """ store = {} def dp(k, n): if (k, n) not in store: if n == 0: # 0 层楼 result = 0 elif k == 1: # 1 个鸡蛋,需要扔 n 次 result = n else: # X 遍历 low, high = 1, n # 二分搜索 while low + 1 < high: x = (low + high) // 2 t1 = dp(k - 1, x - 1) t2 = dp(k, n - x) if t1 < t2: low = x elif t1 > t2: high = x else: low = high = x result = 1 + min(max(dp(k - 1, x - 1), dp(k, n - x)) for x in (low, high)) # 记录已经算过的值 store[k, n] = result return store[k, n] return dp(K, N)
9b1276a4bf49429e304c2043a786eae8ce582072
ElAmirr/python_tutorial
/my_python_documentation/strings.py
801
4.5625
5
# Strings in python are surrounded by either single or double quotation marks. Let's look at string formatting and some string methods name = 'Brad' age = 37 # Concatenate print('Hello my name is ' + name + ' and I am ' + str(age)) # String Formatting # Arguments by position print('My name is {name} and I am {age}'.format(name=name, age=age)) # F-Strings (3.6+) print(f'My name is {name} and I am {age}') # String Methods s = 'hello world' # Capitalize string print(s.capitalize()) # Make all uppercase print(s.upper()) # Make all lower print(s.lower()) # Swap case print(s.swapcase()) # Get legth print(len(s)) # Replace print(s.replace('world', 'everyone')) # Count sub = 'h' print(s.count(sub)) # Starts with('hello) print(s.startswith('hello')) # Ends with print(s.endswith('d'))
65a3a0c48725a3c0ceaf04d65ce2e9ba7e0620c6
deathlyhallows010/Interview-Bit-Python
/Arrays/Set Matrix Zeros.py
1,148
3.640625
4
# https://www.interviewbit.com/problems/set-matrix-zeros/ # Set Matrix Zeros # Input 1: # [ [1, 0, 1], # [1, 1, 1], # [1, 1, 1] ] # Output 1: # [ [0, 0, 0], # [1, 0, 1], # [1, 0, 1] ] # Input 2: # [ [1, 0, 1], # [1, 1, 1], # [1, 0, 1] ] # Output 2: # [ [0, 0, 0], # [1, 0, 1], # [0, 0, 0] ] class Solution: # @param A : list of list of integers # @return the same list modified def setZeroes(A): m = len(A[0]) n = len(A) list_row = [] list_col = [] for i in range(n): for j in range(m): if A[i][j] == 0: if i not in list_row: list_row.append(i) if j not in list_col: list_col.append(j) #print list_row, list_col row = [0]*m for i in range(n): if i in list_row: A[i] = row for j in range(m): if j in list_col: A[i][j] = 0 return A
be95522a5b4004f0652b557b08c66cf25664dd5b
firewut/data-transform-pipelines-api
/src/core/utils/url.py
478
4.0625
4
""" https://stackoverflow.com/questions/1793261/how-to-join-components-of-a-path-when-you-are-constructing-a-url-in-python """ def urljoin(*args): """ Joins given arguments into an url. Trailing but not leading slashes are stripped for each argument. """ url = "/".join(map(lambda x: str(x).rstrip("/"), args)) if "/" in args[-1]: url += "/" if "/" not in args[0]: url = "/" + url url = url.replace("//", "/") return url
b5f5ab0e5ffd77703bf633f6582b6dd25384f93f
JunHwaPark/ProblemSolveByPython
/Binary search/부품 찾기 - 한빛.py
560
3.5625
4
n = int(input()) arr1 = list(map(int, input().split())) m = int(input()) arr2 = list(map(int, input().split())) arr1.sort() def b_search(start, end, val): mid = (start + end) // 2 if start > end: return False elif arr1[mid] == val: return True elif val < arr1[mid]: return b_search(start, mid - 1, val) elif arr1[mid] < val: return b_search(mid + 1, end, val) for i in arr2: present = b_search(0, n - 1, i) if present: print('yes', end=' ') else: print('no', end=' ') print()
03dcb27c84d92928e4780af218f9b5b14d760a8d
SCERush/Crypto-System
/autokey.py
2,736
3.515625
4
# -*- coding: UTF-8 -*- # @File: autokey.py # @Author: SCERush # @Contact: 1037920609@qq.com # @Datetime: 20/7/6 13:57 # @Software: PyCharm """ 文件说明: """ import re def removePunctuation(text, filter='[^A-Z]'): return re.sub(filter, '', text.upper()) def encryptPlain(text, keyword): """ 对于Autokey Plaintext,本质上和vigenere相同,相当于将明文附加在key后面作为密钥来进行vigenere加密 但明文中的空格、非字母字符会影响加密,所以在Autokey的加解密中将除去所有非字母字符,并将全部字母大写 :param text: :param keyword: :return: """ text = removePunctuation(text) res = "" key = keyword.upper() for (i, c) in enumerate(text): if i < len(key): # 明文前i项,使用key进行vigenere加密 offset = ord(key[i]) - 65 else: # 从明文的i+1项,使用明文作为密钥进行vigenere加密 offset = ord(text[i - len(key)]) - 65 res += chr((ord(c) - 65 + offset) % 26 + 65) return res def decryptPlain(text, keyword): """ 因为Autokey本质上是vigenere加密,所以在解密上唯一不同的点就是“-offset” """ text = removePunctuation(text) res = "" key = keyword.upper() for (i, c) in enumerate(text): if i < len(key): offset = ord(key[i]) - 65 else: offset = ord(res[i - len(key)]) - 65 res += chr((ord(c) - 65 - offset) % 26 + 65) # 不同点 return res def encryptCipher(text, keyword): """ Autokey Cipher的加解密与Autokey Plain的解加密相对应 但在求offset上不同,此处使用的与plain相反 :param text: :param keyword: :return: """ text = removePunctuation(text) res = "" key = keyword.upper() for (i, c) in enumerate(text): if i < len(key): offset = ord(key[i]) - 65 else: offset = ord(res[i - len(key)]) - 65 res += chr((ord(c) - 65 + offset) % 26 + 65) return res def decryptCipher(text, keyword): text = removePunctuation(text) res = "" key = keyword.upper() for (i, c) in enumerate(text): if i < len(key): offset = ord(key[i]) - 65 else: offset = ord(text[i - len(key)]) - 65 res += chr((ord(c) - 65 - offset) % 26 + 65) return res if __name__ == '__main__': m = "This is autokey cipher" k = "key" c = encryptPlain(m, k) print(c) d = decryptPlain(c, k) print(d) cc = encryptCipher(m, k) print(cc) dd = decryptCipher(cc, k) print(dd)
0dfed8616136c7eae01d7a55457904accbaebbd8
robertrowe1013/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/12-roman_to_int.py
418
3.5
4
#!/usr/bin/python3 def roman_to_int(roman_string): rom_n = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1} prev = 0 roman_sum = 0 if type(roman_string) is str: for n in roman_string: if rom_n[n] > prev: roman_sum -= prev else: roman_sum += prev prev = rom_n[n] roman_sum += prev return roman_sum
73bfe706df16947f75c5de53f1e05f583cb6a8e4
Coaxecva/COMP4030-Design-and-Analysis-of-Algorithms
/Codes/assignment2.py
1,967
3.65625
4
''' Q3. Explain why (i) 10n + 2n^2 is in O(n^2) [By definition, this means: 10n + 2n^2 <= c*n^2 for all large values of n.] Answer: 10n + 2n^2 <= 10n^2 + 2n^2 = 12n^2 for n>1. Therefore, we found c to be 12. (ii) 10n + 2n^2 is in Omega(n^2) [By definition, this means: 10n + 2n^2 >= c*n^2 for all large values of n.] Answer: 10n + 2n^2 >= n^2 for n>1. c is 1. Q4. Answer: n log n. FALSE. c * n log n. CORRECT O(n + log n). FALSE O(n^2). CORRECT O(n log n). CORRECT (better than the others) Theta(n log n). Q5. (1) Smallest input size is when L has 0 element. The program is correct if L has 0 element. (first two lines) (2) Let's say L has k elements. Then, L[1:] has k-1 elements. So, if we assume the function add is correct for fewer than k elements, then add(L[1:]) returns the sum of all elements starting from the second element. Then, add is correct if L has k elements because L[0] + (sum of all elements starting from the second) is the sum of all elements. Q6. Let you do this at home. ''' # Q2 A = [1,3,4,5,8,20] B = [0,15,30,40] # [0] + def rec_merge(A,B): # smallest input sizes if len(A)==0: return B if len(B)==0: return A # A and B are not empty if A[0] > B[0]: return [B[0]] + rec_merge(A, B[1:]) else: return [A[0]] + rec_merge(A[1:], B) # Q1 def iter_merge2(A,B): C = A + B return sorted(C) # Time complexity: O(n+m), Omega(n+m), Theta(n+m) # Space complexity: Theta(n+m) def iter_merge(A,B): C = [] a, b = 0, 0 while a < len(A) and b < len(B): if A[a] < B[b]: C.append(A[a]) a += 1 else: C.append(B[b]) b += 1 if a==len(A): C = C + B[b:] else: C = C + A[a:] return C # Running time: T(n) = c + T(n-1) # T(n) is the running time of add when L has n elements. # When L has n-1 elements, the running time is T(n-1) def add(L): if len(L)==0: return 0 return L[0] + add(L[1:])
3a3600127741a8b4970e5295538eb6b4db2156b8
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/910 Smallest Range II.py
1,867
3.703125
4
#!/usr/bin/python3 """ Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K, and add x to A[i] (only once). After this process, we have some array B. Return the smallest possible difference between the maximum value of B and the minimum value of B. Example 1: Input: A = [1], K = 0 Output: 0 Explanation: B = [1] Example 2: Input: A = [0,10], K = 2 Output: 6 Explanation: B = [2,8] Example 3: Input: A = [1,3,6], K = 3 Output: 3 Explanation: B = [4,6,3] Note: 1 <= A.length <= 10000 0 <= A[i] <= 10000 0 <= K <= 10000 """ ____ t___ _______ L.. c_ Solution: ___ smallestRangeII A: L..[i..], K: i.. __ i.. """ Say A[i] is the largest i that goes up. A[i+1] would be the smallest goes down Then A[0] + K, A[i] + K, A[i+1] - K, A[A.length - 1] - K """ A.s..() mn m..(A) mx m..(A) ret mx - mn ___ i __ r..(l..(A) - 1 cur_mx m..(mx - K, A[i] + K) cur_mn m..(mn + K, A[i+1] - K) ret m..(ret, cur_mx - cur_mn) r.. ret ___ smallestRangeII_error A: L..[i..], K: i.. __ i.. """ find the min max is not enough, since the min max after +/- K may change """ mini m..(A) maxa m..(A) # mini + K, maxa - K B # list max_upper_diff 0 max_lower_diff 0 upper m..(mini + K, maxa - K) # may cross lower m..(mini + K, maxa - K) ___ a __ A: diffs [(a + K) - upper, lower - (a - K)] cur_diff m..(diffs) __ cur_diff __ diffs[0] a.. cur_diff >_ max_upper_diff: max_upper_diff cur_diff ____ cur_diff __ diffs[1] a.. cur_diff >_ max_lower_diff: max_lower_diff cur_diff r.. upper + max_upper_diff - (lower + max_lower_diff)
fe3b750259f0974c204a249c9d47355aea1496fa
Linkney/LeetCode
/BasicSort/draft_paper.py
1,268
3.6875
4
class POINT: def __init__(self, x, y): self.x = x self.y = y def cross(p1, p2, p3): x1 = p2.x - p1.x y1 = p2.y - p1.y x2 = p3.x - p1.x y2 = p3.y - p1.y return x1 * y2 - x2 * y1 def if_two_line_intersection(p1, p2, p3, p4): if max(p1.x, p2.x) >= min(p3.x, p4.x) and max(p3.x, p4.x) >= min(p1.x, p2.x) and \ max(p1.y, p2.y) >= min(p3.y, p4.y) and max(p3.y, p4.y) >= min(p1.y, p2.y): if cross(p1, p2, p3) * cross(p1, p2, p4) <= 0 and cross(p3, p4, p1) * cross(p3, p4, p2) <= 0: return True else: return False else: return False if __name__ == '__main__': i = "-1,2,-1,1" # -1 无依赖 -2 已完成 work = list(map(int, i.split(","))) ans = [] while len(ans) < len(work): # -1 √ for i in range(len(work)): if work[i] == -1: ans.append(i) work[i] = -2 print("work:", work) print("ans:", ans) # x -1 for i in range(len(work)): if work[i] == -2: continue if work[work[i]] == -2: work[i] = -1 print("work:", work) print("ans:", ans) print(",".join(map(str, ans)))
cdc2934583142502e34362f9dd53bdddef2bcc55
dongzeyuan/Practise
/CP2/ICPP2_1.py
310
3.84375
4
# coding=UTF-8 # 通过键盘输入一系列值,输入0则表示输入结束,将这些值(不包含0)建立为一个列表 # 然后再输出该列表的各元素 data_list = [] a = 1 while a: x = int(input("请输入数字: ")) data_list.append(x) a = x data_list.pop() print(data_list)
33a96a0ff635e53ef60cd56a5d563dfe9b74e269
niujinshuchong/stochastic_processes
/hw4/mm1_queue.py
2,904
3.671875
4
import numpy as np import random import math import matplotlib.pyplot as plt arrival_rate = 2 arrival_service_ratio = 0.8 service_rate = arrival_rate / arrival_service_ratio print(1. / ( service_rate - arrival_rate), arrival_rate / (service_rate * (arrival_rate - service_rate))) # simulation trial = 100000 # since arrival time and and service time are exponential distribution, # we first generate all arrival time and service time with exponential distribution # then we do the simulation: check every ones response time, queueing time arrival_times = np.random.exponential(1. / arrival_rate, trial) service_times = np.random.exponential(1. / service_rate, trial) arrival_times = np.cumsum(arrival_times) response_times = np.zeros_like(arrival_times) queueing_times = np.zeros_like(arrival_times) leave_times = np.zeros_like(arrival_times) end_of_last_service = 0.0 # service for every one for i in range(trial): # no body is waiting if arrival_times[i] >= end_of_last_service: queueing_times[i] = 0 response_times[i] = service_times[i] end_of_last_service = arrival_times[i] + service_times[i] leave_times[i] = end_of_last_service # some one is waiting else: queueing_times[i] = end_of_last_service - arrival_times[i] response_times[i] = queueing_times[i] + service_times[i] end_of_last_service += service_times[i] leave_times[i] = end_of_last_service # simulation ends when last person arrivals leave_times = leave_times[leave_times < arrival_times[-1]] # number of jobs in the system arrival_count = np.ones_like(arrival_times) leave_count = - np.ones_like(leave_times) count = np.concatenate((arrival_count, leave_count), axis=0) times = np.concatenate((arrival_times, leave_times), axis=0) count = count[times.argsort(axis=0)] times = times[times.argsort(axis=0)] count = np.cumsum(count) print('the mean and variance of the number of jobs in the system') mean = np.sum((times[1:] - times[:-1]) * count[:-1]) / arrival_times[-1] var = np.sum((times[1:] - times[:-1]) * (count[:-1] - mean) ** 2 ) / arrival_times[-1] print(mean, var) print('the mean response time of jobs in the system') print(np.mean(response_times)) print('the mean queueing time of jobs in the system') print(np.mean(queueing_times)) plt.figure(figsize=(10, 6)) plt.subplot(211) plt.plot(times, count) plt.ylabel('jobs in system') plt.subplot(234) plt.hist(queueing_times, density=True) plt.title('distribution of queueing time') plt.ylabel('density') plt.xlabel('time') plt.subplot(235) plt.hist(response_times, density=True) plt.title('distribution of response time') plt.ylabel('density') plt.xlabel('time') plt.subplot(236) plt.hist(count, density=True) plt.title('distribution of jobs') plt.ylabel('density') plt.xlabel('number of jobs in system') plt.savefig("mm1_queue_%.1lf.png"%(arrival_service_ratio), dpi=300) plt.show()