blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
c6b7b9de260949fbf77a4440d6ea2bc8b1582c89
wabain/tact
/src/tact/agent/__init__.py
843
3.8125
4
"""Support for agents which handle the gameplay of a given player""" from __future__ import annotations from abc import ABC, abstractmethod from typing import Optional from ..game_model import GameModel, Move __author__ = "William Bain" __copyright__ = "William Bain" __license__ = "mit" class AbstractAgent(ABC): """Base class to support agents. Agents must implement methods to declare what player they represent and to choose moves. """ @property @abstractmethod def player(self): raise NotImplementedError('player') def choose_move(self, game: GameModel, opponent_move: Optional[Move]) -> Move: """Make a new move. The caller is supplied with the current state of the game as well as the opponent's last move. """ raise NotImplementedError('choose_move')
d066b5f153c401f14ec6c7a8ee2e18922831b76d
josiegit/untitled1-
/testing/test_yield.py
190
3.640625
4
# -*- coding:utf-8 -*- #yield+函数==生成器 def provider(): for i in range(5): yield i #生成器:return i + 暂停 p=provider() print(next(p)) print(next(p)) print(next(p))
4df75339e297a06764078b076354d165b5c48af2
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/etwum/lesson02/series.py
3,258
4.40625
4
def fibonacci(n): # this function finds the nth integer in the fibonacci series # fibonacci series ....0, 1, 1, 2, 3, 5, 8, 13 # the next integer is determined by summing the previous two # starting two numbers of the fibonacci series (0 and 1) x = 0 y = 1 # adds the starting two numbers to a list fibonacci_list = [x,y] # variable used to keep count of the nth value count = 1 while count < n: # loops while the variable count is less than the parameter n # find the length of the list and substracts 1 and 2 # in order to find the previous two numbers in the fibonacci series x2 = len(fibonacci_list) -2 x3 = len(fibonacci_list) - 1 x4 = fibonacci_list[x2] + fibonacci_list[x3] # add the next number of the fibonacci series to the list fibonacci_list.append(x4) #iterate the count variable count += 1 # return the nth fibonacci integer return print(fibonacci_list[-2]) def lucas(n): # this function finds the nth integer in the lucas series # lucas series ....2, 1, 3, 4, 7, 11, 18, 29 # the next integer is determined by summing the previous two # starting two numbers of the lucas series (0 and 1) x = 2 y = 1 # adds the starting two numbers to a list lucas_list = [x,y] # variable used to keep count of the nth value count = 1 while count < n: # loops while the variable count is less than the parameter n # find the length of the list and substracts 1 and 2 # in order to find the previous two numbers in the lucas series x2 = len(lucas_list) -2 x3 = len(lucas_list) - 1 x4 = lucas_list[x2] + lucas_list[x3] # add the next number of the lucas series to the list lucas_list.append(x4) # iterate the count variable count += 1 # return the nth lucas integer return print(lucas_list[-2]) def sum_series(n ,y = 0, z = 1): # this function finds the nth integer in any series based on the input parameters # the next integer is determined by summing the previous two # adds the starting two numbers to a list series_list = [y,z] # variable used to keep count of the nth value count = 1 while count < n: # loops while the variable count is less than the parameter n # find the length of the list and substracts 1 and 2 # in order to find the previous two numbers in the series x2 = len(series_list) -2 x3 = len(series_list) - 1 x4 = series_list[x2] + series_list[x3] # add the next number of the series to the list series_list.append(x4) # iterate the count variable count += 1 # return the nth integer return print(series_list[-2]) while True: #Test functions x = int(input("input a number")) y = int(input("input a number")) z = int(input("input a number")) # test to make sure the value of x is greater than zero assert x > 0 # test to make sure the values of y + z are greater than zero for the sum_series function assert y + z > 0 fibonacci(x) lucas(x) sum_series(x,y,z) break
a2c6576ad8fde1230432eee02146f142ec2a4b85
MarioViamonte/Curso_Python
/exercicio/exercicio1.py
925
4.3125
4
""" faça um programa que peça ao usuário para digitar um número inteiro, informe se este número é par ou ímpar. Caso o usuário não digite um número inteiro, informe que não é número inteiro. """ numero_inteiro = input('digite um numero inteiro: ') if numero_inteiro.isdigit(): # checar se pode converter a string para um inteiro (tem só numero nessa string?) numero_inteiro = int(numero_inteiro) if numero_inteiro % 2 == 0: print(f' {numero_inteiro} é par') else: print(f'{numero_inteiro} é impar') else: print('não é número inteiro.') # checagem invertida numero_interio = input('digite um número: ') if not numero_inteiro.isdigit(): print('isso não é um número inteiro') else: numero_inteiro = int(numero_inteiro) if not numero_inteiro % 2 == 0: print(f'{numero_inteiro} é impar') else: print(f'{numero_inteiro} é par')
11a847f35b6f8b035907c5725667013bb975e067
reveo/TKOM
/Python/POS/for.py
98
3.796875
4
For I in range(0,10): a = 5; a = "abc"; b = a; print(b); for J in range(2): print("Hello");
9f8d32d49274367e6d6177a47581dad6a6e9c6a4
hbyyy/TIL
/study/python_100quiz/quiz52.py
1,648
3.84375
4
# def qsort(num_list): # num_list_len = len(num_list) # if num_list_len <= 1: # return num_list # pivot = num_list.pop(num_list_len // 2) # num_list_front = [] # num_list_back = [] # # for i in range(num_list_len - 1): # if num_list[i] < pivot: # num_list_front.append(num_list[i]) # else: # num_list_back.append(num_list[i]) # return qsort(num_list_front) + qsort(num_list_back) # # # list1 = input().split(' ') # # 내용을 채워주세요. # # print(qsort(list1)) from copy import copy def qsort1(num_list): if len(num_list) <= 1: return num_list pivot = num_list.pop(len(num_list)//2) pivot_front_list = [] pivot_back_list = [] for i in range(len(num_list)): if num_list[i] < pivot: pivot_front_list.append(num_list[i]) else: pivot_back_list.append(num_list[i]) return qsort1(pivot_front_list) + [pivot] + qsort1(pivot_back_list) list1 = [9,2] print(list1) print(qsort1(list1)) print(list1) # def qsort2(num_list): # if len(num_list) <= 1: # return num_list # pivot = len(num_list)//2 # pivot_front_list = [] # pivot_back_list = [] # for i in range(len(num_list)): # if num_list[i] < num_list[pivot]: # pivot_front_list.append(num_list[i]) # elif num_list[i] > num_list[pivot]: # pivot_back_list.append(num_list[i]) # else: # continue # # return qsort2(pivot_front_list) + [num_list[pivot]] + qsort2(pivot_back_list) # # list1 = [1,6,9,2,3,4] # print(list1) # print(qsort2(list1)) # print(list1)
933046baeeeb0122a68c290202beb29b197d36cb
MadSkittles/leetcode
/318.py
540
3.5
4
class Solution: def maxProduct(self, words): w = {} for word in words: w[word] = set(word) max_product = 0 for i in range(len(words) - 1): for j in range(i + 1, len(words)): if not w[words[i]].intersection(w[words[j]]): max_product = max(max_product, len(words[i]) * len(words[j])) return max_product if __name__ == '__main__': solution = Solution() print(solution.maxProduct(["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]))
d3d3b33b40cb1b3cbff98e1562e2a9538ca9919e
tachajet/IS211_Assignment7
/pig_game.py
3,192
4.0625
4
from random import randint,seed import argparse seed(0) class Dice: """ This program unfortunately does not work as I'd hoped, but at least I think I can explain why """ @staticmethod def roll(): return randint(1, 6) class Player: """ Dice and Player classes are OK, I think """ def __init__(self, num): self.num = num self.total_score = 0 self.play = True def __str__(self): return f"{self.num}" # Here's where I lost the thread: class Pig: def __init__(self, num_players): # I had wanted to try to make a version with a customizable number of players... self.pig_players = [Player(x) for x in range(0, num_players)] # ...but that led to me short-sightedly trying to define the entire game below: def play(self): # this is the current player p = 0 winner = False while not winner: current_player = self.pig_players[p] # Looping through the player objects doesn't work # once you run out of players! It just terminates the loop without meeting endgame conditions. # I should have broken this up further for any hope of making it functional current_player.play = True current_score = 0 while current_player.play: choice = input(f"Player {current_player}, would you like to hold (h) or roll (r)? ") if choice.upper() == "H": current_player.total_score += current_score current_player.play = False elif choice.upper() == "R": roll_score = Dice.roll() if roll_score == 1: print(f"Sorry Player {current_player}. You have rolled a 1 and your turn is over.") current_player.play = False else: current_score += roll_score print(f"Congratulations Player {current_player}, you rolled a {roll_score}, " f" and your current score is {current_score} " f" and your possible total score is {current_player.total_score + current_score} " ) # check if the current player won if current_player.total_score + current_score >= 100: winner = True current_player.play = False current_player.total_score += current_score print(f"Player {current_player} is the winner with {current_player.total_score}") else: print("Not a valid input, please try again") # Move to next player if not winner: p += 1 if p == len(self.pig_players): p = 0 def main(): parser = argparse.ArgumentParser() parser.add_argument('--numPlayers', type=int, default=2) args = parser.parse_args() pig_game = Pig(args.numPlayers) pig_game.play() if __name__ == "__main__": main()
48a04a8770191c3f3c51c5899eeaa1bc10f8bf1d
vamshiderdasari/5363-CRYPTOGRAPHY-vamshiderdasari
/Vamshider.Dasari.Elliptical/elliptical.py
1,537
4.40625
4
############################################### # Name: Vamshider Reddy,Dasari # Class: CMPS 5363 Cryptography # Date: 04 August 2015 # Program 3 - Elliptical Curve. ############################################### ##including header files import string import argparse import random import sys from pprint import pprint import math from fractions import Fraction ##This function will check weather the points are on the curve and find the third. #@parameters: both the points,slope, and also the co-efficents are given as parameters. def checkPoint(a,b,x1,y1,x2,y2,m): m= findSlope(x1,y1,x2,y2,a) print("slope =",m) x3=0.0 y3=0.0 checkp1=x1**3+a*x1+b-y1**2 checkp2=x2**3+a*x2+b-y2**2 if checkp1==0 and checkp2==0 : print("Both the points exist on the curve.") x3 =Fraction( m**2-x1-x2).limit_denominator(1000) y3 =Fraction(m*(x3-x1)+y1).limit_denominator(1000) else: print("The Points does not exist on curve") return (x3,y3) ##this function is used to find the slope ##@parameters : the two points are given as input and also the a value. def findSlope(x1,y1,x2,y2,a): m=0.0 if x1==x2 and y1==y2: print("Tthe two points are similar") m = float(3*x1**2+a)/float(2*y2) elif (x1==x2 and y1!= y2): print("The Slope cannot be found ") else: m=float(y2-y1)/float(x2-x1) return m def main(): slope= findSlope(x1,y1,x2,y2,a) x3,y3= checkPoint(a,b,x1,y1,x2,y2,slope) if __name__ == '__main__': main()
e02f9db4512aab24cd8b6dbed60025e944154ee8
a87150/learnpy
/starred_expression.py
1,439
3.9375
4
def one(a,*b): # a是一个普通传入参数,*b是一个非关键字星号参数 print(b) one(1,2,3,4,5,6) #-------- def two(a=1,**b): # a是一个普通关键字参数,**b是一个关键字双星号参数 print(b) two(a=1,b=2,c=3,d=4,e=5,f=6) def three(*x): # 输出传入的第一个参数 print(x[0]) lst={"a","b","c","d"} stri="www.pythontab.com" three(stri,lst) three(lst) three(*stri) def test_kwargs(first, *args, **kwargs): print('Required argument: ', first) for v in args: print('Optional argument (*args): ', v) for k, v in kwargs.items(): print('Optional argument %s (*kwargs): %s' % (k, v)) test_kwargs(1, 2, 3, 4, k1=5, k2=6) ''' *args和**kwargs语法不仅可以在函数定义中使用,同样可以在函数调用的时候使用。 不同的是,如果说在函数定义的位置使用*args和**kwargs是一个将参数pack的过程,那么在函数调用的时候就是一个将参数unpack的过程了。 下面使用一个例子来加深理解: ''' def test_args(first, second, third, fourth, fifth): print('First argument: ', first) print('Second argument: ', second) print('Third argument: ', third) print('Fourth argument: ', fourth) print('Fifth argument: ', fifth) # Use *args args = [1, 2, 3, 4, 5] test_args(*args) kwargs = { 'first': 1, 'second': 2, 'third': 3, 'fourth': 4, 'fifth': 5 } test_args(**kwargs)
b89e13baef9e8e357181ba1c2c146e4b55d8fc50
rafaelperazzo/programacao-web
/moodledata/vpl_data/129/usersdata/149/44333/submittedfiles/al7.py
193
3.71875
4
# -*- coding: utf-8 -*- n=int(input('digite o valor de n:')) i=0 soma=0 for i in range(1,n,1): if n%i==0: j=n//i+i print(i) soma=soma+i if j==n: print(PERFEITO)
45a620b302549c9a3dc494794b0fb91107eb01d6
trigodeepak/Programming
/Recursively_remove_duplicates.py
332
3.53125
4
#Program to recursively remove all the same arrays a = 'geeksforgeeg' a = list(a) l = len(a) i = 0 while(i<l-1): if a[i] == a[i+1]: s = i a.pop(i+1) l-=1 while(i+1<l and a[i]==a[i+1]): a.pop(i+1) l-=1 a.pop(i) l-=1 i-=2 i+=1 print ''.join(a)
e3d7fd79863b8438f5aaef3fcbda61641c80ca37
zuxinlin/leetcode
/leetcode/268.MissingNumber.py
939
4.09375
4
#! /usr/bin/env python # coding: utf-8 ''' Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Example 1: Input: [3,0,1] Output: 2 Example 2: Input: [9,6,4,2,3,5,7,0,1] Output: 8 连续整数数组,其中丢失一个数字,求丢失的数字 1. 求和 2. 异或 ''' class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ # 加法求解 # return (1 + len(nums)) * len(nums) / 2 - sum(nums) # 异或求解 n = len(nums) first, second = 0, 0 for i in range(n+1): first ^= i for i in nums: second ^= i return first^second if __name__ == '__main__': solution = Solution() assert solution.missingNumber([3, 0, 1]) == 2 assert solution.missingNumber([9, 6, 4, 2, 3, 5, 7, 0, 1]) == 8
a3b578691ab55d88165cb522ba6e873c8931de35
RyoWakabayashi/hello-worlds
/python/scripts/hello_branch.py
265
3.53125
4
""" Say hello. """ __author__ = "RyoWakabayashi <gfdmkm573@gmail.com>" __version__ = "1.0.0" __date__ = "2021/04/20" HELLO_WORLD = "Hello, world!" if HELLO_WORLD == "Good morning": print("morning") elif "Hello" in HELLO_WORLD: print("noon") else: print("night")
68df6a2a5cbb0980afb6ddff3df84a6a292804a3
Gabriel-ino/python_basics
/adivinhação.py
356
3.90625
4
from random import randint from time import sleep b = randint(0, 5) a = int(input('Vou pensar em um número inteiro entre 0 e 5, tente adivinhar qual é!\nDigite:')) print('Vamos ver...') sleep(2.0) if a == b: print('Você acertou! Eu pensei exatamente {}!'.format(b)) else: print('Que pena! Você errou, o número em que pensei foi: {}'.format(b))
f9e19a575fea26dd85ec24fc800f922bbbb3f8f1
messaoudi-mounir/orientation_tool
/lib/mlModel.py
2,913
3.5625
4
# coding=utf-8 import numpy as np import scipy as sp import pandas as pd from abc import ABC, abstractmethod class AbstractMLOperator(ABC): """Python ABC class""" def __init__(self,dt): self.dt = dt self.nchannel=None self.ntStep=None # super.__init__(self) @abstractmethod def initialize(self): pass @abstractmethod def getData(self): print('This is the abstract class') class MLOperator(object): """Base class""" # def __init__(self): def __init__(self,dt): self.dt = dt self.nchannel=None self.ntStep=None def initialize(self): """set processing paramters""" print('do some processing') raise NotImplementedError("This is a required method, do something") def getData(self): """get data as numpy arrays""" raise NotImplementedError("This is a required method") def process(self): """do some processing""" raise NotImplementedError("This is a required method") def getPrediction(self): """get back result""" raise NotImplementedError("This is a required method") class DummyMLOperator2(AbstractMLOperator): def initialize(self,ntStep=1,nchannel=0,channelList=[]): self.ntStep=ntStep self.nchannel=nchannel self.channelList=channelList print('Initialize operator') print('Using channels:') print(channelList) # def getData(self): # print('This is the child class') class DummyMLOperator(MLOperator): def __init__(self,dt): self.dt = dt self.nchannel=None self.ntStep=None self.channelList=None self.torqueArray=None self.rpmArray=None self.result=None def initialize(self,ntStep=1,nchannel=0,channelList=[]): self.ntStep=ntStep self.nchannel=nchannel self.channelList=channelList print('Initialize operator') print('Using channels:') print(channelList) # def initialize(self): def getData(self, dataFrame): dataList=[np.array(dataFrame[ch]) for ch in self.channelList] return dataList # call for every sample def process(self,dataList): assert len(dataList)==self.nchannel return dataList[0]*dataList[1] def main(): import matplotlib.pyplot as plt op=DummyMLOperator(1) ntstep=10 op.initialize(ntStep=ntstep,nchannel=2,channelList=['rpm','torque']) data=np.random.random((300,2)) df=pd.DataFrame(data=data,columns=['rpm','torque']) nwin=10 istart=0 iend=ntstep while iend<df.shape[0]: data=op.getData(df.loc[istart:iend]) result=op.process(data) print(result) istart+=ntstep iend=istart+ntstep if __name__ =='__main__': main()
ac33fd47a31c45afcc32a02a39cc1a2063714ad5
haavardsjef/NTNU
/TDT4110 - Informasjonsteknologi, grunnkurs/Oving2/Betingelser.py
1,051
4.03125
4
#Generelt om betingelser av Håvard Hjelmeseth , Øving 2 ITGK x = float(input("Skriv inn ditt første tall: ")) #Første tallvaribel, input av bruker y = float(input("Skriv inn ditt andre tall: ")) #Andre tallvariabel sum = x + y #Summerer første og andre tallvariabel og lagrer i en variabel sum prod = x * y #Tar produktet av første og andre variabel og lagrer i en variabel prod if sum < prod: #Hvis summen av de to tallvariablene er mindre en produktet av dem print("Summen av", x, "og", y, "er", sum, #Printer at summen har lavere verdi enn produktet "og er mindre enn produktet av de to.") elif sum > prod: #Hvis summen av de to tallvariablene er større enn produktet av dem print("Produktet av", x, "og", y, "er", #Printer at produktet har lavere verdie enn summen prod, "og er mindre enn summen av de to") else: #Hvis ingen av de to betingelsene over er sann, dvs at summen må være lik produktet print("Summen og produktet av de to", #Printer at summen er lik produktet "tallene er begge:", sum)
fb37930b7e0ceebc5fb1b364d88765f3c77409dd
w8833531/mypython
/other/function/dict.py
224
4
4
#!/usr/bin/env python # -*- coding utf-8 -*- d = {'Michael': 95, 'Bob': 75, 'Tracy': 85} print d['Bob'] c = {'Larry': 95, 'Abe': 97, 'Lee': 99} print c['Lee'] c['Lee'] = 97 print c['Lee'] a = d d.pop('Bob') print d print a
ba2dd51b3e9b73bd712571684f651519956fff82
guangyw/algo
/mergeIntervals.py
647
4
4
""" Definition of Interval. class Interval(object): def __init__(self, start, end): self.start = start self.end = end """ class Solution: """ @param intervals: interval list. @return: A new interval list. """ def merge(self, a): # write your code here a.sort(key = lambda interval: interval.start) ans = [] prev = None for interval in a: if prev == None or prev.end < interval.start: ans.append(interval) prev = interval else: prev.end = max(prev.end, interval.end) return ans
609ed1e7ef4f87bb82c1a0845eba530f5bb52e7e
gaurapanasenko/unilab
/06/ZI_Lab2/vigener.py
1,935
3.921875
4
#!/usr/bin/python import sys ALPHABET = ([chr(ord('а') + i) for i in range(0, 32)] + [chr(ord('a') + i) for i in range(0, 26)] + [" "]) ENCRYPT = 2 DECRYPT = 4 def main(): """Main function.""" dothing = 0 for arg in sys.argv[1:]: if arg == "--encrypt": dothing = dothing | ENCRYPT if arg == "--decrypt": dothing = dothing | DECRYPT print("Введите ключевое строку: ") raw_keyword = sys.stdin.readline()[:-1] print("Введите исходную строку: ") string = sys.stdin.readline()[:-1] keyword = [] for i, char in enumerate(string): kind = i % len(raw_keyword) if string[i] not in ALPHABET or raw_keyword[kind] not in ALPHABET: print("Ошибка: такого символа нет в алфавите") sys.exit(1) for j in range(i+1, len(keyword)): if keyword[i] == keyword[j]: print("Ошибка: ключевое слово имеет повторяющиеся символы") sys.exit(1) keyword.append(raw_keyword[i % len(raw_keyword)]) if dothing & ENCRYPT: outstring = "" for i, char in enumerate(string): key_index = ALPHABET.index(keyword[i]) str_index = ALPHABET.index(char) outstring += ALPHABET[(key_index + str_index) % len(ALPHABET)] print("Зашифрованный вариант %s" % outstring) if dothing & DECRYPT: outstring = "" for i, char in enumerate(string): length = len(ALPHABET) key_index = ALPHABET.index(keyword[i]) str_index = ALPHABET.index(char) outstring += ALPHABET[(length + length + str_index - key_index) % length] print("Расшифрованный вариант %s" % outstring) if __name__ == "__main__": main()
05e563150e8bf14d300cea41eda4fc71c69c14d8
VinayHaryan/String
/q13.py
1,602
4.375
4
''' PRINT THE INITIALS OF A NAME WITH LAST NAME IN FULL given a name, print the initials of a name(uppercase) with last name(with first alphabet in uppercase) written in full separated by dots Examples: Input : geeks for geeks Output : G.F.Geeks Input : mohandas karamchand gandhi Output : M.K.Gandhi A naive approach of this will be to iterate for spaces and print the next letter after every space except the last space. At last space we have to take all the characters after the last space in a simple approach. Using Python in inbuilt functions we can split the words into a list, then traverse till the second last word and print the first character in capitals using upper() function in python and then add the last word using title() function in Python which automatically converts the first alphabet to capital. ''' # # python program to print initials of a name # def name(s): # # split the string into a list # l = s.split() # new = '' # # traverse in the list # for i in range(len(l) - 1): # s = l[i] # # add the capital first character # new += (s[0].upper()+'.') # # l[-1] gives last item of list l. we # # use title to print first character in # # capital # new += l[-1].title() # return new # # driver code # s = 'mohandas karamchand gandhi' # print(name(s)) def sort_name(name): v = name.split() new = '' for i in range(len(v)-1): s = v[i] new += (s[0].upper()+'.') new += v[-1].title() return new name = 'vinava shinava tinva' print(sort_name(name))
55cb6274444d63ea3b7724784685fafc4bc9597f
Acova/Medieval_Construction_Manager
/building_level.py
1,420
3.5625
4
class BuildingLevel: """All the data in a building level""" def __init__(self, name, settlementType, buildingConditions, convert_to, buildingCost, upgrades, capabilities): self.name = name self.settlementType = settlementType self.buildingConditions = buildingConditions self.convert_to = convert_to #Level of the building to wich this converts when changing castle <> cith self.capabilities = capabilities self.buildingCost = buildingCost self.upgrades = upgrades #string with the name of the upgrades def getName(self): return self.name def getLevel(self): s = ("\t\t" + self.name + " " + self.settlementType) firstCond = True for condition in self.buildingConditions: if firstCond: s = s + " requieres " + condition firstCond = False else: s = s + " and " + condition s = s + "\n" s = s + ("\t\t" + "{" + "\n" + "\t\t\tconvert_to " + self.convert_to + "\n" + "\t\t\tcapability" + "\n" + "\t\t\t{\n") for capability in self.capabilities: s = (s + "\t\t\t\t" + capability + "\n") s = (s + "\t\t\t}\n" + self.buildingCost + "\t\t\tupgrades\n\t\t\t{\n\t\t\t\t" + self.upgrades + "\n\t\t\t}\n\t\t}\n") return s
07100da452d2c0fb249d1255b426bc9951b71043
zzz136454872/leetcode
/isRectangleCover.py
1,615
3.703125
4
from typing import List class Solution: def isRectangleCover(self, rectangles: List[List[int]]) -> bool: def area(rec): return (rec[3] - rec[1]) * (rec[2] - rec[0]) nodes = {} totalArea = 0 for rec in rectangles: nodes[(rec[0], rec[1])] = nodes.get((rec[0], rec[1]), 0) + 1 nodes[(rec[2], rec[3])] = nodes.get((rec[2], rec[3]), 0) + 1 nodes[(rec[0], rec[3])] = nodes.get((rec[0], rec[3]), 0) + 1 nodes[(rec[2], rec[1])] = nodes.get((rec[2], rec[1]), 0) + 1 totalArea += area(rec) vertexs = [] print('flag') print(nodes) for node in nodes.keys(): if nodes[node] == 1: vertexs.append(node) elif nodes[node] == 2 or nodes[node] == 4: continue else: return False print('flag1') if len(vertexs) != 4: return False vertexs.sort() if vertexs[0][0] != vertexs[1][0] or vertexs[2][0] != vertexs[3][ 0] or vertexs[0][1] != vertexs[2][1] or vertexs[1][ 1] != vertexs[3][1]: return False return area(vertexs[0] + vertexs[3]) == totalArea rectangles = [[1, 1, 3, 3], [3, 1, 4, 2], [3, 2, 4, 4], [1, 3, 2, 4], [2, 3, 3, 4]] rectangles = [[1, 1, 2, 3], [1, 3, 2, 4], [3, 1, 4, 2], [3, 2, 4, 4]] rectangles = [[1, 1, 3, 3], [3, 1, 4, 2], [1, 3, 2, 4], [3, 2, 4, 4]] rectangles = [[1, 1, 3, 3], [3, 1, 4, 2], [1, 3, 2, 4], [2, 2, 4, 4]] print(Solution().isRectangleCover(rectangles))
ecade0666baa69442fbf9f6ba238c416fe894d70
evaristrust/Courses-Learning
/DSFIRST/PANDAS/Dataframe.py
621
3.65625
4
import numpy as np import pandas as pd from pandas import Series, DataFrame data = pd.read_clipboard() print(data) print(data.columns) new_names = ['date', 'expenses', 'amount', 'iou', 'receipt', 'paid'] new_data = data.set_axis(new_names, axis='columns') print(new_data) print(new_data['expenses']) analysis = new_data.loc[:, ['date', 'expenses', 'amount']] print(analysis) # construct a DataFrame from a dictionary cities = {'City_name': ['KGL', 'NG', 'KY'], 'employees': [20, 21, 11]} cities_frame = DataFrame(cities) print(cities_frame) #series or datafrome is created from dictionaries print(new_data.describe())
f337d07d74a97c032ce8883c4a7d1740a023744a
sue0805/Algorithm_BJ_Python
/SWExpertAcademy/desertCafe.py
1,676
3.5625
4
import sys cafes = list() result = -1 def cafe_tour(x, y, cnt, visited, home, size, direction): global result if x == home[0] and y == home[1] and len(visited) != 0: result = max(result, cnt) return if cafes[x][y] in visited: return if y != home[1] and x == home[0]: return if direction == "r": if x + 1 < size and y + 1 < size: cafe_tour(x + 1, y + 1, cnt + 1, visited + [cafes[x][y]], home, size, "r") if x + 1 < size and y - 1 >= 0 and len(visited) > 0: cafe_tour(x + 1, y - 1, cnt + 1, visited + [cafes[x][y]], home, size, "d") elif direction == "d": if x + 1 < size and y - 1 >= 0: cafe_tour(x + 1, y - 1, cnt + 1, visited + [cafes[x][y]], home, size, "d") if x - 1 >= 0 and y - 1 >= 0: cafe_tour(x - 1, y - 1, cnt + 1, visited + [cafes[x][y]], home, size, "l") elif direction == "l": if x - 1 >= 0 and y - 1 >= 0: cafe_tour(x - 1, y - 1, cnt + 1, visited + [cafes[x][y]], home, size, "l") if x - 1 >= 0 and y + 1 < size: cafe_tour(x - 1, y + 1, cnt + 1, visited + [cafes[x][y]], home, size, "t") elif x - 1 >= 0 and y + 1 < size and direction == "t": cafe_tour(x - 1, y + 1, cnt + 1, visited + [cafes[x][y]], home, size, "t") T = int(sys.stdin.readline()) for i in range(0, T): N = int(sys.stdin.readline()) cafes = list() result = -1 for j in range(0, N): cafes.append(list(map(int, sys.stdin.readline().split()))) for j in range(1, N - 1): for k in range(0, N - 2): cafe_tour(k, j, 0, [], [k, j], N, "r") print(result)
6437d3b6dab4ae399a6d513471d602ee305e0ff4
kwonseongjae/p1_201611055
/w7main_3.py
937
3.5
4
def saveTracks(): import turtle wn=turtle.Screen() t1=turtle.Turtle() t1.speed(1) t1.pu() mytracks=list() t1.goto(-370,370) t1.rt(90) t1.pd() mytracks.append(t1.pos()) t1.pencolor("Red") t1.fd(300) t1.lt(90) mytracks.append(t1.pos()) t1.fd(400) t1.lt(90) mytracks.append(t1.pos()) t1.fd(150) t1.rt(90) mytracks.append(t1.pos()) t1.fd(200) t1.rt(90) mytracks.append(t1.pos()) t1.fd(300) t1.fd(100) t1.lt(90) mytracks.append(t1.pos()) t1.fd(200) mytracks.append(t1.pos()) return mytracks for i in range(0,len(mytracks)): t1.goto(mytracks[i]) def replayTracks(mytracks): for i in range(0,len(mytracks)): print(mytracks[i]) def lab7(): mytracks=saveTracks() replayTracks(mytracks) def main(): lab7() main() if __name__=="main": main() wn.exitonclick()
c46f2d79056ad4493fb7420954c1f5142936c91f
junthbasnet/Project-Euler
/ProjectEuler #2[Even Fibonacci Numbers].py
405
3.859375
4
#!/usr/bim/python #Author@ Junth Basnet #Mathematics(Fibonacci numbers) #Time Complexity:O(28*T) #Formula:f(n)=f(n-1)+f(n-2) #Even Numbers:E(n)=4E(n-1)+E(n-2) import sys def fibonacci(max=4*10**16): a,b=0,1 while(a<max): yield a a,b=b,a+b fib=[] for i in fibonacci(): if i%2==0: fib.append(i) for i in range(input()): n=input() evennumbers = filter(lambda x:x<=n,fib) print sum(evennumbers)
7c756475384bf25924ced95045ef06c202188f51
mkvenkatesh/Random-Programming-Exercises
/contiguous_subarray_count_start_end_index.py
1,809
3.875
4
""" Contiguous Subarrays You are given an array arr of N integers. For each index i, you are required to determine the number of contiguous subarrays that fulfills the following conditions: The value at index i must be the maximum element in the contiguous subarrays, and These contiguous subarrays must either start from or end on index i. Input Array arr is a non-empty list of unique integers that range between 1 to 1,000,000,000 Size N is between 1 and 1,000,000 Output An array where each index i contains an integer denoting the maximum number of contiguous subarrays of arr[i] Example: arr = [3, 4, 1, 6, 2] output = [1, 3, 1, 5, 1] Explanation: For index 0 - [3] is the only contiguous subarray that starts (or ends) with 3, and the maximum value in this subarray is 3. For index 1 - [4], [3, 4], [4, 1] For index 2 - [1] For index 3 - [6], [6, 2], [1, 6], [4, 1, 6], [3, 4, 1, 6] For index 4 - [2] So, the answer for the above input is [1, 3, 1, 5, 1] """ a = [3, 4, 1, 6, 2] #a = [1,2,3,4,5] n = len(a) lans = [0] * n s = [] # Calculating the left subarray for a given index that satisfy the given # conditions is the same as calculating it for reverse of the array. So if Li is # the left subarray counts and Ri is the left subarray for the reversed array # counts then the final answer ans = Li + Ri -1 # To calculate L1 efficient we can use the previously stored information on # counts using a stack for i in range(n): while len(s) > 0 and a[s[-1]] < a[i]: lans[i] += lans[s.pop()] s.append(i) lans[i] += 1 rans = [0] * n s = [] for i in range(n-1, -1, -1): while len(s) > 0 and a[s[-1]] < a[i]: rans[i] += rans[s.pop()] s.append(i) rans[i] += 1 for i in range(n): lans[i] = lans[i] + rans[i] - 1 print(lans)
49e4f2a8780e922fea900fc7ea102e49d57e6849
iulidev/code
/ternary.py
323
3.78125
4
# Ternary if-else operator # value_true if condition else value_false numar = 6 paritate = 'par' if numar %2 == 0 else 'impar' print('Numarul', numar, 'este ', paritate) pret_maxim_de_achizitie = 30 pret_actual = 40 print('Achizitia este aprobata' if pret_actual<=pret_maxim_de_achizitie else 'Achizitia este suspendata')
34dc5c73629cc005bd3276b74876509c0c9e6ff0
tzxyz/leetcode
/problems/0009-palindrome-number.py
1,218
3.65625
4
class Solution: """ 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 示例 1: 输入: 121 输出: true 示例 2: 输入: -121 输出: false 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。 示例 3: 输入: 10 输出: false 解释: 从右向左读, 为 01 。因此它不是一个回文数。 进阶: 你能不将整数转为字符串来解决这个问题吗? """ def isPalindrome(self, x: int) -> bool: """ 转换成字符串后对比 s[idx], s[len(s) - idx - 1] 是否相等,如果不等就不是回文数 更简洁的方法 ===> return str(x) == str(x)[::-1] :param x: :return: """ s = str(x) for idx, n in enumerate(s): if s[idx] != s[len(s) - idx - 1]: return False return True if __name__ == '__main__': tests = [ (121, True), (-121, False), (10, False), ] for i, o in tests: assert Solution().isPalindrome(i) == o
d467529bdb8f32a0c038d9ecd3c916f8f6c2e9d7
33percent/python-DSA
/problems/leet_code_8.py
1,293
4.125
4
""" Given two arrays of integers nums and index. Your task is to create target array under the following rules: Initially target array is empty. From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. Repeat the previous step until there are no elements to read in nums and index. Return the target array. It is guaranteed that the insertion operations will be valid. """ class Solution(object): def createTargetArray(self, nums, index): """ :type nums: List[int] :type index: List[int] :rtype: List[int] """ # workflow # first create an empty list target # copy that list temporarily # loop through individual items index - i # split the list by i # insert at that position # add both the lists # return the new one target = [] for idx,val in enumerate(index): if not target: target.append(nums[idx]) else: pr_list = target[:val] post_list = target[val:] new_list = pr_list +[nums[idx]] + post_list target = new_list return target s = Solution() print(s.createTargetArray([1,2,3,4,0],[0,1,2,3,0]))
ebba0ce712495e0c6072fe021c2f69bbf826b36a
pavelkang/pomodoro
/draw.py
951
3.734375
4
# This is used to draw the vector map of GHC7 using GHC7_vector.txt # Author: Kai Kang import matplotlib.pyplot as plt fig = plt.figure(figsize=(5,4)) ax = fig.add_subplot(1,1,1) def getVectors(filename="GHC7_vector.txt"): start_points = [] end_points = [] with open(filename, 'r') as f: for line in f: data = map(float, line.split(",")) start = (data[0], data[1]) end = (data[2], data[3]) start_points.append(start) end_points.append(end) return (start_points, end_points) def drawVectors(start_points, end_points): for i in xrange(len(start_points)): x_data = [start_points[i][0], end_points[i][0]] y_data = [start_points[i][1], end_points[i][1]] ax.plot(x_data, y_data, color="blue", linewidth="1") if __name__ == "__main__": start_points, end_points = getVectors() drawVectors(start_points, end_points) plt.show()
93a15537b29d73d9ec01ccc6989d5bfa7d3e9f8b
eastglow-zz/kky2413
/과제2 2번.py
150
3.671875
4
def int_sum(arg1): b=0 for i in arg1: if i.isdigit(): b=b+int(i) return int(b) c=int_sum('sh452 ?sf56d') print(c)
6f02cb6349f29842a7b541b115191f15d1bd72be
Cperbony/intensivo-python
/cap4/exercise_4.py
597
4.15625
4
for value in range (1, 20): print(value) one_million = list(range(1, 10000)) print(one_million) print(min(one_million)) print(max(one_million)) print(sum(one_million)) odd_numbers = list(range(1, 20, 2)) print(odd_numbers) multiple_of_threes = list(range(3, 31, 3)) print() print("List of multiples of 3") for number in multiple_of_threes: print(number) print() print("List of Cubes") cubes = list(range(1, 11)) for cube in cubes: cube = cube**3 print(cube) print() print("Cube Comprehension") cubes = [value**3 for value in range(1, 11)] for cube in cubes: print(cube)
9c4cf2192c5eec5854dc1eeca9cde409b7590529
Barathnatrayan/Barath-Repository
/calculator.py
1,169
4.1875
4
def add(num1,num2): """Adddition funcction""" return num1+num2 def sub(num1,num2): """Substractoin funcction""" return num1-num2 def mul(num1,num2): """Multiplication funcction""" return num1*num2 def div(num1,num2): """Division funcction""" return num1/num2 """Display all the options available for calculation""" print("Calculator") print("1. Addition") print("2. Substraction") print("3. MMultiplication") print("4. Division") """Get the input choice from the Client""" choice = input("Enter choice") """Get the number input from the client""" num1 = int(input("Enter Number1")) num2 = int(input("Enter Number2")) """Check the choice using the If statement and call the respecctive functions""" if choice == '1': print("Addition of ",num1,"and",num2,"is ",add(num1,num2)) elif choice == '2': print("Subtraction of ", num1, "and", num2, "is ", sub(num1, num2)) elif choice == '3': print("Multiploication of ", num1, "and", num2, "is ", mul(num1, num2)) elif choice == '4': print("Division of ", num1, "and", num2, "is ", div(num1, num2)) else: print("invalid input")
09819c86e4f3b4e31bc89e514268faff6cb355ed
eldss-classwork/nlp-sandwich-shop
/sandwich.py
2,289
4.125
4
import sandwichlib as sl def main(): '''Gets an order from a customer, records the order, and confirms it is correct.''' # Init the shop shop = sl.SandwichShop("Evan's Sandwich Shop") # Greet the customer shop.greeting() while True: # Ask if they want to see a menu affirmatives = {"yes", "yep", "yeah", "yes please", "yes, please", "please", "yup", "y", "sure", "ok", "why not"} choice = input("Would you like to see the menu? (q to quit)\n") if choice == "q": print() print("Come again!") break # Assume anything other than an affirmative means no if choice.strip().lower() in affirmatives: shop.print_menu() print() # Ask what they want / Get order prompt = ("After the sandwich name, let me know if you want to substitute\n" + "a different bread or spread, and any extra options you'd like.\n" + "Please include exceptions at the end of your order.\n\n" + "What can I get for you today? (q to quit)\n") order = input(prompt) if order == "q": print() print("Come again!") break # Process order try: parser = sl.OrderParser(shop.menu, order) (name, bread, spread, options, exceptions) = parser.get_order() sandwich = shop.make_sandwich( name, bread, spread, options, exceptions) except ValueError: print() print("Sorry, I didn't recognize the sandwich you ordered.") print("Please order again.") continue # Check everything is correct negatives = {"no", "nope", "nah", "n", "no thanks"} print() print("Let's make sure we got everything right. We have a:") sandwich.display() is_correct = input("Is that correct? (Type 'no' to reorder)\n") print() if is_correct.lower() in negatives: print("Sorry about that! Let me try again.") print() continue else: print("Great! We'll have that right out for you.") break if __name__ == "__main__": main()
6d7fee281b5d47521b1f77e108e49efc4efdb882
PeterTheOne/epu-accounting
/functions_db.py
2,684
3.921875
4
import sqlite3 from sqlite3 import Error def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) return None def create_table(conn, create_table_sql): """ create a table from the create_table_sql statement :param conn: Connection object :param create_table_sql: a CREATE TABLE statement :return: """ try: c = conn.cursor() c.execute(create_table_sql) except Error as e: print(e) def create_account(conn, account): """ Create a new account into the accounts table :param conn: :param account: :return: account id """ sql = ''' INSERT INTO accounts(parent_id,main_account,iban,email,creditcard_no,name) VALUES((SELECT IFNULL((SELECT id FROM accounts WHERE name = :parent), 0)), :main_account,:iban,:email,:creditcard_no,:name) ''' cur = conn.cursor() cur.execute(sql, account) return cur.lastrowid def create_record(conn, record): """ Create a new record into the records table :param conn: :param record: :return: record id """ sql = ''' INSERT INTO records(parent_id,account_id,accounting_no,accounting_date,status, text,value_date,posting_date,billing_date,amount,currency, subject,line_id,comment,contra_name,contra_iban,contra_bic,import_preset) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ''' cur = conn.cursor() cur.execute(sql, record) return cur.lastrowid def create_file(conn, file): """ Create a new file into the files table :param conn: :param file: :return: file id """ sql = ''' INSERT INTO files(record_id,path) VALUES(?,?) ''' cur = conn.cursor() cur.execute(sql, file) return cur.lastrowid def get_primary_accounts(conn): cur = conn.cursor() cur.execute("SELECT name FROM accounts WHERE main_account = ?", (True,)) return cur.fetchall() def get_secondary_accounts(conn): cur = conn.cursor() cur.execute("SELECT name FROM accounts WHERE main_account = ?", (False,)) return cur.fetchall() # generator to flatten values of irregular nested sequences, # modified from answers http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python def flatten(l): for el in l: try: yield from flatten(el) except TypeError: yield el
22b2039a358fba167b4796652c355868985d3865
brandonhong/Cryptopals-Challenge
/Set 1/s1c6.py
4,683
3.859375
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 9 11:34:31 2018 @author: Brandon Set 1 Challenge 6 Set 1 challenges available on https://cryptopals.com/sets/1 The goal of this challenge is to decipher the ciphertext given in a text file format. The file is based 64'd AFTER being encrypted by some repeating-key xor cipher. The length and value of the key is not given. Thus, the Hamming distance will be used to systematically determine the correct length of the key. Keysize will be brute forced from lengths 2-40 and Hamming distance will be averaged and standardized. The keysize producing the smallest Hamming distance is likely the correct length. A Background on the Hamming Distance The Hamming distance is the mimumum number of positions between two equal length strings in which one string differs from the other. The bitwise Hamming distance between 11110101 and 11011011 would be 4. In English diction, two random letters are usually skewed in their binary in a way that they do not differ as much as two uniformly randomly distributed bytes. This means on average the Hamming distance between two random English letters is 2-3 bits but for two uniformly random bytes it is 4 bits. The difference is additive as strings get longer. The next point is that the Hamming distance is minimized for a cipher key of correct length. Given a random English letter X and Y from the plaintext, the Hamming distance between X and key K is H(X, K). Likewise for Y and K it is H(Y, K). If the key is the correct length the difference between H(X, K) and H(Y, K) is in fact just H(X, Y) - this is minimized to 2-3 bits. However, if the key is incorrect, K', then the distance between H(X, K) and H(Y, K') is on average 4 bits because this is basically comparing two uniformly random bytes. """ from cryptohacks import * #First, load in the text file with open("c6.txt") as f: ciphertext = f.readlines() ciphertext = [line.strip() for line in ciphertext] #Now convert this list of strings into one big string ciphertext = "".join(ciphertext) #Since it has been base 64'd, we can decode the base 64 to get the ciphertext that has been xor'd ciphertext = codecs.encode(codecs.decode(ciphertext.encode(), 'base 64'), 'hex').decode('utf8') #Notice above the ciphertext is wrapped in a final encode in hex #This is needed to get rid of ascii encoding such as "\x42" showing up as "B" #Note this will double the length of ciphertext from 2876 to 5752, meaning one char is two elements long textSize = len(ciphertext) #From here I calculate a normalized Hamming distance for key sizes between 2-40 #And store the Hamming distance in a dict hamDist = {} for keySize in range(2,41): textChunks = [ciphertext[i:i + keySize*2] for i in range(0, textSize, keySize*2)] block1 = textChunks[0] blockSize = len(block1) #Now we can calculate the average Hamming distance, that is normalized by keySize #The additional condition if len(a) == blockSize ensures that the two strings passed to hamming are the same length avgHamming = sum((hamming(block1, a, "hex")) for a in (textChunks[1:]) if len(a) == blockSize)/keySize avgHamming /= (len(ciphertext)//(blockSize) - 1) hamDist[keySize] = avgHamming keySize = min(hamDist, key=hamDist.get) print("Probable keysize length: %d\n" % keySize) textChunks = [ciphertext[i:i + keySize*2] for i in range(0, textSize, keySize*2)] #Now that we have a list of the ciphertext broken up into blocks of length keySize #It is possbile to transpose the list and break the cipher character by character keys = range(256) finalKey = "" for i in range(len(textChunks[0])//2): tposeText = "".join(line[i*2:i*2 + 2] for line in textChunks) textLen = len(tposeText) #Now the brute force decipher beings msgs = {} for i in keys: key = "" while len(key) != textLen: key += hex(i)[2:] hexMsg = xor(tposeText, key) msg = codecs.decode(hexMsg, 'hex').decode('utf8') msg += chr(i) msgs[msg] = score(msg[:-1], scoresDict) decoded = max(msgs, key = msgs.get) # print(decoded[:-1]) # print("Key: %s" % decoded[-1]) finalKey += decoded[-1] #Finally with the correct key, encode it in hex #Now the ciphertext can be broken down into plaintext hexKey = codecs.encode(finalKey.encode(), 'hex').decode('utf8') #Repeat the key to the same length as the hex encoded text repKey = hexKey * (textSize//len(hexKey) + 1) repKey = repKey[:textSize] hexText = xor(ciphertext, repKey) plaintext = codecs.decode(hexText, 'hex').decode('utf8') print(plaintext)
de63233ccfa4316b7016111a6d83d3e9e284d0ec
Sookmyung-Algos/2021algos
/algos_assignment/2nd_grade/김가영_kijh30123/week3/1920.py
450
3.734375
4
import sys def binary_search(num): left=0 right=len(arr) while left<right: mid=(left+right)//2 if arr[mid]<num: left=mid+1 elif arr[mid]==num: return 1 else: right=mid return 0 N=int(input()) arr=list(map(int,sys.stdin.readline().split())) M=int(input()) b=list(map(int,sys.stdin.readline().split())) arr.sort() for i in range(M): print(binary_search(b[i]))
4d51b0449ec3feebdf05210f151bf99be95c8f15
tanajis/python
/problems/dutchNationalFlagProblemAlgorithm.py
2,783
3.8125
4
############################################################################## # This problem was asked by Google. # Given an array of strictly the characters 'R', 'G', and 'B', # segregate the values of the array so that all the Rs come first, the Gs come second, and the Bs come last. # You can only swap elements of the array. # Do this in linear time and in-place. # For example, given the array ['G', 'B', 'R', 'R', 'B', 'R', 'G'], # it should become ['R', 'R', 'R', 'G', 'G', 'B', 'B']. #============================================================================================= #!/usr/bin/env python #title :dutchNationalFlagProblemAlgorithm.py #description :DailyCoding #35 HARD #author :Tanaji Sutar #date :2020-Mar-21 #python_version :2.7/3 #ref : #============================================================================================ #Check https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/ #Thius is also know as Dutch National Flag Problem #http://users.monash.edu/~lloyd/tildeAlgDS/Sort/Flag/ #------------------------------------------------------ #---dutch national flag problem algorithm ##------------------------------------------------------ from __future__ import print_function from copy import deepcopy def segregate(input_array): """ This is standerd approach using Dutch National Flag Problem """ #take three variables #represent R low = 0 #represent G mid = 0 #represent B high = len(input_array) - 1 while(mid <= high): if input_array[mid] == 'R': ##element at mid is B, move to high, move it to low by swaping input_array[mid],input_array[low] = input_array[low],input_array[mid] mid = mid + 1 low = low + 1 elif input_array[mid] == 'G': #element at mid is G then ok ,move to next mid mid = mid + 1 elif input_array[mid] == 'B': #element at mid is B, move to high by swaping input_array[mid],input_array[high] = input_array[high],input_array[mid] high = high - 1 return input_array def segregate2(input_array): """ This is approach designed by me """ map = [0,0,0] #counst of R,G,B for c in input_array: if c == 'R': map[0] = map[0] + 1 elif c == 'G': map[1] = map[1] + 1 elif c == 'B': map[2] = map[2] + 1 output = ['R']*map[0] +['G']*map[1] + ['B']*map[2] return output if __name__ == "__main__": input_array = ['G', 'B', 'R', 'R', 'B', 'R', 'G'] assert segregate(input_array) == ['R', 'R', 'R', 'G', 'G', 'B', 'B'] print(segregate(input_array))
f2393231b3b843b9624bb09160ae4201ce8ecd5c
CerzBbz/daily-programmer
/closest_string/closest_string.py
1,048
3.59375
4
# /r/DailyProgrammer # [2018-03-05] Challenge #353 [Easy] Closest String # https://www.reddit.com/r/dailyprogrammer/comments/826coe/20180305_challenge_353_easy_closest_string/ # Author: CerzBbz def get_input(): with open('inputs.txt', 'r') as file: data = [line.strip() for line in file.readlines()] data.pop(0) return data def calculate_hamming_distance(string1, string2): distance = 0 length = len(string1) i = 0 while i < length: if string1[i] != string2[i]: distance += 1 i += 1 return distance def determine_closest(strings): closest_string = '' closest_string_total = -1 for string1 in strings: total = 0 for string2 in strings: total += calculate_hamming_distance(string1, string2) if closest_string_total == -1 or total < closest_string_total: closest_string = string1 closest_string_total = total return closest_string input_values = get_input() print(determine_closest(input_values))
0c63ccdee5dd9d10eec6f4972dafd53f21439f42
MobyDick69/python_work
/test_vscode_5.py
2,797
3.6875
4
############################ Reading a txt file ############################### file = 'C:\\Users\\andre\\Documents\\python_work\\files\\py_digits.txt' with open(file) as file_obj: for line in file_obj: print(line.rstrip()) ############################################################################### ####################### Ex 10-1,2 Python Crash Course ######################### filename = 'files\\learning_python.txt' with open(filename) as file_obj: lines = file_obj.readlines() for phrase in lines: phrase_mod = phrase.replace('Python','SAS') print(phrase_mod.rstrip()) ############################################################################### ############################ Writing to a file ################################ filename = 'files\\learning_python.txt' with open(filename, 'a') as file_obj: file_obj.write('In Python you can also write to a txt file!\n') file_obj.write('In Python you can also create an app that run on browser!') ############################################################################### ################################## Exceptions ################################# print("Inserisci numeratore e denominatore ('q' per uscire)\n") while True: num = input("Numeratore: ") if num == 'q': break den = input("Denominatore: ") if den == 'q': break try: result = int(num) / int(den) except ZeroDivisionError: print("Non si può dividere un numero per 0;" " prego re-immettere il denominatore") except ValueError: print("Prego immettere un numero") else: print(result) ############################################################################### ######################## Ex 10-10 Python Crash Course ######################### filename = "C:\\Users\\andre\\Documents\\python_work\\files\\moby_dick.txt" with open(filename, encoding='utf-8') as f: content = f.read() words = content.split() dick_count = 0 for word in words: if word.lower() == 'dick': dick_count += 1 print(dick_count) ############################################################################### ######################## Ex 10-11 Python Crash Course ######################### # Importo il modulo json per salvare ed estrarre dati in file json: import json as j # Salvo input dell'user in un file json: filename = 'files\\fav_num.json' with open(filename, 'w') as file_obj: fav_number = input("Qual'è il tuo numero preferito? ") j.dump(fav_number, file_obj) # Leggo dal file json il numero salvato: with open(filename) as f: fav_number_written = j.load(f) print(f"Il tuo numero preferito è: {fav_number_written}") ###############################################################################
f645fbdf69d33c5130e8dab0327c3055c32244e2
dungruoc/GeeksforGeeks
/DynamicProgramming/longest_common_substr.py
1,232
3.75
4
#!/bin/env python import sys # Returns length of longest common # substring of X[0..m-1] and Y[0..n-1] def LCSubStr(X, Y): m = len(X) n = len(Y) # Create a table to store lengths of # longest common suffixes of substrings. # Note that LCSuff[i][j] contains the # length of longest common suffix of # X[0...i-1] and Y[0...j-1]. The first # row and first column entries have no # logical meaning, they are used only # for simplicity of the program. # LCSuff is the table with zero # value initially in each cell LCSuff = [[(0, '') for k in range(n+1)] for l in range(m+1)] # To store the length of # longest common substring result = (0, '') # Following steps to build # LCSuff[m+1][n+1] in bottom up fashion for i in range(m + 1): for j in range(n + 1): if (i == 0 or j == 0): LCSuff[i][j] = (0, '') elif (X[i-1] == Y[j-1]): LCSuff[i][j] = (LCSuff[i-1][j-1][0] + 1, LCSuff[i-1][j-1][1] + X[i-1]) if LCSuff[i][j][0] > result[0]: result = LCSuff[i][j] else: LCSuff[i][j] = (0, '') return result def main(): print LCSubStr(sys.argv[1], sys.argv[2]) if __name__ == '__main__': main()
d4fecfd9aa79660a4008880962653fe15ab72fa9
ben-nathanson/miscellaneous
/pacer.py
746
3.90625
4
from time import sleep def format(d) -> str: return str(int(d)).zfill(2) time_in_minutes = int(input("How many minutes long is your exam?\n")) number_of_questions = int(input("How many questions are on the exam?")) if number_of_questions <= 0: exit() if time_in_minutes <= 0: exit() pace = time_in_minutes / number_of_questions time_remaining = time_in_minutes question = 1 while time_remaining > 0: seconds = time_remaining % 1 * 60 minutes = time_remaining - (time_remaining % 1) print(f"{format(minutes)}:{format(seconds)} remaining.") print(f"You should be at question #{question}.") question = question + 1 time_remaining = time_remaining - pace sleep( pace * 60 ) print("Congrats.")
f3f5ad10e1b6ea39dac1d0f2a5a009e4301c40c1
BrotherB1/343-Zork
/Bar.py
370
3.65625
4
import random """Class for Chocolate Bar. Uses basic getters. Created by Luke Bassett Fall 2017""" class Bar: def __init__(self): self.use = 4 self.mult = 0 def used(self): self.use = self.use - 1 def getMult(self): self.mult = random.uniform(2.0, 2.4) return self.mult def getUse(self): return self.use def getString(self): return "Chocolate Bar"
20cb5a6781b564b50af55ada697248a5c515c372
liyangjie110/weiboProject
/test03.py
876
3.71875
4
# -*- coding: utf-8 -*- import random print "hello,test!" #random 方法生成0-1之间的浮点数 print random.random() #uniform(1,10) 指定范围内的随机浮点数 random.uniform(1,10); #randint(1,10)指定范围内的随机整数 random.randint(1,10) li=["苹果","柚子","香蕉"] li[random.randint(1,2)] num = 20 i=0 while i<3: b = input("请输入数字:") if b == num: print "恭喜,猜中了!" break; elif b>num: print "数字太大!" else: print "数字或太小!" i=i+1 else: print "3次机会已用尽!" for i in range(3): b = input("请输入数字:") if b == num: print "恭喜,猜中了!" break; elif b>num: print "数字太大!" else: print "数字或太小!" if i==2: print "3次机会已用尽!"
5b54d69790c6d524c1b253b8bec1c32ad83c4bf8
LoktevM/Skillbox-Python-Homework
/lesson_011/01_shapes.py
1,505
4.25
4
# -*- coding: utf-8 -*- # На основе вашего кода из решения lesson_004/01_shapes.py сделать функцию-фабрику, # которая возвращает функции рисования треугольника, четырехугольника, пятиугольника и т.д. # # Функция рисования должна принимать параметры # - точка начала рисования # - угол наклона # - длина стороны # # Функция-фабрика должна принимать параметр n - количество сторон. import simple_draw as sd def get_polygon(n): def draw_shape(point, angle, length): v_first = sd.get_vector(start_point=point, angle=angle, length=length, width=3) sd.line(v_first.start_point, v_first.end_point, width=3) v_next = v_first for i in range(n - 1): if i != n - 2: v_next = sd.get_vector(start_point=v_next.end_point, angle=angle + (360 / n) * (i + 1), length=length, width=3) sd.line(v_next.start_point, v_next.end_point, width=3) else: sd.line(v_next.end_point, v_first.start_point, width=3) return draw_shape draw_triangle = get_polygon(n=8) draw_triangle(point=sd.get_point(200, 200), angle=13, length=100) sd.pause()
8a4f0fb95d0cc2660d18dd66dcf3db3e3d7da704
SuperYIP/PythonCode
/极客晨星/part1/py0232函数的四种类型.py
527
3.578125
4
#coding=utf-8 ''' 课件 ''' # def calculateNum(num): # result = 0 # for i in range(1, num+1): # result += i # return result # # print(calculateNum(50)) # def testB(): # print('----testB start----') # print('此时执行testB') # print('----testB end----') # def testA(): # print('----testA start----') # testB() # print('----testA end----') # testA() def huahengxian(): print('-' * 30) def huahengxian_n(num): for i in range(num): huahengxian() huahengxian_n(3)
b7ead8c14c8217fb24333ff5b88d41f11a77d2c4
itsrbpandit/fuck-coding-interviews
/problems/tests/test_camel_case.py
471
3.625
4
# coding: utf-8 import unittest from problems.camel_case import camelcase class TestCase(unittest.TestCase): def test(self): test_data = [ {'input': 'saveChangesInTheEditor', 'expected': 5}, ] for data in test_data: s = data['input'] expected = data['expected'] with self.subTest(s=s): self.assertEqual(camelcase(s), expected) if __name__ == '__main__': unittest.main()
9653cda2df6106e6205251c7df63c19f9f7e1fb4
asihacker/python3_bookmark
/python笔记/aaa基础内置/类相关/property.py
719
3.953125
4
class Apple: """ debug """ def __init__(self): self._age = None @property def age(self): """ :return: """ return self._age @age.getter def age(self): """ :return: """ print('我被调用了getter') # return f'{self._age}是我的年龄' return self._age @age.setter def age(self, value): """ :param value: :return: """ print('我被调用了setter') if isinstance(value, int): self._age = value return else: raise ValueError('age 必须为int类型') a = Apple() a.age = '123' print(a.age)
e59be7bf1909ff36c8bc35b1725b433f4751cb1a
nikhilvkn/python
/PythonPrograms:Basic-Advanced/password-manager.py
2,807
3.796875
4
import pyperclip import shelve import sys pwdList = shelve.open('UserPwd') if len(sys.argv) == 2 and sys.argv[1].lower() == '--help': print('Usage: ./passwordSafer.py [-l | -a | -d | -m]') print('-l : to list the entire accounts in database\n-a : to add a new account to database\n-d : to delete an existing account\n-g : helps to get the password of an account in your clipboard [ ./passwordSafe.pl -g <account_name> ]\n-m : modify the value of an existing account') sys.exit() #Function to Add account details..!!! def addMe(): while True: print('Enter the name of account you wish to add : [Or nothing to exit]') account = input().split(",") if account == '': sys.exit() if account not in pwdList: print('Enter the password :') pwd = input() pwdList[account] = pwd print('Successfully Updated Database!!') anAccount = input('Do you want to add another account (y/n): ') if anAccount == 'y': continue else: sys.exit() else: print('Account ' + account + ' exists in Database. To view the details, use (-l | -g) option') #Function to Delete the account...!!! def deleteMe(): while True: print('Enter the account name to delete : [Or nothing to exit]') delAccount = input() if delAccount == '': sys.exit() if delAccount not in pwdList: print('Account not found in database') continue else: del pwdList[delAccount] print('Successfully Deleted Account!!') #Function to List all accounts...!!! def listMe(): print('The complete list of Accounts are :') for k in pwdList.keys(): print('\t ' + k) #Function to Get the value in Clipboard...!!! def getMe(): if sys.argv[2] in pwdList: pyperclip.copy(pwdList[sys.argv[2]]) print('Password copied to Clipboard') else: print('Account not in Database, Check with ( -l ) option ') #Function to Modify account value...!!! def modifyMe(): print('You can give your account name here : [Or nothing to exit]') accName = input() if accName == '': sys.exit() if accName in pwdList: print('Account is present in Database, Please add the new value') newValue = input() pwdList[accName] = newValue print('Account Successfully Modified') else: print('Account ' + accName + ' not found in Database') toList = input('Do you want to list all Account (y/n): ') if toList == 'y': listMe() else: sys.exit() #Main Program if len(sys.argv) == 2 and sys.argv[1].lower() == '-a': addMe() elif len(sys.argv) == 2 and sys.argv[1].lower() == '-d': deleteMe() elif len(sys.argv) == 2 and sys.argv[1].lower() == '-l': listMe() elif len(sys.argv) == 2 and sys.argv[1].lower() == '-m': modifyMe() elif len(sys.argv) == 3 and sys.argv[1].lower() == '-g': getMe() else: print('Check the syntax with --help') #Close the Shelve variable pwdList.close()
5acaae9d5574c13c3dac229506fe623ba169c2ce
prodahouse/trading.ml
/2016Code/PiazzaCode/#MC1/HWK1/stdev_code.py
759
3.796875
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 20 03:15:00 2016 @author: Owen """ import math as m # calculate the population standard deviation def stdev_p(data): datamean=m.fsum(data)/len(data) result = 0 for i in test: result+=m.pow(i-datamean, 2) result = m.sqrt(result/len(data)) return result # calculate the sample standard deviation def stdev_s(data): datamean=m.fsum(data)/len(data) result = 0 for i in test: result+=m.pow(i-datamean, 2) result = m.sqrt(result/(len(data)-1)) return result if __name__ == "__main__": test = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0] #len(test) print "the population stdev is", stdev_p(test) print "the sample stdev is", stdev_s(test)
99684d3f327cd662d85f4f4239c882ef3b130bf5
eshthakkar/coding_challenges
/closing_paran_index.py
2,161
4.0625
4
def get_closing_paran_index(sentence, open_paran_index): """ Problem : Return the closing paranthesis index from the input string Complexity Analysis: O(n) time and O(1) space Tests: >>> sentence = "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing." >>> print get_closing_paran_index(sentence, 10) 79 # Raises exception as expected # >>> sentence = "((tomorrow)" # >>> print get_closing_paran_index(sentence, 0) """ # start with the next character after the opening bracket position = open_paran_index + 1 count = 0 while position <= len(sentence) - 1: if sentence[position] == "(": count += 1 elif sentence[position] == ")": if count == 0: return position else: count -= 1 position += 1 raise Exception("No closing paranthesis") def is_valid(code): """ Problem: Check if the paranthesis are correctly nested Complexity Analysis: O(n) time and O(n) space complexity Tests: >>> code = "{ [ ] ( ) }" >>> print is_valid(code) True >>> code = "{ [ ( ] ) }" >>> print is_valid(code) False >>> code = "{ [ }" >>> print is_valid(code) False """ st = [] paran_vocab = { "(" : ")", "{" : "}", "[" : "]" } openers = set(paran_vocab.keys()) closers = set(paran_vocab.values()) for char in code: if char in openers: st.append(char) elif char in closers: if not st: return False else: last_seen_opener = st.pop() if not paran_vocab[last_seen_opener] == char: return False return len(st) == 0 if __name__ == "__main__": import doctest print result = doctest.testmod() if not result.failed: print "All tests passed. Good work!" print
53eb3207428d63bd3126405e5766142af75bce29
suyeon0610/python
/Module/module_basic01.py
553
3.640625
4
''' * 모듈 임포트 - 모듈은 파이썬 코드를 작성해 놓은 스크립트 파일이며 모듈 안에는 변수, 함수, 클래스 등이 정의되어 있음 - 파이썬에서는 주요 기능들을 표준 모듈로 구성하여 표준 라이브러리로 제공 - 표준 모듈이나 외부 모듈을 현재 모듈로 불러서 사용할 때는 import 사용 ''' import math # pi = 3.14 print(5 * 5 * math.pi) print(math.sqrt(3)) # 제곱근 print(math.factorial(6)) # 6! print(math.log10(2)) print(math.log(3, 4)) print(math.pow(7, 4))
42fca238a25992b2a1e68f8927469716c9dc09a1
PPGY0711/viscourse
/draw_density.py
4,902
3.625
4
# -*- coding:utf-8 -*- """ Created on 2020/11/29 @Author: ppgy0711 @Contact: pgy20@mails.tsinghua.edu.cn @Function: Implement the density Map of Visualization based on MNIST DataSet """ import numpy as np import matplotlib.pyplot as plt from sklearn.manifold import TSNE import scipy.stats as st def pre_handle_images(dataSet, saturated=False): """ If the input ndarray.shape == 3 and image pixels are represented using a matrix, flatten the pixel matrix first. Prepare data for PCA :param images: :return: Y with 2 dimensions """ Y = [] if dataSet.ndim == 3: if not saturated: for i in range(dataSet.shape[0]): image = dataSet[i, :, :] # 不能直接把灰度加进去,后面的D算出来太大了导致了exp之后P算出来基本上都是0 # 这个对每一个像素点的值归一化一下(每一个都除255) pixels = image.flatten()/255 # print(pixels) Y.append(pixels) Y = np.array(Y) return Y else: for i in range(dataSet.shape[0]): image = dataSet[i, :, :] # 将像素提升到只有0和255之分 image = image.flatten() image = np.where(image > 0, 255, 0) pixels = image.flatten()/255 # print(pixels) Y.append(pixels) Y = np.array(Y) return Y else: return dataSet def kde(data=np.array([]), filename=""): """ Using different kernel function (gaussian) to esimate the density function :param data: :return: """ # Prepare for data x = data[:, 0] y = data[:, 1] xmin, xmax = int(np.min(data[:, 0])-10), int(np.max(data[:, 0])+10) ymin, ymax = int(np.min(data[:, 1])-10), int(np.max(data[:, 1])+10) # Peform the kernel density estimate xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j] positions = np.vstack([xx.ravel(), yy.ravel()]) values = np.vstack([x, y]) # Kernel density estimate with gaussian kernel = st.gaussian_kde(values) # Draw density map f = np.reshape(kernel(positions).T, xx.shape) fig = plt.figure() ax = fig.gca() ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) # Contourf plot (filling with color of contour) cfset = ax.contourf(xx, yy, f, 10, cmap='Blues') cb = fig.colorbar(cfset) # Contour plot (just plot the shape of contour) cset = ax.contour(xx, yy, f, 10, colors='k') # Label plot ax.clabel(cset, inline=1, fontsize=8) ax.set_xlabel('X') ax.set_ylabel('Y') plt.savefig(filename) plt.show() def draw_density(X=np.array([]), labels=np.array([]), dims=2, perplexity=30.0, saturated=False): """ Using sklearn TSNE package to reduce the data dimension to 2-D and draw the density Map :param X: :param dims: :return: """ X_embedded = TSNE(n_components=dims, perplexity=perplexity).fit_transform(X) # Using TSNE provided by sklearn # draw density map if not saturated: if X.shape[0] == 1000: np.save('density/mnist1000_X_%d_0.npy' % (int(perplexity)), X_embedded) kde(X_embedded, 'density/mnist%d_X_%d_0_density_map.png' % (X_embedded.shape[0], int(perplexity))) picname = 'density/mnist%d_X_%d_0.png' % (X_embedded.shape[0], int(perplexity)) else: np.save('density/mnist2500_X_%d_1.npy' % (int(perplexity)), X_embedded) kde(X_embedded, 'density/mnist%d_X_%d_1_density_map.png' % (X_embedded.shape[0], int(perplexity))) picname = 'density/mnist%d_X_%d_1.png' % (X_embedded.shape[0], int(perplexity)) else: np.save('density/mnist1000_X_%d_1.npy' % (int(perplexity)), X_embedded) kde(X_embedded, 'density/mnist%d_X_%d_1_density_map.png' % (X_embedded.shape[0], int(perplexity))) picname = 'density/mnist%d_X_%d_1.png' % (X_embedded.shape[0], int(perplexity)) plt.scatter(X_embedded[:, 0], X_embedded[:, 1], 20, labels) plt.savefig(picname) plt.show() def draw_density_map(perplexity=30.0): """ Test function to generate density map with different perplexity :param perplexity: :return: """ dataSet1 = np.loadtxt('data/mnist2500_X.txt') dataSet2 = np.load('data/sampled_image.npy') dataSet2 = pre_handle_images(dataSet2) dataSet3 = np.load('data/sampled_image.npy') dataSet3 = pre_handle_images(dataSet3, True) labelSet1 = np.loadtxt('data/mnist2500_labels.txt') labelSet2 = np.load('data/sampled_label.npy') draw_density(dataSet1, labelSet1, 2, perplexity) draw_density(dataSet2, labelSet2, 2, perplexity) draw_density(dataSet3, labelSet2, 2, perplexity, True) if __name__ == "__main__": # print() draw_density_map(20.0) draw_density_map(30.0) draw_density_map(40.0)
077301af7fe2815de79649f4f28d0b888a8e7902
harman666666/Algorithms-Data-Structures-and-Design
/Other Practice/Crack the Coding Interview Algorithms/Graphs/DirectedGraphs/RouteBetweenNodes.py
3,397
3.859375
4
'''Given a directed graph, design an algorithm to find out whether there is a route between 2 nodes:''' '''This is a directed graph''' A = { 0: [1], 1: [2], 2: [0,3], 3: [2], 4: [6], 5: [4], 6: [5] } CS241Example = { "a": ["b", "c", "d"], "b": ["d"], "d": ["a", "c", "f","e"], "c": ["a", "e"], "e" : ["d"], "f" : [] } ''' DFS ALGO" ''' def dfsSearch(graph, node1, node2): visited = {} start = {} finish = {} timer = [1] for i in graph: visited[i] = False visited[node1] = True found = [False] dfsSearchRecursive(graph, node1, node2, visited, start, finish, timer, found) print("Visited") print(visited) print("Start") print(start) print("Finish") print(finish) return found[0] def dfsSearchRecursive(graph, node1, node2, visited, start, finish, timer, found): start[node1] = timer[0] neighbours = graph.get(node1) for i in neighbours: if(visited.get(i) == False): timer[0] += 1 visited[i] = True if(i == node2): found[0] = True else: dfsSearchRecursive(graph, i, node2, visited, start, finish, timer, found) finish[node1] = timer[0] return class StackNode(): def __init__(self, data): self.data = data self.next = None self.prev = None class Stack(): def __init__(self): self.topNode = None def push(self, data): newNode = StackNode(data) if(self.topNode is None): self.topNode = newNode else: self.topNode.next = newNode newNode.prev = self.topNode self.topNode = newNode def top(self): if self.topNode is None: return None else: return self.topNode.data def pop(self): if self.topNode is None: return ReferenceError else: prev = self.topNode.prev self.topNode = prev def empty(self): return self.topNode is None '''dfs search with a stack and for loop''' def dfsSearchLoopy(graph, nodeA, nodeB): visited = {} start = {} finish = {} for i in graph: visited[i] = False visited[nodeA] = True stack = Stack() stack.push(nodeA) found = False timer = 1 while not stack.empty(): node = stack.top() stack.pop() start[node] = timer neighbours = graph[node] for i in neighbours: if(visited[i] == False): timer += 1 visited[i] = True if( i == nodeB ): found = True finish[node] = timer break else: # print(i) stack.push(i) finish[node] = timer print("Visited") print(visited) print("Start") print(start) print("Finish") print(finish) return found #print(dfsSearch(A, 1, 2)) #print(dfsSearch(A, 0, 2)) #print(dfsSearch(CS241Example, "a", "f")) print("") print(dfsSearchLoopy(A, 1, 2)) print(dfsSearchLoopy(A, 0, 2)) print(dfsSearchLoopy(A, 0, 4)) print(dfsSearchLoopy(CS241Example, "a", "f")) print("") def bfsSearch(arr, nodeA, nodeB): '''Need a queue for this'''
9568babdcf2c4bd62a291cc453b39968844bb410
connectheshelf/connectheshelf
/reader/extrafunctions.py
301
3.859375
4
def encrypt(message): message=message.upper() newmess="" for i in message: if(i>='A' and i<='Z'): newmess+=chr(ord('A')+ord('z')-ord(i)) elif(i>='0' and i<='9'): newmess+=str(9-int(i)) else: newmess+=i return newmess.upper()
b73ad5322ac5090651102c3e8ccc0aaabd72ed09
ChenBaiYii/DataStructure
/singleton/singleton.py
368
3.640625
4
#!/usr/bin/python3 # __new__ 实现单例类 class Singleton: def __new__(cls, *args, **kwargs): if not hasattr(cls, "_instance"): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kwargs) return cls._instance class MyClass(Singleton): a = 1 a = MyClass() b = MyClass() assert id(a) == id(b)
078d4c6b8cf633377982d09afc5a4ec3b182f59f
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/rna-transcription/6c9bdc2e91814708b237dcdb97810854.py
329
3.703125
4
class DNA: def __init__(self, seq): self.seq = seq def to_rna(self): rna = '' sequence = list(self.seq) for letter in sequence: if letter == 'A': rna += 'U' elif letter == 'C': rna += 'G' elif letter == 'G': rna += 'C' elif letter == 'T': rna += 'A' else: 'Not valid' return rna
157f329091f074ecd52c62763d3a192cb39d16a5
amrishparmar/Sammy-for-MyAnimeList
/menuinterface/search.py
4,458
3.53125
4
import html import click import requests from bs4 import BeautifulSoup import add def display_entry_details(entry): """Display all the details of a given entry :param entry: an anime or manga entry as a Beautiful Soup Tag object """ for detail in entry.children: # ignore newlines in children if detail != "\n": # replace in tag name the underscores with spaces and convert to title case detail_name = detail.name.replace("_", " ").title() # set the string to be the detail.string by default detail_string = detail.string # check that the string contains something if detail_string is not None: # unescape html entities and remove break tags detail_string = html.unescape(detail_string).replace("<br />", "") click.echo("{}: {}".format(detail_name, detail_string)) def search(credentials, search_type): """Search for an anime or manga entry and return it :param credentials: A tuple containing valid MAL account details in the format (username, password) :param search_type: A string denoting the media type to search for, should be either "anime" or "manga" :return: """ if search_type not in ["anime", "manga"]: raise ValueError("Invalid argument for {}, must be either {} or {}.".format(search_type, "anime", "manga")) click.echo() click.echo("{} search".format(search_type.title())) # get search terms from the user search_string = click.prompt("Enter a search term ('q' to cancel)") # escape route for users who change their mind if search_string == "q": return # get the results r = requests.get("https://myanimelist.net/api/{}/search.xml".format(search_type), params={"q": search_string.replace(" ", "+")}, auth=credentials, stream=True) if r.status_code == 204: click.echo("No results found for query \"{}\"".format(search_string)) click.pause() else: # decode the raw content so beautiful soup can read it as xml not a string r.raw.decode_content = True soup = BeautifulSoup(r.raw, "xml") # get all entries matches = soup.find_all("entry") # store the length of all_matched list since needed multiple times num_results = len(matches) if num_results == 1: return matches[0] else: click.echo("We found {} results. Did you mean:".format(num_results)) # iterate over the matches and print them out for i in range(num_results): # use a different layout for entries that don't have any synonyms title_format = "{}> {} ({})" if matches[i].synonyms.get_text() != "" else "{}> {}" click.echo(title_format.format(i + 1, matches[i].title.get_text(), matches[i].synonyms.get_text())) click.echo("{}> [None of these]".format(num_results + 1)) # get a valid choice from the user while True: option = click.prompt("Please choose an option", type=int) if 1 <= option <= num_results + 1: break else: click.echo("You must enter a value between {} and {}".format(1, num_results + 1)) click.echo() # check that the user didn't choose the none of these option before trying to display entry if option != num_results + 1: return matches[option - 1] def anime_search(credentials): """Search for an anime and print out the results :param credentials: A tuple containing valid MAL account details in the format (username, password) :return: """ result = search(credentials, "anime") if result is not None: display_entry_details(result) if click.confirm("Add this entry to your anime list?"): add.add_anime_entry(credentials, entry=result) def manga_search(credentials): """Search for a manga and print out the results :param credentials: A tuple containing valid MAL account details in the format (username, password) :return: """ result = search(credentials, "manga") if result is not None: display_entry_details(result) if click.confirm("Add this entry to your manga list?"): add.add_manga_entry(credentials, entry=result)
46c5c49b6f9c5107b89708b6a4faffeb21006448
AliceDreaming/python_classes
/musicians.py
1,741
3.71875
4
class Musician(object): def __init__(self, sounds): self.sounds = sounds def solo(self, length): for i in range(length): print(self.sounds[i % len(self.sounds)]) # The Musician class is the parent of the Bassist class class Bassist(Musician): def __init__(self): # Call the __init__ method of the parent class super(Bassist, self).__init__(["Twang", "Thrumb", "Bling"]) class Guitarist(Musician): def __init__(self): # Call the __init__ method of the parent class super(Guitarist, self).__init__(["Boink", "Bow", "Boom"]) def tune(self): print("Be with you in a moment") print("Twoning, sproing, splang") class Drummer(Musician): def __init__(self): #TODO # Forgive me I really have no idea how to describe drum sound in English super(Drummer, self).__init__(["Dong", "Tong", "Ting", "Hehe"]) def __count__(self): for i in range(4): print i class Band(object): def __init__(self): self.musicians=[] def hire_musician(self, musician): self.musicians.append(musician) def fire_musician(self, musician): self.musicians.remove(musician) def play_solo(self, length): for musician in self.musicians: musician.solo(length) if(__name__ == '__main__'): david = Guitarist() derek= Bassist() jorge = Drummer() popBand = Band() popBand.hire_musician(david) popBand.hire_musician(derek) popBand.hire_musician(jorge) jorge.__count__() length = 10 popBand.play_solo(length) popBand.fire_musician(david) popBand.play_solo(length)
38ba251362f38281ae16948bc13a1e36fa5d3e59
VitaliySid/Geekbrains.Python
/lesson8/task2.py
1,339
4.15625
4
# 2. Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. # Проверьте его работу на данных, вводимых пользователем. # При вводе пользователем нуля в качестве делителя программа должна корректно обработать эту ситуацию # и не завершиться с ошибкой. class ZeroDivisionException(Exception): pass class ArgumentException(Exception): pass while True: number1_str = input('Введите первое число:') number2_str = input('Введите второе число:') try: if number1_str.isnumeric() and number2_str.isnumeric(): number1 = int(number1_str) number2 = int(number2_str) if number2 == 0: raise ZeroDivisionException('Ошибка деления на ноль') else: print('Результат: ', number1/number2) break else: raise ArgumentException('Введены некорректные данные') except ZeroDivisionException as ex: print(ex) except ArgumentException as ex: print(ex)
1974776ae1559db1daba2628f92856ed5303e06b
DNSingh-15/MyProjects
/Email-Collector.pyw
1,024
3.625
4
from tkinter import * import tkinter.messagebox as tmsg import re def collect(): inputValue = text.get("1.0", "end-1c") email = re.findall(r'[\w\.-]+@[\w\.-]+\.\w+', inputValue) for mail in email: print(f"Your email are as follows: {mail}") tmsg.showinfo("Emails", mail) root = Tk() root.geometry("644x500") root.maxsize(400, 500) root.title("Email Collector") photo = PhotoImage(file="email.png") root.iconphoto(False, photo) # frame = Frame(root,bg="grey",borderwidth=7,relief="raised") # frame.pack(fill="x") label = Label(text="WELCOME TO EMAIL COLLECTOR", font="Helvetica 10 bold", pady="15") label.pack() photo = PhotoImage(file="email.png") label1 = Label(image=photo) label1.pack() button = Button(text="COLLECT", font="comisansms 12 bold", command=collect) button.pack(pady=30) label2 = Label(text="TEXT AREA IS BELOW", font="lucida 10 bold") label2.pack() text = Text(root, font="lucida", relief="sunken") text.pack() root.mainloop()
01fcfefc1861b32063c15eed1d0fc752cb90a13c
JustinOliver/ATBS
/2048.py
1,642
3.515625
4
#! python3 # 2048.py - A program to automate the game 2048 from the webpage remotely from selenium import webdriver import time from selenium.webdriver.common.keys import Keys browser = webdriver.Firefox() browser.get('https://gabrielecirulli.github.io/2048/') time.sleep(10) # Give page time to load body = browser.find_element_by_tag_name('body') # Select area for arrow keys to function turns = 0 times = input('How many times do you want the game to run?:') for i in range (int(times)): print('Game is running....') while True: body.send_keys(Keys.UP) #time.sleep(4) # Give time to view moves, if desired remove comment hash body.send_keys(Keys.RIGHT) #time.sleep(4) body.send_keys(Keys.DOWN) #time.sleep(2) body.send_keys(Keys.LEFT) #time.sleep(2) turns += 4 try: status = browser.find_element_by_class_name('game-message.game-over') time.sleep(1) # give it time to compute final score, otherwise you end up with goofy text score = browser.find_element_by_class_name('score-container') score_t = score.text print('Game over! That went {} turns for a score of {}'.format(turns, score_t)) break except: continue turns = 0 retry = browser.find_element_by_class_name('retry-button') retry.click()
a9ec2f7b017f2e9b26ab325aa7bfd69c0b07565b
mukundajmera/competitiveprogramming
/Circular Linked List/Circular Linked List Insertion At Position.py
1,907
3.890625
4
#User function Template for python3 ''' class Node: def __init__(self, data): self.data = data self.next = None ''' def insertAtPosition(head,pos,data): #code here node = Node(data) if pos == 1 and head == None: node.next = node return node elif pos == 1 and head != None: node.next = head.next head.next = node head.data, node.data = node.data, head.data return head else: current = head prev = None while pos > 1: pos -= 1 prev = current current = current.next if current == head: if pos == 1: node.next = prev.next prev.next = node return head node.next = current.next current.next = node return head #{ # Driver Code Starts #Initial Template for Python 3 # contributed by RavinderSinghPB class Node: def __init__(self, data): self.data = data self.next = None class Llist: def __init__(self): self.head = None def insert(self, data, tail): node = Node(data) if not self.head: self.head = node return node tail.next = node return node def displayList(head): t=head while t.next!=head: print(t.data,end=' ') t=t.next print(t.data,end=' ') if __name__ == '__main__': t = int(input()) for tcs in range(t): n = int(input()) arr = [int(x) for x in input().split()] pos,data=[int(x) for x in input().split()] ll = Llist() tail = None for nodeData in arr: tail = ll.insert(nodeData, tail) #making circular tail.next=ll.head insertAtPosition(ll.head,pos,data) displayList(ll.head) print() # } Driver Code Ends
d35a2becbe1cfe364da351179d1c3bcc96dee08f
wfgiles/P3FE
/Week 12 Chapter 10/CH 10 slides2.py
1,065
3.90625
4
##counts = {'chuck' : 1, 'annie' : 42, 'jan' : 100} ##lst = counts.keys() ##print lst ##lst.sort() ##for key in lst: ## print key, counts[key] ##------------- ##d = {'a':10, 'b':1, 'c':22} ##print d.items() ## ##print sorted(d.items()) ##-------------- ##SORT BY VALUE ##d = {'a':10, 'b':1, 'c':22} ## ##print d.items() ## ##print sorted(d.items()) ## ##for k, v in sorted(d.items()): ## print k, v ##------------------- ##SORT BY VALUE INSTEAD OF KAY ##c = {'a':10, 'b':1, 'c':22} ##tmp = list() ##for k, v in c.items(): ## tmp.append((v, k)) ##print tmp ## ##tmp = sorted(tmp,reverse=True) ##print tmp ##------------- ##*****KNOW THIS****** ##TOP 10 COMMON WORDS IN A FILE ##fhand = open('romeo.txt') ##counts = dict() ##for line in fhand: ## words = line.split() ## for word in words: ## counts[word] = counts.get(word,0) + 1 ## ##lst = list() ##for key, val in counts.items(): ## newtup = (val, key) ## lst.append(newtup) ## ##lst = sorted(lst, reverse=True) ## ##for val, key in lst[:10]: ## print(key, val)
6b2da7154250f58898b1e8f091aa7a7990ac6609
evarenteronieto/Tutorials
/Python/python/codecademy_itirator_dict.py
2,023
4.40625
4
#Create your own Python dictionary, my_dict, in the editor to the right with two or three key/value pairs. #Then, print the result of calling the my_dict.items(). my_dict= { 'Boyfriend':'Dan', 'Age': '41', 'Race': 'other european' } print(my_dict.items()) #Remove your call to .items() and replace it with a call to .keys() and a call to .values(), each on its own line. #Make sure to print both! my_dict= { 'Boyfriend':'Dan', 'Age': '41', 'Race': 'other european' } print(my_dict.keys()) print(my_dict.values()) print(my_dict) #For each key in my_dict: print out the key , #then a space, then the value stored by that key. (You should use print a, b rather than print a + " " + b.) my_dict= { 'Boyfriend':'Dan', 'Age': '41', 'Race': 'other european' } for key in my_dict: print(key, my_dict[key]) #Check out the list comprehension example in the editor. When you're pretty sure you know what it'll do, #click Run to see it in action. evens_to_50 = [i for i in range(51) if i % 2 == 0] print(evens_to_50) #Use a list comprehension to build a list called even_squares in the editor. #Your even_squares list should include the squares of the #even numbers between 1 to 11. Your list should start [4, 16, 36...] and go from there. even_squares = [x ** 2 for x in range(1,11) if x % 2 == 0] print(even_squares) #Use a list comprehension to create a list, cubes_by_four. #The comprehension should consist of the cubes of the #numbers 1 through 10 only if the cube is evenly divisible by four. #Finally, print that list to the console. #Note that in this case, the cubed number should be #evenly divisible by 4, not the original number. cubes_by_four = [ x ** 3 for x in range(1,11) if x % 2 == 0] print(cubes_by_four) #Use list slicing to print out every odd element of my_list from start to finish. #Omit the start and end index. You only need to specify a stride. #Check the Hint if you need help. my_list = range(1, 11) # List of numbers 1 - 10 # Add your code below! print my_list[::2]
186881d37c7457ede261461b90c8fc8a6cc55d71
juancho1007234717/EJERCICIOS-PROGRAM
/Ejercicio15
481
3.640625
4
# -*- coding: utf-8 -*- """ Created on Fri Feb 12 16:10:39 2021 @author: juanj """ cal1 = int(input("Ingrese calificacion del primer bimestre:")) cal2 = int(input("Ingrese calificacion del primer bimestre:")) cal3 = int(input("Ingrese calificacion del segundo bimestre:")) cal4 = int(input("Ingrese calificacion del segundo bimestre:")) promedio = (cal1 + cal2 + cal3 + cal4) / 4 if promedio >= 3.5: print("Aprobado") else: print("reprobado")
60724e2d545c018e061fb14208830fd2ce101429
Aasthaengg/IBMdataset
/Python_codes/p03712/s735974449.py
215
3.5
4
h, w = map(int, input().split()) s = [list(input()) for i in range(h)] s = [["#"] + i + ["#"] for i in s] s = [["#" for i in range(w+2)]] + s + [["#" for i in range(w+2)]] for i in range(h+2): print("".join(s[i]))
6f811ec8db75e2f2042a2cf19bb8c035cb8a0129
ruanchaves/Zero-Shot-Entity-Linking
/src/toy.py
346
3.625
4
class A(object): def __init__(self, a, b, c): self.a = a self.b = b self.c = c class B(A): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class C(A): def __init__(self, *args): print(args) super().__init__(*args) c = C(3,4,5) print(c) b = B(1,2,3) print(b)
ecc5cb4b42b6bbe9bb98a7efbff439e0f59a1d42
IvamFSouza/ExerciciosPython
/Exercicio-18.py
733
4.28125
4
# Crie um programa que leia o nome completo de uma pessoa e mostre: # · O nome com todas as letras maiúsculas; # · O nome com todas as letras minúsculas; # · Quantas letras ao todo (sem considerar espaços); # · Quantas letras tem o primeiro nome. nome = str(input('\nDigite seu nome completo: ')).strip() print('+'*22) print('Analisando seu nome...') print('+'*22) print(f'Seu nome com letras maiúsculas: {nome.upper()}') print(f'Seu nome com letras minúsculas: {nome.lower()}') print(f'O seu nome {nome}, tem',len(nome) - nome.count(' '),'letras.') #print(f'Seu primeiro nome tem: {nome} letras.',(nome.find(' '))) separa = nome.split() print(f'Seu primeiro nome é {separa[0]} e tem',len(separa[0]),'letras' ) print('\n')
d8afee215b71970a86e759475dba3ec1d706ee11
Hafswa/birthday
/birthday.py
595
3.984375
4
import calendar name=input('ENTER NAME: ') days=['Monday', 'Tuesday','Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] endings=['st','nd','rd']+17*['th']+['st','nd','rd']+7*['th']+['st'] print('Hey '+name+', I can tell the day of your Birthday') D=input('Enter Day(1-31): ') M=input('Enter Month(1-12): ') Y=input('Enter Year: ') day_number=int(D) month_number=int(M) year_number=int(Y) day=calendar.weekday(month=month_number, day=day_number, year=year_number) print(name+', your day of birth is '+ days[day]+' '+D+endings[day_number-1]+'/'+M+'/'+Y) input('Press <Enter> to Exit')
ae30a0bacf43318a3238bd3dde9c7077e7cd360e
jingong171/jingong-homework
/孙林轩/第一次作业/第一次作业 金工17-1 2017310392 孙林轩/体重指数.py
173
3.859375
4
h=1.88 w=72.01 m=h*h t=w/m if t<18: print("为低体重") elif t<=25: print("为正常体重") elif t<=27: print("为超重体重") else: print("为肥胖")
1e45dfc42dbb2a1fc359b88194330459575bc4fb
Soooyeon-Kim/Object-Oriented-Programming
/sample.py
444
3.96875
4
# 9주차 2차시 # 산술 연산자 오버로딩 class SampleClass: def __init__ (self, value): self.value =value def __add__(self, another): result = self.value + another.value return SampleClass(result) def __str__(self): return f'value is: {self.value}' if __name__== '__main__': obj1 = SampleClass(10) obj2 = SampleClass(20) obj3 = obj1 + obj2 print(obj3)
844c60c667287081736d1daeb45e0958b5d7023a
shunz/Python-100-Days_Practice
/PythonExam/北京理工大学Python语言程序设计-Mooc/Chapter5/5.1.4.py
530
3.96875
4
# 计算 n!//m # 定义可选参数,放在必选参数后面 def fact(n, m=1): s = 1 for i in range(1, n+1): s *= i return s//m print(fact(10)) print(fact(10,10)) # 参数传递的两种方式,函数调用时, # 参数可以按照位置或名称传递 print(fact(m=20,n=10)) # 可变参数传递 # 计算 n!乘数 def fact2(n, *b): s = 1 for i in range(1, n+1): s *= i for item in b: s *= item return s print(fact2(10)) print(fact2(10,3)) print(fact2(10,3,5,8))
e8e3f76d00d8865efde28d35024f0afe05c220a0
rafaelperazzo/programacao-web
/moodledata/vpl_data/1/usersdata/102/142/submittedfiles/formula.py
119
3.59375
4
p=input('valor de p:') n=input('valor de n:') i=input('valor de i:') v=(p*(1+i)**n-1)/i print('resutado de v:%.2f'%v)
788a516d0a949ea12b6b12d7498cae8555a9fd4a
rajatsachdeva/Python_Programming
/Python 3 Essential Training/08 Operators/boolean.py
881
4.375
4
#!/usr/bin/python3 # Boolean Operators def main(): print("Main Starts !") print("7 < 5 = {}".format(7 < 5)) print("5 == 5 = {}".format(5 == 5)) print("type(True) = {}".format(type(True))) print("True and False = {}".format(True and False)) print("True and True = {}".format(True and True)) print("True or False = {}".format(True or False)) print("True or True = {}".format(True or True)) print("False or False = {}".format(False or False)) # Bitwise Operation # this different from the logical boolean operation print("True & True = {}".format(True & True)) a, b = 0, 1 x, y = 'zero', 'one' print("a < b = {}".format(a < b)) print("x < y = {}".format(x < y)) if a < b and x < y: print("yes") else: print("no") if __name__ == "__main__": main()
5ed759e0742d9f4186da7a41fca2faa1aba5c575
liubaoxing/51reboot
/20150418/8.py
99
3.515625
4
a = range(9) b = [] for i in range(len(a)): b.append(a.pop()) # a.insert(i,a.pop()) print b
dfcc63059496191ccc1280cfaf0c32fea88542aa
PhillipHage202/Python_programs
/near.py
361
3.8125
4
def near (string_main, string_sub): list_parent = list(string_main) for letter in string_main: word_with_letter_removed = string_main.replace(letter, "") if word_with_letter_removed == string_sub: return True return False word1= input("Enter first word:") word2= input("Enter first word:") print(near(word1, word2))
58c88e2d1acb817e7a83c34cf9d97d6658ed6f88
JWilson45/cmpt120Wilson
/credentials.py
1,232
4.15625
4
# CMPT 120 Intro to Programming # Lab #4 – Working with Strings and Functions # Author: Jason Wison # Created: 2018-02-20 def FirstandLast(): first,last = input("Enter your first name: "),input("Enter your last name: ") first,last = first.lower(),last.lower() return [first,last] def username(first,last): uname = first +'.'+ last return uname def pword(): strong = 1 while strong == 1: strong = pstrong(input("Create a new password: ")) strong = pcapcheck(strong) return strong def pstrong(pa): while len(pa) < 8: print("Fool of a Took! That password is feeble! Make it longer!") return 1 return pa def pcapcheck(cap): if cap == 1: return 1 passCoppy1,passCoppy2 = cap,cap passCoppy1 = passCoppy1.upper() passCoppy2 = passCoppy2.lower() if passCoppy1 == cap or passCoppy2 == cap: print('Your password needs UPPER and lower case characters') return 1 else: return cap def main(): name = FirstandLast() uname = username(name[0],name[1]) passwd = pword() print("The force is strong in this one...") print("Account configured. Your new email address is",uname + "@marist.edu") main()
539371616d7ded4cb5adfdc94c8c2f2b2b4907a4
adwanAK/adwan_python_core
/think_python_solutions/chapter-09/exercise-9.4.py
2,032
4.40625
4
#!/usr/bin/env python # encoding: utf-8 """ exercise-9.4.py Write program with a function that will accept user-entered list of required letters and a word, and return True if the word doesn't use only the required letters, and False if it does. Created by Terry Bates on 2012-09-16. Copyright (c) 2012 http://the-awesome-python-blog.posterous.com. All rights reserved.""" import swampy # Neat trick learned from from os import path #swampy_dir = path.join(path.dirname(__file__), 'swampy') swampy_dir = "/Library/Python/2.7/site-packages/swampy-2.1.1-py2.7.egg/swampy/" def uses_only(word, uses_only_list): # iterate over the letters in word for letter in word: # we want to be case insensitive. letter = letter.lower() if letter not in uses_only_list and letter != " ": print "Letter %s is not in %s " % (letter, uses_only_list) return False return True def letters_list(): my_string = raw_input("Please enter a list of letters to use only: ").strip() # Create an empty list letters_list = [] # Run through the string we are given for char in my_string: letters_list.append(char) return letters_list def main(): print my_word = raw_input("Please enter the word of your choice: ").strip() print print "my word is: ", my_word print use_only_string = letters_list() print print "You wish to use only: ", use_only_string print print uses_only(my_word, use_only_string) # Now, we try running through words.txt with the avoid list #create a variable called 'words_txt', make it have path of words.txt words_txt = swampy_dir + '/words.txt' # # open a filehandle f = open(words_txt) # # Excluding the least == Including the most # for line in f: # line = line.strip() # if uses_only( line, use_only_string ): # print "line : %s only uses %s" % (line, use_only_string) if __name__ == '__main__': main()
cff2894eb92fb79764b5b117272322ba741b6f0e
hrishikeshtak/Coding_Practises_Solutions
/hackerrank/si/graph/si-longest-path-in-graph-brute-force.py
1,024
3.671875
4
#!/usr/bin/python3 # BFS with distance array |V|*(|V| + |E|) from collections import defaultdict class Graph: def __init__(self, N, M): self.G = defaultdict(list) self.V = N self.E = M def insert(self, u, v): self.G[u].append(v) self.G[v].append(u) def length_of_the_longest_path(self): ans = 0 for i in self.G: ans = max(ans, self.BFS(i)) return ans def BFS(self, s): Q = [] d = [-1] * (self.V+1) d[s] = 0 Q.append(s) while Q: u = Q.pop(0) for i in self.G[u]: if d[i] == -1: d[i] = d[u] + 1 Q.append(i) return max(d) if __name__ == '__main__': for _ in range(int(input())): N, M = map(int, input().split()) obj = Graph(N, M) for _ in range(M): u, v = map(int, input().split()) obj.insert(u, v) print(obj.length_of_the_longest_path())
459a27fe620e442782ee75f434ff5384b34cc262
asferreir/CursoEmVideo
/Exercicios/ex007.py
282
3.90625
4
""" DESENVOLVA UM PROGRAMA QUE LEIA AS DUAS NOTAS DE UM ALUNO E MOSTRE SUA MEDIA. """ nome = input('Nome do Aluno: ') n1 = float(input('Informe Nota 1: ')) n2 = float(input('Informe Nota 2: ')) media = (n1 + n2) / 2 print('A media do Aluno {}, é = {}.'.format( nome, media))
bbec07f472f90c7adcd799a91ae01f2789733bfa
ShawnDong98/Algorithm-Book
/leetcode/python/74.py
1,033
3.75
4
import bisect from typing import List class Solution: def searchMatrix_v20220405(self, matrix: List[List[int]], target: int) -> bool: if not matrix: return False for row in matrix: ret = bisect.bisect_left(row, target) if ret < len(row) and row[ret] == target: return True return False def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: if not matrix: return False def binary_search(nums, target): left, right = 0, len(nums) while left < right: mid = (left + right) // 2 if nums[mid] == target: return True if nums[mid] > target: right = mid else: left = mid + 1 return False for row in matrix: if binary_search(row, target): return True return False matix = [[1, 3, 5]] S = Solution() print(S.searchMatrix(matix, 1))
89a2a8bb4638493f1af993a622a97962cffbef25
uccser/codewof
/codewof/programming/content/en/prime-numbers/solution.py
378
4.25
4
number = int(input("Enter a positive integer: ")) if number < 2: print('No primes.') else: print(2) for possible_prime in range(3, number + 1): prime = True for divisor in range(2, possible_prime): if (possible_prime % divisor) == 0: prime = False break if prime: print(possible_prime)
4ab27467f210f24ce2a014df07030b9c3c71550d
angolpow/gbhw
/Python/05/Task3.py
1,398
3.75
4
""" 3. Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов (не менее 10 строк). Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников. Пример файла: Иванов 23543.12 Петров 13749.32 """ def analyze_pay(filename): result = 'Сотрудники с окладом ниже 20000:' # длина строки 32, ниже это используется result_dict = {} average = 0 with open(filename, 'r', encoding='utf-8') as f: for line in f: key, value = line.split() result_dict[key] = float(value) for key, value in result_dict.items(): if value < 20000: result += ' ' + key + ',' average += value average = f'\nСредний доход сотрудников: {round(average / len(result_dict), 2)}' result = result[:-1] + average if len(result) > 32 \ else 'Сотрудников с окладом меньше 20к нет' + average return result print(analyze_pay('t3-1')) print(analyze_pay('t3-2'))
b59ece29eb816299e950931ecb0432e1c2f98928
sgrade/pytest
/leetcode/design-underground-system.py
1,157
3.59375
4
# 1396. Design Underground System # https://leetcode.com/problems/design-underground-system/ class UndergroundSystem: def __init__(self): self.checkins = {} self.averages = {} def checkIn(self, id: int, stationName: str, t: int) -> None: self.checkins[id] = [stationName, t] def checkOut(self, id: int, stationName: str, t: int) -> None: checkin_station, checkin_time = self.checkins[id] travel_time = t - checkin_time stations = checkin_station + '-' + stationName if stations in self.averages: self.averages[stations][0] += travel_time self.averages[stations][1] += 1 else: self.averages[stations] = [travel_time, 1] def getAverageTime(self, startStation: str, endStation: str) -> float: stations = startStation + '-' + endStation return self.averages[stations][0] / self.averages[stations][1] # Your UndergroundSystem object will be instantiated and called as such: # obj = UndergroundSystem() # obj.checkIn(id,stationName,t) # obj.checkOut(id,stationName,t) # param_3 = obj.getAverageTime(startStation,endStation)
f09e95db9ecad205a682a00d4574c3a2f02e9bf7
egraven14/portfolio
/Euler 1
289
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 16 17:55:32 2019 @author: eric """ result = 0 num = 0 while num < 1000: if num%3 ==0 or num%5 == 0: result = result + num num = num + 1 else: num = num + 1 print (result)
9230fce167659cef98fc8cee08ba06f3239c8fcf
nsunga/CMSI_485_Artificial_Intelligence
/homework-2/MazeClause.py
6,102
3.609375
4
''' AUTHOR: NICK SUNGA MazeClause.py Specifies a Propositional Logic Clause formatted specifically for Grid Maze Pathfinding problems. Clauses are a disjunction of GridPropositions (2-tuples of (symbol, location)) mapped to their negated status in the sentence. ''' import unittest class MazeClause: def __init__ (self, props): self.props = {} self.valid = False for key, value in props: if key in self.props: if self.props[key] != value: self.valid = True self.props = {} break else: self.props[key] = value def getProp (self, prop): return self.props[prop] if prop in self.props else None def isValid (self): return self.valid def isEmpty (self): return True if len(self.props) == 0 and self.valid == False else False def __eq__ (self, other): return self.props == other.props and self.valid == other.valid def __hash__ (self): # Hashes an immutable set of the stored props for ease of # lookup in a set return hash(frozenset(self.props.items())) def __str__ (self): return str(self.props) @staticmethod def resolve (c1, c2): results = set() removed_once = False complimentary_keys = set() if c1.isValid() or c2.isValid(): return results(MazeClause([])) for key in c2.props: c1_value = c1.getProp(key) c2_value = c2.getProp(key) if c1_value is not None and c1_value != c2_value: complimentary_keys.add(key) for key in c1.props: c1_value = c1.getProp(key) c2_value = c2.getProp(key) if c2_value is not None and c2_value != c1_value: complimentary_keys.add(key) for key in c1.props: if key not in complimentary_keys: results.add((key, c1.getProp(key))) for key in c2.props: if key not in complimentary_keys: results.add((key, c2.getProp(key))) results_mc = MazeClause(results) # adding something true makes no difference if results_mc.isValid(): results.clear() return results # adding the same clause makes no difference if results_mc == c1 or results_mc == c2: results.clear() return results # two clauses, length one, that are compliments: give empty set if len(results) == 0 and len(complimentary_keys) == 1: results.add(MazeClause([])) return results # can only eliminate one literal at a time -> union becomes true if len(complimentary_keys) > 1: results.clear() return results resolved_clause = set() resolved_clause.add(results_mc) return resolved_clause class MazeClauseTests(unittest.TestCase): def test_mazeprops1(self): mc = MazeClause([(("X", (1, 1)), True), (("X", (2, 1)), True), (("Y", (1, 2)), False)]) self.assertTrue(mc.getProp(("X", (1, 1)))) self.assertTrue(mc.getProp(("X", (2, 1)))) self.assertFalse(mc.getProp(("Y", (1, 2)))) self.assertTrue(mc.getProp(("X", (2, 2))) is None) self.assertFalse(mc.isEmpty()) def test_mazeprops2(self): mc = MazeClause([(("X", (1, 1)), True), (("X", (1, 1)), True)]) self.assertTrue(mc.getProp(("X", (1, 1)))) self.assertFalse(mc.isEmpty()) def test_mazeprops3(self): mc = MazeClause([(("X", (1, 1)), True), (("Y", (2, 1)), True), (("X", (1, 1)), False)]) self.assertTrue(mc.isValid()) self.assertTrue(mc.getProp(("X", (1, 1))) is None) self.assertFalse(mc.isEmpty()) def test_mazeprops4(self): mc = MazeClause([]) self.assertFalse(mc.isValid()) self.assertTrue(mc.isEmpty()) def test_mazeprops5(self): mc1 = MazeClause([(("X", (1, 1)), True)]) mc2 = MazeClause([(("X", (1, 1)), True)]) res = MazeClause.resolve(mc1, mc2) self.assertEqual(len(res), 0) def test_mazeprops6(self): mc1 = MazeClause([(("X", (1, 1)), True)]) mc2 = MazeClause([(("X", (1, 1)), False)]) mc1.getProp(("X", (1, 1))) res = MazeClause.resolve(mc1, mc2) self.assertEqual(len(res), 1) self.assertTrue(MazeClause([]) in res) def test_mazeprops7(self): mc1 = MazeClause([(("X", (1, 1)), True), (("Y", (1, 1)), True)]) mc2 = MazeClause([(("X", (1, 1)), False), (("Y", (2, 2)), True)]) res = MazeClause.resolve(mc1, mc2) self.assertEqual(len(res), 1) self.assertTrue(MazeClause([(("Y", (1, 1)), True), (("Y", (2, 2)), True)]) in res) def test_mazeprops8(self): mc1 = MazeClause([(("X", (1, 1)), True), (("Y", (1, 1)), False)]) mc2 = MazeClause([(("X", (1, 1)), False), (("Y", (1, 1)), True)]) res = MazeClause.resolve(mc1, mc2) self.assertEqual(len(res), 0) def test_mazeprops9(self): mc1 = MazeClause([(("X", (1, 1)), True), (("Y", (1, 1)), False), (("Z", (1, 1)), True)]) mc2 = MazeClause([(("X", (1, 1)), False), (("Y", (1, 1)), True), (("W", (1, 1)), False)]) res = MazeClause.resolve(mc1, mc2) self.assertEqual(len(res), 0) def test_mazeprops10(self): mc1 = MazeClause([(("X", (1, 1)), True), (("Y", (1, 1)), False), (("Z", (1, 1)), True)]) mc2 = MazeClause([(("X", (1, 1)), False), (("Y", (1, 1)), False), (("W", (1, 1)), False)]) res = MazeClause.resolve(mc1, mc2) self.assertEqual(len(res), 1) self.assertTrue(MazeClause([(("Y", (1, 1)), False), (("Z", (1, 1)), True), (("W", (1, 1)), False)]) in res) # ~X ^ X Resolve -> self.props empty, self.valid is false if __name__ == "__main__": unittest.main()
95d521b8ea1adee8a0012d1d4109c9ffcc35227e
JerryHDev/Functional-Programming
/Chapter 8/8_9.py
1,038
4.0625
4
#Jerry Huang #Period 4 def main(): print("This program computes the fuel efficiency of a multi-leg journey.") print("Exit the program by pressing the <Enter> key.") odometer = eval(input("Enter the starting odometer reading: ")) x = 1 gas = 0 total_gas = 0 user_input = input("Enter the current odometer reading and amount of gas used after this leg (separated by a space): ") while user_input != "": user_input = user_input.split(" ") miles_traveled = int(user_input[0]) - odometer odometer = int(user_input[0]) gas_used = int(user_input[1]) - gas gas = int(user_input[1]) MPG = miles_traveled / gas_used print("On leg", x, "you achieved", MPG, "miles per gallon") x = x + 1 user_input = input("Enter the current odometer reading and amount of gas used after this leg (separated by a space): ") total_miles = odometer total_gas = gas print("The total miles per gallon for the trip is", total_miles/total_gas) main()
a7844f2f3d095e4d84b212d28332d3de20ff69a7
Saradippity26/Beginning-Python
/lists.py
1,095
4.1875
4
""" Learn about lists: regular python does not have arrays it has lists. reason hard to explain an array to non coders. List is easier to explain. performance wise arrays do better than lists because the size is set and you are not constructing and destructing objects all the time. Unlike lists, lists are mutable (can be replaced), you can append update elements to it """ l = [1, 2, 3] #use [] for defining a lists; elements are separated by commas print("List", 1, type(1)) #can have lists of any types because it is a list of objects a = ["apple", "orange", "pear"] #acces by index notation print(a, a[1]) #Note: first index is zero #replace an element a[0] = "tomatoes" print(a, a[1]) a[1] = 3.14 print(a, a[1]) #Begin with an empty list : use a while loop to request three users to enter thier names. find a method names = [] #plural is a list #ask user to enter 3 names, and add them to the list (append is your friend) total = 0 while total < 3: name = input("enter a name") names.append(name) total = total + 1 # display list print(names) #hashes: accessed by a key.
edf78ee62578bd56ba859b869e49873c3dd49b90
HugoPorto/PythonCodes
/PythonZumbis/lista2/questao07.py
223
3.6875
4
area_pintar = input("Tamanho da area a ser pintada: ") litros = area_pintar / 3.0 if (litros / 18) > 0: latas = int((litros / 18) + 1) else: latas = int((litros / 18)) print "Total de latas necessarias: ", latas
e353075bf68189741316043c309e36a98deac6f8
rostun/ittyBitty
/intro/intro101.py
6,105
4.25
4
""" Using Python 3.4.0 """ #python intro101.py print("Hello") my_int = 7 my_float = 1.23 my_bool = True my_int = 3 print (my_int) #function def spam(): eggs = 12 return eggs print (spam()) #adding count_to = 100 + 10 print (count_to) #exponent eggs = 10 ** 2 print (eggs) #modulo spam = 101%100 print (spam) #reassigning variables meal = 44.50 tax = 0.0675 tip = 0.15 meal = meal + meal * tax total = meal + meal*tip #display precision 2 print("%.2f" % total) #backslash any apostrphes 'This isn\'t flying!' #finding positions of strings fifth_letter = "MONTY"[4] #length, case, strings parrot = "Blah" print(len(parrot)) print(parrot.lower()) print(parrot.upper()) pi = 3.14 print(str(pi)) #string formatting string_1 = "Camelot" string_2 = "place" print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2) name = raw_input("What is your name?") quest = raw_input("What is your quest?") color = raw_input("What is your favorite color?") print "Ah, so your name is %s, your quest is %s, " \ "and your favorite color is %s." %(name, quest, color) #datetime library from datetime import datetime now = datetime.now() print(now) print(now.year) print(now.month) print(now.day) print '%s/%s/%s' % (now.year, now.month, now.day) print '%s/%s/%s %s:%s:%s' % (now.year, now.month, now.day, now.hour, now.minute, now.second) #can directly compare to set boolean values #not is evaluated first, and and then or bool_one = 3 < 5 # True bool_one = not False and True bool_one = 3 < 5 or 3 < 1 if len(name) and name.isalpha(): #pyglatin translator pyg = 'ay' original = raw_input('Enter a word:') if len(original) > 0 and original.isalpha(): word = original.lower() first = word[0] new_word = word[1:len(word)] + first + pyg print new_word else: print 'empty' # math library import math print math.sqrt(25) # or can just do from math import sqrt #import everything from the math module from math import * # now we can just use sqrt by itself import math # Imports the math module everything = dir(math) # Sets everything to a list of things from math print everything # Prints 'em all! maximum = max(1, 2, 3, 4) # max function minimum = min(1, 2, 3, 4) # min function absolute = abs(-3) # absolute value print type("string") #overall example def distance_from_zero(number): if type(number) == int or type(number) == float: return abs(number) else: return "Nope" #lists suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"] #first include second excluded first = suitcase[0:2] # The first and second items (index zero and one) middle = suitcase[2:4] # Third and fourth items (index two and three) last = suitcase[4:6]# The last two items (index four and five) animals = ["aardvark", "badger", "duck", "emu", "fennec fox"] duck_index = animals.index("duck") # Use index() to find "duck" animals.insert(duck_index, "cobra") print animals #for loop my_list = [1,9,3,8,5,7] for number in my_list: print 2 * number #sort start_list = [5, 3, 1, 2, 4] square_list = [] start_list.remove(5) # remove for number in start_list: square_list.append(number**2) square_list.sort() print square_list #dictionaries # Assigning a dictionary with three key-value pairs to residents: residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106} print residents['Puffin'] # Prints Puffin's room number residents['owl'] = 130 del residents['owl'] print residents['Sloth'] # can reassign as well print residents['Burmese Python'] #combingin everything inventory = { 'gold' : 500, 'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key 'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'] } # Adding a key 'burlap bag' and assigning a list to it inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth'] # Sorting the list found under the key 'pouch' inventory['pouch'].sort() inventory['pocket'] = ['seashell', 'strange berry', 'lint'] inventory['backpack'].sort() inventory['backpack'].remove('dagger') inventory['gold'] += 50 #looping throuhg dictionary webster = { "Aardvark" : "A star of a popular children's cartoon show.", "Baa" : "The sound a goat makes.", "Carpet": "Goes on the floor.", "Dab": "A small amount." } for web in webster: print webster[web] #two things prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 } for fruit in prices: print fruit print "price: %s" % prices[fruit] print "stock: %s" % stock[fruit] total = 0 for key in prices: total += prices[key]*stock[key] print total #more dictionaries (classroom edition) lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] } students = [lloyd, alice, tyler] for student in students: print student["name"] print student["homework"] print student["quizzes"] print student["tests"] def average(numbers): total = float(sum(numbers)) total = total/len(numbers) return total def get_average(student): homework = average(student["homework"]) quizzes = average(student["quizzes"]) tests = average(student["tests"]) sum = .10*homework + .3*quizzes + .6*tests return sum def get_letter_grade(score): if score >= 90: return "A" elif score >= 80: return "B" elif score >= 70: return "C" elif score >= 60: return "D" else: return "F" def get_class_average(students): results = [] for student in students: results.append(get_average(student)) return average(results) print(get_class_average(students)) print(get_letter_grade(get_class_average(students)))
451b9fc012e61d7d5f37d5223fc3d01c1c7abb1f
Rika321/Snake
/model/board.py
520
3.703125
4
from random import randint class Board: UP = ( 0, -1) DOWN = ( 0, 1) LEFT = (-1, 0) RIGHT = ( 1, 0) def __init__(self, height, width): self.width = width self.height = height self.food = [2, 2] def new_food(self, cells): new_food = [randint(1, self.height-2), randint(1, self.width-2)] while new_food in cells: new_food = [randint(1, self.height-2), randint(1, self.width-2)] self.food = new_food return self.food
96f96ab222284dc1c5ce6e51465037d487699af1
LeonGrund/EPX-JAM-2017-Demo
/hackerrank/trees.py
1,006
3.6875
4
#import treeOperations class Tree: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def __str__(self): return (str(self.data)) class Operations: def preOrder(root): pre = '' if (root is None): return '' elif (root.left is None and root.right is None): return str(root.data) if (root.left is not None): pre += Operations.preOrder(root.left) + ' ' + str(root.data) if (root.right is not None): pre += ' ' + str(root.data) + ' '+ Operations.preOrder(root.right) new_pre = '' for i in pre: if i in pre.split() and i not in new_pre: new_pre += i + ' ' return new_pre if __name__ == "__main__": test_Tree = Tree(1, None, Tree(2, None, Tree(5, Tree(3, None, Tree(4)), Tree(6, None, None)))) test_results = Operations.preOrder(test_Tree) print(test_results)
7e5e63931b402bbeef9c1b038cf4be69263f237f
pbhandaru/Hacker_Rank_Programming_Exercises
/lists.py
449
3.75
4
#!/usr/bin/python ################ N = int(raw_input()) i = 0 L = [] while i <= N: F=raw_input().split() i += 1 if F[0] == 'insert': L.insert(int(F[1]), int(F[2])) elif F[0] == 'append': L.append(int(F[1])) elif F[0] == 'print': print L elif F[0] == 'remove': L.remove(int(F[1])) elif F[0] == 'sort': L.sort() elif F[0] == 'pop': L.pop() elif F[0] == 'reverse': L.reverse() if str(i) == str(N): break
837f6e6d2610fb529e3ab6470bc39f9bcb90796f
abhishekshanbhag/Design-By-Software-HW-Files
/Week_4/w4_polynomial.py
5,371
3.765625
4
# AUTHOR Abhishek Shanbhag anshan@bu.edu # AUTHOR Ziteng Xu zxu83@bu.edu class Polynomial(): def __init__(self, sequence = []): self.sequence = dict({}) for i in range(len(sequence)): if(sequence[i] != 0): self.sequence.update({len(sequence) - 1 - i:sequence[i]}) #self.max = len(sequence) - 1 #self.min = 0 #print("Created new Polynomial with sequence: " + str(self.sequence)) #print("Max Power = " + str(self.max)) #print("Min Power = " + str(self.min)) def __str__(self): poly = "" s = list(reversed(sorted(self.sequence))) for i in s: if((i > 1) or (i < 0)): poly += "%sx^%d" %(str(self.sequence[i]), i) elif(i == 1): poly += "%sx" %(str(self.sequence[i])) else: poly += "%s" %(str(self.sequence[i])) if(i != min(s)): poly += " + " return poly def __repr__(self): poly = "" s = list(reversed(sorted(self.sequence))) for i in s: if((i > 1) or (i < 0)): poly += "%sx^%d" %(str(self.sequence[i]), i) elif(i == 1): poly += "%sx" %(str(self.sequence[i])) else: poly += "%s" %(str(self.sequence[i])) if(i != min(s)): poly += " + " return poly def __setitem__(self, k, v): if(v != 0): self.sequence.update({k:v}) print("Added item. Sequence is now: " + str(self.sequence)) """if(k > self.max): self.max = k print("Max changed to: "+ str(self.max)) if(k < self.min): self.min = k #print("Min changed to: " + str(self.min))""" else: print("Not added item as value of coefficient is 0.") def __getitem__(self, key): if key in self.sequence: return self.sequence[key] else: return 0 def __add__(self, poly): sum_poly = Polynomial([0]) """if(self.max > poly.max): sum_poly.max = self.max else: sum_poly.max = poly.max if(self.min < poly.min): sum_poly.min = self.min else: sum_poly.min = poly.min""" #print("Max in Sum: "+str(sum_poly.max)) #print("Min in Sum: "+str(sum_poly.min)) for i in self.sequence: if (i in poly.sequence): sum_poly.sequence[i] = (self.sequence[i] + poly.sequence[i]) else: sum_poly.sequence[i] = self.sequence[i] for i in poly.sequence: if not(i in self.sequence): sum_poly.sequence[i] = poly.sequence[i] return sum_poly """def __radd__(self, poly): sum_poly = Polynomial([0]) if(self.max > poly.max): sum_poly.max = self.max else: sum_poly.max = poly.max if(self.max < poly.max): sum_poly.min = self.min else: sum_poly.min = poly.min #print("Max in Sum: "+str(sum_poly.max)) #print("Min in Sum: "+str(sum_poly.min)) for i in self.sequence: if (i in poly.sequence): sum_poly.sequence[i] = (self.sequence[i] + poly.sequence[i]) else: sum_poly.sequence[i] = self.sequence[i] for i in poly.sequence: if not(i in self.sequence): sum_poly.sequence[i] = poly.sequence[i] return sum_poly""" def __sub__(self, poly): sum_poly = Polynomial([0]) """if(self.max > poly.max): sum_poly.max = self.max else: sum_poly.max = poly.max if(self.min < poly.min): sum_poly.min = self.min else: sum_poly.min = poly.min""" #print("Max in Sum: "+str(sum_poly.max)) #print("Min in Sum: "+str(sum_poly.min)) for i in self.sequence: if (i in poly.sequence): sum_poly.sequence[i] = (self.sequence[i] - poly.sequence[i]) else: sum_poly.sequence[i] = self.sequence[i] for i in poly.sequence: if not(i in self.sequence): sum_poly.sequence[i] = -poly.sequence[i] return sum_poly def __rsub__(self, poly): sum_poly = Polynomial([0]) """if(self.max > poly.max): sum_poly.max = self.max else: sum_poly.max = poly.max if(self.min < poly.min): sum_poly.min = self.min else: sum_poly.min = poly.min""" #print("Max in Sum: "+str(sum_poly.max)) #print("Min in Sum: "+str(sum_poly.min)) for i in self.sequence: if (i in poly.sequence): sum_poly.sequence[i] = (poly.sequence[i] - self.sequence[i]) else: sum_poly.sequence[i] = -self.sequence[i] for i in poly.sequence: if not(i in self.sequence): sum_poly.sequence[i] = poly.sequence[i] return sum_poly def __eq__(self, poly): try: if(len(self.sequence) == len(poly.sequence)): for i in self.sequence: if(self.sequence[i] != poly.sequence[i]): return False return True else: return False except: return False def deriv(self): der = Polynomial() for i in self.sequence: if(i != 0): der.sequence[i - 1] = self.sequence[i]*i """if(self.max != 0): der.max = self.max - 1 if(self.min != 0): der.min = self.min - 1""" return der def __mul__(self, poly): mul_poly = Polynomial() for i in self.sequence: for j in poly.sequence: if((i + j) in mul_poly.sequence): mul_poly.sequence[i+j] += (self.sequence[i] * poly.sequence[j]) else: mul_poly.sequence[i+j] = (self.sequence[i] * poly.sequence[j]) """if((i+j) > mul_poly.max): mul_poly.max = (i+j) if((i+j) < mul_poly.min): mul_poly.min = (i-j)""" return mul_poly def eval(self, val): sum = 0 for i in self.sequence: sum += self.sequence[i]*(val**i) return sum def main(): x = Polynomial() print(str(x)) x[-5] = 6 x[3] = complex(2,4) print(str(x)) y = Polynomial([5,-4,complex(6,4),6,2,-1]) z = x+y print(str(z)) print(z) print(str(x)) z = y+x print(str(x)) print(str(x[-5])) pass if __name__ == '__main__': main()
ea6a68681509029b162146b208acba28a39948ad
msGenDev/bioinformatics_algorithms
/approximate_pattern_matching_problem.py
740
3.90625
4
## Python function to find all starting positions where Pattern appears as a substring of Text with at most d mismatches ## given strings Pattern and Text along with an integer d. def find_pattern(p, q, d): count = 0 for x, y in zip(p,q): if x != y: count = count + 1 if count > d: return False return True def approximate_pattern_matching_problem(pattern, genome, d): pos = [] k = len(pattern) l = len(genome) for i in range(l-k): if find_pattern(pattern, genome[i:i+k], d): pos = pos + [i] return pos string = "".join(open("approximate_match_data.txt")).split() approximate_pattern_matching_problem(string[0], string[1], int(string[2]))
a822556316b285d494e26bb89c3149e82935d3b9
Schrodingfa/PY3_TRAINING
/day3/for_demo/ex12.py
453
3.59375
4
# 累加1 -- 100 之间 能被3整除的整数和 # count = 0 # for i in range(100): # if not ( i + 1 ) % 3 : # count += ( i + 1 ) # else: # continue # print(count) # count = 0 # for i in range(1, 100): # # 如果满足条件则累加 # if not i % 3 : # count += i # print(count) count = 0 for i in range(1, 100): # 如果不满足条件则跳过 if i % 3 : continue count += i print(count)
434813f98c2b1ad3f21a33fbc044b845d7503b00
elise-baumgartner/Python-Sleuth
/src/timer.py
3,202
3.53125
4
import time from logger import Logger from globals import Globals class Error(Exception): pass class TimeError(Exception): def __init__(self, message): self.message = message class Timer: def __init__(self, name): self.name = name self.start_time = 0.0 self.stop_time = 0.0 self.num_calls = 0 self.is_running = False self.total_time = 0.0 self.average_time = 0.0 def start(self): if self.is_running: raise TimeError("Timer is running, use .stop() to stop it") self.start_time = time.perf_counter() self.is_running = True self.num_calls += 1 def read(self): if not self.is_running: raise TimeError("Timer is not running. Use .start() to start it") current_time = time.perf_counter() return ((current_time - self.start_time) * 1000) + self.total_time def stop(self): if not self.is_running: raise TimeError("Timer is not running. Use .start() to start it") self.stop_time = time.perf_counter() self.total_time += (self.stop_time - self.start_time) * 1000 self.average_time = self.total_time / self.num_calls self.is_running = False def __str__(self): return f"{self.name:15s} {self.num_calls:5} {self.average_time:8.2f} " \ f"{self.total_time:10.2f} = {self.format_total_time()}" def format_total_time(self): seconds = self.total_time / 1000 days = int(seconds / (60 * 60 * 24)) seconds -= days hours = int(seconds / (60 * 60)) seconds -= hours minutes = int(seconds / 60) seconds -= minutes seconds = int(seconds) % 60 return f"{days:02d}:{hours:02d}:{minutes:02d}:{seconds:02d}" class TimerUtility: timers = { "spr_spread": Timer("spr_spread"), "spr_phase1n3": Timer("spr_phase1n3"), "spr_phase4": Timer("spr_phase4"), "spr_phase5": Timer("spr_phase5"), "gdif_WriteGIF": Timer("gdif_WriteGIF"), "gdif_ReadGIF": Timer("gdif_ReadGIF"), "delta_deltatron": Timer("delta_deltatron"), "delta_phase1": Timer("delta_phase1"), "delta_phase2": Timer("delta_phase2"), "grw_growth": Timer("grw_growth"), "drv_driver": Timer("drv_driver"), "total_time": Timer("total_time") } @staticmethod def start_timer(key): timer = TimerUtility.timers[key] timer.start() @staticmethod def read_timer(key): timer = TimerUtility.timers[key] return timer.read() @staticmethod def stop_timer(key): timer = TimerUtility.timers[key] timer.stop() @staticmethod def log_timers(): Logger.log("\n\n****************************LOG OF TIMINGS***********************************") Logger.log(" Routine #Calls Avg Time Total Time") Logger.log(" (millisec) (millisec)") for key in TimerUtility.timers: timer = TimerUtility.timers[key] Logger.log(timer) Logger.log(f"Number of CPUs = {Globals.npes}")